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 # does sqlite support remote servers?
31 if (exists $param{'SQLHost'} and $param{'SQLHost'}) {
32 $dsn .= ":$param{SQLHost}";
33 $hoststr = " to $param{'SQLHost'}";
35 $dbh = DBI->connect($dsn, $user, $pass);
37 if ($dbh && !$dbh->err) {
38 &status("Opened $type connection$hoststr");
40 &ERROR("cannot connect$hoststr.");
41 &ERROR("since $type is not available, shutting down bot!");
42 &ERROR( $dbh->errstr ) if ($dbh);
47 return 0 if ($no_fail);
54 return 0 unless ($dbh);
56 my $x = $param{SQLHost};
57 my $hoststr = ($x) ? " to $x" : "";
59 &status("Closed DBI connection$hoststr.");
66 # Usage: &dbQuote($str);
68 return $dbh->quote($_[0]);
72 # Usage: &dbGet($table, $select, $where);
74 my ($table, $select, $where) = @_;
75 my $query = "SELECT $select FROM $table";
76 $query .= " WHERE $where" if ($where);
78 if (!defined $select or $select =~ /^\s*$/) {
79 &WARN("dbGet: select == NULL.");
83 if (!defined $table or $table =~ /^\s*$/) {
84 &WARN("dbGet: table == NULL.");
89 if (!($sth = $dbh->prepare($query))) {
90 &ERROR("Get: prepare: $DBI::errstr");
96 &ERROR("Get: execute: '$query'");
101 my @retval = $sth->fetchrow_array;
105 if (scalar @retval > 1) {
107 } elsif (scalar @retval == 1) {
115 # Usage: &dbGetCol($table, $select, $where, [$type]);
117 my ($table, $select, $where, $type) = @_;
118 my $query = "SELECT $select FROM $table";
119 $query .= " WHERE ".$where if ($where);
122 my $sth = $dbh->prepare($query);
124 if (!$sth->execute) {
125 &ERROR("GetCol: execute: '$query'");
130 if (defined $type and $type == 2) {
131 &DEBUG("dbgetcol: type 2!");
132 while (my @row = $sth->fetchrow_array) {
133 $retval{$row[0]} = join(':', $row[1..$#row]);
135 &DEBUG("dbgetcol: count => ".scalar(keys %retval) );
137 } elsif (defined $type and $type == 1) {
138 while (my @row = $sth->fetchrow_array) {
139 # reverse it to make it easier to count.
140 if (scalar @row == 2) {
141 $retval{$row[1]}{$row[0]} = 1;
142 } elsif (scalar @row == 3) {
143 $retval{$row[1]}{$row[0]} = 1;
145 # what to do if there's only one or more than 3?
149 while (my @row = $sth->fetchrow_array) {
150 $retval{$row[0]} = $row[1];
160 # Usage: &dbGetColNiceHash($table, $select, $where);
161 sub dbGetColNiceHash {
162 my ($table, $select, $where) = @_;
164 my $query = "SELECT $select FROM $table";
165 $query .= " WHERE ".$where if ($where);
168 my $sth = $dbh->prepare($query);
170 if (!$sth->execute) {
171 &ERROR("GetColNiceHash: execute: '$query'");
172 # &ERROR("GetCol => $DBI::errstr");
177 %retval = %{ $sth->fetchrow_hashref() };
185 # Usage: &dbGetColInfo($table);
189 my $query = "SHOW COLUMNS from $table";
190 if ($param{DBType} =~ /^pg/i) {
191 $query = "SELECT * FROM $table LIMIT 1";
196 my $sth = $dbh->prepare($query);
198 if (!$sth->execute) {
199 &ERROR("GRI => '$query'");
200 &ERROR("GRI => $DBI::errstr");
206 while (my @row = $sth->fetchrow_array) {
207 push(@cols, $row[0]);
215 # Usage: &dbSet($table, $primhash_ref, $hash_ref);
216 # Note: dbSet does dbQuote.
218 my ($table, $phref, $href) = @_;
219 my $where = join(' AND ', map {
220 $_."=".&dbQuote($phref->{$_})
224 if (!defined $phref) {
225 &WARN("dbset: phref == NULL.");
229 if (!defined $href) {
230 &WARN("dbset: href == NULL.");
234 if (!defined $table) {
235 &WARN("dbset: table == NULL.");
239 my $result = &dbGet($table, join(',', keys %{$phref}), $where);
242 foreach (keys %{$href}) {
244 push(@vals, &dbQuote($href->{$_}) );
247 if (!@keys or !@vals) {
248 &WARN("dbset: keys or vals is NULL.");
253 if (defined $result) {
255 for(my$i=0; $i<scalar @keys; $i++) {
256 push(@keyval, $keys[$i]."=".$vals[$i] );
259 $query = "UPDATE $table SET ".
260 join(' AND ', @keyval).
263 foreach (keys %{$phref}) {
265 push(@vals, &dbQuote($phref->{$_}) );
268 $query = sprintf("INSERT INTO $table (%s) VALUES (%s)",
269 join(',',@keys), join(',',@vals) );
272 &dbRaw("Set", $query);
278 # Usage: &dbUpdate($table, $primkey, $primval, %hash);
279 # Note: dbUpdate does dbQuote.
281 my ($table, $primkey, $primval, %hash) = @_;
284 foreach (keys %hash) {
285 push(@array, "$_=".&dbQuote($hash{$_}) );
288 &dbRaw("Update", "UPDATE $table SET ".join(', ', @array).
289 " WHERE $primkey=".&dbQuote($primval)
296 # Usage: &dbInsert($table, $primkey, %hash);
297 # Note: dbInsert does dbQuote.
299 my ($table, $primkey, %hash, $delay) = @_;
304 &DEBUG("dbI: delay => $delay");
308 foreach (keys %hash) {
310 push(@vals, &dbQuote( $hash{$_} ));
313 &dbRaw("Insert($table)", "INSERT $p INTO $table (".join(',',@keys).
314 ") VALUES (".join(',',@vals).")"
321 # Usage: &dbReplace($table, $key, %hash);
322 # Note: dbReplace does optional dbQuote.
324 my ($table, $key, %hash) = @_;
327 foreach (keys %hash) {
328 if (s/^-//) { # as is.
330 push(@vals, $hash{'-'.$_});
333 push(@vals, &dbQuote( $hash{$_} ));
337 # hrm... does pgsql support REPLACE?
338 # if not, well... fuck it.
339 &dbRaw("Replace($table)", "REPLACE INTO $table (".join(',',@keys).
340 ") VALUES (". join(',',@vals). ")"
347 # Usage: &dbSetRow($table, $vref, $delay);
348 # Note: dbSetRow does dbQuote.
350 my ($table, $vref, $delay) = @_;
351 my $p = ($delay) ? " DELAYED " : "";
353 # see 'perldoc perlreftut'
355 foreach (@{ $vref }) {
356 push(@values, &dbQuote($_) );
359 if (!scalar @values) {
360 &WARN("dbSetRow: values array == NULL.");
364 return &dbRaw("SetRow", "INSERT $p INTO $table VALUES (".
365 join(",", @values) .")" );
369 # Usage: &dbDel($table, $primkey, $primval, [$key]);
370 # Note: dbDel does dbQuote
372 my ($table, $primkey, $primval, $key) = @_;
374 &dbRaw("Del", "DELETE FROM $table WHERE $primkey=".
381 # Usage: &dbRaw($prefix,$rawquery);
383 my ($prefix,$query) = @_;
386 if (!($sth = $dbh->prepare($query))) {
387 &ERROR("Raw($prefix): !prepare => '$query'");
392 if (!$sth->execute) {
393 &ERROR("Raw($prefix): !execute => '$query'");
403 # Usage: &dbRawReturn($rawquery);
408 my $sth = $dbh->prepare($query);
410 # what happens when it can't execute it? does it throw heaps more
411 # error lines? if so. follow dbRaw()'s style.
412 &ERROR("RawReturn => '$query'.") unless $sth->execute;
413 while (my @row = $sth->fetchrow_array) {
414 push(@retval, $row[0]);
421 ####################################################################
422 ##### Misc DBI stuff...
426 # Usage: &countKeys($table, [$col]);
428 my ($table, $col) = @_;
430 &DEBUG("&countKeys($table, $col);");
432 return (&dbRawReturn("SELECT count($col) FROM $table"))[0];
436 # Usage: &sumKey($table, $col);
438 my ($table, $col) = @_;
440 return (&dbRawReturn("SELECT sum($col) FROM $table"))[0];
444 # Usage: &randKey($table, $select);
446 my ($table, $select) = @_;
447 my $rand = int(rand(&countKeys($table) - 1));
448 my $query = "SELECT $select FROM $table LIMIT $rand,1";
449 if ($param{DBType} =~ /^pg/i) {
450 $query =~ s/$rand,1/1,$rand/;
453 my $sth = $dbh->prepare($query);
455 &WARN("randKey($query)") unless $sth->execute;
456 my @retval = $sth->fetchrow_array;
463 # Usage: &deleteTable($table);
465 &dbRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
469 # Usage: &searchTable($table, $select, $key, $str);
470 # Note: searchTable does dbQuote.
472 my($table, $select, $key, $str) = @_;
476 # allow two types of wildcards.
477 if ($str =~ /^\^(.*)\$$/) {
478 &DEBUG("searchTable: should use dbGet(), heh.");
481 $str .= "%" if ($str =~ s/^\^//);
482 $str = "%".$str if ($str =~ s/\$$//);
483 $str = "%".$str."%" if ($str eq $origStr); # el-cheapo fix.
487 $str =~ s/\?/_/g; # '.' should be supported, too.
491 my $query = "SELECT $select FROM $table WHERE $key LIKE ".
493 my $sth = $dbh->prepare($query);
496 if (!$sth->execute) {
497 &WARN("Search($query)");
502 while (my @row = $sth->fetchrow_array) {
503 push(@results, $row[0]);
512 my(@path) = ($bot_data_dir, ".","..","../..");
517 my $file = "$_/setup/$table.sql";
518 &DEBUG("dbCT: table => '$table', file => '$file'");
519 next unless ( -f $file );
521 &DEBUG("dbCT: found!!!");
536 &dbRaw("dbcreateTable($table)", $data);
542 my $database_exists = 0;
545 if ($param{DBType} =~ /^mysql$/i) {
546 my $sql = "SHOW DATABASES";
547 foreach ( &dbRawReturn($sql) ) {
548 $database_exists++ if ($_ eq $param{'DBName'});
551 unless ($database_exists) {
552 &status("Creating database $param{DBName}...");
553 my $query = "CREATE DATABASE $param{DBName}";
554 &dbRaw("create(db $param{DBName})", $query);
557 # retrieve a list of db's from the server.
558 foreach ($dbh->func('_ListTables')) {
562 } elsif ($param{DBType} =~ /^SQLite$/i) {
564 # retrieve a list of db's from the server.
565 foreach ( &dbRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
570 if (!scalar keys %db) {
571 &status("Creating database $param{'DBName'}...");
572 my $query = "CREATE DATABASE $param{'DBName'}";
573 &dbRaw("create(db $param{'DBName'})", $query);
577 foreach ( qw(factoids freshmeat rootwarn seen stats) ) {
578 next if (exists $db{$_});
579 &status("checkTables: creating new table $_...");