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 my $retval = $sth->fetchrow_hashref();
194 # Usage: &dbGetColInfo($table);
198 my $query = "SHOW COLUMNS from $table";
199 if ($param{DBType} =~ /^pg/i) {
200 $query = "SELECT * FROM $table LIMIT 1";
205 my $sth = $dbh->prepare($query);
207 if (!$sth->execute) {
208 &ERROR("GRI => '$query'");
209 &ERROR("GRI => $DBI::errstr");
215 while (my @row = $sth->fetchrow_array) {
216 push(@cols, $row[0]);
223 ##### NOTE: not used yet.
224 # Usage: &dbSelectHashref($select, $from, $where, $other)
225 sub dbSelectHashref {
226 my $c = dbSelectManyHash(@_);
227 my $H = $c->fetchrow_hashref;
232 ##### NOTE: not used yet.
233 # Usage: &dbSelectHashref($select, $from, $where, $other)
234 sub dbSelectManyHash {
235 my($select, $from, $where, $other) = @_;
238 $sql = "SELECT $select ";
239 $sql .= "FROM $from " if $from;
240 $sql .= "WHERE $where " if $where;
241 $sql .= "$other" if $other;
244 my $c = $dbh->prepare($sql);
245 # $c->execute or print "\n<P><B>SQL Hashref Error</B><BR>\n";
247 unless ($c->execute) {
257 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
258 # Note: dbSet does dbQuote.
260 my ($table, $phref, $href) = @_;
261 my $where = join(' AND ', map {
262 $_."=".&dbQuote($phref->{$_})
266 if (!defined $phref) {
267 &WARN("dbset: phref == NULL.");
271 if (!defined $href) {
272 &WARN("dbset: href == NULL.");
276 if (!defined $table) {
277 &WARN("dbset: table == NULL.");
282 foreach (keys %{$href}) {
284 push(@vals, &dbQuote($href->{$_}) );
287 if (!@keys or !@vals) {
288 &WARN("dbset: keys or vals is NULL.");
292 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
295 if (defined $result) {
297 for(my$i=0; $i<scalar @keys; $i++) {
298 push(@keyval, $keys[$i]."=".$vals[$i] );
301 $query = "UPDATE $table SET ".
305 foreach (keys %{$phref}) {
307 push(@vals, &dbQuote($phref->{$_}) );
310 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
311 join(',',@keys), join(',',@vals) );
314 &dbRaw("Set", $query);
320 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
321 # Note: dbUpdate does dbQuote.
323 my ($table, $primkey, $primval, %hash) = @_;
326 foreach (keys %hash) {
327 push(@array, "$_=".&dbQuote($hash{$_}) );
330 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
331 " WHERE $primkey=".&dbQuote($primval)
338 # Usage: &dbInsert($table, $primkey, %hash);
339 # Note: dbInsert does dbQuote.
341 my ($table, $primkey, %hash, $delay) = @_;
346 &DEBUG("dbI: delay => $delay");
350 foreach (keys %hash) {
352 push(@vals, &dbQuote( $hash{$_} ));
355 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
356 ") VALUES (".join(',',@vals).")"
363 # Usage: &dbReplace($table, $key, %hash);
364 # Note: dbReplace does optional dbQuote.
366 my ($table, $key, %hash) = @_;
369 foreach (keys %hash) {
370 if (s/^-//) { # as is.
372 push(@vals, $hash{'-'.$_});
375 push(@vals, &dbQuote( $hash{$_} ));
379 # hrm... does pgsql support REPLACE?
380 # if not, well... fuck it.
381 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
382 ") VALUES (". join(',',@vals). ")"
389 # Usage: &dbSetRow($table, $vref, $delay);
390 # Note: dbSetRow does dbQuote.
392 my ($table, $vref, $delay) = @_;
393 my $p = ($delay) ? " DELAYED " : "";
395 # see 'perldoc perlreftut'
397 foreach (@{ $vref }) {
398 push(@values, &dbQuote($_) );
401 if (!scalar @values) {
402 &WARN("dbSetRow: values array == NULL.");
406 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
407 join(",", @values) .")" );
411 # Usage: &dbDel($table, $primkey, $primval, [$key]);
412 # Note: dbDel does dbQuote
414 my ($table, $primkey, $primval, $key) = @_;
416 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
423 # Usage: &dbRaw($prefix,$rawquery);
425 my ($prefix,$query) = @_;
428 if (!($sth = $dbh->prepare($query))) {
429 &ERROR("Raw($prefix): !prepare => '$query'");
434 if (!$sth->execute) {
435 &ERROR("Raw($prefix): !execute => '$query'");
445 # Usage: &dbRawReturn($rawquery);
450 my $sth = $dbh->prepare($query);
452 # what happens when it can't execute it? does it throw heaps more
453 # error lines? if so. follow dbRaw()'s style.
454 &ERROR("RawReturn => '$query'.") unless $sth->execute;
455 while (my @row = $sth->fetchrow_array) {
456 push(@retval, $row[0]);
463 ####################################################################
464 ##### Misc DBI stuff...
468 # Usage: &countKeys($table, [$col]);
470 my ($table, $col) = @_;
472 &DEBUG("&countKeys($table, $col);");
474 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
478 # Usage: &sumKey($table, $col);
480 my ($table, $col) = @_;
482 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
486 # Usage: &randKey($table, $select);
488 my ($table, $select) = @_;
489 my $rand = int(rand(&countKeys($table) - 1));
490 my $query = "SELECT $select FROM $table LIMIT $rand,1";
491 if ($param{DBType} =~ /^pg/i) {
492 $query =~ s/$rand,1/1,$rand/;
495 my $sth = $dbh->prepare($query);
497 &WARN("randKey($query)") unless $sth->execute;
498 my @retval = $sth->fetchrow_array;
505 # Usage: &deleteTable($table);
507 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
511 # Usage: &searchTable($table, $select, $key, $str);
512 # Note: searchTable does dbQuote.
514 my($table, $select, $key, $str) = @_;
518 # allow two types of wildcards.
519 if ($str =~ /^\^(.*)\$$/) {
520 &DEBUG("searchTable: should use dbGet(), heh.");
523 $str .= "%" if ($str =~ s/^\^//);
524 $str = "%".$str if ($str =~ s/\$$//);
525 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
529 $str =~ s/\?/_/g; # '.' should be supported, too.
533 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
535 my $sth = $dbh->prepare($query);
538 if (!$sth->execute) {
539 &WARN("Search($query)");
544 while (my @row = $sth->fetchrow_array) {
545 push(@results, $row[0]);
554 my(@path) = ($bot_data_dir, ".","..","../..");
559 my $file = "$_/setup/$table.sql";
560 &DEBUG("dbCT: table => '$table', file => '$file'");
561 next unless ( -f $file );
563 &DEBUG("dbCT: found!!!");
578 &dbRaw("dbcreateTable($table)", $data);
584 my $database_exists = 0;
587 if ($param{DBType} =~ /^mysql$/i) {
588 my $sql = "SHOW DATABASES";
589 foreach ( &dbRawReturn($sql) ) {
590 $database_exists++ if ($_ eq $param{'DBName'});
593 unless ($database_exists) {
594 &status("Creating database $param{DBName}...");
595 my $query = "CREATE DATABASE $param{DBName}";
596 &dbRaw("create(db $param{DBName})", $query);
599 # retrieve a list of db's from the server.
600 foreach ($dbh->func('_ListTables')) {
604 } elsif ($param{DBType} =~ /^SQLite$/i) {
606 # retrieve a list of db's from the server.
607 foreach ( &dbRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
612 if (!scalar keys %db) {
613 &status("Creating database $param{'DBName'}...");
614 my $query = "CREATE DATABASE $param{'DBName'}";
615 &dbRaw("create(db $param{'DBName'})", $query);
619 foreach ( qw(factoids freshmeat rootwarn seen stats botmail) ) {
620 next if (exists $db{$_});
621 &status("checkTables: creating new table $_...");