2 # dbi.pl: DBI (mysql/pgsql/sqlite) database frontend.
4 # Version: v0.9a (20021124)
6 # Notes: based on db_mysql.pl
7 # overhauled to be 31337.
13 use vars qw($dbh $shm $bot_data_dir);
18 # This wrapper's sole purpose in life is to keep the dbh connection open.
21 # These are DBI methods which do not require an active DB
22 # connection. [Eg, don't check to see if the database is working
23 # by pinging it for these methods.]
25 @no_ping{qw(ping err err_str quote disconnect clone)} = (1) x 6;
29 return undef unless $dbh;
30 $class = ref($class) if ref($class);
31 my $self = {dbh=>$dbh};
38 my $method = $AUTOLOAD;
40 die "Undefined subroutine $method called" unless defined $self;
41 ($method) = $method =~ /([^\:]+)$/;
42 unshift @_, $self->{dbh};
43 return undef if not defined $self->{dbh};
44 goto &{$self->{dbh}->can($method)} if exists $no_ping{$method} and $no_ping{$method};
46 while (++$ping_count < 10){
47 last if $self->{dbh}->ping;
48 $self->{dbh}->disconnect;
49 $self->{dbh} = $self->{dbh}->clone;
51 if ($ping_count >=10 and not $self->{dbh}->ping){
52 &ERROR("Tried real hard but was unable to reconnect");
56 my $coderef = $self->{dbh}->can($method);
57 goto &$coderef if defined $coderef;
58 # Dumb DBI doesn't have a can method for some
59 # functions. Like func.
61 return eval "\$self->{dbh}->$method(\@_)" or die $@;
67 # &sqlOpenDB($dbname, $dbtype, $sqluser, $sqlpass, $nofail);
69 my ($db, $type, $user, $pass, $no_fail) = @_;
70 # this is a mess. someone fix it, please.
71 if ($type =~ /^SQLite(2)?$/i) {
72 $db = "dbname=$db.sqlite";
73 } elsif ($type =~ /^pg/i) {
78 my $dsn = "DBI:$type:$db";
80 # SQLHost should be unset for SQLite
81 if (exists $param{'SQLHost'} and $param{'SQLHost'}) {
82 $dsn .= ":$param{SQLHost}";
83 $hoststr = " to $param{'SQLHost'}";
85 # SQLite ignores $user and $pass
86 $dbh = Bloot::DBI->new(DBI->connect($dsn, $user, $pass));
88 if ($dbh && !$dbh->err) {
89 &status("Opened $type connection$hoststr");
91 &ERROR("Cannot connect$hoststr.");
92 &ERROR("Since $type is not available, shutting down bot!");
93 &ERROR( $dbh->errstr ) if ($dbh);
98 return 0 if ($no_fail);
105 return 0 unless ($dbh);
107 my $x = $param{SQLHost};
108 my $hoststr = ($x) ? " to $x" : "";
110 &status("Closed DBI connection$hoststr.");
117 # Usage: &sqlQuote($str);
119 return $dbh->quote($_[0]);
123 # Usage: &sqlSelectMany($table, $select, [$where_href], [$other]);
124 # Return: $sth (Statement handle object)
126 my($table, $select, $where_href, $other) = @_;
127 my $query = "SELECT $select FROM $table";
130 if (!defined $select or $select =~ /^\s*$/) {
131 &WARN("sqlSelectMany: select == NULL.");
135 if (!defined $table or $table =~ /^\s*$/) {
136 &WARN("sqlSelectMany: table == NULL.");
141 my $where = &hashref2where($where_href);
142 $query .= " WHERE $where" if ($where);
144 $query .= " $other" if ($other);
146 if (!($sth = $dbh->prepare($query))) {
147 &ERROR("sqlSelectMany: prepare: $DBI::errstr");
153 return if (!$sth->execute);
159 # Usage: &sqlSelect($table, $select, [$where_href, [$other]);
160 # Return: scalar if one element, array if list of elements.
161 # Note: Suitable for one column returns, that is, one column in $select.
162 # Todo: Always return array?
164 my $sth = &sqlSelectMany(@_);
166 &WARN("sqlSelect failed.");
169 my @retval = $sth->fetchrow_array;
172 if (scalar @retval > 1) {
174 } elsif (scalar @retval == 1) {
182 # Usage: &sqlSelectColArray($table, $select, [$where_href], [$other]);
184 sub sqlSelectColArray {
185 my $sth = &sqlSelectMany(@_);
189 &WARN("sqlSelect failed.");
193 while (my @row = $sth->fetchrow_array) {
194 push(@retval, $row[0]);
202 # Usage: &sqlSelectColHash($table, $select, [$where_href], [$other], [$type]);
203 # Return: type = 1: $retval{ col2 }{ col1 } = 1;
204 # Return: no type: $retval{ col1 } = col2;
205 # Note: does not support $other, yet.
206 sub sqlSelectColHash {
207 my ($table, $select, $where_href, $other, $type) = @_;
208 my $sth = &sqlSelectMany($table, $select, $where_href, $other);
210 &WARN("sqlSelectColhash failed.");
215 if (defined $type and $type == 2) {
216 &DEBUG("sqlSelectColHash: type 2!");
217 while (my @row = $sth->fetchrow_array) {
218 $retval{$row[0]} = join(':', $row[1..$#row]);
220 &DEBUG("sqlSelectColHash: count => ".scalar(keys %retval) );
222 } elsif (defined $type and $type == 1) {
223 while (my @row = $sth->fetchrow_array) {
224 # reverse it to make it easier to count.
225 if (scalar @row == 2) {
226 $retval{$row[1]}{$row[0]} = 1;
227 } elsif (scalar @row == 3) {
228 $retval{$row[1]}{$row[0]} = 1;
230 # what to do if there's only one or more than 3?
234 while (my @row = $sth->fetchrow_array) {
235 $retval{$row[0]} = $row[1];
245 # Usage: &sqlSelectRowHash($table, $select, [$where_href]);
246 # Return: $hash{ col } = value;
247 # Note: useful for returning only one/first row of data.
248 sub sqlSelectRowHash {
249 my $sth = &sqlSelectMany(@_);
251 &WARN("sqlSelectRowHash failed.");
254 my $retval = $sth->fetchrow_hashref();
265 # End of SELECT functions.
269 # Usage: &sqlSet($table, $where_href, $data_href);
270 # Return: 1 for success, undef for failure.
272 my ($table, $where_href, $data_href) = @_;
274 if (!defined $table or $table =~ /^\s*$/) {
275 &WARN("sqlSet: table == NULL.");
279 if (!defined $data_href or ref($data_href) ne "HASH") {
280 &WARN("sqlSet: data_href == NULL.");
284 # any column can be NULL... so just get them all.
285 my $k = join(',', keys %{ $where_href } );
286 my $result = &sqlSelect($table, $k, $where_href);
287 # &DEBUG("result is not defined :(") if (!defined $result);
289 # this was hardwired to use sqlUpdate. sqlite does not do inserts on sqlUpdate.
290 if (defined $result) {
291 &sqlUpdate($table, $data_href, $where_href);
294 my %hash = %{ $where_href };
295 # add data_href values...
296 foreach (keys %{ $data_href }) {
297 $hash{ $_ } = ${ $data_href }{$_};
301 &sqlInsert($table, $data_href);
308 # Usage: &sqlUpdate($table, $data_href, $where_href);
310 my ($table, $data_href, $where_href) = @_;
312 if (!defined $data_href or ref($data_href) ne "HASH") {
313 &WARN("sqlSet: data_href == NULL.");
317 my $where = &hashref2where($where_href) if ($where_href);
318 my $update = &hashref2update($data_href) if ($data_href);
320 &sqlRaw("Update", "UPDATE $table SET $update WHERE $where");
326 # Usage: &sqlInsert($table, $data_href, $other);
328 my ($table, $data_href, $other) = @_;
329 # note: if $other == 1, add "DELAYED" to function instead.
331 if (!defined $data_href or ref($data_href) ne "HASH") {
332 &WARN("sqlInsert: data_href == NULL.");
336 my ($k_aref, $v_aref) = &hashref2array($data_href);
337 my @k = @{ $k_aref };
338 my @v = @{ $v_aref };
341 &WARN("sqlInsert: keys or vals is NULL.");
345 &sqlRaw("Insert($table)", sprintf(
346 "INSERT %s INTO %s (%s) VALUES (%s)",
347 ($other || ""), $table, join(',',@k), join(',',@v)
354 # Usage: &sqlReplace($table, $data_href);
356 my ($table, $data_href) = @_;
358 if (!defined $data_href or ref($data_href) ne "HASH") {
359 &WARN("sqlReplace: data_href == NULL.");
363 my ($k_aref, $v_aref) = &hashref2array($data_href);
364 my @k = @{ $k_aref };
365 my @v = @{ $v_aref };
368 &WARN("sqlReplace: keys or vals is NULL.");
372 &sqlRaw("Replace($table)", sprintf(
373 "REPLACE INTO %s (%s) VALUES (%s)",
374 $table, join(',',@k), join(',',@v)
381 # Usage: &sqlDelete($table, $where_href);
383 my ($table, $where_href) = @_;
385 if (!defined $where_href or ref($where_href) ne "HASH") {
386 &WARN("sqlDelete: where_href == NULL.");
390 my $where = &hashref2where($where_href);
392 &sqlRaw("Delete", "DELETE FROM $table WHERE $where");
398 # Usage: &sqlRaw($prefix, $query);
399 # Return: 1 for success, 0 for failure.
401 my ($prefix, $query) = @_;
404 if (!defined $query or $query =~ /^\s*$/) {
405 &WARN("sqlRaw: query == NULL.");
409 if (!($sth = $dbh->prepare($query))) {
410 &ERROR("Raw($prefix): !prepare => '$query'");
415 if (!$sth->execute) {
416 &ERROR("Raw($prefix): !execute => '$query'");
427 # Usage: &sqlRawReturn($query);
434 if (!defined $query or $query =~ /^\s*$/) {
435 &WARN("sqlRawReturn: query == NULL.");
439 if (!($sth = $dbh->prepare($query))) {
440 &ERROR("RawReturn: !prepare => '$query'");
445 if (!$sth->execute) {
446 &ERROR("RawReturn: !execute => '$query'");
451 while (my @row = $sth->fetchrow_array) {
452 push(@retval, $row[0]);
460 ####################################################################
461 ##### Misc DBI stuff...
467 if (!defined $href) {
468 &WARN("hashref2where: href == NULL.");
472 if (ref($href) ne "HASH") {
473 &WARN("hashref2where: href is not HASH ref (href => $href)");
477 my %hash = %{ $href };
478 foreach (keys %hash) {
481 if (s/^-//) { # as is.
483 delete $hash{'-'.$_};
485 $hash{$_} = &sqlQuote($v);
489 return join(' AND ', map { $_."=".$hash{$_} } keys %hash );
495 if (ref($href) ne "HASH") {
496 &WARN("hashref2update: href is not HASH ref.");
501 foreach (keys %{ $href }) {
503 my $v = ${ $href }{$_};
505 # is there a better way to do this?
506 if ($k =~ s/^-//) { # as is.
515 return join(', ', map { $_."=".$hash{$_} } sort keys %hash);
521 if (ref($href) ne "HASH") {
522 &WARN("hashref2update: href is not HASH ref.");
527 foreach (keys %{ $href }) {
529 my $v = ${ $href }{$_};
531 # is there a better way to do this?
532 if ($k =~ s/^-//) { # as is.
546 # Usage: &countKeys($table, [$col]);
548 my ($table, $col) = @_;
551 return (&sqlRawReturn("SELECT count($col) FROM $table"))[0];
555 # Usage: &sumKey($table, $col);
557 my ($table, $col) = @_;
559 return (&sqlRawReturn("SELECT sum($col) FROM $table"))[0];
563 # Usage: &randKey($table, $select);
565 my ($table, $select) = @_;
566 my $rand = int(rand(&countKeys($table)));
567 my $query = "SELECT $select FROM $table LIMIT 1 OFFSET $rand";
568 if ($param{DBType} =~ /^mysql$/i) {
569 # WARN: only newer MySQL supports "LIMIT limit OFFSET offset"
570 $query = "SELECT $select FROM $table LIMIT $rand,1";
572 my $sth = $dbh->prepare($query);
574 &WARN("randKey($query)") unless $sth->execute;
575 my @retval = $sth->fetchrow_array;
582 # Usage: &deleteTable($table);
584 &sqlRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
588 # Usage: &searchTable($table, $select, $key, $str);
589 # Note: searchTable does sqlQuote.
591 my($table, $select, $key, $str) = @_;
595 # allow two types of wildcards.
596 if ($str =~ /^\^(.*)\$$/) {
597 &FIXME("searchTable: can't do \"$str\"");
600 $str .= "%" if ($str =~ s/^\^//);
601 $str = "%".$str if ($str =~ s/\$$//);
602 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
606 $str =~ s/\?/_/g; # '.' should be supported, too.
610 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
612 my $sth = $dbh->prepare($query);
615 if (!$sth->execute) {
616 &WARN("Search($query)");
621 while (my @row = $sth->fetchrow_array) {
622 push(@results, $row[0]);
631 my(@path) = ($bot_data_dir, ".","..","../..");
636 my $file = "$_/setup/$table.sql";
637 next unless ( -f $file );
652 &sqlRaw("sqlCreateTable($table)", $data);
658 my $database_exists = 0;
661 if ($param{DBType} =~ /^mysql$/i) {
662 my $sql = "SHOW DATABASES";
663 foreach ( &sqlRawReturn($sql) ) {
664 $database_exists++ if ($_ eq $param{'DBName'});
667 unless ($database_exists) {
668 &status("Creating database $param{DBName}...");
669 my $query = "CREATE DATABASE $param{DBName}";
670 &sqlRaw("create(db $param{DBName})", $query);
673 # retrieve a list of db's from the server.
674 my @tables = map {s/^\`//; s/\`$//; $_;} $dbh->func('_ListTables');
676 @tables = $dbh->tables;
678 &status("Tables: ".join(',',@tables));
679 @db{@tables} = (1) x @tables;
681 } elsif ($param{DBType} =~ /^SQLite(2)?$/i) {
683 # retrieve a list of db's from the server.
684 foreach ( &sqlRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
688 # create database not needed for SQLite
691 foreach ( qw(botmail connections factoids rootwarn seen stats onjoin) ) {
692 if (exists $db{$_}) {
693 $cache{has_table}{$_} = 1;
697 &status("checkTables: creating new table $_...");
699 $cache{create_table}{$_} = 1;