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);
19 # This wrapper's sole purpose in life is to keep the dbh connection open.
22 # These are DBI methods which do not require an active DB
23 # connection. [Eg, don't check to see if the database is working
24 # by pinging it for these methods.]
26 @no_ping{qw(ping err err_str quote disconnect clone)} = (1) x 6;
31 return undef unless $dbh;
32 $class = ref($class) if ref($class);
33 my $self = { dbh => $dbh };
41 my $method = $AUTOLOAD;
43 die "Undefined subroutine $method called" unless defined $self;
44 ($method) = $method =~ /([^\:]+)$/;
45 unshift @_, $self->{dbh};
46 return undef if not defined $self->{dbh};
47 goto &{ $self->{dbh}->can($method) }
48 if exists $no_ping{$method} and $no_ping{$method};
51 while ( ++$ping_count < 10 ) {
52 last if $self->{dbh}->ping;
53 $self->{dbh}->disconnect;
54 $self->{dbh} = $self->{dbh}->clone;
56 if ( $ping_count >= 10 and not $self->{dbh}->ping ) {
57 &ERROR("Tried real hard but was unable to reconnect");
61 my $coderef = $self->{dbh}->can($method);
62 goto &$coderef if defined $coderef;
64 # Dumb DBI doesn't have a can method for some
65 # functions. Like func.
67 return eval "\$self->{dbh}->$method(\@_)" or die $@;
73 # &sqlOpenDB($dbname, $dbtype, $sqluser, $sqlpass, $nofail);
75 my ( $db, $type, $user, $pass, $no_fail ) = @_;
77 # this is a mess. someone fix it, please.
78 if ( $type =~ /^SQLite(2)?$/i ) {
79 $db = "dbname=$db.sqlite";
81 elsif ( $type =~ /^pg/i ) {
86 my $dsn = "DBI:$type:$db";
89 # SQLHost should be unset for SQLite
90 if ( exists $param{'SQLHost'} and $param{'SQLHost'} ) {
92 # PostgreSQL requires ";" and keyword 'host'. See perldoc Pg -- troubled
93 if ( $type eq 'Pg' ) {
94 $dsn .= ";host=$param{SQLHost}";
97 $dsn .= ":$param{SQLHost}";
99 $hoststr = " to $param{'SQLHost'}";
102 # SQLite ignores $user and $pass
103 $dbh = Bloot::DBI->new( DBI->connect( $dsn, $user, $pass ) );
105 if ( $dbh && !$dbh->err ) {
106 &status("Opened $type connection$hoststr");
109 &ERROR("Cannot connect$hoststr.");
110 &ERROR("Since $type is not available, shutting down bot!");
111 &ERROR( $dbh->errstr ) if ($dbh);
116 return 0 if ($no_fail);
123 return 0 unless ($dbh);
125 my $x = $param{SQLHost};
126 my $hoststr = ($x) ? " to $x" : '';
128 &status("Closed DBI connection$hoststr.");
135 # Usage: &sqlQuote($str);
137 return $dbh->quote( $_[0] );
141 # Usage: &sqlSelectMany($table, $select, [$where_href], [$other]);
142 # Return: $sth (Statement handle object)
144 my ( $table, $select, $where_href, $other ) = @_;
145 my $query = "SELECT $select FROM $table";
148 if ( !defined $select or $select =~ /^\s*$/ ) {
149 &WARN("sqlSelectMany: select == NULL.");
153 if ( !defined $table or $table =~ /^\s*$/ ) {
154 &WARN("sqlSelectMany: table == NULL.");
159 my $where = &hashref2where($where_href);
160 $query .= " WHERE $where" if ($where);
162 $query .= " $other" if ($other);
164 if ( !( $sth = $dbh->prepare($query) ) ) {
165 &ERROR("sqlSelectMany: prepare: $DBI::errstr");
171 return if ( !$sth->execute );
177 # Usage: &sqlSelect($table, $select, [$where_href, [$other]);
178 # Return: scalar if one element, array if list of elements.
179 # Note: Suitable for one column returns, that is, one column in $select.
180 # Todo: Always return array?
182 my $sth = &sqlSelectMany(@_);
183 if ( !defined $sth ) {
184 &WARN("sqlSelect failed.");
187 my @retval = $sth->fetchrow_array;
190 if ( scalar @retval > 1 ) {
193 elsif ( scalar @retval == 1 ) {
202 # Usage: &sqlSelectColArray($table, $select, [$where_href], [$other]);
204 sub sqlSelectColArray {
205 my $sth = &sqlSelectMany(@_);
208 if ( !defined $sth ) {
209 &WARN("sqlSelect failed.");
213 while ( my @row = $sth->fetchrow_array ) {
214 push( @retval, $row[0] );
222 # Usage: &sqlSelectColHash($table, $select, [$where_href], [$other], [$type]);
223 # Return: type = 1: $retval{ col2 }{ col1 } = 1;
224 # Return: no type: $retval{ col1 } = col2;
225 # Note: does not support $other, yet.
226 sub sqlSelectColHash {
227 my ( $table, $select, $where_href, $other, $type ) = @_;
228 my $sth = &sqlSelectMany( $table, $select, $where_href, $other );
229 if ( !defined $sth ) {
230 &WARN("sqlSelectColhash failed.");
235 if ( defined $type and $type == 2 ) {
236 &DEBUG("sqlSelectColHash: type 2!");
237 while ( my @row = $sth->fetchrow_array ) {
238 $retval{ $row[0] } = join( ':', $row[ 1 .. $#row ] );
240 &DEBUG( "sqlSelectColHash: count => " . scalar( keys %retval ) );
243 elsif ( defined $type and $type == 1 ) {
244 while ( my @row = $sth->fetchrow_array ) {
246 # reverse it to make it easier to count.
247 if ( scalar @row == 2 ) {
248 $retval{ $row[1] }{ $row[0] } = 1;
250 elsif ( scalar @row == 3 ) {
251 $retval{ $row[1] }{ $row[0] } = 1;
254 # what to do if there's only one or more than 3?
259 while ( my @row = $sth->fetchrow_array ) {
260 $retval{ $row[0] } = $row[1];
270 # Usage: &sqlSelectRowHash($table, $select, [$where_href]);
271 # Return: $hash{ col } = value;
272 # Note: useful for returning only one/first row of data.
273 sub sqlSelectRowHash {
274 my $sth = &sqlSelectMany(@_);
275 if ( !defined $sth ) {
276 &WARN("sqlSelectRowHash failed.");
279 my $retval = $sth->fetchrow_hashref();
291 # End of SELECT functions.
295 # Usage: &sqlSet($table, $where_href, $data_href);
296 # Return: 1 for success, undef for failure.
298 my ( $table, $where_href, $data_href ) = @_;
300 if ( !defined $table or $table =~ /^\s*$/ ) {
301 &WARN("sqlSet: table == NULL.");
305 if ( !defined $data_href or ref($data_href) ne 'HASH' ) {
306 &WARN("sqlSet: data_href == NULL.");
310 # any column can be NULL... so just get them all.
311 my $k = join( ',', keys %{$where_href} );
312 my $result = &sqlSelect( $table, $k, $where_href );
314 # &DEBUG("result is not defined :(") if (!defined $result);
316 # this was hardwired to use sqlUpdate. sqlite does not do inserts on sqlUpdate.
317 if ( defined $result ) {
318 &sqlUpdate( $table, $data_href, $where_href );
323 my %hash = %{$where_href};
325 # add data_href values...
326 foreach ( keys %{$data_href} ) {
327 $hash{$_} = ${$data_href}{$_};
331 &sqlInsert( $table, $data_href );
338 # Usage: &sqlUpdate($table, $data_href, $where_href);
340 my ( $table, $data_href, $where_href ) = @_;
342 if ( !defined $data_href or ref($data_href) ne 'HASH' ) {
343 &WARN("sqlSet: data_href == NULL.");
347 my $where = &hashref2where($where_href) if ($where_href);
348 my $update = &hashref2update($data_href) if ($data_href);
350 &sqlRaw( 'Update', "UPDATE $table SET $update WHERE $where" );
356 # Usage: &sqlInsert($table, $data_href, $other);
358 my ( $table, $data_href, $other ) = @_;
360 # note: if $other == 1, add 'DELAYED' to function instead.
361 # note: ^^^ doesnt actually do anything lol. Need code to s/1/DELAYED/ below -- troubled
363 if ( !defined $data_href or ref($data_href) ne 'HASH' ) {
364 &WARN("sqlInsert: data_href == NULL.");
368 my ( $k_aref, $v_aref ) = &hashref2array($data_href);
373 &WARN("sqlInsert: keys or vals is NULL.");
380 "INSERT %s INTO %s (%s) VALUES (%s)",
392 # Usage: &sqlReplace($table, $data_href, [$pkey]);
394 my ( $table, $data_href, $pkey ) = @_;
396 if ( !defined $data_href or ref($data_href) ne 'HASH' ) {
397 &WARN("sqlReplace: data_href == NULL.");
401 my ( $k_aref, $v_aref ) = &hashref2array($data_href);
406 &WARN("sqlReplace: keys or vals is NULL.");
410 if ( $param{'DBType'} =~ /^pgsql$/i ) {
412 # OK, heres the scoop. There is currently no REPLACE INTO in Pgsql.
413 # However, the bot already seems to search for factoids before insert
414 # anyways. Perhaps we could change this to a generic INSERT INTO so
415 # we can skip the seperate sql? -- troubled to: TimRiker
416 # PGSql syntax: UPDATE table SET key = 'value', key2 = 'value2' WHERE key = 'value'
418 # &sqlRaw("Replace($table)", sprintf(
419 # "INSERT INTO %s (%s) VALUES (%s)",
420 # $table, join(',',@k), join(',',@v)
425 "REPLACE INTO %s (%s) VALUES (%s)",
437 "REPLACE INTO %s (%s) VALUES (%s)",
449 # Usage: &sqlDelete($table, $where_href);
451 my ( $table, $where_href ) = @_;
453 if ( !defined $where_href or ref($where_href) ne 'HASH' ) {
454 &WARN("sqlDelete: where_href == NULL.");
458 my $where = &hashref2where($where_href);
460 &sqlRaw( 'Delete', "DELETE FROM $table WHERE $where" );
466 # Usage: &sqlRaw($prefix, $query);
467 # Return: 1 for success, 0 for failure.
469 my ( $prefix, $query ) = @_;
472 if ( !defined $query or $query =~ /^\s*$/ ) {
473 &WARN("sqlRaw: query == NULL.");
477 if ( !( $sth = $dbh->prepare($query) ) ) {
478 &ERROR("Raw($prefix): !prepare => '$query'");
483 if ( !$sth->execute ) {
484 &ERROR("Raw($prefix): !execute => '$query'");
495 # Usage: &sqlRawReturn($query);
502 if ( !defined $query or $query =~ /^\s*$/ ) {
503 &WARN("sqlRawReturn: query == NULL.");
507 if ( !( $sth = $dbh->prepare($query) ) ) {
508 &ERROR("RawReturn: !prepare => '$query'");
513 if ( !$sth->execute ) {
514 &ERROR("RawReturn: !execute => '$query'");
519 while ( my @row = $sth->fetchrow_array ) {
520 push( @retval, $row[0] );
528 ####################################################################
529 ##### Misc DBI stuff...
534 if ( !defined $href ) {
535 &WARN("hashref2where: href == NULL.");
539 if ( ref($href) ne 'HASH' ) {
540 &WARN("hashref2where: href is not HASH ref (href => $href)");
545 foreach ( keys %hash ) {
548 if (s/^-//) { # as is.
550 delete $hash{ '-' . $_ };
553 $hash{$_} = &sqlQuote($v);
557 return join( ' AND ', map { $_ . "=" . $hash{$_} } keys %hash );
563 if ( ref($href) ne 'HASH' ) {
564 &WARN("hashref2update: href is not HASH ref.");
569 foreach ( keys %{$href} ) {
571 my $v = ${$href}{$_};
573 # is there a better way to do this?
574 if ( $k =~ s/^-// ) { # as is.
584 return join( ', ', map { $_ . "=" . $hash{$_} } sort keys %hash );
590 if ( ref($href) ne 'HASH' ) {
591 &WARN("hashref2update: href is not HASH ref.");
596 foreach ( keys %{$href} ) {
598 my $v = ${$href}{$_};
600 # is there a better way to do this?
601 if ( $k =~ s/^-// ) { # as is.
616 # Usage: &countKeys($table, [$col]);
618 my ( $table, $col ) = @_;
621 return ( &sqlRawReturn("SELECT count($col) FROM $table") )[0];
625 # Usage: &sumKey($table, $col);
627 my ( $table, $col ) = @_;
629 return ( &sqlRawReturn("SELECT sum($col) FROM $table") )[0];
633 # Usage: &randKey($table, $select);
635 my ( $table, $select ) = @_;
636 my $rand = int( rand( &countKeys($table) ) );
637 my $query = "SELECT $select FROM $table LIMIT 1 OFFSET $rand";
638 if ( $param{DBType} =~ /^mysql$/i ) {
640 # WARN: only newer MySQL supports "LIMIT limit OFFSET offset"
641 $query = "SELECT $select FROM $table LIMIT $rand,1";
643 my $sth = $dbh->prepare($query);
645 &WARN("randKey($query)") unless $sth->execute;
646 my @retval = $sth->fetchrow_array;
653 # Usage: &deleteTable($table);
655 &sqlRaw( "deleteTable($_[0])", "DELETE FROM $_[0]" );
659 # Usage: &searchTable($table, $select, $key, $str);
660 # Note: searchTable does sqlQuote.
662 my ( $table, $select, $key, $str ) = @_;
666 # allow two types of wildcards.
667 if ( $str =~ /^\^(.*)\$$/ ) {
668 &FIXME("searchTable: can't do \"$str\"");
672 $str .= "%" if ( $str =~ s/^\^// );
673 $str = "%" . $str if ( $str =~ s/\$$// );
674 $str = "%" . $str . "%" if ( $str eq $origStr ); # el-cheapo fix.
678 $str =~ s/\?/_/g; # '.' should be supported, too.
683 my $query = "SELECT $select FROM $table WHERE $key LIKE " . &sqlQuote($str);
684 my $sth = $dbh->prepare($query);
687 if ( !$sth->execute ) {
688 &WARN("Search($query)");
693 while ( my @row = $sth->fetchrow_array ) {
694 push( @results, $row[0] );
702 my ( $table, $dbtype ) = @_;
703 my (@path) = ( $bot_data_dir, ".", "..", "../.." );
706 $dbtype = lc $dbtype;
709 my $file = "$_/setup/$dbtype/$table.sql";
710 next unless ( -f $file );
727 &sqlRaw( "sqlCreateTable($table)", $data );
733 my $database_exists = 0;
736 if ( $param{DBType} =~ /^mysql$/i ) {
737 my $sql = "SHOW DATABASES";
738 foreach ( &sqlRawReturn($sql) ) {
739 $database_exists++ if ( $_ eq $param{'DBName'} );
742 unless ($database_exists) {
743 &status("Creating database $param{DBName}...");
744 my $query = "CREATE DATABASE $param{DBName}";
745 &sqlRaw( "create(db $param{DBName})", $query );
748 # retrieve a list of db's from the server.
749 my @tables = map { s/^\`//; s/\`$//; $_; } $dbh->func('_ListTables');
750 if ( $#tables == -1 ) {
751 @tables = $dbh->tables;
753 &status( "Tables: " . join( ',', @tables ) );
754 @db{@tables} = (1) x @tables;
757 elsif ( $param{DBType} =~ /^SQLite(2)?$/i ) {
759 # retrieve a list of db's from the server.
761 &sqlRawReturn("SELECT name FROM sqlite_master WHERE type='table'") )
766 # create database not needed for SQLite
769 elsif ( $param{DBType} =~ /^pgsql$/i ) {
771 # $sql_showDB = SQL to select the DB list
772 # $sql_showTBL = SQL to select all tables for the current connection
774 my $sql_showDB = "SELECT datname FROM pg_database";
775 my $sql_showTBL = "SELECT tablename FROM pg_tables \
776 WHERE schemaname = 'public'";
778 foreach ( &sqlRawReturn($sql_showDB) ) {
779 $database_exists++ if ( $_ eq $param{'DBName'} );
782 unless ($database_exists) {
783 &status("Creating PostgreSQL database $param{'DBName'}");
784 &status("(actually, not really, please read the INSTALL file)");
787 # retrieve a list of db's from the server. This code is from mysql above, please check -- troubled
788 my @tables = map { s/^\`//; s/\`$//; $_; } &sqlRawReturn($sql_showTBL);
789 if ( $#tables == -1 ) {
790 @tables = $dbh->tables;
792 &status( "Tables: " . join( ',', @tables ) );
793 @db{@tables} = (1) x @tables;
796 foreach (qw(botmail connections factoids rootwarn seen stats onjoin)) {
797 if ( exists $db{$_} ) {
798 $cache{has_table}{$_} = 1;
802 &status("checkTables: creating new table $_...");
804 $cache{create_table}{$_} = 1;
806 &sqlCreateTable( $_, $param{DBType} );
812 # vim:ts=4:sw=4:expandtab:tw=80