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 if (1 or defined $result) {
244 &sqlUpdate($table, $data_href, $where_href);
247 my %hash = %{ $where_href };
248 # add data_href values...
249 foreach (keys %{ $data_href }) {
250 $hash{ $_ } = ${ $data_href }{$_};
254 &sqlInsert($table, $data_href);
261 # Usage: &sqlUpdate($table, $data_href, $where_href);
263 my ($table, $data_href, $where_href) = @_;
265 if (!defined $data_href or ref($data_href) ne "HASH") {
266 &WARN("sqlSet: data_href == NULL.");
270 my $where = &hashref2where($where_href) if ($where_href);
271 my $update = &hashref2update($data_href) if ($data_href);
273 &sqlRaw("Update", "UPDATE $table SET $update WHERE $where");
279 # Usage: &sqlInsert($table, $data_href, $other);
281 my ($table, $data_href, $other) = @_;
282 # note: if $other == 1, add "DELAYED" to function instead.
284 if (!defined $data_href or ref($data_href) ne "HASH") {
285 &WARN("sqlInsert: data_href == NULL.");
289 my ($k_aref, $v_aref) = &hashref2array($data_href);
290 my @k = @{ $k_aref };
291 my @v = @{ $v_aref };
294 &WARN("sqlInsert: keys or vals is NULL.");
298 &sqlRaw("Insert($table)", sprintf(
299 "INSERT %s INTO %s (%s) VALUES (%s)",
300 ($other || ""), $table, join(',',@k), join(',',@v)
307 # Usage: &sqlReplace($table, $data_href);
309 my ($table, $data_href) = @_;
311 if (!defined $data_href or ref($data_href) ne "HASH") {
312 &WARN("sqlReplace: data_href == NULL.");
316 my ($k_aref, $v_aref) = &hashref2array($data_href);
317 my @k = @{ $k_aref };
318 my @v = @{ $v_aref };
321 &WARN("sqlReplace: keys or vals is NULL.");
325 &sqlRaw("Replace($table)", sprintf(
326 "REPLACE INTO %s (%s) VALUES (%s)",
327 $table, join(',',@k), join(',',@v)
334 # Usage: &sqlDelete($table, $where_href);
336 my ($table, $where_href) = @_;
338 if (!defined $where_href or ref($where_href) ne "HASH") {
339 &WARN("sqlDelete: where_href == NULL.");
343 my $where = &hashref2where($where_href);
345 &sqlRaw("Delete", "DELETE FROM $table WHERE $where");
351 # Usage: &sqlRaw($prefix, $query);
352 # Return: 1 for success, 0 for failure.
354 my ($prefix, $query) = @_;
357 if (!defined $query or $query =~ /^\s*$/) {
358 &WARN("sqlRaw: query == NULL.");
362 if (!($sth = $dbh->prepare($query))) {
363 &ERROR("Raw($prefix): !prepare => '$query'");
368 if (!$sth->execute) {
369 &ERROR("Raw($prefix): !execute => '$query'");
380 # Usage: &sqlRawReturn($query);
387 if (!defined $query or $query =~ /^\s*$/) {
388 &WARN("sqlRawReturn: query == NULL.");
392 if (!($sth = $dbh->prepare($query))) {
393 &ERROR("RawReturn: !prepare => '$query'");
398 if (!$sth->execute) {
399 &ERROR("RawReturn: !execute => '$query'");
404 while (my @row = $sth->fetchrow_array) {
405 push(@retval, $row[0]);
413 ####################################################################
414 ##### Misc DBI stuff...
420 if (!defined $href) {
421 &WARN("hashref2where: href == NULL.");
425 if (ref($href) ne "HASH") {
426 &WARN("hashref2where: href is not HASH ref (href => $href)");
430 my %hash = %{ $href };
431 foreach (keys %hash) {
434 if (s/^-//) { # as is.
436 delete $hash{'-'.$_};
438 $hash{$_} = &sqlQuote($v);
442 return join(' AND ', map { $_."=".$hash{$_} } keys %hash );
448 if (ref($href) ne "HASH") {
449 &WARN("hashref2update: href is not HASH ref.");
454 foreach (keys %{ $href }) {
456 my $v = ${ $href }{$_};
458 # is there a better way to do this?
459 if ($k =~ s/^-//) { # as is.
468 return join(', ', map { $_."=".$hash{$_} } sort keys %hash);
474 if (ref($href) ne "HASH") {
475 &WARN("hashref2update: href is not HASH ref.");
480 foreach (keys %{ $href }) {
482 my $v = ${ $href }{$_};
484 # is there a better way to do this?
485 if ($k =~ s/^-//) { # as is.
499 # Usage: &countKeys($table, [$col]);
501 my ($table, $col) = @_;
503 &DEBUG("&countKeys($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 &DEBUG("dbCT: table => '$table', file => '$file'");
592 next unless ( -f $file );
594 &DEBUG("dbCT: found!!!");
609 &sqlRaw("sqlCreateTable($table)", $data);
615 my $database_exists = 0;
618 if ($param{DBType} =~ /^mysql$/i) {
619 my $sql = "SHOW DATABASES";
620 foreach ( &sqlRawReturn($sql) ) {
621 $database_exists++ if ($_ eq $param{'DBName'});
624 unless ($database_exists) {
625 &status("Creating database $param{DBName}...");
626 my $query = "CREATE DATABASE $param{DBName}";
627 &sqlRaw("create(db $param{DBName})", $query);
630 # retrieve a list of db's from the server.
631 foreach ($dbh->func('_ListTables')) {
635 } elsif ($param{DBType} =~ /^SQLite$/i) {
637 # retrieve a list of db's from the server.
638 foreach ( &sqlRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
643 if (!scalar keys %db) {
644 &status("Creating database $param{'DBName'}...");
645 my $query = "CREATE DATABASE $param{'DBName'}";
646 &sqlRaw("create(db $param{'DBName'})", $query);
650 foreach ( qw(factoids rootwarn seen stats botmail) ) {
651 next if (exists $db{$_});
652 &status("checkTables: creating new table $_...");