blib/lib/DB.pm untested

filter: Statementstmt 0.0% 0 / 263 Branchbran 0.0% 0 / 124 Conditioncond 0.0% 0 / 15 MC/DCmcdc 0.0% 0 / 10 Subroutinesub 0.0% 0 / 27 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 460 CC 63 SCAR 37.1
CC
63
Cov
0%
sqlSelectAllHashRef
110.0
sqlSelect
72.0
sqlSelectAllArrayRef
56.0
CRAP 40.9
1 package DB;
2  
3 use strict;
4 use Config '%Config';
5 use Data::Dumper;
6 use DBIx::Password;
7 use Carp qw(cluck);
8  
9 use vars qw($VERSION @ISA);
10  
11 $VERSION = ' $Revision: 0.99 $ ' =~ /\$Revision:\s+([^\s]+)/;
12  
13 =pod
14  
15  
16 DB.pm (to be named ... DBIx::?)
17 - (documentation to be released)
18  
19 =cut
20  
21 # Copyright (C) 2005 Patrick Galbraith
22 #
23 # This program is free software; you can redistribute it and/or modify
24 # it under the terms of the GNU General Public License as published by
25 # the Free Software Foundation; either version 2 of the License, or
26 # (at your option) any later version.
27 #
28 # This program is distributed in the hope that it will be useful,
29 # but WITHOUT ANY WARRANTY; without even the implied warranty of
30 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
31 # GNU General Public License for more details.
32 #
33 # You should have received a copy of the GNU General Public License
34 # along with this program; if not, write to the Free Software
35 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */
36 #
37  
38 ##################################################
39 sub new {
40 my ($caller, $opts) = @_;
41  
42 my $class = ref($caller) || $caller;
43  
44 my $self = {};
45 # set this to your liking!
46 $self->{_timeout}= 30;
47 $self->{virtual_user} = $opts->{virtual_user} ;
48  
49 bless ($self, ref($class) || $class);
50 $self->sqlConnect();
51 return($self);
52 }
53  
54 ##################################################
55 sub sqlConnect {
56 my ($self, $reset) = @_;
57  
58 if ($reset) {
59 $self->{_dbh}->disconnect;
60 }
61  
62 if (!(defined $self->{_dbh}) || ! $self->{_dbh}->ping) {
63  
64 {
65 local @_ ;
66  
67 eval {
68 local $SIG{'ALRM'} = sub { die 'Connection timed out!'};
69 alarm $self->{_timeout} if $Config{d_alarm};
70 $self->{_dbh} = DBIx::Password->connect_cached($self->{virtual_user});
71 alarm 0 if $Config{d_alarm};
72 };
73  
74 if ( $@ || ! (defined $self->{_dbh}) ) {
75 # couldn't connect
76 return 0;
77 }
78 }
79 }
80 $self->{_dbh}->{RaiseError} = 1;
81 # we have a connect
82 return 1;
83 }
84  
85 ##################################################
86 sub _whereClauseBind {
87 my ($self, $whereref) = @_;
88  
89 return({}) unless $whereref;
90  
91 my $values = [];
92 my @tmp;
93 my $where = '';
94 my $whereClauseRef = {};
95  
96  
97 if (ref($whereref) eq 'HASH') {
98 for (keys %$whereref) {
99 if ($_ =~ /^-(\w+)/) {
100 push(@tmp, $1 . " = " . $whereref->{$_});
101  
102 } elsif ($_ =~ /^\~(\w+)/) {
103 push(@tmp, "$1 LIKE ?");
104 push(@$values,$whereref->{$_});
105  
106 } else {
107 push(@tmp, "$_ = ?");
108 push(@$values,$whereref->{$_});
109 }
110 }
111 $where = join (" AND ", @tmp);
112 } else {
113 $where = $whereref;
114 }
115 $whereClauseRef = {
116 where => $where,
117 values => $values
118 };
119  
120 return($whereClauseRef);
121 }
122  
123 ##################################################
124 sub _whereClause {
125 my ($self, $whereref) = @_;
126 return({}) unless $whereref;
127  
128 my @tmp;
129 my $whereClauseRef = {};
130  
131 if (ref($whereref) eq 'HASH') {
132 map { push(@tmp,"$_ = " . $self->{_dbh}->quote($whereref->{$_}) ) } keys %$whereref;
133 $whereClauseRef->{where} = join (" AND ", @tmp);
134 } else {
135 $whereClauseRef->{where} = $whereref;
136 }
137 return($whereClauseRef);
138 }
139  
140 ##################################################
141 sub sqlExec {
142 my ($self, $params) = @_;
143  
144 my $sth;
145 my $rows;
146  
147 eval { $sth = $self->{_dbh}->prepare_cached($params->{sql}); };
148 if ($@) {
149 return $self->errorHandler("DB::sqlExec prepare_cached sql $params->{sql} error ");
150 }
151  
152 eval { $rows = $sth->execute(@{$params->{values}}); };
153 if ($@) {
154 return $self->errorHandler("DB::sqlExec sth->execute error ");
155 }
156  
157 return $sth;
158 }
159 ########################################################
160 sub sqlSelectColumns {
161 my($self, $table) = @_;
162 return unless $table;
163  
164 my $rows = $self->{_dbh}->selectcol_arrayref("SHOW COLUMNS FROM $table");
165 return $rows;
166 }
167  
168 ##################################################
169 sub sqlCount {
170 my ($self, $select, $from, $whereref, $other, $options) = @_;
171 my $count;
172 $count = ($count == '*') ? '*' : '';
173 $count = ($select =~ /^(\w+)\,?/) ? $1 : '*';
174  
175 my $val = $self->sqlSelect("count($count)", $from, $whereref, '', $options);
176  
177 return($val);
178 }
179  
180 ##################################################
181 sub sqlSelect {
182 my ($self, $select, $from, $whereref, $other, $options) = @_;
183  
184 my @row;
185  
186 my $whereClauseRef = $self->_whereClauseBind($whereref);
187  
188 my $distinct = ($options && $options->{distinct}) ? "DISTINCT" : "";
189 my $sql = "SELECT $distinct $select ";
190 $sql .= "FROM $from " if $from;
191 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
192 $sql .= "$other " if $other;
193  
194 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
195 return(0) unless $sth;
196  
197 if (@row = $sth->fetchrow) {
198 $sth->finish;
199  
200 if (wantarray()) {
201 return @row;
202 } else {
203 return $row[0];
204 }
205 } else {
206 return(0);
207 }
208 }
209  
210 ########################################################
211 sub getLastInsertId {
212 my($self) = @_;
213 return $self->sqlSelect('LAST_INSERT_ID()');
214 }
215  
216 ########################################################
217 sub sqlSelectArrayRef {
218 my ($self, $select, $from, $whereref, $other, $options) = @_;
219  
220 my $arrayRef = [];
221  
222 my $whereClauseRef = $self->_whereClauseBind($whereref);
223  
224 my $sql = "SELECT $select ";
225 $sql .= "FROM $from " if $from;
226 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
227 $sql .= "$other" if $other;
228  
229 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
230 return(0) unless $sth;
231  
232 if ($arrayRef = $sth->fetchrow_arrayref) {
233 $sth->finish;
234 return $arrayRef;
235 } else {
236 return(0);
237 }
238 }
239  
240 ########################################################
241 sub sqlSelectHashRef {
242 my ($self, $select, $from, $whereref, $other, $options) = @_;
243  
244 my $hashRef = {};
245  
246 my $whereClauseRef = $self->_whereClauseBind($whereref);
247  
248 my $sql = "SELECT $select ";
249 $sql .= "FROM $from " if $from;
250 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
251 $sql .= "$other" if $other;
252  
253 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
254 return(0) unless $sth;
255  
256 if ($hashRef = $sth->fetchrow_hashref) {
257 $sth->finish;
258 return $hashRef;
259 } else {
260 return(0);
261 }
262 }
263  
264 ########################################################
265 sub sqlSelectAllArrayRef {
266 my ($self, $select, $from, $whereref, $other, $options) = @_;
267  
268 my $arrayRef = [];
269  
270 my $whereClauseRef = $self->_whereClauseBind($whereref);
271  
272 my $distinct = $options->{distinct} ? 'DISTINCT' : '';
273  
274 my $sql = "SELECT $distinct $select ";
275 $sql .= "FROM $from " if $from;
276 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
277 $sql .= "$other" if $other;
278  
279 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
280 return(0) unless $sth;
281  
282 if ($arrayRef = $sth->fetchall_arrayref()) {
283 $sth->finish;
284 return $arrayRef;
285 } else {
286 return(0);
287 }
288 }
289  
290 ########################################################
291 sub sqlSelectAllHashRef {
292 my ($self, $select, $from, $whereref, $other, $options) = @_;
293  
294 my $hashRef;
295  
296 # fetchall_hashref needs a prime to key it's results by
297 # assume first field in select, else try to get
298 # from options
299 my $prime = $options->{prime} ? $options->{prime} : ($select =~ /^(\w+)\,?/) ? $1 : undef ;
300  
301 if (! $prime) {
302 $self->{err_msg} = "NO PRIME PROVIDED";
303 return(0);
304 }
305  
306 my $whereClauseRef = $self->_whereClauseBind($whereref);
307  
308 my $distinct = $options->{distinct} ? 'DISTINCT' : '';
309  
310 my $sql = "SELECT $distinct $select ";
311 $sql .= "FROM $from " if $from;
312 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
313 $sql .= "$other" if $other;
314  
315 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
316 return(0) unless $sth;
317  
318 if ($hashRef = $sth->fetchall_hashref($prime)) {
319 $sth->finish;
320 return $hashRef;
321 } else {
322 return(0);
323 }
324  
325 }
326  
327 ##################################################
328 sub sqlInsert {
329 my ($self, $table, $params, $options) = @_;
330  
331 my @bindValues;
332 my ($i, $sql, $fieldString, $valueString) = (1, '', '','');
333 my $numParams = (keys %$params);
334 my $sth;
335  
336 for (keys %$params) {
337 if ($_ =~ /^-/) {
338 $valueString .= $params->{$_};
339 $valueString .= "," if $i < $numParams;
340 $_ =~ s/^-//;
341 } else {
342 $valueString .= "?";
343 $valueString .= "," if $i < $numParams;
344 push(@bindValues,$params->{$_});
345 }
346 $fieldString .= $_ . ",";
347 }
348  
349 chop($fieldString);
350 chop($valueString);
351  
352 $sql = sprintf("INSERT INTO %s (%s) VALUES (%s)", $table, $fieldString, $valueString);
353  
354 $sth = $self->sqlExec({ sql => $sql, values => \@bindValues });
355  
356 return(0) unless $sth;
357 return($sth->rows());
358 }
359  
360 ##################################################
361 # currently, only same columns for every record
362 sub sqlInsertMany {
363 my ($self, $table, $records, $options) = @_;
364  
365 my ($i, $rows, $sql) = (0, 0, '');
366 my $sth;
367 my (@values, @fields);
368  
369 @fields = sort keys %{$records->[0]}; # sort required
370 my $noQuoteFlag = 0;
371 map { $noQuoteFlag++ if $_ =~ /^-?(\w+)/ } @fields;
372  
373 if ($noQuoteFlag) {
374 for my $record (@$records) {
375 $rows += $self->sqlInsert($table, $record, $options);
376 }
377 return($rows);
378 } else {
379 my $fieldList = join (',',@fields);
380 my $valueList = join (',', ('?')x@fields);
381  
382 $sql = sprintf "INSERT INTO %s (%s) VALUES (%s)",
383 $table, join(',', @fields), join(',', ('?')x@fields);
384  
385 eval { $sth = $self->{_dbh}->prepare_cached($sql); };
386 return $self->errorHandler() if $@;
387  
388 for (@$records) {
389 my @values = @{$_}{@fields};
390 eval { $sth->execute(@values); };
391 return $self->errorHandler() if $@;
392 }
393  
394 return(0) unless $sth;
395  
396 return($sth->{rows});
397 }
398 }
399  
400 ##################################################
401 sub sqlUpdate {
402 my ($self, $table, $params, $whereref, $options) = @_;
403  
404 my ($sql, $updateString) = ('', '');
405 my @bindValues;
406  
407 $sql = "UPDATE $table SET ";
408 my $whereClauseRef = $self->_whereClause($whereref);
409  
410 for (keys %$params) {
411 if ($_ =~ /^-(\w+)/) {
412 $updateString .= $1 . " = " . $params->{$_} . ",";
413 } else {
414 $updateString .= $_ . " = ?,";
415 push(@bindValues,$params->{$_});
416 }
417 }
418  
419 chop($updateString);
420 $sql .= $updateString;
421 $sql .= " WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
422  
423 my $sth = $self->sqlExec({ sql => $sql, values => \@bindValues});
424  
425 return($sth ? $sth->{rows} : 0 );
426 }
427  
428 ##################################################
429 sub sqlDelete {
430 my ($self, $from, $whereref, $other, $options) = @_;
431  
432 my $whereClauseRef = $self->_whereClauseBind($whereref);
433  
434 my $sql = "DELETE FROM $from ";
435 $sql .= "WHERE $whereClauseRef->{where} " if $whereClauseRef->{where};
436 $sql .= "$other" if $other;
437  
438 my $sth = $self->sqlExec({ sql => $sql, values => $whereClauseRef->{values} });
439 return($sth->{rows});
440 }
441  
442 ##################################################
443 sub sqlDeleteMany {
444 my ($self, $from, $whereref, $other, $options) = @_;
445  
446 my $rows = 0;
447 for my $i(0 .. $#{$whereref}) {
448 $rows += $self->sqlDelete($from, $whereref->[$i],$other, $options);
449 }
450 return($rows);
451 }
452  
453 ##################################################
454 sub errorHandler {
455 my ($self, $msg) = @_;
456 $self->{err_msg} .= "ERROR: " . $msg . " " . $@;
457 $self->{err_msg} .= "\nDBI::errstr " . $self->{_dbh}->errstr;
458 return(0);
459 }
460  
461 ##################################################
462 sub errorMessage {
463 my ($self) = @_;
464 return($self->{err_msg});
465 }
466 ##################################################
467 sub DESTROY {
468 my ($self) = @_;
469 $self->{_dbh}->disconnect();
470  
471 }
472  
473 1;