2 # db_mysql.pl: MySQL database frontend.
4 # Version: v0.2c (19991224)
10 if (&IsParam("useStrict")) { use strict; }
13 my ($db, $user, $pass) = @_;
14 my $dsn = "DBI:mysql:$db:$param{'SQLHost'}";
15 $dbh = DBI->connect($dsn, $user, $pass);
18 &status("Opened MySQL connection to $param{'SQLHost'}");
20 &ERROR("cannot connect to $param{'SQLHost'}.");
21 &ERROR("since mysql is not available, shutting down bot!");
31 return 0 unless ($dbh);
33 &status("Closed MySQL connection to $param{'SQLHost'}.");
40 # Usage: &dbQuote($str);
42 return $dbh->quote($_[0]);
46 # Usage: &dbGet($table, $select, $where);
48 my ($table, $select, $where) = @_;
49 my $query = "SELECT $select FROM $table";
50 $query .= " WHERE $where" if ($where);
52 if (!defined $select or $select =~ /^\s*$/) {
53 &WARN("dbGet: select == NULL.");
57 if (!defined $table or $table =~ /^\s*$/) {
58 &WARN("dbGet: table == NULL.");
63 if (!($sth = $dbh->prepare($query))) {
64 &ERROR("Get: prepare: $DBI::errstr");
70 &ERROR("Get: execute: '$query'");
75 my @retval = $sth->fetchrow_array;
79 if (scalar @retval > 1) {
81 } elsif (scalar @retval == 1) {
89 # Usage: &dbGetCol($table, $select, $where, [$type]);
91 my ($table, $select, $where, $type) = @_;
92 my $query = "SELECT $select FROM $table";
93 $query .= " WHERE ".$where if ($where);
96 my $sth = $dbh->prepare($query);
99 &ERROR("GetCol: execute: '$query'");
104 if (defined $type and $type == 2) {
105 &DEBUG("dbgetcol: type 2!");
106 while (my @row = $sth->fetchrow_array) {
107 $retval{$row[0]} = join(':', $row[1..$#row]);
109 &DEBUG("dbgetcol: count => ".scalar(keys %retval) );
111 } elsif (defined $type and $type == 1) {
112 while (my @row = $sth->fetchrow_array) {
113 # reverse it to make it easier to count.
114 if (scalar @row == 2) {
115 $retval{$row[1]}{$row[0]} = 1;
116 } elsif (scalar @row == 3) {
117 $retval{$row[1]}{$row[0]} = 1;
119 # what to do if there's only one or more than 3?
123 while (my @row = $sth->fetchrow_array) {
124 $retval{$row[0]} = $row[1];
134 # Usage: &dbGetColNiceHash($table, $select, $where);
135 sub dbGetColNiceHash {
136 my ($table, $select, $where) = @_;
138 my $query = "SELECT $select FROM $table";
139 $query .= " WHERE ".$where if ($where);
142 my $sth = $dbh->prepare($query);
144 if (!$sth->execute) {
145 &ERROR("GetColNiceHash: execute: '$query'");
146 # &ERROR("GetCol => $DBI::errstr");
151 %retval = %{ $sth->fetchrow_hashref() };
159 # Usage: &dbGetColInfo($table);
163 my $query = "SHOW COLUMNS from $table";
166 my $sth = $dbh->prepare($query);
168 if (!$sth->execute) {
169 &ERROR("GRI => '$query'");
170 &ERROR("GRI => $DBI::errstr");
176 while (my @row = $sth->fetchrow_array) {
177 push(@cols, $row[0]);
185 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
186 # Note: dbSet does dbQuote.
188 my ($table, $phref, $href) = @_;
189 my $where = join(' AND ', map {
190 $_."=".&dbQuote($phref->{$_})
194 if (!defined $phref) {
195 &WARN("dbset: phref == NULL.");
199 if (!defined $href) {
200 &WARN("dbset: href == NULL.");
204 if (!defined $table) {
205 &WARN("dbset: table == NULL.");
209 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
212 foreach (keys %{$href}) {
214 push(@vals, &dbQuote($href->{$_}) );
217 if (!@keys or !@vals) {
218 &WARN("dbset: keys or vals is NULL.");
223 if (defined $result) {
225 for(my$i=0; $i<scalar @keys; $i++) {
226 push(@keyval, $keys[$i]."=".$vals[$i] );
229 $query = "UPDATE $table SET ".
230 join(' AND ', @keyval).
233 foreach (keys %{$phref}) {
235 push(@vals, &dbQuote($phref->{$_}) );
238 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
239 join(',',@keys), join(',',@vals) );
242 &dbRaw("Set", $query);
248 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
249 # Note: dbUpdate does dbQuote.
251 my ($table, $primkey, $primval, %hash) = @_;
254 foreach (keys %hash) {
255 push(@array, "$_=".&dbQuote($hash{$_}) );
258 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
259 " WHERE $primkey=".&dbQuote($primval)
266 # Usage: &dbInsert($table, $primkey, %hash);
267 # Note: dbInsert does dbQuote.
269 my ($table, $primkey, %hash, $delay) = @_;
274 &DEBUG("dbI: delay => $delay");
278 foreach (keys %hash) {
280 push(@vals, &dbQuote($hash{$_}));
283 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
284 ") VALUES (".join(',',@vals).")"
291 # Usage: &dbReplace($table, $key, %hash);
292 # Note: dbReplace does optional dbQuote.
294 my ($table, $key, %hash) = @_;
297 foreach (keys %hash) {
298 if (s/^-//) { # as is.
300 push(@vals, $hash{'-'.$_});
303 push(@vals, &dbQuote($hash{$_}));
308 &DEBUG("REPLACE INTO $table (".join(',',@keys).
309 ") VALUES (". join(',',@vals). ")" );
312 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
313 ") VALUES (". join(',',@vals). ")"
320 # Usage: &dbSetRow($table, $vref, $delay);
321 # Note: dbSetRow does dbQuote.
323 my ($table, $vref, $delay) = @_;
324 my $p = ($delay) ? " DELAYED " : "";
326 # see 'perldoc perlreftut'
328 foreach (@{ $vref }) {
329 push(@values, &dbQuote($_) );
332 if (!scalar @values) {
333 &WARN("dbSetRow: values array == NULL.");
337 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
338 join(",", @values) .")" );
342 # Usage: &dbDel($table, $primkey, $primval, [$key]);
343 # Note: dbDel does dbQuote
345 my ($table, $primkey, $primval, $key) = @_;
347 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
354 # Usage: &dbRaw($prefix,$rawquery);
356 my ($prefix,$query) = @_;
359 if (!($sth = $dbh->prepare($query))) {
360 &ERROR("Raw($prefix): $DBI::errstr");
364 # &DEBUG("query => '$query'.");
367 if (!$sth->execute) {
368 &ERROR("Raw($prefix): => '$query'");
369 # $DBI::errstr is printed as warning automatically.
379 # Usage: &dbRawReturn($rawquery);
384 my $sth = $dbh->prepare($query);
386 &ERROR("RawReturn => '$query'.") unless $sth->execute;
387 while (my @row = $sth->fetchrow_array) {
388 push(@retval, $row[0]);
395 ####################################################################
396 ##### Misc DBI stuff...
400 # Usage: &countKeys($table, [$col]);
402 my ($table, $col) = @_;
405 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
408 # Usage: &sumKey($table, $col);
410 my ($table, $col) = @_;
412 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
416 # Usage: &randKey($table, $select);
418 my ($table, $select) = @_;
419 my $rand = int(rand(&countKeys($table) - 1));
420 my $query = "SELECT $select FROM $table LIMIT $rand,1";
422 my $sth = $dbh->prepare($query);
424 &WARN("randKey($query)") unless $sth->execute;
425 my @retval = $sth->fetchrow_array;
432 # Usage: &deleteTable($table);
434 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
438 # Usage: &searchTable($table, $select, $key, $str);
439 # Note: searchTable does dbQuote.
441 my($table, $select, $key, $str) = @_;
445 # allow two types of wildcards.
446 if ($str =~ /^\^(.*)\$$/) {
447 &DEBUG("searchTable: should use dbGet(), heh.");
450 $str .= "%" if ($str =~ s/^\^//);
451 $str = "%".$str if ($str =~ s/\$$//);
452 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
456 $str =~ s/\?/\_/g; # '.' should be supported, too.
459 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
461 my $sth = $dbh->prepare($query);
463 if (!$sth->execute) {
464 &WARN("Search($query)");
468 while (my @row = $sth->fetchrow_array) {
469 push(@results, $row[0]);
478 my(@path) = ($bot_data_dir, ".","..","../..");
483 my $file = "$_/setup/$table.sql";
484 &DEBUG("dbCT: file => $file");
485 next unless ( -f $file );
487 &DEBUG("dbCT: found!!!");
502 &dbRaw("createTable($table)", $data);
508 my $database_exists = 0;
509 foreach ( &dbRawReturn("SHOW DATABASES") ) {
510 $database_exists++ if ($_ eq $param{'DBName'});
513 unless ($database_exists) {
514 &status("Creating database $param{DBName}...");
515 $query = "CREATE DATABASE $param{DBName}";
516 &dbRaw("create(db $param{DBName})", $query);
519 # retrieve a list of db's from the server.
521 foreach ($dbh->func('_ListTables')) {
526 if (!scalar keys %db) {
527 # &status("Creating database $param{'DBName'}...");
528 # $query = "CREATE DATABASE $param{'DBName'}";
529 # &dbRaw("create(db $param{'DBName'})", $query);
532 foreach ("factoids", "freshmeat", "rootwarn", "seen", "stats",
534 next if (exists $db{$_});
535 &status(" creating new table $_...");