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 # &sqlOpenDB($dbname, $dbtype, $sqluser, $sqlpass, $nofail);
20 my ($db, $type, $user, $pass, $no_fail) = @_;
21 # this is a mess. someone fix it, please.
22 if ($type =~ /^SQLite$/i) {
23 $db = "dbname=$db.sqlite";
24 } elsif ($type =~ /^pg/i) {
29 my $dsn = "DBI:$type:$db";
31 # SQLHost should be unset for SQLite
32 if (exists $param{'SQLHost'} and $param{'SQLHost'}) {
33 $dsn .= ":$param{SQLHost}";
34 $hoststr = " to $param{'SQLHost'}";
36 # SQLite ignores $user and $pass
37 $dbh = DBI->connect($dsn, $user, $pass);
39 if ($dbh && !$dbh->err) {
40 &status("Opened $type connection$hoststr");
42 &ERROR("Cannot connect$hoststr.");
43 &ERROR("Since $type is not available, shutting down bot!");
44 &ERROR( $dbh->errstr ) if ($dbh);
49 return 0 if ($no_fail);
56 return 0 unless ($dbh);
58 my $x = $param{SQLHost};
59 my $hoststr = ($x) ? " to $x" : "";
61 &status("Closed DBI connection$hoststr.");
68 # Usage: &sqlQuote($str);
70 return $dbh->quote($_[0]);
74 # Usage: &sqlSelectMany($table, $select, [$where_href], [$other]);
75 # Return: $sth (Statement handle object)
77 my($table, $select, $where_href, $other) = @_;
78 my $query = "SELECT $select FROM $table";
81 if (!defined $select or $select =~ /^\s*$/) {
82 &WARN("sqlSelectMany: select == NULL.");
86 if (!defined $table or $table =~ /^\s*$/) {
87 &WARN("sqlSelectMany: table == NULL.");
91 $query .= " WHERE" if (($where_href) || ($other));
93 my $where = &hashref2where($where_href);
94 $query .= " $where" if ($where);
96 $query .= " $other" if $other;
98 if (!($sth = $dbh->prepare($query))) {
99 &ERROR("sqlSelectMany: prepare: $DBI::errstr");
104 if (!$sth->execute) {
105 &ERROR("sqlSelectMany: execute: '$query'");
113 # Usage: &sqlSelect($table, $select, [$where_href, [$other]);
114 # Return: scalar if one element, array if list of elements.
115 # Note: Suitable for one column returns, that is, one column in $select.
116 # Todo: Always return array?
118 my $sth = &sqlSelectMany(@_);
120 &WARN("sqlSelect failed.");
123 my @retval = $sth->fetchrow_array;
126 if (scalar @retval > 1) {
128 } elsif (scalar @retval == 1) {
136 # Usage: &sqlSelectColArray($table, $select, [$where_href], [$other]);
138 sub sqlSelectColArray {
139 my $sth = &sqlSelectMany(@_);
143 &WARN("sqlSelect failed.");
147 while (my @row = $sth->fetchrow_array) {
148 push(@retval, $row[0]);
156 # Usage: &sqlSelectColHash($table, $select, [$where_href], [$other], [$type]);
157 # Return: type = 1: $retval{ col2 }{ col1 } = 1;
158 # Return: no type: $retval{ col1 } = col2;
159 # Note: does not support $other, yet.
160 sub sqlSelectColHash {
161 my ($table, $select, $where_href, $other, $type) = @_;
162 my $sth = &sqlSelectMany($table, $select, $where_href, $other);
164 &WARN("sqlSelectColhash failed.");
169 if (defined $type and $type == 2) {
170 &DEBUG("sqlSelectColHash: type 2!");
171 while (my @row = $sth->fetchrow_array) {
172 $retval{$row[0]} = join(':', $row[1..$#row]);
174 &DEBUG("sqlSelectColHash: count => ".scalar(keys %retval) );
176 } elsif (defined $type and $type == 1) {
177 while (my @row = $sth->fetchrow_array) {
178 # reverse it to make it easier to count.
179 if (scalar @row == 2) {
180 $retval{$row[1]}{$row[0]} = 1;
181 } elsif (scalar @row == 3) {
182 $retval{$row[1]}{$row[0]} = 1;
184 # what to do if there's only one or more than 3?
188 while (my @row = $sth->fetchrow_array) {
189 $retval{$row[0]} = $row[1];
199 # Usage: &sqlSelectRowHash($table, $select, [$where_href]);
200 # Return: $hash{ col } = value;
201 # Note: useful for returning only one/first row of data.
202 sub sqlSelectRowHash {
203 my $sth = &sqlSelectMany(@_);
205 &WARN("sqlSelectRowHash failed.");
208 my $retval = $sth->fetchrow_hashref();
219 # End of SELECT functions.
223 # Usage: &sqlSet($table, $where_href, $data_href);
224 # Return: 1 for success, undef for failure.
226 my ($table, $where_href, $data_href) = @_;
228 if (!defined $table or $table =~ /^\s*$/) {
229 &WARN("sqlSet: table == NULL.");
233 if (!defined $data_href or ref($data_href) ne "HASH") {
234 &WARN("sqlSet: data_href == NULL.");
238 # any column can be NULL... so just get them all.
239 my $k = join(',', keys %{ $where_href } );
240 my $result = &sqlSelect($table, $k, $where_href);
241 # &DEBUG("result is not defined :(") if (!defined $result);
243 # this was hardwired to use sqlUpdate. sqlite does not do inserts on sqlUpdate.
244 if (defined $result) {
245 &sqlUpdate($table, $data_href, $where_href);
248 my %hash = %{ $where_href };
249 # add data_href values...
250 foreach (keys %{ $data_href }) {
251 $hash{ $_ } = ${ $data_href }{$_};
255 &sqlInsert($table, $data_href);
262 # Usage: &sqlUpdate($table, $data_href, $where_href);
264 my ($table, $data_href, $where_href) = @_;
266 if (!defined $data_href or ref($data_href) ne "HASH") {
267 &WARN("sqlSet: data_href == NULL.");
271 my $where = &hashref2where($where_href) if ($where_href);
272 my $update = &hashref2update($data_href) if ($data_href);
274 &sqlRaw("Update", "UPDATE $table SET $update WHERE $where");
280 # Usage: &sqlInsert($table, $data_href, $other);
282 my ($table, $data_href, $other) = @_;
283 # note: if $other == 1, add "DELAYED" to function instead.
285 if (!defined $data_href or ref($data_href) ne "HASH") {
286 &WARN("sqlInsert: data_href == NULL.");
290 my ($k_aref, $v_aref) = &hashref2array($data_href);
291 my @k = @{ $k_aref };
292 my @v = @{ $v_aref };
295 &WARN("sqlInsert: keys or vals is NULL.");
299 &sqlRaw("Insert($table)", sprintf(
300 "INSERT %s INTO %s (%s) VALUES (%s)",
301 ($other || ""), $table, join(',',@k), join(',',@v)
308 # Usage: &sqlReplace($table, $data_href);
310 my ($table, $data_href) = @_;
312 if (!defined $data_href or ref($data_href) ne "HASH") {
313 &WARN("sqlReplace: data_href == NULL.");
317 my ($k_aref, $v_aref) = &hashref2array($data_href);
318 my @k = @{ $k_aref };
319 my @v = @{ $v_aref };
322 &WARN("sqlReplace: keys or vals is NULL.");
326 &sqlRaw("Replace($table)", sprintf(
327 "REPLACE INTO %s (%s) VALUES (%s)",
328 $table, join(',',@k), join(',',@v)
335 # Usage: &sqlDelete($table, $where_href);
337 my ($table, $where_href) = @_;
339 if (!defined $where_href or ref($where_href) ne "HASH") {
340 &WARN("sqlDelete: where_href == NULL.");
344 my $where = &hashref2where($where_href);
346 &sqlRaw("Delete", "DELETE FROM $table WHERE $where");
352 # Usage: &sqlRaw($prefix, $query);
353 # Return: 1 for success, 0 for failure.
355 my ($prefix, $query) = @_;
358 if (!defined $query or $query =~ /^\s*$/) {
359 &WARN("sqlRaw: query == NULL.");
363 if (!($sth = $dbh->prepare($query))) {
364 &ERROR("Raw($prefix): !prepare => '$query'");
369 if (!$sth->execute) {
370 &ERROR("Raw($prefix): !execute => '$query'");
381 # Usage: &sqlRawReturn($query);
388 if (!defined $query or $query =~ /^\s*$/) {
389 &WARN("sqlRawReturn: query == NULL.");
393 if (!($sth = $dbh->prepare($query))) {
394 &ERROR("RawReturn: !prepare => '$query'");
399 if (!$sth->execute) {
400 &ERROR("RawReturn: !execute => '$query'");
405 while (my @row = $sth->fetchrow_array) {
406 push(@retval, $row[0]);
414 ####################################################################
415 ##### Misc DBI stuff...
421 if (!defined $href) {
422 &WARN("hashref2where: href == NULL.");
426 if (ref($href) ne "HASH") {
427 &WARN("hashref2where: href is not HASH ref (href => $href)");
431 my %hash = %{ $href };
432 foreach (keys %hash) {
435 if (s/^-//) { # as is.
437 delete $hash{'-'.$_};
439 $hash{$_} = &sqlQuote($v);
443 return join(' AND ', map { $_."=".$hash{$_} } keys %hash );
449 if (ref($href) ne "HASH") {
450 &WARN("hashref2update: href is not HASH ref.");
455 foreach (keys %{ $href }) {
457 my $v = ${ $href }{$_};
459 # is there a better way to do this?
460 if ($k =~ s/^-//) { # as is.
469 return join(', ', map { $_."=".$hash{$_} } sort keys %hash);
475 if (ref($href) ne "HASH") {
476 &WARN("hashref2update: href is not HASH ref.");
481 foreach (keys %{ $href }) {
483 my $v = ${ $href }{$_};
485 # is there a better way to do this?
486 if ($k =~ s/^-//) { # as is.
500 # Usage: &countKeys($table, [$col]);
502 my ($table, $col) = @_;
505 return (&sqlRawReturn("SELECT count($col) FROM $table"))[0];
509 # Usage: &sumKey($table, $col);
511 my ($table, $col) = @_;
513 return (&sqlRawReturn("SELECT sum($col) FROM $table"))[0];
517 # Usage: &randKey($table, $select);
519 my ($table, $select) = @_;
520 my $rand = int(rand(&countKeys($table) - 1));
521 my $query = "SELECT $select FROM $table LIMIT $rand,1";
522 if ($param{DBType} =~ /^pg/i) {
523 $query =~ s/$rand,1/1,$rand/;
526 my $sth = $dbh->prepare($query);
528 &WARN("randKey($query)") unless $sth->execute;
529 my @retval = $sth->fetchrow_array;
536 # Usage: &deleteTable($table);
538 &sqlRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
542 # Usage: &searchTable($table, $select, $key, $str);
543 # Note: searchTable does sqlQuote.
545 my($table, $select, $key, $str) = @_;
549 # allow two types of wildcards.
550 if ($str =~ /^\^(.*)\$$/) {
551 &FIXME("searchTable: can't do \"$str\"");
554 $str .= "%" if ($str =~ s/^\^//);
555 $str = "%".$str if ($str =~ s/\$$//);
556 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
560 $str =~ s/\?/_/g; # '.' should be supported, too.
564 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
566 my $sth = $dbh->prepare($query);
569 if (!$sth->execute) {
570 &WARN("Search($query)");
575 while (my @row = $sth->fetchrow_array) {
576 push(@results, $row[0]);
585 my(@path) = ($bot_data_dir, ".","..","../..");
590 my $file = "$_/setup/$table.sql";
591 next unless ( -f $file );
606 &sqlRaw("sqlCreateTable($table)", $data);
612 my $database_exists = 0;
615 if ($param{DBType} =~ /^mysql$/i) {
616 my $sql = "SHOW DATABASES";
617 foreach ( &sqlRawReturn($sql) ) {
618 $database_exists++ if ($_ eq $param{'DBName'});
621 unless ($database_exists) {
622 &status("Creating database $param{DBName}...");
623 my $query = "CREATE DATABASE $param{DBName}";
624 &sqlRaw("create(db $param{DBName})", $query);
627 # retrieve a list of db's from the server.
628 foreach ($dbh->func('_ListTables')) {
632 } elsif ($param{DBType} =~ /^SQLite$/i) {
634 # retrieve a list of db's from the server.
635 foreach ( &sqlRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
640 if (!scalar keys %db) {
641 &status("Creating database $param{'DBName'}...");
642 my $query = "CREATE DATABASE $param{'DBName'}";
643 &sqlRaw("create(db $param{'DBName'})", $query);
647 foreach ( qw(factoids rootwarn seen stats botmail) ) {
648 next if (exists $db{$_});
649 &status("checkTables: creating new table $_...");