2 # dbi.pl: DBI (mysql/pgsql/sqlite) database frontend.
4 # Version: v0.2c (19991224)
6 # Notes: based on db_mysql.pl
12 use vars qw($dbh $shm $bot_data_dir);
17 # &openDB($dbname, $dbtype, $sqluser, $sqlpass, $nofail);
19 my ($db, $type, $user, $pass, $no_fail) = @_;
20 # this is a mess. someone fix it, please.
21 if ($type =~ /^SQLite$/i) {
22 $db = "dbname=$db.sqlite";
23 } elsif ($type =~ /^pg/i) {
28 my $dsn = "DBI:$type:$db";
30 # SQLHost should be unset for SQLite
31 if (exists $param{'SQLHost'} and $param{'SQLHost'}) {
32 $dsn .= ":$param{SQLHost}";
33 $hoststr = " to $param{'SQLHost'}";
35 # SQLite ignores $user and $pass
36 $dbh = DBI->connect($dsn, $user, $pass);
38 if ($dbh && !$dbh->err) {
39 &status("Opened $type connection$hoststr");
41 &ERROR("cannot connect$hoststr.");
42 &ERROR("since $type is not available, shutting down bot!");
43 &ERROR( $dbh->errstr ) if ($dbh);
48 return 0 if ($no_fail);
55 return 0 unless ($dbh);
57 my $x = $param{SQLHost};
58 my $hoststr = ($x) ? " to $x" : "";
60 &status("Closed DBI connection$hoststr.");
67 # Usage: &dbQuote($str);
69 return $dbh->quote($_[0]);
73 # Usage: &dbGet($table, $select, $where);
75 my ($table, $select, $where) = @_;
76 my $query = "SELECT $select FROM $table";
77 $query .= " WHERE $where" if ($where);
79 if (!defined $select or $select =~ /^\s*$/) {
80 &WARN("dbGet: select == NULL.");
84 if (!defined $table or $table =~ /^\s*$/) {
85 &WARN("dbGet: table == NULL.");
90 if (!($sth = $dbh->prepare($query))) {
91 &ERROR("Get: prepare: $DBI::errstr");
97 &ERROR("Get: execute: '$query'");
102 my @retval = $sth->fetchrow_array;
106 if (scalar @retval > 1) {
108 } elsif (scalar @retval == 1) {
116 # Usage: &dbGetCol($table, $select, $where, [$type]);
118 my ($table, $select, $where, $type) = @_;
119 my $query = "SELECT $select FROM $table";
120 $query .= " WHERE ".$where if ($where);
123 my $sth = $dbh->prepare($query);
125 if (!$sth->execute) {
126 &ERROR("GetCol: execute: '$query'");
131 if (defined $type and $type == 2) {
132 &DEBUG("dbgetcol: type 2!");
133 while (my @row = $sth->fetchrow_array) {
134 $retval{$row[0]} = join(':', $row[1..$#row]);
136 &DEBUG("dbgetcol: count => ".scalar(keys %retval) );
138 } elsif (defined $type and $type == 1) {
139 while (my @row = $sth->fetchrow_array) {
140 # reverse it to make it easier to count.
141 if (scalar @row == 2) {
142 $retval{$row[1]}{$row[0]} = 1;
143 } elsif (scalar @row == 3) {
144 $retval{$row[1]}{$row[0]} = 1;
146 # what to do if there's only one or more than 3?
150 while (my @row = $sth->fetchrow_array) {
151 $retval{$row[0]} = $row[1];
161 # Usage: &dbGetColNiceHash($table, $select, $where);
162 sub dbGetColNiceHash {
163 my ($table, $select, $where) = @_;
165 my $query = "SELECT $select FROM $table";
166 $query .= " WHERE ".$where if ($where);
170 if (!($sth = $dbh->prepare($query))) {
171 &ERROR("GetColNiceHash: prepare: $DBI::errstr");
175 if (!$sth->execute) {
176 &ERROR("GetColNiceHash: execute: '$query'");
177 # &ERROR("GetCol => $DBI::errstr");
182 %retval = %{ $sth->fetchrow_hashref() };
190 # Usage: &dbGetColInfo($table);
194 my $query = "SHOW COLUMNS from $table";
195 if ($param{DBType} =~ /^pg/i) {
196 $query = "SELECT * FROM $table LIMIT 1";
201 my $sth = $dbh->prepare($query);
203 if (!$sth->execute) {
204 &ERROR("GRI => '$query'");
205 &ERROR("GRI => $DBI::errstr");
211 while (my @row = $sth->fetchrow_array) {
212 push(@cols, $row[0]);
219 ##### NOTE: not used yet.
220 # Usage: &dbSelectHashref($select, $from, $where, $other)
221 sub dbSelectHashref {
222 my $c = dbSelectManyHash(@_);
223 my $H = $c->fetchrow_hashref;
228 ##### NOTE: not used yet.
229 # Usage: &dbSelectHashref($select, $from, $where, $other)
230 sub dbSelectManyHash {
231 my($select, $from, $where, $other) = @_;
234 $sql = "SELECT $select ";
235 $sql .= "FROM $from " if $from;
236 $sql .= "WHERE $where " if $where;
237 $sql .= "$other" if $other;
240 my $c = $dbh->prepare($sql);
241 # $c->execute or print "\n<P><B>SQL Hashref Error</B><BR>\n";
243 unless ($c->execute) {
253 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
254 # Note: dbSet does dbQuote.
256 my ($table, $phref, $href) = @_;
257 my $where = join(' AND ', map {
258 $_."=".&dbQuote($phref->{$_})
262 if (!defined $phref) {
263 &WARN("dbset: phref == NULL.");
267 if (!defined $href) {
268 &WARN("dbset: href == NULL.");
272 if (!defined $table) {
273 &WARN("dbset: table == NULL.");
278 foreach (keys %{$href}) {
280 push(@vals, &dbQuote($href->{$_}) );
283 if (!@keys or !@vals) {
284 &WARN("dbset: keys or vals is NULL.");
288 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
291 if (defined $result) {
293 for(my$i=0; $i<scalar @keys; $i++) {
294 push(@keyval, $keys[$i]."=".$vals[$i] );
297 $query = "UPDATE $table SET ".
301 foreach (keys %{$phref}) {
303 push(@vals, &dbQuote($phref->{$_}) );
306 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
307 join(',',@keys), join(',',@vals) );
310 &dbRaw("Set", $query);
316 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
317 # Note: dbUpdate does dbQuote.
319 my ($table, $primkey, $primval, %hash) = @_;
322 foreach (keys %hash) {
323 push(@array, "$_=".&dbQuote($hash{$_}) );
326 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
327 " WHERE $primkey=".&dbQuote($primval)
334 # Usage: &dbInsert($table, $primkey, %hash);
335 # Note: dbInsert does dbQuote.
337 my ($table, $primkey, %hash, $delay) = @_;
342 &DEBUG("dbI: delay => $delay");
346 foreach (keys %hash) {
348 push(@vals, &dbQuote( $hash{$_} ));
351 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
352 ") VALUES (".join(',',@vals).")"
359 # Usage: &dbReplace($table, $key, %hash);
360 # Note: dbReplace does optional dbQuote.
362 my ($table, $key, %hash) = @_;
365 foreach (keys %hash) {
366 if (s/^-//) { # as is.
368 push(@vals, $hash{'-'.$_});
371 push(@vals, &dbQuote( $hash{$_} ));
375 # hrm... does pgsql support REPLACE?
376 # if not, well... fuck it.
377 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
378 ") VALUES (". join(',',@vals). ")"
385 # Usage: &dbSetRow($table, $vref, $delay);
386 # Note: dbSetRow does dbQuote.
388 my ($table, $vref, $delay) = @_;
389 my $p = ($delay) ? " DELAYED " : "";
391 # see 'perldoc perlreftut'
393 foreach (@{ $vref }) {
394 push(@values, &dbQuote($_) );
397 if (!scalar @values) {
398 &WARN("dbSetRow: values array == NULL.");
402 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
403 join(",", @values) .")" );
407 # Usage: &dbDel($table, $primkey, $primval, [$key]);
408 # Note: dbDel does dbQuote
410 my ($table, $primkey, $primval, $key) = @_;
412 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
419 # Usage: &dbRaw($prefix,$rawquery);
421 my ($prefix,$query) = @_;
424 if (!($sth = $dbh->prepare($query))) {
425 &ERROR("Raw($prefix): !prepare => '$query'");
430 if (!$sth->execute) {
431 &ERROR("Raw($prefix): !execute => '$query'");
441 # Usage: &dbRawReturn($rawquery);
446 my $sth = $dbh->prepare($query);
448 # what happens when it can't execute it? does it throw heaps more
449 # error lines? if so. follow dbRaw()'s style.
450 &ERROR("RawReturn => '$query'.") unless $sth->execute;
451 while (my @row = $sth->fetchrow_array) {
452 push(@retval, $row[0]);
459 ####################################################################
460 ##### Misc DBI stuff...
464 # Usage: &countKeys($table, [$col]);
466 my ($table, $col) = @_;
468 &DEBUG("&countKeys($table, $col);");
470 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
474 # Usage: &sumKey($table, $col);
476 my ($table, $col) = @_;
478 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
482 # Usage: &randKey($table, $select);
484 my ($table, $select) = @_;
485 my $rand = int(rand(&countKeys($table) - 1));
486 my $query = "SELECT $select FROM $table LIMIT $rand,1";
487 if ($param{DBType} =~ /^pg/i) {
488 $query =~ s/$rand,1/1,$rand/;
491 my $sth = $dbh->prepare($query);
493 &WARN("randKey($query)") unless $sth->execute;
494 my @retval = $sth->fetchrow_array;
501 # Usage: &deleteTable($table);
503 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
507 # Usage: &searchTable($table, $select, $key, $str);
508 # Note: searchTable does dbQuote.
510 my($table, $select, $key, $str) = @_;
514 # allow two types of wildcards.
515 if ($str =~ /^\^(.*)\$$/) {
516 &DEBUG("searchTable: should use dbGet(), heh.");
519 $str .= "%" if ($str =~ s/^\^//);
520 $str = "%".$str if ($str =~ s/\$$//);
521 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
525 $str =~ s/\?/_/g; # '.' should be supported, too.
529 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
531 my $sth = $dbh->prepare($query);
534 if (!$sth->execute) {
535 &WARN("Search($query)");
540 while (my @row = $sth->fetchrow_array) {
541 push(@results, $row[0]);
550 my(@path) = ($bot_data_dir, ".","..","../..");
555 my $file = "$_/setup/$table.sql";
556 &DEBUG("dbCT: table => '$table', file => '$file'");
557 next unless ( -f $file );
559 &DEBUG("dbCT: found!!!");
574 &dbRaw("dbcreateTable($table)", $data);
580 my $database_exists = 0;
583 if ($param{DBType} =~ /^mysql$/i) {
584 my $sql = "SHOW DATABASES";
585 foreach ( &dbRawReturn($sql) ) {
586 $database_exists++ if ($_ eq $param{'DBName'});
589 unless ($database_exists) {
590 &status("Creating database $param{DBName}...");
591 my $query = "CREATE DATABASE $param{DBName}";
592 &dbRaw("create(db $param{DBName})", $query);
595 # retrieve a list of db's from the server.
596 foreach ($dbh->func('_ListTables')) {
600 } elsif ($param{DBType} =~ /^SQLite$/i) {
602 # retrieve a list of db's from the server.
603 foreach ( &dbRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
608 if (!scalar keys %db) {
609 &status("Creating database $param{'DBName'}...");
610 my $query = "CREATE DATABASE $param{'DBName'}";
611 &dbRaw("create(db $param{'DBName'})", $query);
615 foreach ( qw(factoids freshmeat rootwarn seen stats botmail) ) {
616 next if (exists $db{$_});
617 &status("checkTables: creating new table $_...");