TUWF/DB.pm untested

filter: Statementstmt 0.0% 0 / 129 Branchbran 0.0% 0 / 68 Conditioncond 0.0% 0 / 50 MC/DCmcdc 0.0% 0 / 32 Subroutinesub 0.0% 0 / 22 Podpod 0.0% 0 / 14 totaltotal 0.0% 0 / 315 CC 35 SCAR 40.8
CC
35
Cov
0%
sqlprint
156.0
sqlhelper
110.0
dbInit
20.0
CRAP 59.4
1  
2 package TUWF::DB;
3  
4 use strict;
5 use warnings;
6 use Carp 'croak';
7 use Exporter 'import';
8 use Time::HiRes 'time';
9  
10 our $VERSION = '1.6';
11 our @EXPORT = qw|
12 dbInit dbh dbCheck dbDisconnect dbCommit dbRollBack
13 dbExec dbVal dbRow dbAll dbPage
14 |;
15 our @EXPORT_OK = ('sqlprint');
16  
17  
18 sub dbInit {
19 my $self = shift;
20 require DBI;
21 my $login = $self->{_TUWF}{db_login};
22 my $sql;
23 if(ref($login) eq 'CODE') {
24 $sql = $login->($self);
25 croak 'db_login subroutine did not return a DBI instance.' if !ref($sql) || !$sql->isa('DBI::db');
26 } elsif(ref($login) eq 'ARRAY' && @$login == 3) {
27 $sql = DBI->connect(@$login, {
28 PrintError => 0, RaiseError => 1, AutoCommit => 0,
29 mysql_enable_utf8 => 1, # DBD::mysql
30 pg_enable_utf8 => 1, # DBD::Pg
31 sqlite_unicode => 1, # DBD::SQLite
32 });
33 } else {
34 croak 'Invalid value for the db_login setting.';
35 }
36 $sql->{private_tuwf} = 1;
37 inject_logging();
38  
39 $self->{_TUWF}{DB} = {
40 sql => $sql,
41 queries => [],
42 };
43  
44 $_->() for @{$self->{_TUWF}{hooks}{db_connect}};
45 }
46  
47  
48 sub dbh {
49 my($self) = @_;
50 $self->dbInit if !$self->{_TUWF}{DB}{sql};
51 $self->{_TUWF}{DB}{sql};
52 }
53  
54  
55 sub dbCheck {
56 my $self = shift;
57 my $info = $self->{_TUWF}{DB};
58 return $self->dbInit if !$info || !$info->{sql};
59  
60 my $start = time;
61 $info->{queries} = [];
62  
63 if(!$info->{sql}->ping) {
64 $self->dbInit;
65 warn "Ping failed, reconnected to database";
66 }
67 $self->dbRollBack;
68 push(@{$info->{queries}}, [ 'ping/rollback', {}, time-$start ]);
69 }
70  
71  
72 sub dbDisconnect {
73 (shift->{_TUWF}{DB}{sql} // return)->disconnect();
74 }
75  
76  
77 sub dbCommit {
78 my $self = shift;
79 my $start = [Time::HiRes::gettimeofday()] if $self->debug || $self->{_TUWF}{log_slow_pages};
80 ($self->{_TUWF}{DB}{sql} // return)->commit();
81 push(@{$self->{_TUWF}{DB}{queries}}, [ 'commit', {}, Time::HiRes::tv_interval($start) ])
82 if $self->debug || $self->{_TUWF}{log_slow_pages};
83 }
84  
85  
86 sub dbRollBack {
87 (shift->{_TUWF}{DB}{sql} // return)->rollback();
88 }
89  
90  
91 # execute a query and return the number of rows affected
92 sub dbExec {
93 return sqlhelper(shift, 0, @_);
94 }
95  
96  
97 # ..return the first column of the first row
98 sub dbVal {
99 return sqlhelper(shift, 1, @_);
100 }
101  
102  
103 # ..return the first row as an hashref
104 sub dbRow {
105 return sqlhelper(shift, 2, @_);
106 }
107  
108  
109 # ..return all rows as an arrayref of hashrefs
110 sub dbAll {
111 return sqlhelper(shift, 3, @_);
112 }
113  
114  
115 # same as dbAll, but paginates results by adding
116 # an OFFSET and LIMIT to the query, the first argument
117 # should be a hashref with the keys page and results.
118 # Returns the usual value from dbAll and a value
119 # indicating whether there is a next page
120 sub dbPage {
121 my($s, $o, $q, @a) = @_;
122 my $r = $s->dbAll($q.' LIMIT ? OFFSET ?', @a, $o->{results}+(wantarray?1:0), $o->{results}*($o->{page}-1));
123 return $r if !wantarray;
124 return ($r, 0) if $#$r != $o->{results};
125 pop @$r;
126 return ($r, 1);
127 }
128  
129  
130 sub sqlhelper { # type, query, @list
131 my $self = shift;
132 my $type = shift;
133 my $sqlq = shift;
134  
135 $sqlq =~ s/\r?\n/ /g;
136 $sqlq =~ s/ +/ /g;
137 my(@q) = @_ ? sqlprint($sqlq, @_) : ($sqlq);
138  
139 my($q, $r);
140 my $ret = eval {
141 $q = $self->dbh->prepare($q[0]);
142 $q->execute($#q ? @q[1..$#q] : ());
143 $r = $type == 1 ? ($q->fetchrow_array)[0] :
144 $type == 2 ? $q->fetchrow_hashref :
145 $type == 3 ? $q->fetchall_arrayref({}) :
146 $q->rows;
147 1;
148 };
149  
150 # re-throw the error in the context of the calling code
151 croak($self->dbh->errstr || $@) if !$ret;
152  
153 $r = 0 if $type == 0 && (!$r || $r == 0);
154 $r = {} if $type == 2 && (!$r || ref($r) ne 'HASH');
155 $r = [] if $type == 3 && (!$r || ref($r) ne 'ARRAY');
156  
157 return $r;
158 }
159  
160  
161 # sqlprint:
162 # ? normal placeholder
163 # !l list of placeholders, expects arrayref
164 # !H list of SET-items, expects hashref or arrayref: format => (bind_value || \@bind_values)
165 # !W same as !H, but for WHERE clauses (AND'ed together)
166 # !s the classic sprintf %s, use with care
167 # This isn't sprintf, so all other things won't work,
168 # Only the ? placeholder is supported, so no dollar sign numbers or named placeholders
169  
170 sub sqlprint { # query, bind values. Returns new query + bind values
171 my @a;
172 my $q='';
173 for my $p (split /(\?|![lHWs])/, shift) {
174 next if !defined $p;
175 if($p eq '?') {
176 push @a, shift;
177 $q .= $p;
178 } elsif($p eq '!s') {
179 $q .= shift;
180 } elsif($p eq '!l') {
181 my $l = shift;
182 $q .= join ', ', map '?', 0..$#$l;
183 push @a, @$l;
184 } elsif($p eq '!H' || $p eq '!W') {
185 my $h=shift;
186 my @h=ref $h eq 'HASH' ? %$h : @$h;
187 my @r;
188 while(my($k,$v) = (shift(@h), shift(@h))) {
189 last if !defined $k;
190 my($n,@l) = sqlprint($k, ref $v eq 'ARRAY' ? @$v : $v);
191 push @r, $n;
192 push @a, @l;
193 }
194 $q .= ($p eq '!W' ? 'WHERE ' : 'SET ').join $p eq '!W' ? ' AND ' : ', ', @r
195 if @r;
196 } else {
197 $q .= $p;
198 }
199 }
200 return($q, @a);
201 }
202  
203  
204 # There are generally two approaches to adding logging to DBI: The common and
205 # clean approach is to subclass DBD::st and DBD::db (e.g. DBIx::LogAny). But
206 # subclassing doesn't stack nicely, and you may need to implement more methods
207 # because methods calling each other internally won't be caught.
208 #
209 # The other approach is to replace the methods of DBD::st and DBD::db directly,
210 # as done in DBI::Log. The downside is that it's hacky, unreliable when DBD::*
211 # modules come with their own implementation of something, and this approach
212 # affects *all* DBI interation and not just those of selected handlers. The
213 # latter issue is easily solved by setting a private flag in the DBI object
214 # ('private_tuwf' in this case).
215 sub inject_logging {
216 require DBI;
217 no warnings 'redefine';
218  
219 # The measured SQL timing only includes that of the execute() call, but it's
220 # likely that some query processing also happens during fetching.
221 # Unfortunately, I haven't found a reliable way to trigger on "Okay, I'm done
222 # with executing and fetching this statement". The final() method is not
223 # implicitely called, and adding an object destructor wouldn't work with
224 # cached prepared statements.
225 my $orig_execute = \&DBI::st::execute;
226 *DBI::st::execute = sub {
227 my($self) = @_;
228 my $start = time;
229 my $ret = $orig_execute->(@_);
230  
231 if($self->{Database}{private_tuwf}) {
232 my $time = time - $start;
233 my %params = %{$self->{ParamValues} || {}};
234  
235 $TUWF::OBJ->log(sprintf
236 '[%7.2fms] %s | %s',
237 $time*1000,
238 $self->{Statement},
239 join ', ',
240 map "$_:".DBI::neat($params{$_}),
241 sort { $a =~ /^[0-9]+$/ && $b =~ /^[0-9]+$/ ? $a <=> $b : $a cmp $b }
242 keys %params
243 ) if $TUWF::OBJ->{_TUWF}{log_queries};
244  
245 push @{$TUWF::OBJ->{_TUWF}{DB}{queries}}, [ $self->{Statement}, \%params , $time ];
246 }
247  
248 return $ret;
249 };
250 }
251  
252  
253 1;