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) {
53 &WARN("dbGet: select == NULL. table => $table");
58 if (!($sth = $dbh->prepare($query))) {
59 &ERROR("Get: prepare: $DBI::errstr");
65 &ERROR("Get: execute: '$query'");
70 my @retval = $sth->fetchrow_array;
74 if (scalar @retval > 1) {
76 } elsif (scalar @retval == 1) {
84 # Usage: &dbGetCol($table, $select, $where, [$type]);
86 my ($table, $select, $where, $type) = @_;
87 my $query = "SELECT $select FROM $table";
88 $query .= " WHERE ".$where if ($where);
91 my $sth = $dbh->prepare($query);
94 &ERROR("GetCol: execute: '$query'");
99 if (defined $type and $type == 2) {
100 &DEBUG("dbgetcol: type 2!");
101 while (my @row = $sth->fetchrow_array) {
102 $retval{$row[0]} = join(':', $row[1..$#row]);
104 &DEBUG("dbgetcol: count => ".scalar(keys %retval) );
106 } elsif (defined $type and $type == 1) {
107 while (my @row = $sth->fetchrow_array) {
108 # reverse it to make it easier to count.
109 if (scalar @row == 2) {
110 $retval{$row[1]}{$row[0]} = 1;
111 } elsif (scalar @row == 3) {
112 $retval{$row[1]}{$row[0]} = 1;
114 # what to do if there's only one or more than 3?
118 while (my @row = $sth->fetchrow_array) {
119 $retval{$row[0]} = $row[1];
129 # Usage: &dbGetColNiceHash($table, $select, $where);
130 sub dbGetColNiceHash {
131 my ($table, $select, $where) = @_;
133 my $query = "SELECT $select FROM $table";
134 $query .= " WHERE ".$where if ($where);
137 &DEBUG("dbGetColNiceHash: query => '$query'.");
139 my $sth = $dbh->prepare($query);
141 if (!$sth->execute) {
142 &ERROR("GetColNiceHash: execute: '$query'");
143 # &ERROR("GetCol => $DBI::errstr");
148 %retval = %{ $sth->fetchrow_hashref() };
156 # Usage: &dbGetColInfo($table);
160 my $query = "SHOW COLUMNS from $table";
163 my $sth = $dbh->prepare($query);
165 if (!$sth->execute) {
166 &ERROR("GRI => '$query'");
167 &ERROR("GRI => $DBI::errstr");
173 while (my @row = $sth->fetchrow_array) {
174 push(@cols, $row[0]);
182 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
183 # Note: dbSet does dbQuote.
185 my ($table, $phref, $href) = @_;
186 my $where = join(' AND ', map {
187 $_."=".&dbQuote($phref->{$_})
191 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
194 foreach (keys %{$href}) {
196 push(@vals, &dbQuote($href->{$_}) );
199 if (!@keys or !@vals) {
200 &WARN("dbset: keys or vals is NULL.");
205 if (defined $result) {
207 for(my$i=0; $i<scalar @keys; $i++) {
208 push(@keyval, $keys[$i]."=".$vals[$i] );
211 $query = "UPDATE $table SET ".
212 join(' AND ', @keyval).
215 foreach (keys %{$phref}) {
217 push(@vals, &dbQuote($phref->{$_}) );
220 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
221 join(',',@keys), join(',',@vals) );
224 &dbRaw("Set", $query);
230 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
231 # Note: dbUpdate does dbQuote.
233 my ($table, $primkey, $primval, %hash) = @_;
236 foreach (keys %hash) {
237 push(@array, "$_=".&dbQuote($hash{$_}) );
240 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
241 " WHERE $primkey=".&dbQuote($primval)
248 # Usage: &dbInsert($table, $primkey, %hash);
249 # Note: dbInsert does dbQuote.
251 my ($table, $primkey, %hash, $delay) = @_;
256 &DEBUG("dbI: delay => $delay");
260 foreach (keys %hash) {
262 push(@vals, &dbQuote($hash{$_}));
265 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
266 ") VALUES (".join(',',@vals).")"
273 # Usage: &dbReplace($table, $key, %hash);
274 # Note: dbReplace does optional dbQuote.
276 my ($table, $key, %hash) = @_;
279 foreach (keys %hash) {
280 if (s/^-//) { # as is.
282 push(@vals, $hash{'-'.$_});
285 push(@vals, &dbQuote($hash{$_}));
290 &DEBUG("REPLACE INTO $table (".join(',',@keys).
291 ") VALUES (". join(',',@vals). ")" );
294 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
295 ") VALUES (". join(',',@vals). ")"
302 # Usage: &dbSetRow($table, $vref, $delay);
303 # Note: dbSetRow does dbQuote.
305 my ($table, $vref, $delay) = @_;
306 my $p = ($delay) ? " DELAYED " : "";
308 # see 'perldoc perlreftut'
310 foreach (@{ $vref }) {
311 push(@values, &dbQuote($_) );
314 if (!scalar @values) {
315 &WARN("dbSetRow: values array == NULL.");
319 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
320 join(",", @values) .")" );
324 # Usage: &dbDel($table, $primkey, $primval, [$key]);
325 # Note: dbDel does dbQuote
327 my ($table, $primkey, $primval, $key) = @_;
329 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
336 # Usage: &dbRaw($prefix,$rawquery);
338 my ($prefix,$query) = @_;
341 if (!($sth = $dbh->prepare($query))) {
342 &ERROR("Raw($prefix): $DBI::errstr");
346 # &DEBUG("query => '$query'.");
349 if (!$sth->execute) {
350 &ERROR("Raw($prefix): => '$query'");
351 # $DBI::errstr is printed as warning automatically.
361 # Usage: &dbRawReturn($rawquery);
366 my $sth = $dbh->prepare($query);
368 &ERROR("RawReturn => '$query'.") unless $sth->execute;
369 while (my @row = $sth->fetchrow_array) {
370 push(@retval, $row[0]);
377 ####################################################################
378 ##### Misc DBI stuff...
382 # Usage: &countKeys($table, [$col]);
384 my ($table, $col) = @_;
387 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
390 # Usage: &sumKey($table, $col);
392 my ($table, $col) = @_;
394 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
398 # Usage: &randKey($table, $select);
400 my ($table, $select) = @_;
401 my $rand = int(rand(&countKeys($table) - 1));
402 my $query = "SELECT $select FROM $table LIMIT $rand,1";
404 my $sth = $dbh->prepare($query);
406 &WARN("randKey($query)") unless $sth->execute;
407 my @retval = $sth->fetchrow_array;
414 # Usage: &deleteTable($table);
416 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
420 # Usage: &searchTable($table, $select, $key, $str);
421 # Note: searchTable does dbQuote.
423 my($table, $select, $key, $str) = @_;
427 # allow two types of wildcards.
428 if ($str =~ /^\^(.*)\$$/) {
429 &DEBUG("searchTable: should use dbGet(), heh.");
432 $str .= "%" if ($str =~ s/^\^//);
433 $str = "%".$str if ($str =~ s/\$$//);
434 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
438 $str =~ s/\?/\_/g; # '.' should be supported, too.
441 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
443 my $sth = $dbh->prepare($query);
445 if (!$sth->execute) {
446 &WARN("Search($query)");
450 while (my @row = $sth->fetchrow_array) {
451 push(@results, $row[0]);
460 my(@path) = (".","..","../..");
465 my $file = "$_/setup/$table.sql";
466 &DEBUG("dbCT: file => $file");
467 next unless ( -f $file );
469 &DEBUG("dbCT: found!!!");
484 &dbRaw("createTable($table)", $data);
490 my $database_exists = 0;
491 foreach ( &dbRawReturn("SHOW DATABASES") ) {
492 $database_exists++ if ($_ eq $param{'DBName'});
495 unless ($database_exists) {
496 &status("Creating database $param{DBName}...");
497 $query = "CREATE DATABASE $param{DBName}";
498 &dbRaw("create(db $param{DBName})", $query);
501 # retrieve a list of db's from the server.
503 foreach ($dbh->func('_ListTables')) {
508 if (!scalar keys %db) {
509 # &status("Creating database $param{'DBName'}...");
510 # $query = "CREATE DATABASE $param{'DBName'}";
511 # &dbRaw("create(db $param{'DBName'})", $query);
514 foreach ("factoids", "freshmeat", "rootwarn", "seen", "stats",
516 next if (exists $db{$_});
517 &status(" creating new table $_...");