]> git.donarmstrong.com Git - infobot.git/blob - src/dbi.pl
sqlite needs inserts, not updates. why was this off?
[infobot.git] / src / dbi.pl
1 #
2 #   dbi.pl: DBI (mysql/pgsql/sqlite) database frontend.
3 #   Author: dms
4 #  Version: v0.9a (20021124)
5 #  Created: 19991203
6 #    Notes: based on db_mysql.pl
7 #           overhauled to be 31337.
8 #
9
10 use strict;
11
12 use vars qw(%param);
13 use vars qw($dbh $shm $bot_data_dir);
14
15 package main;
16
17 #####
18 # &sqlOpenDB($dbname, $dbtype, $sqluser, $sqlpass, $nofail);
19 sub sqlOpenDB {
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) {
25         $db = "dbname=$db";
26         $type = "Pg";
27     }
28
29     my $dsn = "DBI:$type:$db";
30     my $hoststr = "";
31     # SQLHost should be unset for SQLite
32     if (exists $param{'SQLHost'} and $param{'SQLHost'}) {
33         $dsn    .= ":$param{SQLHost}";
34         $hoststr = " to $param{'SQLHost'}";
35     }
36     # SQLite ignores $user and $pass
37     $dbh    = DBI->connect($dsn, $user, $pass);
38
39     if ($dbh && !$dbh->err) {
40         &status("Opened $type connection$hoststr");
41     } else {
42         &ERROR("Cannot connect$hoststr.");
43         &ERROR("Since $type is not available, shutting down bot!");
44         &ERROR( $dbh->errstr ) if ($dbh);
45         &closePID();
46         &closeSHM($shm);
47         &closeLog();
48
49         return 0 if ($no_fail);
50
51         exit 1;
52     }
53 }
54
55 sub sqlCloseDB {
56     return 0 unless ($dbh);
57
58     my $x = $param{SQLHost};
59     my $hoststr = ($x) ? " to $x" : "";
60
61     &status("Closed DBI connection$hoststr.");
62     $dbh->disconnect();
63
64     return 1;
65 }
66
67 #####
68 # Usage: &sqlQuote($str);
69 sub sqlQuote {
70     return $dbh->quote($_[0]);
71 }
72
73 #####
74 #  Usage: &sqlSelectMany($table, $select, [$where_href], [$other]);
75 # Return: $sth (Statement handle object)
76 sub sqlSelectMany {
77     my($table, $select, $where_href, $other) = @_;
78     my $query = "SELECT $select FROM $table";
79     my $sth;
80
81     if (!defined $select or $select =~ /^\s*$/) {
82         &WARN("sqlSelectMany: select == NULL.");
83         return;
84     }
85
86     if (!defined $table or $table =~ /^\s*$/) {
87         &WARN("sqlSelectMany: table == NULL.");
88         return;
89     }
90
91     $query .= " WHERE" if (($where_href) || ($other));
92     if ($where_href) {
93         my $where = &hashref2where($where_href);
94         $query .= " $where" if ($where);
95     }
96     $query .= " $other"         if $other;
97
98     if (!($sth = $dbh->prepare($query))) {
99         &ERROR("sqlSelectMany: prepare: $DBI::errstr");
100         return;
101     }
102
103     &SQLDebug($query);
104     if (!$sth->execute) {
105         &ERROR("sqlSelectMany: execute: '$query'");
106         return;
107     }
108
109     return $sth;
110 }
111
112 #####
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?
117 sub sqlSelect {
118     my $sth     = &sqlSelectMany(@_);
119     if (!defined $sth) {
120         &WARN("sqlSelect failed.");
121         return;
122     }
123     my @retval  = $sth->fetchrow_array;
124     $sth->finish;
125
126     if (scalar @retval > 1) {
127         return @retval;
128     } elsif (scalar @retval == 1) {
129         return $retval[0];
130     } else {
131         return;
132     }
133 }
134
135 #####
136 #  Usage: &sqlSelectColArray($table, $select, [$where_href], [$other]);
137 # Return: array.
138 sub sqlSelectColArray {
139     my $sth     = &sqlSelectMany(@_);
140     my @retval;
141
142     if (!defined $sth) {
143         &WARN("sqlSelect failed.");
144         return;
145     }
146
147     while (my @row = $sth->fetchrow_array) {
148         push(@retval, $row[0]);
149     }
150     $sth->finish;
151
152     return @retval;
153 }
154
155 #####
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);
163     if (!defined $sth) {
164         &WARN("sqlSelectColhash failed.");
165         return;
166     }
167     my %retval;
168
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]);
173         }
174         &DEBUG("sqlSelectColHash: count => ".scalar(keys %retval) );
175
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;
183             }
184             # what to do if there's only one or more than 3?
185         }
186
187     } else {
188         while (my @row = $sth->fetchrow_array) {
189             $retval{$row[0]} = $row[1];
190         }
191     }
192
193     $sth->finish;
194
195     return %retval;
196 }
197
198 #####
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(@_);
204     if (!defined $sth) {
205         &WARN("sqlSelectRowHash failed.");
206         return;
207     }
208     my $retval  = $sth->fetchrow_hashref();
209     $sth->finish;
210
211     if ($retval) {
212         return %{ $retval };
213     } else {
214         return;
215     }
216 }
217
218 #
219 # End of SELECT functions.
220 #
221
222 #####
223 #  Usage: &sqlSet($table, $where_href, $data_href);
224 # Return: 1 for success, undef for failure.
225 sub sqlSet {
226     my ($table, $where_href, $data_href) = @_;
227
228     if (!defined $table or $table =~ /^\s*$/) {
229         &WARN("sqlSet: table == NULL.");
230         return;
231     }
232
233     if (!defined $data_href or ref($data_href) ne "HASH") {
234         &WARN("sqlSet: data_href == NULL.");
235         return;
236     }
237
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);
242
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);
246     } else {
247         # hack.
248         my %hash = %{ $where_href };
249         # add data_href values...
250         foreach (keys %{ $data_href }) {
251             $hash{ $_ } = ${ $data_href }{$_};
252         }
253
254         $data_href = \%hash;
255         &sqlInsert($table, $data_href);
256     }
257
258     return 1;
259 }
260
261 #####
262 # Usage: &sqlUpdate($table, $data_href, $where_href);
263 sub sqlUpdate {
264     my ($table, $data_href, $where_href) = @_;
265
266     if (!defined $data_href or ref($data_href) ne "HASH") {
267         &WARN("sqlSet: data_href == NULL.");
268         return;
269     }
270
271     my $where  = &hashref2where($where_href) if ($where_href);
272     my $update = &hashref2update($data_href) if ($data_href);
273
274     &sqlRaw("Update", "UPDATE $table SET $update WHERE $where");
275
276     return 1;
277 }
278
279 #####
280 # Usage: &sqlInsert($table, $data_href, $other);
281 sub sqlInsert {
282     my ($table, $data_href, $other) = @_;
283     # note: if $other == 1, add "DELAYED" to function instead.
284
285     if (!defined $data_href or ref($data_href) ne "HASH") {
286         &WARN("sqlInsert: data_href == NULL.");
287         return;
288     }
289
290     my ($k_aref, $v_aref) = &hashref2array($data_href);
291     my @k = @{ $k_aref };
292     my @v = @{ $v_aref };
293
294     if (!@k or !@v) {
295         &WARN("sqlInsert: keys or vals is NULL.");
296         return;
297     }
298
299     &sqlRaw("Insert($table)", sprintf(
300         "INSERT %s INTO %s (%s) VALUES (%s)",
301         ($other || ""), $table, join(',',@k), join(',',@v)
302     ) );
303
304     return 1;
305 }
306
307 #####
308 # Usage: &sqlReplace($table, $data_href);
309 sub sqlReplace {
310     my ($table, $data_href) = @_;
311
312     if (!defined $data_href or ref($data_href) ne "HASH") {
313         &WARN("sqlReplace: data_href == NULL.");
314         return;
315     }
316
317     my ($k_aref, $v_aref) = &hashref2array($data_href);
318     my @k = @{ $k_aref };
319     my @v = @{ $v_aref };
320
321     if (!@k or !@v) {
322         &WARN("sqlReplace: keys or vals is NULL.");
323         return;
324     }
325
326     &sqlRaw("Replace($table)", sprintf(
327         "REPLACE INTO %s (%s) VALUES (%s)",
328         $table, join(',',@k), join(',',@v)
329     ) );
330
331     return 1;
332 }
333
334 #####
335 # Usage: &sqlDelete($table, $where_href);
336 sub sqlDelete {
337     my ($table, $where_href) = @_;
338
339     if (!defined $where_href or ref($where_href) ne "HASH") {
340         &WARN("sqlDelete: where_href == NULL.");
341         return;
342     }
343
344     my $where   = &hashref2where($where_href);
345
346     &sqlRaw("Delete", "DELETE FROM $table WHERE $where");
347
348     return 1;
349 }
350
351 #####
352 #  Usage: &sqlRaw($prefix, $query);
353 # Return: 1 for success, 0 for failure.
354 sub sqlRaw {
355     my ($prefix, $query) = @_;
356     my $sth;
357
358     if (!defined $query or $query =~ /^\s*$/) {
359         &WARN("sqlRaw: query == NULL.");
360         return 0;
361     }
362
363     if (!($sth = $dbh->prepare($query))) {
364         &ERROR("Raw($prefix): !prepare => '$query'");
365         return 0;
366     }
367
368     &SQLDebug($query);
369     if (!$sth->execute) {
370         &ERROR("Raw($prefix): !execute => '$query'");
371         $sth->finish;
372         return 0;
373     }
374
375     $sth->finish;
376
377     return 1;
378 }
379
380 #####
381 #  Usage: &sqlRawReturn($query);
382 # Return: array.
383 sub sqlRawReturn {
384     my ($query) = @_;
385     my @retval;
386     my $sth;
387
388     if (!defined $query or $query =~ /^\s*$/) {
389         &WARN("sqlRawReturn: query == NULL.");
390         return 0;
391     }
392
393     if (!($sth = $dbh->prepare($query))) {
394         &ERROR("RawReturn: !prepare => '$query'");
395         return 0;
396     }
397
398     &SQLDebug($query);
399     if (!$sth->execute) {
400         &ERROR("RawReturn: !execute => '$query'");
401         $sth->finish;
402         return 0;
403     }
404
405     while (my @row = $sth->fetchrow_array) {
406         push(@retval, $row[0]);
407     }
408
409     $sth->finish;
410
411     return @retval;
412 }
413
414 ####################################################################
415 ##### Misc DBI stuff...
416 #####
417
418 sub hashref2where {
419     my ($href) = @_;
420
421     if (!defined $href) {
422         &WARN("hashref2where: href == NULL.");
423         return;
424     }
425
426     if (ref($href) ne "HASH") {
427         &WARN("hashref2where: href is not HASH ref (href => $href)");
428         return;
429     }
430
431     my %hash = %{ $href };
432     foreach (keys %hash) {
433         my $v = $hash{$_};
434
435         if (s/^-//) {   # as is.
436             $hash{$_} = $v;
437             delete $hash{'-'.$_};
438         } else {
439             $hash{$_} = &sqlQuote($v);
440         }
441     }
442
443     return join(' AND ', map { $_."=".$hash{$_} } keys %hash );
444 }
445
446 sub hashref2update {
447     my ($href) = @_;
448
449     if (ref($href) ne "HASH") {
450         &WARN("hashref2update: href is not HASH ref.");
451         return;
452     }
453
454     my %hash;
455     foreach (keys %{ $href }) {
456         my $k = $_;
457         my $v = ${ $href }{$_};
458
459         # is there a better way to do this?
460         if ($k =~ s/^-//) {   # as is.
461             1;
462         } else {
463             $v = &sqlQuote($v);
464         }
465
466         $hash{$k} = $v;
467     }
468
469     return join(', ', map { $_."=".$hash{$_} } sort keys %hash);
470 }
471
472 sub hashref2array {
473     my ($href) = @_;
474
475     if (ref($href) ne "HASH") {
476         &WARN("hashref2update: href is not HASH ref.");
477         return;
478     }
479
480     my(@k, @v);
481     foreach (keys %{ $href }) {
482         my $k = $_;
483         my $v = ${ $href }{$_};
484
485         # is there a better way to do this?
486         if ($k =~ s/^-//) {   # as is.
487             1;
488         } else {
489             $v = &sqlQuote($v);
490         }
491
492         push(@k, $k);
493         push(@v, $v);
494     }
495
496     return (\@k, \@v);
497 }
498
499 #####
500 # Usage: &countKeys($table, [$col]);
501 sub countKeys {
502     my ($table, $col) = @_;
503     $col ||= "*";
504
505     return (&sqlRawReturn("SELECT count($col) FROM $table"))[0];
506 }
507
508 #####
509 # Usage: &sumKey($table, $col);
510 sub sumKey {
511     my ($table, $col) = @_;
512
513     return (&sqlRawReturn("SELECT sum($col) FROM $table"))[0];
514 }
515
516 #####
517 # Usage: &randKey($table, $select);
518 sub randKey {
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/;
524     }
525
526     my $sth     = $dbh->prepare($query);
527     &SQLDebug($query);
528     &WARN("randKey($query)") unless $sth->execute;
529     my @retval  = $sth->fetchrow_array;
530     $sth->finish;
531
532     return @retval;
533 }
534
535 #####
536 # Usage: &deleteTable($table);
537 sub deleteTable {
538     &sqlRaw("deleteTable($_[0])", "DELETE FROM $_[0]");
539 }
540
541 #####
542 # Usage: &searchTable($table, $select, $key, $str);
543 #  Note: searchTable does sqlQuote.
544 sub searchTable {
545     my($table, $select, $key, $str) = @_;
546     my $origStr = $str;
547     my @results;
548
549     # allow two types of wildcards.
550     if ($str =~ /^\^(.*)\$$/) {
551         &FIXME("searchTable: can't do \"$str\"");
552         $str = $1;
553     } else {
554         $str .= "%"     if ($str =~ s/^\^//);
555         $str = "%".$str if ($str =~ s/\$$//);
556         $str = "%".$str."%" if ($str eq $origStr);      # el-cheapo fix.
557     }
558
559     $str =~ s/\_/\\_/g;
560     $str =~ s/\?/_/g;   # '.' should be supported, too.
561     $str =~ s/\*/%/g;
562     # end of string fix.
563
564     my $query = "SELECT $select FROM $table WHERE $key LIKE ". 
565                 &sqlQuote($str);
566     my $sth = $dbh->prepare($query);
567
568     &SQLDebug($query);
569     if (!$sth->execute) {
570         &WARN("Search($query)");
571         $sth->finish;
572         return;
573     }
574
575     while (my @row = $sth->fetchrow_array) {
576         push(@results, $row[0]);
577     }
578     $sth->finish;
579
580     return @results;
581 }
582
583 sub sqlCreateTable {
584     my($table)  = @_;
585     my(@path)   = ($bot_data_dir, ".","..","../..");
586     my $found   = 0;
587     my $data;
588
589     foreach (@path) {
590         my $file = "$_/setup/$table.sql";
591         next unless ( -f $file );
592
593         open(IN, $file);
594         while (<IN>) {
595             chop;
596             $data .= $_;
597         }
598
599         $found++;
600         last;
601     }
602
603     if (!$found) {
604         return 0;
605     } else {
606         &sqlRaw("sqlCreateTable($table)", $data);
607         return 1;
608     }
609 }
610
611 sub checkTables {
612     my $database_exists = 0;
613     my %db;
614
615     if ($param{DBType} =~ /^mysql$/i) {
616         my $sql = "SHOW DATABASES";
617         foreach ( &sqlRawReturn($sql) ) {
618             $database_exists++ if ($_ eq $param{'DBName'});
619         }
620
621         unless ($database_exists) {
622             &status("Creating database $param{DBName}...");
623             my $query = "CREATE DATABASE $param{DBName}";
624             &sqlRaw("create(db $param{DBName})", $query);
625         }
626
627         # retrieve a list of db's from the server.
628         foreach ($dbh->func('_ListTables')) {
629             $db{$_} = 1;
630         }
631
632     } elsif ($param{DBType} =~ /^SQLite$/i) {
633
634         # retrieve a list of db's from the server.
635         foreach ( &sqlRawReturn("SELECT name FROM sqlite_master WHERE type='table'") ) {
636             $db{$_} = 1;
637         }
638
639         # create database.
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);
644         }
645     }
646
647     foreach ( qw(factoids rootwarn seen stats botmail) ) {
648         next if (exists $db{$_});
649         &status("checkTables: creating new table $_...");
650
651         &sqlCreateTable($_);
652     }
653 }
654
655 1;