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);
169 my $sth = $dbh->prepare($query);
171 if (!$sth->execute) {
172 &ERROR("GetColNiceHash: execute: '$query'");
173 # &ERROR("GetCol => $DBI::errstr");
178 %retval = %{ $sth->fetchrow_hashref() };
186 # Usage: &dbGetColInfo($table);
190 my $query = "SHOW COLUMNS from $table";
191 if ($param{DBType} =~ /^pg/i) {
192 $query = "SELECT * FROM $table LIMIT 1";
197 my $sth = $dbh->prepare($query);
199 if (!$sth->execute) {
200 &ERROR("GRI => '$query'");
201 &ERROR("GRI => $DBI::errstr");
207 while (my @row = $sth->fetchrow_array) {
208 push(@cols, $row[0]);
215 ##### NOTE: not used yet.
216 # Usage: &dbSelectHashref($select, $from, $where, $other)
217 sub dbSelectHashref {
218 my $c = dbSelectManyHash(@_);
219 my $H = $c->fetchrow_hashref;
224 ##### NOTE: not used yet.
225 # Usage: &dbSelectHashref($select, $from, $where, $other)
226 sub dbSelectManyHash {
227 my($select, $from, $where, $other) = @_;
230 $sql = "SELECT $select ";
231 $sql .= "FROM $from " if $from;
232 $sql .= "WHERE $where " if $where;
233 $sql .= "$other" if $other;
236 my $c = $dbh->prepare($sql);
237 # $c->execute or print "\n<P><B>SQL Hashref Error</B><BR>\n";
239 unless ($c->execute) {
249 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
250 # Note: dbSet does dbQuote.
252 my ($table, $phref, $href) = @_;
253 my $where = join(' AND ', map {
254 $_."=".&dbQuote($phref->{$_})
258 if (!defined $phref) {
259 &WARN("dbset: phref == NULL.");
263 if (!defined $href) {
264 &WARN("dbset: href == NULL.");
268 if (!defined $table) {
269 &WARN("dbset: table == NULL.");
273 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
276 foreach (keys %{$href}) {
278 push(@vals, &dbQuote($href->{$_}) );
281 if (!@keys or !@vals) {
282 &WARN("dbset: keys or vals is NULL.");
287 if (defined $result) {
289 for(my$i=0; $i<scalar @keys; $i++) {
290 push(@keyval, $keys[$i]."=".$vals[$i] );
293 $query = "UPDATE $table SET ".
297 foreach (keys %{$phref}) {
299 push(@vals, &dbQuote($phref->{$_}) );
302 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
303 join(',',@keys), join(',',@vals) );
306 &dbRaw("Set", $query);
312 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
313 # Note: dbUpdate does dbQuote.
315 my ($table, $primkey, $primval, %hash) = @_;
318 foreach (keys %hash) {
319 push(@array, "$_=".&dbQuote($hash{$_}) );
322 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
323 " WHERE $primkey=".&dbQuote($primval)
330 # Usage: &dbInsert($table, $primkey, %hash);
331 # Note: dbInsert does dbQuote.
333 my ($table, $primkey, %hash, $delay) = @_;
338 &DEBUG("dbI: delay => $delay");
342 foreach (keys %hash) {
344 push(@vals, &dbQuote( $hash{$_} ));
347 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
348 ") VALUES (".join(',',@vals).")"
355 # Usage: &dbReplace($table, $key, %hash);
356 # Note: dbReplace does optional dbQuote.
358 my ($table, $key, %hash) = @_;
361 foreach (keys %hash) {
362 if (s/^-//) { # as is.
364 push(@vals, $hash{'-'.$_});
367 push(@vals, &dbQuote( $hash{$_} ));
371 # hrm... does pgsql support REPLACE?
372 # if not, well... fuck it.
373 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
374 ") VALUES (". join(',',@vals). ")"
381 # Usage: &dbSetRow($table, $vref, $delay);
382 # Note: dbSetRow does dbQuote.
384 my ($table, $vref, $delay) = @_;
385 my $p = ($delay) ? " DELAYED " : "";
387 # see 'perldoc perlreftut'
389 foreach (@{ $vref }) {
390 push(@values, &dbQuote($_) );
393 if (!scalar @values) {
394 &WARN("dbSetRow: values array == NULL.");
398 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
399 join(",", @values) .")" );
403 # Usage: &dbDel($table, $primkey, $primval, [$key]);
404 # Note: dbDel does dbQuote
406 my ($table, $primkey, $primval, $key) = @_;
408 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
415 # Usage: &dbRaw($prefix,$rawquery);
417 my ($prefix,$query) = @_;
420 if (!($sth = $dbh->prepare($query))) {
421 &ERROR("Raw($prefix): !prepare => '$query'");
426 if (!$sth->execute) {
427 &ERROR("Raw($prefix): !execute => '$query'");
437 # Usage: &dbRawReturn($rawquery);
442 my $sth = $dbh->prepare($query);
444 # what happens when it can't execute it? does it throw heaps more
445 # error lines? if so. follow dbRaw()'s style.
446 &ERROR("RawReturn => '$query'.") unless $sth->execute;
447 while (my @row = $sth->fetchrow_array) {
448 push(@retval, $row[0]);
455 ####################################################################
456 ##### Misc DBI stuff...
460 # Usage: &countKeys($table, [$col]);
462 my ($table, $col) = @_;
464 &DEBUG("&countKeys($table, $col);");
466 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
470 # Usage: &sumKey($table, $col);
472 my ($table, $col) = @_;
474 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
478 # Usage: &randKey($table, $select);
480 my ($table, $select) = @_;
481 my $rand = int(rand(&countKeys($table) - 1));
482 my $query = "SELECT $select FROM $table LIMIT $rand,1";
483 if ($param{DBType} =~ /^pg/i) {
484 $query =~ s/$rand,1/1,$rand/;
487 my $sth = $dbh->prepare($query);
489 &WARN("randKey($query)") unless $sth->execute;
490 my @retval = $sth->fetchrow_array;
497 # Usage: &deleteTable($table);
499 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
503 # Usage: &searchTable($table, $select, $key, $str);
504 # Note: searchTable does dbQuote.
506 my($table, $select, $key, $str) = @_;
510 # allow two types of wildcards.
511 if ($str =~ /^\^(.*)\$$/) {
512 &DEBUG("searchTable: should use dbGet(), heh.");
515 $str .= "%" if ($str =~ s/^\^//);
516 $str = "%".$str if ($str =~ s/\$$//);
517 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
521 $str =~ s/\?/_/g; # '.' should be supported, too.
525 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
527 my $sth = $dbh->prepare($query);
530 if (!$sth->execute) {
531 &WARN("Search($query)");
536 while (my @row = $sth->fetchrow_array) {
537 push(@results, $row[0]);
546 my(@path) = ($bot_data_dir, ".","..","../..");
551 my $file = "$_/setup/$table.sql";
552 &DEBUG("dbCT: table => '$table', file => '$file'");
553 next unless ( -f $file );
555 &DEBUG("dbCT: found!!!");
570 &dbRaw("dbcreateTable($table)", $data);
576 my $database_exists = 0;
579 if ($param{DBType} =~ /^mysql$/i) {
580 my $sql = "SHOW DATABASES";
581 foreach ( &dbRawReturn($sql) ) {
582 $database_exists++ if ($_ eq $param{'DBName'});
585 unless ($database_exists) {
586 &status("Creating database $param{DBName}...");
587 my $query = "CREATE DATABASE $param{DBName}";
588 &dbRaw("create(db $param{DBName})", $query);
591 # retrieve a list of db's from the server.
592 foreach ($dbh->func('_ListTables')) {
596 } elsif ($param{DBType} =~ /^SQLite$/i) {
598 # retrieve a list of db's from the server.
599 foreach ( &dbRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
604 if (!scalar keys %db) {
605 &status("Creating database $param{'DBName'}...");
606 my $query = "CREATE DATABASE $param{'DBName'}";
607 &dbRaw("create(db $param{'DBName'})", $query);
611 foreach ( qw(factoids freshmeat rootwarn seen stats) ) {
612 next if (exists $db{$_});
613 &status("checkTables: creating new table $_...");