Core/Handle.pm

filter: Statementstmt 48.9% 73 / 149 Branchbran 36.1% 34 / 94 Conditioncond 39.2% 20 / 51 MC/DCmcdc 20.0% 6 / 30 Subroutinesub 46.6% 7 / 15 Podpod 100% 6 / 6 totaltotal 42.3% 146 / 345 CC 68 SCAR 47.1
CC
68
Cov
43%
_quick_query
306.0
_generate_sql
98.3
_get_where_sql
30.0
CRAP 110.7
« Core.pm ↑ Summary
1 package Dancer::Plugin::Database::Core::Handle;
2  
3 3 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
4 3 ▶use Carp;
Subroutine BEGIN: called CC=1 SCAR=0.0
5 3 ▶use DBI;
Subroutine BEGIN: called CC=1 SCAR=0.0
6 3 ▶use base qw(DBI::db);
Subroutine BEGIN: called CC=1 SCAR=0.0
7  
8 3 our $VERSION = '0.02';
9  
10 =head1 NAME
11  
12 Dancer::Plugin::Database::Core::Handle - subclassed DBI connection handle
13  
14 =head1 DESCRIPTION
15  
16 Subclassed DBI connection handle with added convenience features
17  
18  
19 =head1 SYNOPSIS
20  
21 # in your Dancer app:
22 database->quick_insert($tablename, \%data);
23  
24 # Updating a record where id = 42:
25 database->quick_update($tablename, { id => 42 }, { foo => 'New value' });
26  
27 # Fetching a single row quickly in scalar context
28 my $employee = database->quick_select('employees', { id => $emp_id });
29  
30 # Fetching multiple rows in list context - passing an empty hashref to signify
31 # no where clause (i.e. return all rows - so "select * from $table_name"):
32 my @all_employees = database->quick_select('employees', {});
33  
34 # count number of male employees
35 my $count = database->quick_count('employees', { gender => 'male' });
36  
37 =head1 Added features
38  
39 A C<Dancer::Plugin::Database::Handle> object is a subclassed L<DBI::db> L<DBI>
40 database handle, with the following added convenience methods:
41  
42 =over 4
43  
44 =item quick_insert
45  
46 database->quick_insert('mytable', { foo => 'Bar', baz => 5 });
47  
48 Given a table name and a hashref of data (where keys are column names, and the
49 values are, well, the values), insert a row in the table.
50  
51 If you need any of the values to be interpolated straight into the SQL, for
52 instance if you need to use a function call like C<NOW()> or similar, then you
53 can provide them as a scalarref:
54  
55 database->quick_insert('mytable', { foo => 'Bar', timestamp => \'NOW()' });
56  
57 Of course, if you do that, you must be careful to avoid SQL injection attacks!
58 =cut
59  
60 sub quick_insert {
61 0 ▶ my ($self, $table_name, $data) = @_;
Subroutine quick_insert: not called CC=1 SCAR=6.9
Pod documented
62 0 return $self->_quick_query('INSERT', $table_name, $data);
63 }
64  
65 =item quick_update
66  
67 database->quick_update('mytable', { id => 42 }, { foo => 'Baz' });
68  
69 Given a table name, a hashref describing a where clause and a hashref of
70 changes, update a row.
71  
72 As per quick_insert, if you need any of the values to be interpolated straight
73 in the SQL, for e.g. to use a function call, provide a scalarref:
74  
75 database->quick_update('mytable', { id => 42 }, { counter => \'counter + 1' });
76  
77 Of course, if you do that, you must be careful to avoid SQL injection attacks!
78  
79 =cut
80  
81 sub quick_update {
82 0 ▶ my ($self, $table_name, $where, $data) = @_;
Subroutine quick_update: not called CC=1 SCAR=6.9
Pod documented
83 0 return $self->_quick_query('UPDATE', $table_name, $data, $where);
84 }
85  
86  
87 =item quick_delete
88  
89 database->quick_delete($table, { id => 42 });
90  
91 Given a table name and a hashref to describe the rows which should be deleted
92 (the where clause - see below for further details), delete them.
93  
94 =cut
95  
96 sub quick_delete {
97 0 ▶ my ($self, $table_name, $where) = @_;
Subroutine quick_delete: not called CC=1 SCAR=6.9
Pod documented
98 0 return $self->_quick_query('DELETE', $table_name, undef, $where);
99 }
100  
101  
102 =item quick_select
103  
104 my $row = database->quick_select($table, { id => 42 });
105 my @rows = database->quick_select($table, { id => 42 });
106  
107 Given a table name and a hashref of where clauses (see below for explanation),
108 and an optional hashref of options, returns either the first matching
109 row as a hashref if called in scalar context, or a list of matching rows
110 as hashrefs if called in list context. The third argument is a hashref of
111 options to allow additional control, as documented below. For backwards
112 compatibility, it can also be an arrayref of column names, which acts in the
113 same way as the C<columns> option.
114  
115 The options you can provide are:
116  
117 =over 4
118  
119 =item C<columns>
120  
121 An arrayref of column names to return, if you only want certain columns returned
122  
123 =item C<order_by>
124  
125 Specify how the results should be ordered. This option can take various values:
126  
127 =over 4
128  
129 =item * a straight scalar or arrayref sorts by the given column(s):
130  
131 { order_by => 'foo' } # equivalent to "ORDER BY foo"
132 { order_by => [ qw(foo bar) ] } # equiv to "ORDER BY foo,bar"
133  
134 =item * a hashref of C<order => column name>, e.g.:
135  
136 { order_by => { desc => 'foo' } } # equiv to ORDER BY foo DESC
137 { order_by => [ { desc => 'foo' }, { asc => 'bar' } ] }
138 # above is equiv to ORDER BY foo ASC, bar DESC
139  
140 =back
141  
142 =item C<limit>
143  
144 Limit how many records will be returned; equivalent to e.g. C<LIMIT 1> in an SQL
145 query. If called in scalar context, an implicit LIMIT 1 will be added to the
146 query anyway, so you needn't add it yourself.
147  
148 =back
149  
150 An example of using options to control the results you get back:
151  
152 # Get the name & phone number of the 10 highest-paid men:
153 database->quick_select(
154 'employees',
155 { gender => 'male' },
156 { order_by => 'salary', limit => 10, columns => [qw(name phone)] }
157 );
158  
159 =cut
160  
161 =item C<offset> number
162  
163 C<Offset> says to skip that many rows before beginning to return rows (postgresql).
164  
165  
166 Example:
167  
168 # Get the name & phone number of the 10 highest-paid men starting from 11th:
169 database->quick_select(
170 'employees',
171 { gender => 'male' },
172 { order_by => 'salary', offset => 10, limit => 10, columns => [qw(name phone)] }
173 );
174  
175  
176 =cut
177  
178 sub quick_select {
179 0 ▶ my ($self, $table_name, $where, $opts) = @_;
Subroutine quick_select: not called CC=4 SCAR=30.0
Pod documented
180  
181 # For backwards compatibility, accept an arrayref of column names as the 3rd
182 # arg, instead of an arrayref of options:
183 0 ▶ if ($opts && ref $opts eq 'ARRAY') {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts and ref $opts eq "ARRAY") 0 0 0
Condition0%0/3
$opts and ref $opts eq "ARRAY"
!ll&&!rl&&r
000
MC/DC0%0/2
$opts and ref $opts eq "ARRAY"
$opts ref $opts eq "ARRAY"
Truth table0%0/3
A and B
A= $optsB= ref $opts eq "ARRAY"
ABresult
0X0
100
111
184 0 $opts = { columns => $opts };
185 }
186  
187 # Make sure to call _quick_query in the same context we were called.
188 # This is a little ugly, rewrite this perhaps.
189 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
190 0 return ($self->_quick_query('SELECT', $table_name, $opts, $where));
191 } else {
192 0 return $self->_quick_query('SELECT', $table_name, $opts, $where);
193 }
194 }
195  
196 =item quick_lookup
197  
198 my $id = database->quick_lookup($table, { email => $params->{'email'} }, 'userid' );
199  
200 This is a bit of syntactic sugar when you just want to lookup a specific
201 field, such as when you're converting an email address to a userid (say
202 during a login handler.)
203  
204 This call always returns a single scalar value, not a hashref of the
205 entire row (or partial row) like most of the other methods in this library.
206  
207 Returns undef when there's no matching row or no such field found in
208 the results.
209  
210 =cut
211  
212 sub quick_lookup {
213 0 ▶ my ($self, $table_name, $where, $data) = @_;
Subroutine quick_lookup: not called CC=3 SCAR=24.8
Pod documented
214 0 my $opts = { columns => [$data] };
215 0 my $row = $self->_quick_query('SELECT', $table_name, $opts, $where);
216  
217 0 ▶ return ( $row && exists $row->{$data} ) ? $row->{$data} : undef;
Branch: 1 branch
BranchTrueFalseTotal
$row && exists $row->{$data} ? : 0 0 0
Condition0%0/3
$row and exists $row->{$data}
!ll&&!rl&&r
000
MC/DC0%0/2
$row and exists $row->{$data}
$row exists $row->{$data}
Truth table0%0/3
A and B
A= $rowB= exists $row->{$data}
ABresult
0X0
100
111
218 }
219  
220 =item quick_count
221  
222 my $count = database->quick_count($table,
223 { email => $params->{'email'} });
224  
225 This is syntactic sugar to return a count of all rows which match your
226 parameters, useful for pagination.
227  
228 This call always returns a single scalar value, not a hashref of the
229 entire row (or partial row) like most of the other methods in this
230 library.
231  
232 =cut
233  
234 sub quick_count {
235 0 ▶ my ($self, $table_name, $where) = @_;
Subroutine quick_count: not called CC=2 SCAR=17.9
Pod documented
236 0 my $opts = {}; #Options are irrelevant for a count.
237 0 my @row = $self->_quick_query('COUNT', $table_name, $opts, $where);
238  
239 0 ▶ return ( @row ) ? $row[0] : undef ;
Branch: 1 branch
BranchTrueFalseTotal
@row ? : 0 0 0
240 }
241  
242 # The 3rd arg, $data, has a different meaning depending on the type of query
243 # (no, I don't like that much; I may refactor this soon to use named params).
244 # For INSERT/UPDATE queries, it'll be a hashref of field => value.
245 # For SELECT queries, it'll be a hashref of additional options.
246 # For DELETE queries, it's unused.
247 sub _quick_query {
248 0 ▶ my ($self, $type, $table_name, $data, $where) = @_;
Subroutine _quick_query: not called CC=17 SCAR=57.2
249
250 # Basic sanity checks first...
251 0 ▶ if ($type !~ m{^ (SELECT|INSERT|UPDATE|DELETE|COUNT) $}x) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($type =~ /^ (SELECT|INSERT|UPDATE|DELETE|COUNT) $/x) 0 0 0
252 0 carp "Unrecognised query type $type!";
253 0 return;
254 }
255 0 ▶ if (!$table_name || ref $table_name) {
Branch: 1 branch
BranchTrueFalseTotal
if (not $table_name or ref $table_name) 0 0 0
Condition0%0/3
not $table_name or ref $table_name
l!l&&r!l&&!r
000
MC/DC0%0/2
not $table_name or ref $table_name
not $table_name ref $table_name
Truth table0%0/3
not(A) or B
A= not $table_nameB= ref $table_name
ABresult
1X1
011
000
256 0 carp "Expected table name as a straight scalar";
257 0 return;
258 }
259 0 ▶ if (($type eq 'INSERT' || $type eq 'UPDATE')
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "INSERT" || $type eq "UPDATE" and !$data || ref $data ne "HASH") 0 0 0
Condition0%0/9
$type eq "INSERT" || $type eq "UPDATE" and !$data || ref $data ne "HASH"
!ll&&!rl&&r
000
$type eq "INSERT" or $type eq "UPDATE"
l!l&&r!l&&!r
000
not $data or ref $data ne "HASH"
l!l&&r!l&&!r
000
MC/DC0%0/4
$type eq "INSERT" || $type eq "UPDATE" and !$data || ref $data ne "HASH"
$type eq "INSERT" $type eq "UPDATE" not $data ref $data ne "HASH"
Truth table0%0/7
A or B and not(C) or D
A= $type eq "INSERT"B= $type eq "UPDATE"C= not $dataD= ref $data ne "HASH"
ABCDresult
00XX0
1X000
01000
1X1X1
1X011
011X1
01011
260 && (!$data || ref $data ne 'HASH'))
261 {
262 0 carp "Expected a hashref of changes";
263 0 return;
264 }
265 0 ▶ if (($type =~ m{^ (SELECT|UPDATE|DELETE|COUNT) $}x)
Branch: 1 branch
BranchTrueFalseTotal
if ($type =~ /^ (SELECT|UPDATE|DELETE|COUNT) $/x and not $where) 0 0 0
Condition0%0/3
$type =~ /^ (SELECT|UPDATE|DELETE|COUNT) $/x and not $where
!ll&&!rl&&r
000
MC/DC0%0/2
$type =~ /^ (SELECT|UPDATE|DELETE|COUNT) $/x and not $where
$type =~ /^ (SELECT|UPDATE|DELETE|COUNT) $/x not $where
Truth table0%0/3
A and not(B)
A= $type =~ /^ (SELECT|UPDATE|DELETE|COUNT) $/xB= not $where
ABresult
0X0
100
111
266 && (!$where)) {
267 0 carp "Expected where conditions";
268 0 return;
269 }
270  
271 # OK, get the SQL we're going to need
272 # TODO: can we replace our own generation with e.g. SQL::Abstract? How much
273 # backwards-incompatible change would that incur?
274 0 my ($sql, @bind_params) = $self->_generate_sql(
275 $type, $table_name, $data, $where
276 );
277  
278  
279 # Dancer::Plugin::Database will have looked at the log_queries setting and
280 # stashed it away for us to see:
281 0 ▶ if ($self->{private_dancer_plugin_database}{log_queries}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->{"private_dancer_plugin_database"}{"log_queries"}) 0 0 0
282 Dancer::Logger::debug(
283 "Executing $type query $sql with params " . join ',',
284 map {
285 0 ▶ defined $_ ?
Branch: 3 branches
BranchTrueFalseTotal
defined $_ ? : 0 0 0
$_ =~ /^[[:ascii:]]+$/ ? : 0 0 0
length $_ > 50 ? : 0 0 0
286 $_ =~ /^[[:ascii:]]+$/ ?
287 length $_ > 50 ? substr($_, 0, 47) . '...' : $_
288 : "[non-ASCII data not logged]" : 'undef'
289 } @bind_params
290 );
291 }
292  
293 # Select queries, in scalar context, return the first matching row; in list
294 # context, they return a list of matching rows.
295 0 ▶ if ($type eq 'SELECT') {
Branch: 2 branches
BranchTrueFalseTotal
if ($type eq 'SELECT') { } 0 0 0
elsif ($type eq 'COUNT') { } 0 0 0
296 0 ▶ if (wantarray) {
Branch: 1 branch
BranchTrueFalseTotal
if (wantarray) { } 0 0 0
297 return @{
298 0 $self->selectall_arrayref(
299 $sql, { Slice => {} }, @bind_params
300 )
301 };
302 } else {
303 0 return $self->selectrow_hashref($sql, undef, @bind_params);
304 }
305  
306 } elsif ($type eq 'COUNT') {
307 0 return $self->selectrow_array($sql, undef, @bind_params);
308 } else {
309 # INSERT/UPDATE/DELETE queries just return the result of DBI's do()
310 0 return $self->do($sql, undef, @bind_params);
311 }
312 }
313  
314 sub _generate_sql {
315 6 ▶ my ($self, $type, $table_name, $data, $where) = @_;
Subroutine _generate_sql: called CC=36 SCAR=45.9
316  
317 6 my $which_cols = '*';
318 6 ▶ my $opts = $type eq 'SELECT' && $data ? $data : {};
Branch: 1 branch
BranchTrueFalseTotal
$type eq 'SELECT' && $data ? : 2 4 6
Condition100%3/3
$type eq "SELECT" and $data
!ll&&!rl&&r
222
MC/DC100%2/2
$type eq "SELECT" and $data
$type eq "SELECT" $data
Truth table100%3/3
A and B
A= $type eq "SELECT"B= $data
ABresult
0X0
100
111
319 6 ▶ if ($opts->{columns}) {
Branch: 1 branch
BranchTrueFalseTotal
if ($opts->{"columns"}) 1 5 6
320 my @cols = (ref $opts->{columns})
321 1 ? @{ $opts->{columns} }
322 1 ▶ : $opts->{columns} ;
Branch: 1 branch
BranchTrueFalseTotal
ref $opts->{'columns'} ? : 1 0 1
323 1 $which_cols = join(',', map { $self->_quote_identifier($_) } @cols);
324 }
325  
326 6 $table_name = $self->_quote_identifier($table_name);
327 6 my @bind_params;
328  
329 my $sql = {
330 SELECT => "SELECT $which_cols FROM $table_name",
331 INSERT => "INSERT INTO $table_name ",
332 UPDATE => "UPDATE $table_name SET ",
333 DELETE => "DELETE FROM $table_name ",
334 COUNT => "SELECT COUNT(*) FROM $table_name",
335 6 }->{$type};
336 6 ▶ if ($type eq 'INSERT') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "INSERT") 1 5 6
337 1 my (@keys, @values);
338 1 for my $key (sort keys %$data) {
339 2 my $value = $data->{$key};
340 2 push @keys, $self->_quote_identifier($key);
341 2 ▶ if (ref $value eq 'SCALAR') {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $value eq 'SCALAR') { } 1 1 2
342 # If it's a scalarref it goes in the SQL as it is; this is a
343 # potential SQL injection risk, but is documented as such - it
344 # allows the user to include arbitrary SQL, at their own risk.
345 1 push @values, $$value;
346 } else {
347 1 push @values, "?";
348 1 push @bind_params, $value;
349 }
350 }
351  
352 1 $sql .= sprintf "(%s) VALUES (%s)",
353 join(',', @keys), join(',', @values);
354 }
355  
356 6 ▶ if ($type eq 'UPDATE') {
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UPDATE") 1 5 6
357 1 my (@keys, @values);
358 $sql .= join ',', map {
359 1 $self->_quote_identifier($_) .'='
360 2 ▶ . (ref $data->{$_} eq 'SCALAR' ? ${$data->{$_}} : "?")
Branch: 1 branch
BranchTrueFalseTotal
ref $data->{$_} eq 'SCALAR' ? : 1 1 2
361 } sort keys %$data;
362 1 push @bind_params, grep { ref $_ ne 'SCALAR' } values %$data;
363 }
364  
365 6 ▶ if ($type eq 'UPDATE' || $type eq 'DELETE' || $type eq 'SELECT' || $type eq 'COUNT')
Branch: 1 branch
BranchTrueFalseTotal
if ($type eq "UPDATE" or $type eq "DELETE" or $type eq "SELECT" or $type eq "COUNT") 4 1 5
Condition77%7/9
$type eq "UPDATE" or $type eq "DELETE" or $type eq "SELECT" or $type eq "COUNT"
l!l&&r!l&&!r
501
$type eq "UPDATE" or $type eq "DELETE" or $type eq "SELECT"
l!l&&r!l&&!r
141
$type eq "UPDATE" or $type eq "DELETE"
l!l&&r!l&&!r
105
MC/DC50%2/4
$type eq "UPDATE" or $type eq "DELETE" or $type eq "SELECT" or $type eq "COUNT"
$type eq "UPDATE" $type eq "DELETE" $type eq "SELECT" $type eq "COUNT"
Truth table60%3/5
A or B or C or D
A= $type eq "UPDATE"B= $type eq "DELETE"C= $type eq "SELECT"D= $type eq "COUNT"
ABCDresult
1XXX1
01XX1
001X1
00011
00000
366 {
367 5 ▶ if ($where && !ref $where) {
Branch: 3 branches
BranchTrueFalseTotal
if ($where and not ref $where) { } 1 4 5
elsif (ref $where eq 'HASH') { } 2 2 4
elsif (ref $where) { } 0 2 2
Condition100%3/3
$where and not ref $where
!ll&&!rl&&r
221
MC/DC100%2/2
$where and not ref $where
$where not ref $where
Truth table100%3/3
A and not(B)
A= $whereB= not ref $where
ABresult
0X0
100
111
368 1 $sql .= " WHERE " . $where;
369 } elsif ( ref $where eq 'HASH' ) {
370 2 my @stmts;
371 2 foreach my $k ( sort keys %$where ) {
372 3 my $v = $where->{$k};
373 3 ▶ if ( ref $v eq 'HASH' ) {
Branch: 1 branch
BranchTrueFalseTotal
if (ref $v eq 'HASH') { } 0 3 3
374 0 my $not = delete $v->{'not'};
375 0 ▶ while (my($op,$value) = each %$v ) {
Branch: 1 branch
BranchTrueFalseTotal
if (() = each %$v) 0 0 0
376 0 my ($cond, $add_bind_param)
377 = $self->_get_where_sql($op, $not, $value);
378 0 push @stmts, $self->_quote_identifier($k) . $cond;
379 0 ▶ push @bind_params, $v->{$op} if $add_bind_param;
Branch: 1 branch
BranchTrueFalseTotal
if $add_bind_param 0 0 0
380 }
381 } else {
382 3 my $clause .= $self->_quote_identifier($k);
383 3 ▶ if ( ! defined $v ) {
Branch: 3 branches
BranchTrueFalseTotal
if (not defined $v) { } 0 3 3
elsif (not ref $v) { } 3 0 3
elsif (ref $v eq 'ARRAY') { } 0 0 0
384 0 $clause .= ' IS NULL';
385 }
386 elsif ( ! ref $v ) {
387 3 $clause .= '=?';
388 3 push @bind_params, $v;
389 }
390 elsif ( ref $v eq 'ARRAY' ) {
391 0 $clause .= ' IN (' . (join ',', map { '?' } @$v) . ')';
392 0 push @bind_params, @$v;
393 }
394 3 push @stmts, $clause;
395 }
396 }
397 2 ▶ $sql .= " WHERE " . join " AND ", @stmts if keys %$where;
Branch: 1 branch
BranchTrueFalseTotal
if keys %$where 2 0 2
398 } elsif (ref $where) {
399 0 carp "Can't handle ref " . ref $where . " for where";
400 0 return;
401 }
402 }
403  
404 # Add an ORDER BY clause, if we want to:
405 6 ▶ if (exists $opts->{order_by} and defined $opts->{order_by}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"order_by"} and defined $opts->{"order_by"}) 0 6 6
Condition33%1/3
exists $opts->{"order_by"} and defined $opts->{"order_by"}
!ll&&!rl&&r
600
MC/DC0%0/2
exists $opts->{"order_by"} and defined $opts->{"order_by"}
exists $opts->{"order_by"} defined $opts->{"order_by"}
Truth table33%1/3
A and B
A= exists $opts->{"order_by"}B= defined $opts->{"order_by"}
ABresult
0X0
100
111
406 0 $sql .= ' ' . $self->_build_order_by_clause($opts->{order_by});
407 }
408  
409  
410 # Add a LIMIT clause if we want to:
411 6 ▶ if (exists $opts->{limit} and defined $opts->{limit}) {
Branch: 2 branches
BranchTrueFalseTotal
if (exists $opts->{'limit'} and defined $opts->{'limit'}) { } 0 6 6
elsif ($type eq 'SELECT' and not wantarray) { } 0 8 8
Condition33%1/3
exists $opts->{"limit"} and defined $opts->{"limit"}
!ll&&!rl&&r
600
MC/DC0%0/2
exists $opts->{"limit"} and defined $opts->{"limit"}
exists $opts->{"limit"} defined $opts->{"limit"}
Truth table33%1/3
A and B
A= exists $opts->{"limit"}B= defined $opts->{"limit"}
ABresult
0X0
100
111
412 0 my $limit = $opts->{limit};
413 0 $limit =~ s/\s+//g;
414 # Check the limit clause is sane - just a number, or two numbers with a
415 # comma between (if using offset,limit )
416 0 ▶ if ($limit =~ m{ ^ \d+ (?: , \d+)? $ }x) {
Branch: 1 branch
BranchTrueFalseTotal
if ($limit =~ / ^ \d+ (?: , \d+)? $ /x) { } 0 0 0
417 # Checked for sanity above so safe to interpolate
418 0 $sql .= " LIMIT $limit";
419 } else {
420 0 die "Invalid LIMIT param $opts->{limit} !";
421 }
422 ▶ } elsif ($type eq 'SELECT' && !wantarray) {
Condition66%2/3
$type eq "SELECT" and not wantarray
!ll&&!rl&&r
240
MC/DC0%0/2
$type eq "SELECT" and not wantarray
$type eq "SELECT" not wantarray
Truth table66%2/3
A and not(B)
A= $type eq "SELECT"B= not wantarray
ABresult
0X0
100
111
423 # We're only returning one row in scalar context, so don't ask for any
424 # more than that
425 0 $sql .= " LIMIT 1";
426 }
427
428 6 ▶ if (exists $opts->{offset} and defined $opts->{offset}) {
Branch: 1 branch
BranchTrueFalseTotal
if (exists $opts->{"offset"} and defined $opts->{"offset"}) 0 6 6
Condition33%1/3
exists $opts->{"offset"} and defined $opts->{"offset"}
!ll&&!rl&&r
600
MC/DC0%0/2
exists $opts->{"offset"} and defined $opts->{"offset"}
exists $opts->{"offset"} defined $opts->{"offset"}
Truth table33%1/3
A and B
A= exists $opts->{"offset"}B= defined $opts->{"offset"}
ABresult
0X0
100
111
429 0 my $offset = $opts->{offset};
430 0 $offset =~ s/\s+//g;
431 0 ▶ if ($offset =~ /^\d+$/) {
Branch: 1 branch
BranchTrueFalseTotal
if ($offset =~ /^\d+$/) { } 0 0 0
432 0 $sql .= " OFFSET $offset";
433 } else {
434 0 die "Invalid OFFSET param $opts->{offset} !";
435 }
436 }
437 6 return ($sql, @bind_params);
438 }
439  
440 sub _get_where_sql {
441 0 ▶ my ($self, $op, $not, $value) = @_;
Subroutine _get_where_sql: not called CC=5 SCAR=34.0
442  
443 0 $op = lc $op;
444  
445 # "IS" needs special-casing, as it will be either "IS NULL" or "IS NOT NULL"
446 # - there's no need to return a bind param for that.
447 0 ▶ if ($op eq 'is') {
Branch: 1 branch
BranchTrueFalseTotal
if ($op eq "is") 0 0 0
448 0 ▶ if (defined $value) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined $value) 0 0 0
449 0 Dancer::Logger::warning(
450 "Using the 'IS' operator only makes sense to test for nullness,"
451 ." but a non-undef value was passed. Did you mean eq/ne?"
452 );
453 }
454 0 ▶ return $not ? 'IS NOT NULL' : 'IS NULL';
Branch: 1 branch
BranchTrueFalseTotal
$not ? : 0 0 0
455 }
456  
457 0 my %st = (
458 'like' => ' LIKE ?',
459 'is' => ' IS ?',
460 'ge' => ' >= ?',
461 'gt' => ' > ?',
462 'le' => ' <= ?',
463 'lt' => ' < ?',
464 'eq' => ' = ?',
465 'ne' => ' != ?',
466 );
467  
468 # Return the appropriate SQL, and indicate that the value should be added to
469 # the bind params
470 0 ▶ return (($not ? ' NOT' . $st{$op} : $st{$op}), 1);
Branch: 1 branch
BranchTrueFalseTotal
$not ? : 0 0 0
471 }
472  
473 # Given either a column name, or a hashref of e.g. { asc => 'colname' },
474 # or an arrayref of either, construct an ORDER BY clause (quoting col names)
475 # e.g.:
476 # 'foo' => ORDER BY foo
477 # { asc => 'foo' } => ORDER BY foo ASC
478 # ['foo', 'bar'] => ORDER BY foo, bar
479 # [ { asc => 'foo' }, { desc => 'bar' } ]
480 # => 'ORDER BY foo ASC, bar DESC
481 sub _build_order_by_clause {
482 4 ▶ my ($self, $in) = @_;
Subroutine _build_order_by_clause: called CC=7 SCAR=19.8
483  
484 # Input could be a straight scalar, or a hashref, or an arrayref of either
485 # straight scalars or hashrefs. Turn a straight scalar into an arrayref to
486 # avoid repeating ourselves.
487 4 ▶ $in = [ $in ] unless ref $in eq 'ARRAY';
Branch: 1 branch
BranchTrueFalseTotal
unless ref $in eq "ARRAY" 2 2 4
488  
489 # Now, for each of the fields given, add them to the clause
490 4 my @sort_fields;
491 4 for my $field (@$in) {
492 6 ▶ if (!ref $field) {
Branch: 2 branches
BranchTrueFalseTotal
if (not ref $field) { } 3 3 6
elsif (ref $field eq 'HASH') { } 3 0 3
493 3 push @sort_fields, $self->_quote_identifier($field);
494 } elsif (ref $field eq 'HASH') {
495 3 my ($order, $name) = %$field;
496 3 $order = uc $order;
497 3 ▶ if ($order ne 'ASC' && $order ne 'DESC') {
Branch: 1 branch
BranchTrueFalseTotal
if ($order ne "ASC" and $order ne "DESC") 0 3 3
Condition66%2/3
$order ne "ASC" and $order ne "DESC"
!ll&&!rl&&r
210
MC/DC0%0/2
$order ne "ASC" and $order ne "DESC"
$order ne "ASC" $order ne "DESC"
Truth table66%2/3
A and B
A= $order ne "ASC"B= $order ne "DESC"
ABresult
0X0
100
111
498 0 die "Invalid sort order $order used in order_by option!";
499 }
500 # $order has been checked to be 'ASC' or 'DESC' above, so safe to
501 # interpolate
502 3 push @sort_fields, $self->_quote_identifier($name) . " $order";
503 }
504 }
505  
506 4 return "ORDER BY " . join ', ', @sort_fields;
507 }
508  
509 # A wrapper around DBI's quote_identifier which first splits on ".", so that
510 # e.g. database.table gets quoted as `database`.`table`, not `database.table`
511 sub _quote_identifier {
512 23 ▶ my ($self, $identifier) = @_;
Subroutine _quote_identifier: called CC=1 SCAR=0.0
513  
514 return join '.', map {
515 23 $self->quote_identifier($_)
516 } split /\./, $identifier;
517 }
518  
519 =back
520  
521 All of the convenience methods provided take care to quote table and column
522 names using DBI's C<quote_identifier>, and use parameterised queries to avoid
523 SQL injection attacks. See L<http://www.bobby-tables.com/> for why this is
524 important, if you're not familiar with it.
525  
526  
527 =head1 WHERE clauses as hashrefs
528  
529 C<quick_update>, C<quick_delete> and C<quick_select> take a hashref of WHERE
530 clauses. This is a hashref of field => 'value', each of which will be
531 included in the WHERE clause used, for instance:
532  
533 { id => 42 }
534  
535 Will result in an SQL query which would include:
536  
537 WHERE id = 42
538  
539 When more than one field => value pair is given, they will be ANDed together:
540  
541 { foo => 'Bar', bar => 'Baz' }
542  
543 Will result in:
544  
545 WHERE foo = 'Bar' AND bar = 'Baz'
546  
547 (Actually, parameterised queries will be used, with placeholders, so SQL
548 injection attacks will not work, but it's easier to illustrate as though the
549 values were interpolated directly. Don't worry, they're not.)
550  
551 With the same idea in mind, you can check if a value is NULL with:
552  
553 { foo => undef }
554  
555 This will be correctly rewritten to C<foo IS NULL>.
556  
557 You can pass an empty hashref if you want all rows, e.g.:
558  
559 database->quick_select('mytable', {});
560  
561 ... is the same as C<"SELECT * FROM 'mytable'">
562  
563 If you pass in an arrayref as the value, you can get a set clause as in the
564 following example:
565  
566 { foo => [ 'bar', 'baz', 'quux' ] }
567  
568 ... it's the same as C<WHERE foo IN ('bar', 'baz', 'quux')>
569  
570 If you need additional flexibility, you can build fairly complex where
571 clauses by passing a hashref of condition operators and values as the
572 value to the column field key.
573  
574 Currently recognized operators are:
575  
576 =over
577  
578 =item 'like'
579  
580 { foo => { 'like' => '%bar%' } }
581  
582 ... same as C<WHERE foo LIKE '%bar%'>
583  
584 =item 'gt' / 'ge'
585  
586 'greater than' or 'greater or equal to'
587
588 { foo => { 'ge' => '42' } }
589  
590 ... same as C<WHERE foo E<gt>= '42'>
591  
592 =item 'lt' / 'le'
593  
594 'less than' or 'less or equal to'
595  
596 { foo => { 'lt' => '42' } }
597  
598 ... same as C<WHERE foo E<lt> '42'>
599  
600 =item 'eq' / 'ne' / 'is'
601  
602 'equal' or 'not equal' or 'is'
603  
604 { foo => { 'ne' => 'bar' } }
605  
606 ... same as C<WHERE foo != 'bar'>
607  
608 =back
609  
610 You can also include a key named 'not' with a true value in the hashref
611 which will (attempt) to negate the other operator(s).
612  
613 { foo => { 'like' => '%bar%', 'not' => 1 } }
614  
615 ... same as C<WHERE foo NOT LIKE '%bar%'>
616  
617 If you use undef as the value for an operator hashref it will be
618 replaced with 'NULL' in the query.
619  
620 If that's not flexible enough, you can pass in your own scalar WHERE clause
621 string B<BUT> there's no automatic sanitation on that - if you suffer
622 from a SQL injection attack - don't blame me!
623 Don't forget to use C<quote()>/C<quote_identifier()> on it then.
624  
625 =head1 AUTHOR
626  
627 David Precious C< <<davidp@preshweb.co.uk >> >
628  
629 =head1 ACKNOWLEDGEMENTS
630  
631 See L<Dancer::Plugin::Database/ACKNOWLEDGEMENTS>
632  
633 =head1 SEE ALSO
634  
635 L<Dancer::Plugin::Database> and L<Dancer2::Plugin::Database>
636  
637 L<Dancer> and L<Dancer2>
638  
639 L<DBI>
640  
641 =cut
642  
643 3 1;
644 __END__
« Core.pm ↑ Summary