Commit | Line | Data |
96449e8e |
1 | package SQL::Abstract; # see doc at end of file |
2 | |
3 | # LDNOTE : this code is heavy refactoring from original SQLA. |
4 | # Several design decisions will need discussion during |
5 | # the test / diffusion / acceptance phase; those are marked with flag |
6 | # 'LDNOTE' (note by laurent.dami AT free.fr) |
7 | |
96449e8e |
8 | use strict; |
9 | use warnings; |
9d9d5bd6 |
10 | use Carp (); |
312d830b |
11 | use List::Util (); |
12 | use Scalar::Util (); |
96449e8e |
13 | |
14 | #====================================================================== |
15 | # GLOBALS |
16 | #====================================================================== |
17 | |
64b9e432 |
18 | our $VERSION = '1.72'; |
7479e27e |
19 | |
22f1a437 |
20 | # This would confuse some packagers |
c520207b |
21 | $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases |
96449e8e |
22 | |
23 | our $AUTOLOAD; |
24 | |
25 | # special operators (-in, -between). May be extended/overridden by user. |
26 | # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation |
27 | my @BUILTIN_SPECIAL_OPS = ( |
b8db59b8 |
28 | {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'}, |
29 | {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'}, |
96449e8e |
30 | ); |
31 | |
97a920ef |
32 | # unaryish operators - key maps to handler |
59f23b3d |
33 | my @BUILTIN_UNARY_OPS = ( |
a47b433a |
34 | # the digits are backcompat stuff |
b8db59b8 |
35 | { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, |
36 | { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' }, |
37 | { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' }, |
38 | { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' }, |
59f23b3d |
39 | ); |
97a920ef |
40 | |
96449e8e |
41 | #====================================================================== |
42 | # DEBUGGING AND ERROR REPORTING |
43 | #====================================================================== |
44 | |
45 | sub _debug { |
46 | return unless $_[0]->{debug}; shift; # a little faster |
47 | my $func = (caller(1))[3]; |
48 | warn "[$func] ", @_, "\n"; |
49 | } |
50 | |
51 | sub belch (@) { |
52 | my($func) = (caller(1))[3]; |
9d9d5bd6 |
53 | Carp::carp "[$func] Warning: ", @_; |
96449e8e |
54 | } |
55 | |
56 | sub puke (@) { |
57 | my($func) = (caller(1))[3]; |
9d9d5bd6 |
58 | Carp::croak "[$func] Fatal: ", @_; |
96449e8e |
59 | } |
60 | |
61 | |
62 | #====================================================================== |
63 | # NEW |
64 | #====================================================================== |
65 | |
66 | sub new { |
67 | my $self = shift; |
68 | my $class = ref($self) || $self; |
69 | my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_; |
70 | |
71 | # choose our case by keeping an option around |
72 | delete $opt{case} if $opt{case} && $opt{case} ne 'lower'; |
73 | |
74 | # default logic for interpreting arrayrefs |
ef559da3 |
75 | $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR'; |
96449e8e |
76 | |
77 | # how to return bind vars |
78 | # LDNOTE: changed nwiger code : why this 'delete' ?? |
79 | # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal'; |
80 | $opt{bindtype} ||= 'normal'; |
81 | |
82 | # default comparison is "=", but can be overridden |
83 | $opt{cmp} ||= '='; |
84 | |
85 | # try to recognize which are the 'equality' and 'unequality' ops |
86 | # (temporary quickfix, should go through a more seasoned API) |
2281c758 |
87 | $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i; |
88 | $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i; |
96449e8e |
89 | |
90 | # SQL booleans |
91 | $opt{sqltrue} ||= '1=1'; |
92 | $opt{sqlfalse} ||= '0=1'; |
93 | |
9d48860e |
94 | # special operators |
96449e8e |
95 | $opt{special_ops} ||= []; |
b6251592 |
96 | # regexes are applied in order, thus push after user-defines |
96449e8e |
97 | push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS; |
98 | |
9d48860e |
99 | # unary operators |
59f23b3d |
100 | $opt{unary_ops} ||= []; |
101 | push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS; |
102 | |
b6251592 |
103 | # rudimentary saniy-check for user supplied bits treated as functions/operators |
104 | # If a purported function matches this regular expression, an exception is thrown. |
105 | # Literal SQL is *NOT* subject to this check, only functions (and column names |
106 | # when quoting is not in effect) |
96449e8e |
107 | |
b6251592 |
108 | # FIXME |
109 | # need to guard against ()'s in column names too, but this will break tons of |
110 | # hacks... ideas anyone? |
111 | $opt{injection_guard} ||= qr/ |
112 | \; |
113 | | |
114 | ^ \s* go \s |
115 | /xmi; |
96449e8e |
116 | |
b6251592 |
117 | return bless \%opt, $class; |
118 | } |
96449e8e |
119 | |
170e6c33 |
120 | |
121 | sub _assert_pass_injection_guard { |
122 | if ($_[1] =~ $_[0]->{injection_guard}) { |
123 | my $class = ref $_[0]; |
124 | puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the " |
125 | . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own " |
126 | . "{injection_guard} attribute to ${class}->new()" |
127 | } |
128 | } |
129 | |
130 | |
96449e8e |
131 | #====================================================================== |
132 | # INSERT methods |
133 | #====================================================================== |
134 | |
135 | sub insert { |
02288357 |
136 | my $self = shift; |
137 | my $table = $self->_table(shift); |
138 | my $data = shift || return; |
139 | my $options = shift; |
96449e8e |
140 | |
141 | my $method = $self->_METHOD_FOR_refkind("_insert", $data); |
02288357 |
142 | my ($sql, @bind) = $self->$method($data); |
96449e8e |
143 | $sql = join " ", $self->_sqlcase('insert into'), $table, $sql; |
02288357 |
144 | |
e82e648a |
145 | if ($options->{returning}) { |
146 | my ($s, @b) = $self->_insert_returning ($options); |
147 | $sql .= $s; |
148 | push @bind, @b; |
02288357 |
149 | } |
150 | |
96449e8e |
151 | return wantarray ? ($sql, @bind) : $sql; |
152 | } |
153 | |
6b1fe79d |
154 | sub _insert_returning { |
e82e648a |
155 | my ($self, $options) = @_; |
6b1fe79d |
156 | |
e82e648a |
157 | my $f = $options->{returning}; |
158 | |
159 | my $fieldlist = $self->_SWITCH_refkind($f, { |
160 | ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;}, |
161 | SCALAR => sub {$self->_quote($f)}, |
162 | SCALARREF => sub {$$f}, |
6b1fe79d |
163 | }); |
e82e648a |
164 | return $self->_sqlcase(' returning ') . $fieldlist; |
6b1fe79d |
165 | } |
166 | |
96449e8e |
167 | sub _insert_HASHREF { # explicit list of fields and then values |
168 | my ($self, $data) = @_; |
169 | |
170 | my @fields = sort keys %$data; |
171 | |
fe3ae272 |
172 | my ($sql, @bind) = $self->_insert_values($data); |
96449e8e |
173 | |
174 | # assemble SQL |
175 | $_ = $self->_quote($_) foreach @fields; |
176 | $sql = "( ".join(", ", @fields).") ".$sql; |
177 | |
178 | return ($sql, @bind); |
179 | } |
180 | |
181 | sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields) |
182 | my ($self, $data) = @_; |
183 | |
184 | # no names (arrayref) so can't generate bindtype |
185 | $self->{bindtype} ne 'columns' |
186 | or belch "can't do 'columns' bindtype when called with arrayref"; |
187 | |
fe3ae272 |
188 | # fold the list of values into a hash of column name - value pairs |
189 | # (where the column names are artificially generated, and their |
190 | # lexicographical ordering keep the ordering of the original list) |
191 | my $i = "a"; # incremented values will be in lexicographical order |
192 | my $data_in_hash = { map { ($i++ => $_) } @$data }; |
193 | |
194 | return $self->_insert_values($data_in_hash); |
195 | } |
196 | |
197 | sub _insert_ARRAYREFREF { # literal SQL with bind |
198 | my ($self, $data) = @_; |
199 | |
200 | my ($sql, @bind) = @${$data}; |
201 | $self->_assert_bindval_matches_bindtype(@bind); |
202 | |
203 | return ($sql, @bind); |
204 | } |
205 | |
206 | |
207 | sub _insert_SCALARREF { # literal SQL without bind |
208 | my ($self, $data) = @_; |
209 | |
210 | return ($$data); |
211 | } |
212 | |
213 | sub _insert_values { |
214 | my ($self, $data) = @_; |
215 | |
96449e8e |
216 | my (@values, @all_bind); |
fe3ae272 |
217 | foreach my $column (sort keys %$data) { |
218 | my $v = $data->{$column}; |
96449e8e |
219 | |
220 | $self->_SWITCH_refkind($v, { |
221 | |
9d48860e |
222 | ARRAYREF => sub { |
96449e8e |
223 | if ($self->{array_datatypes}) { # if array datatype are activated |
224 | push @values, '?'; |
fe3ae272 |
225 | push @all_bind, $self->_bindtype($column, $v); |
96449e8e |
226 | } |
227 | else { # else literal SQL with bind |
228 | my ($sql, @bind) = @$v; |
fe3ae272 |
229 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
230 | push @values, $sql; |
231 | push @all_bind, @bind; |
232 | } |
233 | }, |
234 | |
235 | ARRAYREFREF => sub { # literal SQL with bind |
236 | my ($sql, @bind) = @${$v}; |
fe3ae272 |
237 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
238 | push @values, $sql; |
239 | push @all_bind, @bind; |
240 | }, |
241 | |
9d48860e |
242 | # THINK : anything useful to do with a HASHREF ? |
5db47f9f |
243 | HASHREF => sub { # (nothing, but old SQLA passed it through) |
244 | #TODO in SQLA >= 2.0 it will die instead |
245 | belch "HASH ref as bind value in insert is not supported"; |
246 | push @values, '?'; |
fe3ae272 |
247 | push @all_bind, $self->_bindtype($column, $v); |
5db47f9f |
248 | }, |
96449e8e |
249 | |
250 | SCALARREF => sub { # literal SQL without bind |
251 | push @values, $$v; |
252 | }, |
253 | |
254 | SCALAR_or_UNDEF => sub { |
255 | push @values, '?'; |
fe3ae272 |
256 | push @all_bind, $self->_bindtype($column, $v); |
96449e8e |
257 | }, |
258 | |
259 | }); |
260 | |
261 | } |
262 | |
263 | my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )"; |
264 | return ($sql, @all_bind); |
265 | } |
266 | |
267 | |
96449e8e |
268 | |
269 | #====================================================================== |
270 | # UPDATE methods |
271 | #====================================================================== |
272 | |
273 | |
274 | sub update { |
275 | my $self = shift; |
276 | my $table = $self->_table(shift); |
277 | my $data = shift || return; |
278 | my $where = shift; |
279 | |
280 | # first build the 'SET' part of the sql statement |
281 | my (@set, @all_bind); |
282 | puke "Unsupported data type specified to \$sql->update" |
283 | unless ref $data eq 'HASH'; |
284 | |
285 | for my $k (sort keys %$data) { |
286 | my $v = $data->{$k}; |
287 | my $r = ref $v; |
288 | my $label = $self->_quote($k); |
289 | |
290 | $self->_SWITCH_refkind($v, { |
9d48860e |
291 | ARRAYREF => sub { |
96449e8e |
292 | if ($self->{array_datatypes}) { # array datatype |
293 | push @set, "$label = ?"; |
294 | push @all_bind, $self->_bindtype($k, $v); |
295 | } |
296 | else { # literal SQL with bind |
297 | my ($sql, @bind) = @$v; |
fe3ae272 |
298 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
299 | push @set, "$label = $sql"; |
fe3ae272 |
300 | push @all_bind, @bind; |
96449e8e |
301 | } |
302 | }, |
303 | ARRAYREFREF => sub { # literal SQL with bind |
304 | my ($sql, @bind) = @${$v}; |
fe3ae272 |
305 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
306 | push @set, "$label = $sql"; |
fe3ae272 |
307 | push @all_bind, @bind; |
96449e8e |
308 | }, |
309 | SCALARREF => sub { # literal SQL without bind |
310 | push @set, "$label = $$v"; |
0ec3aec7 |
311 | }, |
312 | HASHREF => sub { |
313 | my ($op, $arg, @rest) = %$v; |
314 | |
315 | puke 'Operator calls in update must be in the form { -op => $arg }' |
316 | if (@rest or not $op =~ /^\-(.+)/); |
317 | |
318 | local $self->{_nested_func_lhs} = $k; |
319 | my ($sql, @bind) = $self->_where_unary_op ($1, $arg); |
320 | |
321 | push @set, "$label = $sql"; |
322 | push @all_bind, @bind; |
323 | }, |
96449e8e |
324 | SCALAR_or_UNDEF => sub { |
325 | push @set, "$label = ?"; |
326 | push @all_bind, $self->_bindtype($k, $v); |
327 | }, |
328 | }); |
329 | } |
330 | |
331 | # generate sql |
332 | my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ') |
333 | . join ', ', @set; |
334 | |
335 | if ($where) { |
336 | my($where_sql, @where_bind) = $self->where($where); |
337 | $sql .= $where_sql; |
338 | push @all_bind, @where_bind; |
339 | } |
340 | |
341 | return wantarray ? ($sql, @all_bind) : $sql; |
342 | } |
343 | |
344 | |
345 | |
346 | |
347 | #====================================================================== |
348 | # SELECT |
349 | #====================================================================== |
350 | |
351 | |
352 | sub select { |
353 | my $self = shift; |
354 | my $table = $self->_table(shift); |
355 | my $fields = shift || '*'; |
356 | my $where = shift; |
357 | my $order = shift; |
358 | |
359 | my($where_sql, @bind) = $self->where($where, $order); |
360 | |
361 | my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields |
362 | : $fields; |
9d48860e |
363 | my $sql = join(' ', $self->_sqlcase('select'), $f, |
96449e8e |
364 | $self->_sqlcase('from'), $table) |
365 | . $where_sql; |
366 | |
9d48860e |
367 | return wantarray ? ($sql, @bind) : $sql; |
96449e8e |
368 | } |
369 | |
370 | #====================================================================== |
371 | # DELETE |
372 | #====================================================================== |
373 | |
374 | |
375 | sub delete { |
376 | my $self = shift; |
377 | my $table = $self->_table(shift); |
378 | my $where = shift; |
379 | |
380 | |
381 | my($where_sql, @bind) = $self->where($where); |
382 | my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql; |
383 | |
9d48860e |
384 | return wantarray ? ($sql, @bind) : $sql; |
96449e8e |
385 | } |
386 | |
387 | |
388 | #====================================================================== |
389 | # WHERE: entry point |
390 | #====================================================================== |
391 | |
392 | |
393 | |
394 | # Finally, a separate routine just to handle WHERE clauses |
395 | sub where { |
396 | my ($self, $where, $order) = @_; |
397 | |
398 | # where ? |
399 | my ($sql, @bind) = $self->_recurse_where($where); |
400 | $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : ''; |
401 | |
402 | # order by? |
403 | if ($order) { |
404 | $sql .= $self->_order_by($order); |
405 | } |
406 | |
9d48860e |
407 | return wantarray ? ($sql, @bind) : $sql; |
96449e8e |
408 | } |
409 | |
410 | |
411 | sub _recurse_where { |
412 | my ($self, $where, $logic) = @_; |
413 | |
414 | # dispatch on appropriate method according to refkind of $where |
415 | my $method = $self->_METHOD_FOR_refkind("_where", $where); |
311b2151 |
416 | |
9d48860e |
417 | my ($sql, @bind) = $self->$method($where, $logic); |
311b2151 |
418 | |
9d48860e |
419 | # DBIx::Class directly calls _recurse_where in scalar context, so |
311b2151 |
420 | # we must implement it, even if not in the official API |
9d48860e |
421 | return wantarray ? ($sql, @bind) : $sql; |
96449e8e |
422 | } |
423 | |
424 | |
425 | |
426 | #====================================================================== |
427 | # WHERE: top-level ARRAYREF |
428 | #====================================================================== |
429 | |
430 | |
431 | sub _where_ARRAYREF { |
5e1d09d5 |
432 | my ($self, $where, $logic) = @_; |
96449e8e |
433 | |
5e1d09d5 |
434 | $logic = uc($logic || $self->{logic}); |
96449e8e |
435 | $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic"; |
436 | |
437 | my @clauses = @$where; |
438 | |
96449e8e |
439 | my (@sql_clauses, @all_bind); |
96449e8e |
440 | # need to use while() so can shift() for pairs |
9d48860e |
441 | while (my $el = shift @clauses) { |
96449e8e |
442 | |
443 | # switch according to kind of $el and get corresponding ($sql, @bind) |
444 | my ($sql, @bind) = $self->_SWITCH_refkind($el, { |
445 | |
446 | # skip empty elements, otherwise get invalid trailing AND stuff |
447 | ARRAYREF => sub {$self->_recurse_where($el) if @$el}, |
448 | |
c94a6c93 |
449 | ARRAYREFREF => sub { |
450 | my ($s, @b) = @$$el; |
451 | $self->_assert_bindval_matches_bindtype(@b); |
452 | ($s, @b); |
453 | }, |
474e3335 |
454 | |
96449e8e |
455 | HASHREF => sub {$self->_recurse_where($el, 'and') if %$el}, |
456 | # LDNOTE : previous SQLA code for hashrefs was creating a dirty |
457 | # side-effect: the first hashref within an array would change |
458 | # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ] |
9d48860e |
459 | # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)", |
96449e8e |
460 | # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)". |
461 | |
462 | SCALARREF => sub { ($$el); }, |
463 | |
464 | SCALAR => sub {# top-level arrayref with scalars, recurse in pairs |
465 | $self->_recurse_where({$el => shift(@clauses)})}, |
466 | |
467 | UNDEF => sub {puke "not supported : UNDEF in arrayref" }, |
468 | }); |
469 | |
4b7b6026 |
470 | if ($sql) { |
471 | push @sql_clauses, $sql; |
472 | push @all_bind, @bind; |
473 | } |
96449e8e |
474 | } |
475 | |
476 | return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind); |
477 | } |
478 | |
474e3335 |
479 | #====================================================================== |
480 | # WHERE: top-level ARRAYREFREF |
481 | #====================================================================== |
96449e8e |
482 | |
474e3335 |
483 | sub _where_ARRAYREFREF { |
484 | my ($self, $where) = @_; |
c94a6c93 |
485 | my ($sql, @bind) = @$$where; |
486 | $self->_assert_bindval_matches_bindtype(@bind); |
474e3335 |
487 | return ($sql, @bind); |
488 | } |
96449e8e |
489 | |
490 | #====================================================================== |
491 | # WHERE: top-level HASHREF |
492 | #====================================================================== |
493 | |
494 | sub _where_HASHREF { |
495 | my ($self, $where) = @_; |
496 | my (@sql_clauses, @all_bind); |
497 | |
2281c758 |
498 | for my $k (sort keys %$where) { |
96449e8e |
499 | my $v = $where->{$k}; |
500 | |
2281c758 |
501 | # ($k => $v) is either a special unary op or a regular hashpair |
502 | my ($sql, @bind) = do { |
503 | if ($k =~ /^-./) { |
504 | # put the operator in canonical form |
505 | my $op = $k; |
b8db59b8 |
506 | $op = substr $op, 1; # remove initial dash |
2281c758 |
507 | $op =~ s/^\s+|\s+$//g;# remove leading/trailing space |
b8db59b8 |
508 | $op =~ s/\s+/ /g; # compress whitespace |
509 | |
510 | # so that -not_foo works correctly |
511 | $op =~ s/^not_/NOT /i; |
2281c758 |
512 | |
513 | $self->_debug("Unary OP(-$op) within hashref, recursing..."); |
0ec3aec7 |
514 | my ($s, @b) = $self->_where_unary_op ($op, $v); |
515 | |
516 | # top level vs nested |
517 | # we assume that handled unary ops will take care of their ()s |
518 | $s = "($s)" unless ( |
519 | List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}} |
520 | or |
521 | defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k) |
522 | ); |
523 | ($s, @b); |
2281c758 |
524 | } |
525 | else { |
526 | my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v); |
527 | $self->$method($k, $v); |
528 | } |
529 | }; |
96449e8e |
530 | |
531 | push @sql_clauses, $sql; |
532 | push @all_bind, @bind; |
533 | } |
534 | |
535 | return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind); |
536 | } |
537 | |
0ec3aec7 |
538 | sub _where_unary_op { |
2281c758 |
539 | my ($self, $op, $rhs) = @_; |
96449e8e |
540 | |
0ec3aec7 |
541 | if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) { |
542 | my $handler = $op_entry->{handler}; |
543 | |
544 | if (not ref $handler) { |
545 | if ($op =~ s/ [_\s]? \d+ $//x ) { |
546 | belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. ' |
547 | . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]"; |
548 | } |
549 | return $self->$handler ($op, $rhs); |
550 | } |
551 | elsif (ref $handler eq 'CODE') { |
552 | return $handler->($self, $op, $rhs); |
553 | } |
554 | else { |
555 | puke "Illegal handler for operator $op - expecting a method name or a coderef"; |
556 | } |
557 | } |
558 | |
3d86e3b1 |
559 | $self->_debug("Generic unary OP: $op - recursing as function"); |
0ec3aec7 |
560 | |
170e6c33 |
561 | $self->_assert_pass_injection_guard($op); |
b6251592 |
562 | |
2281c758 |
563 | my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, { |
564 | SCALAR => sub { |
a7661cfc |
565 | puke "Illegal use of top-level '$op'" |
566 | unless $self->{_nested_func_lhs}; |
567 | |
568 | return ( |
569 | $self->_convert('?'), |
570 | $self->_bindtype($self->{_nested_func_lhs}, $rhs) |
571 | ); |
2281c758 |
572 | }, |
573 | FALLBACK => sub { |
574 | $self->_recurse_where ($rhs) |
575 | }, |
576 | }); |
96449e8e |
577 | |
953d164e |
578 | $sql = sprintf ('%s %s', |
2281c758 |
579 | $self->_sqlcase($op), |
953d164e |
580 | $sql, |
2281c758 |
581 | ); |
96449e8e |
582 | |
2281c758 |
583 | return ($sql, @bind); |
97a920ef |
584 | } |
585 | |
586 | sub _where_op_ANDOR { |
2281c758 |
587 | my ($self, $op, $v) = @_; |
97a920ef |
588 | |
589 | $self->_SWITCH_refkind($v, { |
590 | ARRAYREF => sub { |
591 | return $self->_where_ARRAYREF($v, $op); |
592 | }, |
593 | |
594 | HASHREF => sub { |
59f23b3d |
595 | return ( $op =~ /^or/i ) |
97a920ef |
596 | ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op ) |
597 | : $self->_where_HASHREF($v); |
598 | }, |
599 | |
9d48860e |
600 | SCALARREF => sub { |
48d9f5f8 |
601 | puke "-$op => \\\$scalar makes little sense, use " . |
a0d6d323 |
602 | ($op =~ /^or/i |
48d9f5f8 |
603 | ? '[ \$scalar, \%rest_of_conditions ] instead' |
604 | : '-and => [ \$scalar, \%rest_of_conditions ] instead' |
605 | ); |
97a920ef |
606 | }, |
607 | |
608 | ARRAYREFREF => sub { |
48d9f5f8 |
609 | puke "-$op => \\[...] makes little sense, use " . |
a0d6d323 |
610 | ($op =~ /^or/i |
48d9f5f8 |
611 | ? '[ \[...], \%rest_of_conditions ] instead' |
612 | : '-and => [ \[...], \%rest_of_conditions ] instead' |
613 | ); |
97a920ef |
614 | }, |
615 | |
616 | SCALAR => sub { # permissively interpreted as SQL |
48d9f5f8 |
617 | puke "-$op => \$value makes little sense, use -bool => \$value instead"; |
97a920ef |
618 | }, |
619 | |
620 | UNDEF => sub { |
621 | puke "-$op => undef not supported"; |
622 | }, |
623 | }); |
624 | } |
625 | |
626 | sub _where_op_NEST { |
9d48860e |
627 | my ($self, $op, $v) = @_; |
97a920ef |
628 | |
96449e8e |
629 | $self->_SWITCH_refkind($v, { |
630 | |
96449e8e |
631 | SCALAR => sub { # permissively interpreted as SQL |
01a01e57 |
632 | belch "literal SQL should be -nest => \\'scalar' " |
633 | . "instead of -nest => 'scalar' "; |
9d48860e |
634 | return ($v); |
96449e8e |
635 | }, |
636 | |
637 | UNDEF => sub { |
638 | puke "-$op => undef not supported"; |
639 | }, |
e9501094 |
640 | |
641 | FALLBACK => sub { |
642 | $self->_recurse_where ($v); |
643 | }, |
644 | |
96449e8e |
645 | }); |
646 | } |
647 | |
648 | |
97a920ef |
649 | sub _where_op_BOOL { |
9d48860e |
650 | my ($self, $op, $v) = @_; |
97a920ef |
651 | |
b8db59b8 |
652 | my ($s, @b) = $self->_SWITCH_refkind($v, { |
653 | SCALAR => sub { # interpreted as SQL column |
654 | $self->_convert($self->_quote($v)); |
655 | }, |
ef03f1bc |
656 | |
b8db59b8 |
657 | UNDEF => sub { |
658 | puke "-$op => undef not supported"; |
659 | }, |
97a920ef |
660 | |
b8db59b8 |
661 | FALLBACK => sub { |
662 | $self->_recurse_where ($v); |
663 | }, |
664 | }); |
ef03f1bc |
665 | |
b8db59b8 |
666 | $s = "(NOT $s)" if $op =~ /^not/i; |
667 | ($s, @b); |
97a920ef |
668 | } |
669 | |
670 | |
96449e8e |
671 | sub _where_hashpair_ARRAYREF { |
672 | my ($self, $k, $v) = @_; |
673 | |
674 | if( @$v ) { |
675 | my @v = @$v; # need copy because of shift below |
676 | $self->_debug("ARRAY($k) means distribute over elements"); |
677 | |
678 | # put apart first element if it is an operator (-and, -or) |
e3cecb45 |
679 | my $op = ( |
680 | (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix) |
681 | ? shift @v |
682 | : '' |
04d940de |
683 | ); |
96449e8e |
684 | my @distributed = map { {$k => $_} } @v; |
04d940de |
685 | |
686 | if ($op) { |
687 | $self->_debug("OP($op) reinjected into the distributed array"); |
688 | unshift @distributed, $op; |
689 | } |
690 | |
f67591bf |
691 | my $logic = $op ? substr($op, 1) : ''; |
96449e8e |
692 | |
f67591bf |
693 | return $self->_recurse_where(\@distributed, $logic); |
9d48860e |
694 | } |
96449e8e |
695 | else { |
696 | # LDNOTE : not sure of this one. What does "distribute over nothing" mean? |
697 | $self->_debug("empty ARRAY($k) means 0=1"); |
698 | return ($self->{sqlfalse}); |
699 | } |
700 | } |
701 | |
702 | sub _where_hashpair_HASHREF { |
eb49170d |
703 | my ($self, $k, $v, $logic) = @_; |
704 | $logic ||= 'and'; |
96449e8e |
705 | |
a7661cfc |
706 | local $self->{_nested_func_lhs} = $self->{_nested_func_lhs}; |
a7661cfc |
707 | |
eb49170d |
708 | my ($all_sql, @all_bind); |
96449e8e |
709 | |
a47b433a |
710 | for my $orig_op (sort keys %$v) { |
711 | my $val = $v->{$orig_op}; |
96449e8e |
712 | |
713 | # put the operator in canonical form |
a47b433a |
714 | my $op = $orig_op; |
b8db59b8 |
715 | |
716 | # FIXME - we need to phase out dash-less ops |
717 | $op =~ s/^-//; # remove possible initial dash |
a47b433a |
718 | $op =~ s/^\s+|\s+$//g;# remove leading/trailing space |
b8db59b8 |
719 | $op =~ s/\s+/ /g; # compress whitespace |
720 | |
170e6c33 |
721 | $self->_assert_pass_injection_guard($op); |
b6251592 |
722 | |
b8db59b8 |
723 | # so that -not_foo works correctly |
724 | $op =~ s/^not_/NOT /i; |
96449e8e |
725 | |
726 | my ($sql, @bind); |
727 | |
2281c758 |
728 | # CASE: col-value logic modifiers |
729 | if ( $orig_op =~ /^ \- (and|or) $/xi ) { |
730 | ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1); |
731 | } |
96449e8e |
732 | # CASE: special operators like -in or -between |
312d830b |
733 | elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) { |
3a2e1a5e |
734 | my $handler = $special_op->{handler}; |
735 | if (! $handler) { |
a47b433a |
736 | puke "No handler supplied for special operator $orig_op"; |
3a2e1a5e |
737 | } |
738 | elsif (not ref $handler) { |
739 | ($sql, @bind) = $self->$handler ($k, $op, $val); |
740 | } |
741 | elsif (ref $handler eq 'CODE') { |
742 | ($sql, @bind) = $handler->($self, $k, $op, $val); |
743 | } |
744 | else { |
a47b433a |
745 | puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef"; |
3a2e1a5e |
746 | } |
96449e8e |
747 | } |
96449e8e |
748 | else { |
cf838930 |
749 | $self->_SWITCH_refkind($val, { |
750 | |
751 | ARRAYREF => sub { # CASE: col => {op => \@vals} |
752 | ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val); |
753 | }, |
754 | |
fe3ae272 |
755 | ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind) |
b3be7bd0 |
756 | my ($sub_sql, @sub_bind) = @$$val; |
fe3ae272 |
757 | $self->_assert_bindval_matches_bindtype(@sub_bind); |
b3be7bd0 |
758 | $sql = join ' ', $self->_convert($self->_quote($k)), |
759 | $self->_sqlcase($op), |
760 | $sub_sql; |
fe3ae272 |
761 | @bind = @sub_bind; |
b3be7bd0 |
762 | }, |
763 | |
cf838930 |
764 | UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL" |
765 | my $is = ($op =~ $self->{equality_op}) ? 'is' : |
766 | ($op =~ $self->{inequality_op}) ? 'is not' : |
a47b433a |
767 | puke "unexpected operator '$orig_op' with undef operand"; |
cf838930 |
768 | $sql = $self->_quote($k) . $self->_sqlcase(" $is null"); |
769 | }, |
a47b433a |
770 | |
2281c758 |
771 | FALLBACK => sub { # CASE: col => {op/func => $stuff} |
07936978 |
772 | |
953d164e |
773 | # retain for proper column type bind |
774 | $self->{_nested_func_lhs} ||= $k; |
07936978 |
775 | |
0ec3aec7 |
776 | ($sql, @bind) = $self->_where_unary_op ($op, $val); |
953d164e |
777 | |
778 | $sql = join (' ', |
779 | $self->_convert($self->_quote($k)), |
780 | $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested |
781 | ); |
cf838930 |
782 | }, |
783 | }); |
96449e8e |
784 | } |
785 | |
eb49170d |
786 | ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql; |
96449e8e |
787 | push @all_bind, @bind; |
788 | } |
eb49170d |
789 | return ($all_sql, @all_bind); |
96449e8e |
790 | } |
791 | |
792 | |
793 | |
794 | sub _where_field_op_ARRAYREF { |
795 | my ($self, $k, $op, $vals) = @_; |
796 | |
ce261791 |
797 | my @vals = @$vals; #always work on a copy |
798 | |
799 | if(@vals) { |
bd6a65ca |
800 | $self->_debug(sprintf '%s means multiple elements: [ %s ]', |
801 | $vals, |
802 | join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ), |
803 | ); |
96449e8e |
804 | |
4030915f |
805 | # see if the first element is an -and/-or op |
806 | my $logic; |
bd6a65ca |
807 | if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) { |
4030915f |
808 | $logic = uc $1; |
ce261791 |
809 | shift @vals; |
4030915f |
810 | } |
811 | |
ce261791 |
812 | # distribute $op over each remaining member of @vals, append logic if exists |
813 | return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic); |
4030915f |
814 | |
9d48860e |
815 | # LDNOTE : had planned to change the distribution logic when |
816 | # $op =~ $self->{inequality_op}, because of Morgan laws : |
96449e8e |
817 | # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate |
9d48860e |
818 | # WHERE field != 22 OR field != 33 : the user probably means |
96449e8e |
819 | # WHERE field != 22 AND field != 33. |
4030915f |
820 | # To do this, replace the above to roughly : |
f2d5020d |
821 | # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR'; |
ce261791 |
822 | # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic); |
96449e8e |
823 | |
9d48860e |
824 | } |
96449e8e |
825 | else { |
9d48860e |
826 | # try to DWIM on equality operators |
96449e8e |
827 | # LDNOTE : not 100% sure this is the correct thing to do ... |
828 | return ($self->{sqlfalse}) if $op =~ $self->{equality_op}; |
829 | return ($self->{sqltrue}) if $op =~ $self->{inequality_op}; |
830 | |
831 | # otherwise |
832 | puke "operator '$op' applied on an empty array (field '$k')"; |
833 | } |
834 | } |
835 | |
836 | |
837 | sub _where_hashpair_SCALARREF { |
838 | my ($self, $k, $v) = @_; |
839 | $self->_debug("SCALAR($k) means literal SQL: $$v"); |
840 | my $sql = $self->_quote($k) . " " . $$v; |
841 | return ($sql); |
842 | } |
843 | |
fe3ae272 |
844 | # literal SQL with bind |
96449e8e |
845 | sub _where_hashpair_ARRAYREFREF { |
846 | my ($self, $k, $v) = @_; |
847 | $self->_debug("REF($k) means literal SQL: @${$v}"); |
c94a6c93 |
848 | my ($sql, @bind) = @$$v; |
fe3ae272 |
849 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
850 | $sql = $self->_quote($k) . " " . $sql; |
96449e8e |
851 | return ($sql, @bind ); |
852 | } |
853 | |
fe3ae272 |
854 | # literal SQL without bind |
96449e8e |
855 | sub _where_hashpair_SCALAR { |
856 | my ($self, $k, $v) = @_; |
857 | $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v"); |
9d48860e |
858 | my $sql = join ' ', $self->_convert($self->_quote($k)), |
859 | $self->_sqlcase($self->{cmp}), |
96449e8e |
860 | $self->_convert('?'); |
861 | my @bind = $self->_bindtype($k, $v); |
862 | return ( $sql, @bind); |
863 | } |
864 | |
865 | |
866 | sub _where_hashpair_UNDEF { |
867 | my ($self, $k, $v) = @_; |
868 | $self->_debug("UNDEF($k) means IS NULL"); |
869 | my $sql = $self->_quote($k) . $self->_sqlcase(' is null'); |
870 | return ($sql); |
871 | } |
872 | |
873 | #====================================================================== |
874 | # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF) |
875 | #====================================================================== |
876 | |
877 | |
878 | sub _where_SCALARREF { |
879 | my ($self, $where) = @_; |
880 | |
881 | # literal sql |
882 | $self->_debug("SCALAR(*top) means literal SQL: $$where"); |
883 | return ($$where); |
884 | } |
885 | |
886 | |
887 | sub _where_SCALAR { |
888 | my ($self, $where) = @_; |
889 | |
890 | # literal sql |
891 | $self->_debug("NOREF(*top) means literal SQL: $where"); |
892 | return ($where); |
893 | } |
894 | |
895 | |
896 | sub _where_UNDEF { |
897 | my ($self) = @_; |
898 | return (); |
899 | } |
900 | |
901 | |
902 | #====================================================================== |
903 | # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between) |
904 | #====================================================================== |
905 | |
906 | |
907 | sub _where_field_BETWEEN { |
908 | my ($self, $k, $op, $vals) = @_; |
909 | |
4d8b3dc4 |
910 | my ($label, $and, $placeholder); |
cf02fc47 |
911 | $label = $self->_convert($self->_quote($k)); |
912 | $and = ' ' . $self->_sqlcase('and') . ' '; |
913 | $placeholder = $self->_convert('?'); |
96449e8e |
914 | $op = $self->_sqlcase($op); |
915 | |
4d8b3dc4 |
916 | my ($clause, @bind) = $self->_SWITCH_refkind($vals, { |
917 | ARRAYREFREF => sub { |
c94a6c93 |
918 | my ($s, @b) = @$$vals; |
919 | $self->_assert_bindval_matches_bindtype(@b); |
920 | ($s, @b); |
4d8b3dc4 |
921 | }, |
922 | SCALARREF => sub { |
923 | return $$vals; |
924 | }, |
925 | ARRAYREF => sub { |
926 | puke "special op 'between' accepts an arrayref with exactly two values" |
927 | if @$vals != 2; |
928 | |
929 | my (@all_sql, @all_bind); |
930 | foreach my $val (@$vals) { |
931 | my ($sql, @bind) = $self->_SWITCH_refkind($val, { |
932 | SCALAR => sub { |
5e5cbf51 |
933 | return ($placeholder, $self->_bindtype($k, $val) ); |
4d8b3dc4 |
934 | }, |
935 | SCALARREF => sub { |
0336eddb |
936 | return $$val; |
4d8b3dc4 |
937 | }, |
938 | ARRAYREFREF => sub { |
939 | my ($sql, @bind) = @$$val; |
c94a6c93 |
940 | $self->_assert_bindval_matches_bindtype(@bind); |
0336eddb |
941 | return ($sql, @bind); |
4d8b3dc4 |
942 | }, |
0336eddb |
943 | HASHREF => sub { |
944 | my ($func, $arg, @rest) = %$val; |
945 | puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN") |
946 | if (@rest or $func !~ /^ \- (.+)/x); |
947 | local $self->{_nested_func_lhs} = $k; |
0ec3aec7 |
948 | $self->_where_unary_op ($1 => $arg); |
0336eddb |
949 | } |
4d8b3dc4 |
950 | }); |
951 | push @all_sql, $sql; |
952 | push @all_bind, @bind; |
953 | } |
954 | |
955 | return ( |
956 | (join $and, @all_sql), |
5e5cbf51 |
957 | @all_bind |
4d8b3dc4 |
958 | ); |
959 | }, |
960 | FALLBACK => sub { |
961 | puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref"; |
962 | }, |
963 | }); |
cf02fc47 |
964 | |
cf02fc47 |
965 | my $sql = "( $label $op $clause )"; |
96449e8e |
966 | return ($sql, @bind) |
967 | } |
968 | |
969 | |
970 | sub _where_field_IN { |
971 | my ($self, $k, $op, $vals) = @_; |
972 | |
973 | # backwards compatibility : if scalar, force into an arrayref |
974 | $vals = [$vals] if defined $vals && ! ref $vals; |
975 | |
96449e8e |
976 | my ($label) = $self->_convert($self->_quote($k)); |
977 | my ($placeholder) = $self->_convert('?'); |
96449e8e |
978 | $op = $self->_sqlcase($op); |
979 | |
8a0d798a |
980 | my ($sql, @bind) = $self->_SWITCH_refkind($vals, { |
981 | ARRAYREF => sub { # list of choices |
982 | if (@$vals) { # nonempty list |
0336eddb |
983 | my (@all_sql, @all_bind); |
984 | |
985 | for my $val (@$vals) { |
986 | my ($sql, @bind) = $self->_SWITCH_refkind($val, { |
987 | SCALAR => sub { |
988 | return ($placeholder, $val); |
989 | }, |
990 | SCALARREF => sub { |
991 | return $$val; |
992 | }, |
993 | ARRAYREFREF => sub { |
994 | my ($sql, @bind) = @$$val; |
995 | $self->_assert_bindval_matches_bindtype(@bind); |
996 | return ($sql, @bind); |
997 | }, |
998 | HASHREF => sub { |
999 | my ($func, $arg, @rest) = %$val; |
1000 | puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN") |
1001 | if (@rest or $func !~ /^ \- (.+)/x); |
1002 | local $self->{_nested_func_lhs} = $k; |
0ec3aec7 |
1003 | $self->_where_unary_op ($1 => $arg); |
279eb282 |
1004 | }, |
1005 | UNDEF => sub { |
1006 | return $self->_sqlcase('null'); |
1007 | }, |
0336eddb |
1008 | }); |
1009 | push @all_sql, $sql; |
1010 | push @all_bind, @bind; |
1011 | } |
96449e8e |
1012 | |
88a89939 |
1013 | return ( |
1014 | sprintf ('%s %s ( %s )', |
1015 | $label, |
1016 | $op, |
1017 | join (', ', @all_sql) |
1018 | ), |
1019 | $self->_bindtype($k, @all_bind), |
0336eddb |
1020 | ); |
8a0d798a |
1021 | } |
1022 | else { # empty list : some databases won't understand "IN ()", so DWIM |
1023 | my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse}; |
1024 | return ($sql); |
1025 | } |
1026 | }, |
1027 | |
4a1f01a3 |
1028 | SCALARREF => sub { # literal SQL |
1029 | my $sql = $self->_open_outer_paren ($$vals); |
1030 | return ("$label $op ( $sql )"); |
1031 | }, |
8a0d798a |
1032 | ARRAYREFREF => sub { # literal SQL with bind |
1033 | my ($sql, @bind) = @$$vals; |
fe3ae272 |
1034 | $self->_assert_bindval_matches_bindtype(@bind); |
4a1f01a3 |
1035 | $sql = $self->_open_outer_paren ($sql); |
8a0d798a |
1036 | return ("$label $op ( $sql )", @bind); |
1037 | }, |
1038 | |
1039 | FALLBACK => sub { |
4a1f01a3 |
1040 | puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)"; |
8a0d798a |
1041 | }, |
1042 | }); |
1043 | |
1044 | return ($sql, @bind); |
96449e8e |
1045 | } |
1046 | |
4a1f01a3 |
1047 | # Some databases (SQLite) treat col IN (1, 2) different from |
1048 | # col IN ( (1, 2) ). Use this to strip all outer parens while |
1049 | # adding them back in the corresponding method |
1050 | sub _open_outer_paren { |
1051 | my ($self, $sql) = @_; |
171a709f |
1052 | $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs; |
4a1f01a3 |
1053 | return $sql; |
1054 | } |
1055 | |
96449e8e |
1056 | |
96449e8e |
1057 | #====================================================================== |
1058 | # ORDER BY |
1059 | #====================================================================== |
1060 | |
1061 | sub _order_by { |
1062 | my ($self, $arg) = @_; |
1063 | |
f267b646 |
1064 | my (@sql, @bind); |
1065 | for my $c ($self->_order_by_chunks ($arg) ) { |
1066 | $self->_SWITCH_refkind ($c, { |
1067 | SCALAR => sub { push @sql, $c }, |
1068 | ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c }, |
1069 | }); |
1070 | } |
1071 | |
1072 | my $sql = @sql |
1073 | ? sprintf ('%s %s', |
1074 | $self->_sqlcase(' order by'), |
1075 | join (', ', @sql) |
1076 | ) |
1077 | : '' |
1078 | ; |
1079 | |
1080 | return wantarray ? ($sql, @bind) : $sql; |
1081 | } |
1082 | |
1083 | sub _order_by_chunks { |
1084 | my ($self, $arg) = @_; |
1085 | |
1086 | return $self->_SWITCH_refkind($arg, { |
96449e8e |
1087 | |
1088 | ARRAYREF => sub { |
f267b646 |
1089 | map { $self->_order_by_chunks ($_ ) } @$arg; |
96449e8e |
1090 | }, |
1091 | |
c94a6c93 |
1092 | ARRAYREFREF => sub { |
1093 | my ($s, @b) = @$$arg; |
1094 | $self->_assert_bindval_matches_bindtype(@b); |
1095 | [ $s, @b ]; |
1096 | }, |
f267b646 |
1097 | |
96449e8e |
1098 | SCALAR => sub {$self->_quote($arg)}, |
f267b646 |
1099 | |
1100 | UNDEF => sub {return () }, |
1101 | |
96449e8e |
1102 | SCALARREF => sub {$$arg}, # literal SQL, no quoting |
96449e8e |
1103 | |
f267b646 |
1104 | HASHREF => sub { |
1105 | # get first pair in hash |
c94a6c93 |
1106 | my ($key, $val, @rest) = %$arg; |
96449e8e |
1107 | |
f267b646 |
1108 | return () unless $key; |
96449e8e |
1109 | |
c94a6c93 |
1110 | if ( @rest or not $key =~ /^-(desc|asc)/i ) { |
f267b646 |
1111 | puke "hash passed to _order_by must have exactly one key (-desc or -asc)"; |
1112 | } |
96449e8e |
1113 | |
f267b646 |
1114 | my $direction = $1; |
96449e8e |
1115 | |
e9bd3547 |
1116 | my @ret; |
f267b646 |
1117 | for my $c ($self->_order_by_chunks ($val)) { |
e9bd3547 |
1118 | my ($sql, @bind); |
96449e8e |
1119 | |
f267b646 |
1120 | $self->_SWITCH_refkind ($c, { |
1121 | SCALAR => sub { |
e9bd3547 |
1122 | $sql = $c; |
f267b646 |
1123 | }, |
1124 | ARRAYREF => sub { |
e9bd3547 |
1125 | ($sql, @bind) = @$c; |
f267b646 |
1126 | }, |
1127 | }); |
96449e8e |
1128 | |
e9bd3547 |
1129 | $sql = $sql . ' ' . $self->_sqlcase($direction); |
96449e8e |
1130 | |
e9bd3547 |
1131 | push @ret, [ $sql, @bind]; |
1132 | } |
96449e8e |
1133 | |
e9bd3547 |
1134 | return @ret; |
f267b646 |
1135 | }, |
1136 | }); |
96449e8e |
1137 | } |
1138 | |
1139 | |
96449e8e |
1140 | #====================================================================== |
1141 | # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES) |
1142 | #====================================================================== |
1143 | |
1144 | sub _table { |
1145 | my $self = shift; |
1146 | my $from = shift; |
1147 | $self->_SWITCH_refkind($from, { |
1148 | ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;}, |
1149 | SCALAR => sub {$self->_quote($from)}, |
1150 | SCALARREF => sub {$$from}, |
96449e8e |
1151 | }); |
1152 | } |
1153 | |
1154 | |
1155 | #====================================================================== |
1156 | # UTILITY FUNCTIONS |
1157 | #====================================================================== |
1158 | |
955e77ca |
1159 | # highly optimized, as it's called way too often |
96449e8e |
1160 | sub _quote { |
955e77ca |
1161 | # my ($self, $label) = @_; |
96449e8e |
1162 | |
955e77ca |
1163 | return '' unless defined $_[1]; |
955e77ca |
1164 | return ${$_[1]} if ref($_[1]) eq 'SCALAR'; |
96449e8e |
1165 | |
b6251592 |
1166 | unless ($_[0]->{quote_char}) { |
170e6c33 |
1167 | $_[0]->_assert_pass_injection_guard($_[1]); |
b6251592 |
1168 | return $_[1]; |
1169 | } |
96449e8e |
1170 | |
07d7c35c |
1171 | my $qref = ref $_[0]->{quote_char}; |
955e77ca |
1172 | my ($l, $r); |
07d7c35c |
1173 | if (!$qref) { |
1174 | ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} ); |
955e77ca |
1175 | } |
07d7c35c |
1176 | elsif ($qref eq 'ARRAY') { |
1177 | ($l, $r) = @{$_[0]->{quote_char}}; |
955e77ca |
1178 | } |
1179 | else { |
1180 | puke "Unsupported quote_char format: $_[0]->{quote_char}"; |
1181 | } |
96449e8e |
1182 | |
07d7c35c |
1183 | # parts containing * are naturally unquoted |
1184 | return join( $_[0]->{name_sep}||'', map |
955e77ca |
1185 | { $_ eq '*' ? $_ : $l . $_ . $r } |
1186 | ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] ) |
1187 | ); |
96449e8e |
1188 | } |
1189 | |
1190 | |
1191 | # Conversion, if applicable |
1192 | sub _convert ($) { |
07d7c35c |
1193 | #my ($self, $arg) = @_; |
96449e8e |
1194 | |
1195 | # LDNOTE : modified the previous implementation below because |
1196 | # it was not consistent : the first "return" is always an array, |
1197 | # the second "return" is context-dependent. Anyway, _convert |
9d48860e |
1198 | # seems always used with just a single argument, so make it a |
96449e8e |
1199 | # scalar function. |
1200 | # return @_ unless $self->{convert}; |
1201 | # my $conv = $self->_sqlcase($self->{convert}); |
1202 | # my @ret = map { $conv.'('.$_.')' } @_; |
1203 | # return wantarray ? @ret : $ret[0]; |
07d7c35c |
1204 | if ($_[0]->{convert}) { |
1205 | return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')'; |
96449e8e |
1206 | } |
07d7c35c |
1207 | return $_[1]; |
96449e8e |
1208 | } |
1209 | |
1210 | # And bindtype |
1211 | sub _bindtype (@) { |
07d7c35c |
1212 | #my ($self, $col, @vals) = @_; |
96449e8e |
1213 | |
9d48860e |
1214 | #LDNOTE : changed original implementation below because it did not make |
96449e8e |
1215 | # sense when bindtype eq 'columns' and @vals > 1. |
1216 | # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals; |
1217 | |
07d7c35c |
1218 | # called often - tighten code |
1219 | return $_[0]->{bindtype} eq 'columns' |
1220 | ? map {[$_[1], $_]} @_[2 .. $#_] |
1221 | : @_[2 .. $#_] |
1222 | ; |
96449e8e |
1223 | } |
1224 | |
fe3ae272 |
1225 | # Dies if any element of @bind is not in [colname => value] format |
1226 | # if bindtype is 'columns'. |
1227 | sub _assert_bindval_matches_bindtype { |
c94a6c93 |
1228 | # my ($self, @bind) = @_; |
1229 | my $self = shift; |
fe3ae272 |
1230 | if ($self->{bindtype} eq 'columns') { |
c94a6c93 |
1231 | for (@_) { |
1232 | if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) { |
3a06278c |
1233 | puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]" |
fe3ae272 |
1234 | } |
1235 | } |
1236 | } |
1237 | } |
1238 | |
96449e8e |
1239 | sub _join_sql_clauses { |
1240 | my ($self, $logic, $clauses_aref, $bind_aref) = @_; |
1241 | |
1242 | if (@$clauses_aref > 1) { |
1243 | my $join = " " . $self->_sqlcase($logic) . " "; |
1244 | my $sql = '( ' . join($join, @$clauses_aref) . ' )'; |
1245 | return ($sql, @$bind_aref); |
1246 | } |
1247 | elsif (@$clauses_aref) { |
1248 | return ($clauses_aref->[0], @$bind_aref); # no parentheses |
1249 | } |
1250 | else { |
1251 | return (); # if no SQL, ignore @$bind_aref |
1252 | } |
1253 | } |
1254 | |
1255 | |
1256 | # Fix SQL case, if so requested |
1257 | sub _sqlcase { |
96449e8e |
1258 | # LDNOTE: if $self->{case} is true, then it contains 'lower', so we |
1259 | # don't touch the argument ... crooked logic, but let's not change it! |
07d7c35c |
1260 | return $_[0]->{case} ? $_[1] : uc($_[1]); |
96449e8e |
1261 | } |
1262 | |
1263 | |
1264 | #====================================================================== |
1265 | # DISPATCHING FROM REFKIND |
1266 | #====================================================================== |
1267 | |
1268 | sub _refkind { |
1269 | my ($self, $data) = @_; |
96449e8e |
1270 | |
955e77ca |
1271 | return 'UNDEF' unless defined $data; |
1272 | |
1273 | # blessed objects are treated like scalars |
1274 | my $ref = (Scalar::Util::blessed $data) ? '' : ref $data; |
1275 | |
1276 | return 'SCALAR' unless $ref; |
1277 | |
1278 | my $n_steps = 1; |
1279 | while ($ref eq 'REF') { |
96449e8e |
1280 | $data = $$data; |
955e77ca |
1281 | $ref = (Scalar::Util::blessed $data) ? '' : ref $data; |
1282 | $n_steps++ if $ref; |
96449e8e |
1283 | } |
1284 | |
848556bc |
1285 | return ($ref||'SCALAR') . ('REF' x $n_steps); |
96449e8e |
1286 | } |
1287 | |
1288 | sub _try_refkind { |
1289 | my ($self, $data) = @_; |
1290 | my @try = ($self->_refkind($data)); |
1291 | push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF'; |
1292 | push @try, 'FALLBACK'; |
955e77ca |
1293 | return \@try; |
96449e8e |
1294 | } |
1295 | |
1296 | sub _METHOD_FOR_refkind { |
1297 | my ($self, $meth_prefix, $data) = @_; |
f39eaa60 |
1298 | |
1299 | my $method; |
955e77ca |
1300 | for (@{$self->_try_refkind($data)}) { |
f39eaa60 |
1301 | $method = $self->can($meth_prefix."_".$_) |
1302 | and last; |
1303 | } |
1304 | |
1305 | return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data); |
96449e8e |
1306 | } |
1307 | |
1308 | |
1309 | sub _SWITCH_refkind { |
1310 | my ($self, $data, $dispatch_table) = @_; |
1311 | |
f39eaa60 |
1312 | my $coderef; |
955e77ca |
1313 | for (@{$self->_try_refkind($data)}) { |
f39eaa60 |
1314 | $coderef = $dispatch_table->{$_} |
1315 | and last; |
1316 | } |
1317 | |
1318 | puke "no dispatch entry for ".$self->_refkind($data) |
1319 | unless $coderef; |
1320 | |
96449e8e |
1321 | $coderef->(); |
1322 | } |
1323 | |
1324 | |
1325 | |
1326 | |
1327 | #====================================================================== |
1328 | # VALUES, GENERATE, AUTOLOAD |
1329 | #====================================================================== |
1330 | |
1331 | # LDNOTE: original code from nwiger, didn't touch code in that section |
1332 | # I feel the AUTOLOAD stuff should not be the default, it should |
1333 | # only be activated on explicit demand by user. |
1334 | |
1335 | sub values { |
1336 | my $self = shift; |
1337 | my $data = shift || return; |
1338 | puke "Argument to ", __PACKAGE__, "->values must be a \\%hash" |
1339 | unless ref $data eq 'HASH'; |
bab725ce |
1340 | |
1341 | my @all_bind; |
1342 | foreach my $k ( sort keys %$data ) { |
1343 | my $v = $data->{$k}; |
1344 | $self->_SWITCH_refkind($v, { |
9d48860e |
1345 | ARRAYREF => sub { |
bab725ce |
1346 | if ($self->{array_datatypes}) { # array datatype |
1347 | push @all_bind, $self->_bindtype($k, $v); |
1348 | } |
1349 | else { # literal SQL with bind |
1350 | my ($sql, @bind) = @$v; |
1351 | $self->_assert_bindval_matches_bindtype(@bind); |
1352 | push @all_bind, @bind; |
1353 | } |
1354 | }, |
1355 | ARRAYREFREF => sub { # literal SQL with bind |
1356 | my ($sql, @bind) = @${$v}; |
1357 | $self->_assert_bindval_matches_bindtype(@bind); |
1358 | push @all_bind, @bind; |
1359 | }, |
1360 | SCALARREF => sub { # literal SQL without bind |
1361 | }, |
1362 | SCALAR_or_UNDEF => sub { |
1363 | push @all_bind, $self->_bindtype($k, $v); |
1364 | }, |
1365 | }); |
1366 | } |
1367 | |
1368 | return @all_bind; |
96449e8e |
1369 | } |
1370 | |
1371 | sub generate { |
1372 | my $self = shift; |
1373 | |
1374 | my(@sql, @sqlq, @sqlv); |
1375 | |
1376 | for (@_) { |
1377 | my $ref = ref $_; |
1378 | if ($ref eq 'HASH') { |
1379 | for my $k (sort keys %$_) { |
1380 | my $v = $_->{$k}; |
1381 | my $r = ref $v; |
1382 | my $label = $self->_quote($k); |
1383 | if ($r eq 'ARRAY') { |
fe3ae272 |
1384 | # literal SQL with bind |
1385 | my ($sql, @bind) = @$v; |
1386 | $self->_assert_bindval_matches_bindtype(@bind); |
96449e8e |
1387 | push @sqlq, "$label = $sql"; |
fe3ae272 |
1388 | push @sqlv, @bind; |
96449e8e |
1389 | } elsif ($r eq 'SCALAR') { |
fe3ae272 |
1390 | # literal SQL without bind |
96449e8e |
1391 | push @sqlq, "$label = $$v"; |
9d48860e |
1392 | } else { |
96449e8e |
1393 | push @sqlq, "$label = ?"; |
1394 | push @sqlv, $self->_bindtype($k, $v); |
1395 | } |
1396 | } |
1397 | push @sql, $self->_sqlcase('set'), join ', ', @sqlq; |
1398 | } elsif ($ref eq 'ARRAY') { |
1399 | # unlike insert(), assume these are ONLY the column names, i.e. for SQL |
1400 | for my $v (@$_) { |
1401 | my $r = ref $v; |
fe3ae272 |
1402 | if ($r eq 'ARRAY') { # literal SQL with bind |
1403 | my ($sql, @bind) = @$v; |
1404 | $self->_assert_bindval_matches_bindtype(@bind); |
1405 | push @sqlq, $sql; |
1406 | push @sqlv, @bind; |
1407 | } elsif ($r eq 'SCALAR') { # literal SQL without bind |
96449e8e |
1408 | # embedded literal SQL |
1409 | push @sqlq, $$v; |
9d48860e |
1410 | } else { |
96449e8e |
1411 | push @sqlq, '?'; |
1412 | push @sqlv, $v; |
1413 | } |
1414 | } |
1415 | push @sql, '(' . join(', ', @sqlq) . ')'; |
1416 | } elsif ($ref eq 'SCALAR') { |
1417 | # literal SQL |
1418 | push @sql, $$_; |
1419 | } else { |
1420 | # strings get case twiddled |
1421 | push @sql, $self->_sqlcase($_); |
1422 | } |
1423 | } |
1424 | |
1425 | my $sql = join ' ', @sql; |
1426 | |
1427 | # this is pretty tricky |
1428 | # if ask for an array, return ($stmt, @bind) |
1429 | # otherwise, s/?/shift @sqlv/ to put it inline |
1430 | if (wantarray) { |
1431 | return ($sql, @sqlv); |
1432 | } else { |
1433 | 1 while $sql =~ s/\?/my $d = shift(@sqlv); |
1434 | ref $d ? $d->[1] : $d/e; |
1435 | return $sql; |
1436 | } |
1437 | } |
1438 | |
1439 | |
1440 | sub DESTROY { 1 } |
1441 | |
1442 | sub AUTOLOAD { |
1443 | # This allows us to check for a local, then _form, attr |
1444 | my $self = shift; |
1445 | my($name) = $AUTOLOAD =~ /.*::(.+)/; |
1446 | return $self->generate($name, @_); |
1447 | } |
1448 | |
1449 | 1; |
1450 | |
1451 | |
1452 | |
1453 | __END__ |
32eab2da |
1454 | |
1455 | =head1 NAME |
1456 | |
1457 | SQL::Abstract - Generate SQL from Perl data structures |
1458 | |
1459 | =head1 SYNOPSIS |
1460 | |
1461 | use SQL::Abstract; |
1462 | |
1463 | my $sql = SQL::Abstract->new; |
1464 | |
1465 | my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order); |
1466 | |
1467 | my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values); |
1468 | |
1469 | my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where); |
1470 | |
1471 | my($stmt, @bind) = $sql->delete($table, \%where); |
1472 | |
1473 | # Then, use these in your DBI statements |
1474 | my $sth = $dbh->prepare($stmt); |
1475 | $sth->execute(@bind); |
1476 | |
1477 | # Just generate the WHERE clause |
abe72f94 |
1478 | my($stmt, @bind) = $sql->where(\%where, \@order); |
32eab2da |
1479 | |
1480 | # Return values in the same order, for hashed queries |
1481 | # See PERFORMANCE section for more details |
1482 | my @bind = $sql->values(\%fieldvals); |
1483 | |
1484 | =head1 DESCRIPTION |
1485 | |
1486 | This module was inspired by the excellent L<DBIx::Abstract>. |
1487 | However, in using that module I found that what I really wanted |
1488 | to do was generate SQL, but still retain complete control over my |
1489 | statement handles and use the DBI interface. So, I set out to |
1490 | create an abstract SQL generation module. |
1491 | |
1492 | While based on the concepts used by L<DBIx::Abstract>, there are |
1493 | several important differences, especially when it comes to WHERE |
1494 | clauses. I have modified the concepts used to make the SQL easier |
1495 | to generate from Perl data structures and, IMO, more intuitive. |
1496 | The underlying idea is for this module to do what you mean, based |
1497 | on the data structures you provide it. The big advantage is that |
1498 | you don't have to modify your code every time your data changes, |
1499 | as this module figures it out. |
1500 | |
1501 | To begin with, an SQL INSERT is as easy as just specifying a hash |
1502 | of C<key=value> pairs: |
1503 | |
1504 | my %data = ( |
1505 | name => 'Jimbo Bobson', |
1506 | phone => '123-456-7890', |
1507 | address => '42 Sister Lane', |
1508 | city => 'St. Louis', |
1509 | state => 'Louisiana', |
1510 | ); |
1511 | |
1512 | The SQL can then be generated with this: |
1513 | |
1514 | my($stmt, @bind) = $sql->insert('people', \%data); |
1515 | |
1516 | Which would give you something like this: |
1517 | |
1518 | $stmt = "INSERT INTO people |
1519 | (address, city, name, phone, state) |
1520 | VALUES (?, ?, ?, ?, ?)"; |
1521 | @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson', |
1522 | '123-456-7890', 'Louisiana'); |
1523 | |
1524 | These are then used directly in your DBI code: |
1525 | |
1526 | my $sth = $dbh->prepare($stmt); |
1527 | $sth->execute(@bind); |
1528 | |
96449e8e |
1529 | =head2 Inserting and Updating Arrays |
1530 | |
1531 | If your database has array types (like for example Postgres), |
1532 | activate the special option C<< array_datatypes => 1 >> |
9d48860e |
1533 | when creating the C<SQL::Abstract> object. |
96449e8e |
1534 | Then you may use an arrayref to insert and update database array types: |
1535 | |
1536 | my $sql = SQL::Abstract->new(array_datatypes => 1); |
1537 | my %data = ( |
1538 | planets => [qw/Mercury Venus Earth Mars/] |
1539 | ); |
9d48860e |
1540 | |
96449e8e |
1541 | my($stmt, @bind) = $sql->insert('solar_system', \%data); |
1542 | |
1543 | This results in: |
1544 | |
1545 | $stmt = "INSERT INTO solar_system (planets) VALUES (?)" |
1546 | |
1547 | @bind = (['Mercury', 'Venus', 'Earth', 'Mars']); |
1548 | |
1549 | |
1550 | =head2 Inserting and Updating SQL |
1551 | |
1552 | In order to apply SQL functions to elements of your C<%data> you may |
1553 | specify a reference to an arrayref for the given hash value. For example, |
1554 | if you need to execute the Oracle C<to_date> function on a value, you can |
1555 | say something like this: |
32eab2da |
1556 | |
1557 | my %data = ( |
1558 | name => 'Bill', |
96449e8e |
1559 | date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"], |
9d48860e |
1560 | ); |
32eab2da |
1561 | |
1562 | The first value in the array is the actual SQL. Any other values are |
1563 | optional and would be included in the bind values array. This gives |
1564 | you: |
1565 | |
1566 | my($stmt, @bind) = $sql->insert('people', \%data); |
1567 | |
9d48860e |
1568 | $stmt = "INSERT INTO people (name, date_entered) |
32eab2da |
1569 | VALUES (?, to_date(?,'MM/DD/YYYY'))"; |
1570 | @bind = ('Bill', '03/02/2003'); |
1571 | |
1572 | An UPDATE is just as easy, all you change is the name of the function: |
1573 | |
1574 | my($stmt, @bind) = $sql->update('people', \%data); |
1575 | |
1576 | Notice that your C<%data> isn't touched; the module will generate |
1577 | the appropriately quirky SQL for you automatically. Usually you'll |
1578 | want to specify a WHERE clause for your UPDATE, though, which is |
1579 | where handling C<%where> hashes comes in handy... |
1580 | |
96449e8e |
1581 | =head2 Complex where statements |
1582 | |
32eab2da |
1583 | This module can generate pretty complicated WHERE statements |
1584 | easily. For example, simple C<key=value> pairs are taken to mean |
1585 | equality, and if you want to see if a field is within a set |
1586 | of values, you can use an arrayref. Let's say we wanted to |
1587 | SELECT some data based on this criteria: |
1588 | |
1589 | my %where = ( |
1590 | requestor => 'inna', |
1591 | worker => ['nwiger', 'rcwe', 'sfz'], |
1592 | status => { '!=', 'completed' } |
1593 | ); |
1594 | |
1595 | my($stmt, @bind) = $sql->select('tickets', '*', \%where); |
1596 | |
1597 | The above would give you something like this: |
1598 | |
1599 | $stmt = "SELECT * FROM tickets WHERE |
1600 | ( requestor = ? ) AND ( status != ? ) |
1601 | AND ( worker = ? OR worker = ? OR worker = ? )"; |
1602 | @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz'); |
1603 | |
1604 | Which you could then use in DBI code like so: |
1605 | |
1606 | my $sth = $dbh->prepare($stmt); |
1607 | $sth->execute(@bind); |
1608 | |
1609 | Easy, eh? |
1610 | |
1611 | =head1 FUNCTIONS |
1612 | |
1613 | The functions are simple. There's one for each major SQL operation, |
1614 | and a constructor you use first. The arguments are specified in a |
9d48860e |
1615 | similar order to each function (table, then fields, then a where |
32eab2da |
1616 | clause) to try and simplify things. |
1617 | |
83cab70b |
1618 | |
83cab70b |
1619 | |
32eab2da |
1620 | |
1621 | =head2 new(option => 'value') |
1622 | |
1623 | The C<new()> function takes a list of options and values, and returns |
1624 | a new B<SQL::Abstract> object which can then be used to generate SQL |
1625 | through the methods below. The options accepted are: |
1626 | |
1627 | =over |
1628 | |
1629 | =item case |
1630 | |
1631 | If set to 'lower', then SQL will be generated in all lowercase. By |
1632 | default SQL is generated in "textbook" case meaning something like: |
1633 | |
1634 | SELECT a_field FROM a_table WHERE some_field LIKE '%someval%' |
1635 | |
96449e8e |
1636 | Any setting other than 'lower' is ignored. |
1637 | |
32eab2da |
1638 | =item cmp |
1639 | |
1640 | This determines what the default comparison operator is. By default |
1641 | it is C<=>, meaning that a hash like this: |
1642 | |
1643 | %where = (name => 'nwiger', email => 'nate@wiger.org'); |
1644 | |
1645 | Will generate SQL like this: |
1646 | |
1647 | WHERE name = 'nwiger' AND email = 'nate@wiger.org' |
1648 | |
1649 | However, you may want loose comparisons by default, so if you set |
1650 | C<cmp> to C<like> you would get SQL such as: |
1651 | |
1652 | WHERE name like 'nwiger' AND email like 'nate@wiger.org' |
1653 | |
1654 | You can also override the comparsion on an individual basis - see |
1655 | the huge section on L</"WHERE CLAUSES"> at the bottom. |
1656 | |
96449e8e |
1657 | =item sqltrue, sqlfalse |
1658 | |
1659 | Expressions for inserting boolean values within SQL statements. |
6e0c6552 |
1660 | By default these are C<1=1> and C<1=0>. They are used |
1661 | by the special operators C<-in> and C<-not_in> for generating |
1662 | correct SQL even when the argument is an empty array (see below). |
96449e8e |
1663 | |
32eab2da |
1664 | =item logic |
1665 | |
1666 | This determines the default logical operator for multiple WHERE |
7cac25e6 |
1667 | statements in arrays or hashes. If absent, the default logic is "or" |
1668 | for arrays, and "and" for hashes. This means that a WHERE |
32eab2da |
1669 | array of the form: |
1670 | |
1671 | @where = ( |
9d48860e |
1672 | event_date => {'>=', '2/13/99'}, |
1673 | event_date => {'<=', '4/24/03'}, |
32eab2da |
1674 | ); |
1675 | |
7cac25e6 |
1676 | will generate SQL like this: |
32eab2da |
1677 | |
1678 | WHERE event_date >= '2/13/99' OR event_date <= '4/24/03' |
1679 | |
1680 | This is probably not what you want given this query, though (look |
1681 | at the dates). To change the "OR" to an "AND", simply specify: |
1682 | |
1683 | my $sql = SQL::Abstract->new(logic => 'and'); |
1684 | |
1685 | Which will change the above C<WHERE> to: |
1686 | |
1687 | WHERE event_date >= '2/13/99' AND event_date <= '4/24/03' |
1688 | |
96449e8e |
1689 | The logic can also be changed locally by inserting |
7cac25e6 |
1690 | a modifier in front of an arrayref : |
96449e8e |
1691 | |
9d48860e |
1692 | @where = (-and => [event_date => {'>=', '2/13/99'}, |
7cac25e6 |
1693 | event_date => {'<=', '4/24/03'} ]); |
96449e8e |
1694 | |
1695 | See the L</"WHERE CLAUSES"> section for explanations. |
1696 | |
32eab2da |
1697 | =item convert |
1698 | |
1699 | This will automatically convert comparisons using the specified SQL |
1700 | function for both column and value. This is mostly used with an argument |
1701 | of C<upper> or C<lower>, so that the SQL will have the effect of |
1702 | case-insensitive "searches". For example, this: |
1703 | |
1704 | $sql = SQL::Abstract->new(convert => 'upper'); |
1705 | %where = (keywords => 'MaKe iT CAse inSeNSItive'); |
1706 | |
1707 | Will turn out the following SQL: |
1708 | |
1709 | WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive') |
1710 | |
1711 | The conversion can be C<upper()>, C<lower()>, or any other SQL function |
1712 | that can be applied symmetrically to fields (actually B<SQL::Abstract> does |
1713 | not validate this option; it will just pass through what you specify verbatim). |
1714 | |
1715 | =item bindtype |
1716 | |
1717 | This is a kludge because many databases suck. For example, you can't |
1718 | just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields. |
1719 | Instead, you have to use C<bind_param()>: |
1720 | |
1721 | $sth->bind_param(1, 'reg data'); |
1722 | $sth->bind_param(2, $lots, {ora_type => ORA_CLOB}); |
1723 | |
1724 | The problem is, B<SQL::Abstract> will normally just return a C<@bind> array, |
1725 | which loses track of which field each slot refers to. Fear not. |
1726 | |
1727 | If you specify C<bindtype> in new, you can determine how C<@bind> is returned. |
1728 | Currently, you can specify either C<normal> (default) or C<columns>. If you |
1729 | specify C<columns>, you will get an array that looks like this: |
1730 | |
1731 | my $sql = SQL::Abstract->new(bindtype => 'columns'); |
1732 | my($stmt, @bind) = $sql->insert(...); |
1733 | |
1734 | @bind = ( |
1735 | [ 'column1', 'value1' ], |
1736 | [ 'column2', 'value2' ], |
1737 | [ 'column3', 'value3' ], |
1738 | ); |
1739 | |
1740 | You can then iterate through this manually, using DBI's C<bind_param()>. |
e3f9dff4 |
1741 | |
32eab2da |
1742 | $sth->prepare($stmt); |
1743 | my $i = 1; |
1744 | for (@bind) { |
1745 | my($col, $data) = @$_; |
1746 | if ($col eq 'details' || $col eq 'comments') { |
1747 | $sth->bind_param($i, $data, {ora_type => ORA_CLOB}); |
1748 | } elsif ($col eq 'image') { |
1749 | $sth->bind_param($i, $data, {ora_type => ORA_BLOB}); |
1750 | } else { |
1751 | $sth->bind_param($i, $data); |
1752 | } |
1753 | $i++; |
1754 | } |
1755 | $sth->execute; # execute without @bind now |
1756 | |
1757 | Now, why would you still use B<SQL::Abstract> if you have to do this crap? |
1758 | Basically, the advantage is still that you don't have to care which fields |
1759 | are or are not included. You could wrap that above C<for> loop in a simple |
1760 | sub called C<bind_fields()> or something and reuse it repeatedly. You still |
1761 | get a layer of abstraction over manual SQL specification. |
1762 | |
deb148a2 |
1763 | Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]> |
1764 | construct (see L</Literal SQL with placeholders and bind values (subqueries)>) |
1765 | will expect the bind values in this format. |
1766 | |
32eab2da |
1767 | =item quote_char |
1768 | |
1769 | This is the character that a table or column name will be quoted |
9d48860e |
1770 | with. By default this is an empty string, but you could set it to |
32eab2da |
1771 | the character C<`>, to generate SQL like this: |
1772 | |
1773 | SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%' |
1774 | |
96449e8e |
1775 | Alternatively, you can supply an array ref of two items, the first being the left |
1776 | hand quote character, and the second the right hand quote character. For |
1777 | example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes |
1778 | that generates SQL like this: |
1779 | |
1780 | SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%' |
1781 | |
9d48860e |
1782 | Quoting is useful if you have tables or columns names that are reserved |
96449e8e |
1783 | words in your database's SQL dialect. |
32eab2da |
1784 | |
1785 | =item name_sep |
1786 | |
1787 | This is the character that separates a table and column name. It is |
1788 | necessary to specify this when the C<quote_char> option is selected, |
1789 | so that tables and column names can be individually quoted like this: |
1790 | |
1791 | SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1 |
1792 | |
b6251592 |
1793 | =item injection_guard |
1794 | |
1795 | A regular expression C<qr/.../> that is applied to any C<-function> and unquoted |
1796 | column name specified in a query structure. This is a safety mechanism to avoid |
1797 | injection attacks when mishandling user input e.g.: |
1798 | |
1799 | my %condition_as_column_value_pairs = get_values_from_user(); |
1800 | $sqla->select( ... , \%condition_as_column_value_pairs ); |
1801 | |
1802 | If the expression matches an exception is thrown. Note that literal SQL |
1803 | supplied via C<\'...'> or C<\['...']> is B<not> checked in any way. |
1804 | |
1805 | Defaults to checking for C<;> and the C<GO> keyword (TransactSQL) |
1806 | |
96449e8e |
1807 | =item array_datatypes |
32eab2da |
1808 | |
9d48860e |
1809 | When this option is true, arrayrefs in INSERT or UPDATE are |
1810 | interpreted as array datatypes and are passed directly |
96449e8e |
1811 | to the DBI layer. |
1812 | When this option is false, arrayrefs are interpreted |
1813 | as literal SQL, just like refs to arrayrefs |
1814 | (but this behavior is for backwards compatibility; when writing |
1815 | new queries, use the "reference to arrayref" syntax |
1816 | for literal SQL). |
32eab2da |
1817 | |
32eab2da |
1818 | |
96449e8e |
1819 | =item special_ops |
32eab2da |
1820 | |
9d48860e |
1821 | Takes a reference to a list of "special operators" |
96449e8e |
1822 | to extend the syntax understood by L<SQL::Abstract>. |
1823 | See section L</"SPECIAL OPERATORS"> for details. |
32eab2da |
1824 | |
59f23b3d |
1825 | =item unary_ops |
1826 | |
9d48860e |
1827 | Takes a reference to a list of "unary operators" |
59f23b3d |
1828 | to extend the syntax understood by L<SQL::Abstract>. |
1829 | See section L</"UNARY OPERATORS"> for details. |
1830 | |
32eab2da |
1831 | |
32eab2da |
1832 | |
96449e8e |
1833 | =back |
32eab2da |
1834 | |
02288357 |
1835 | =head2 insert($table, \@values || \%fieldvals, \%options) |
32eab2da |
1836 | |
1837 | This is the simplest function. You simply give it a table name |
1838 | and either an arrayref of values or hashref of field/value pairs. |
1839 | It returns an SQL INSERT statement and a list of bind values. |
96449e8e |
1840 | See the sections on L</"Inserting and Updating Arrays"> and |
1841 | L</"Inserting and Updating SQL"> for information on how to insert |
1842 | with those data types. |
32eab2da |
1843 | |
02288357 |
1844 | The optional C<\%options> hash reference may contain additional |
1845 | options to generate the insert SQL. Currently supported options |
1846 | are: |
1847 | |
1848 | =over 4 |
1849 | |
1850 | =item returning |
1851 | |
1852 | Takes either a scalar of raw SQL fields, or an array reference of |
1853 | field names, and adds on an SQL C<RETURNING> statement at the end. |
1854 | This allows you to return data generated by the insert statement |
1855 | (such as row IDs) without performing another C<SELECT> statement. |
1856 | Note, however, this is not part of the SQL standard and may not |
1857 | be supported by all database engines. |
1858 | |
1859 | =back |
1860 | |
32eab2da |
1861 | =head2 update($table, \%fieldvals, \%where) |
1862 | |
1863 | This takes a table, hashref of field/value pairs, and an optional |
86298391 |
1864 | hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list |
32eab2da |
1865 | of bind values. |
96449e8e |
1866 | See the sections on L</"Inserting and Updating Arrays"> and |
1867 | L</"Inserting and Updating SQL"> for information on how to insert |
1868 | with those data types. |
32eab2da |
1869 | |
96449e8e |
1870 | =head2 select($source, $fields, $where, $order) |
32eab2da |
1871 | |
9d48860e |
1872 | This returns a SQL SELECT statement and associated list of bind values, as |
96449e8e |
1873 | specified by the arguments : |
32eab2da |
1874 | |
96449e8e |
1875 | =over |
32eab2da |
1876 | |
96449e8e |
1877 | =item $source |
32eab2da |
1878 | |
9d48860e |
1879 | Specification of the 'FROM' part of the statement. |
96449e8e |
1880 | The argument can be either a plain scalar (interpreted as a table |
1881 | name, will be quoted), or an arrayref (interpreted as a list |
1882 | of table names, joined by commas, quoted), or a scalarref |
1883 | (literal table name, not quoted), or a ref to an arrayref |
1884 | (list of literal table names, joined by commas, not quoted). |
32eab2da |
1885 | |
96449e8e |
1886 | =item $fields |
32eab2da |
1887 | |
9d48860e |
1888 | Specification of the list of fields to retrieve from |
96449e8e |
1889 | the source. |
1890 | The argument can be either an arrayref (interpreted as a list |
9d48860e |
1891 | of field names, will be joined by commas and quoted), or a |
96449e8e |
1892 | plain scalar (literal SQL, not quoted). |
1893 | Please observe that this API is not as flexible as for |
e3f9dff4 |
1894 | the first argument C<$table>, for backwards compatibility reasons. |
32eab2da |
1895 | |
96449e8e |
1896 | =item $where |
32eab2da |
1897 | |
96449e8e |
1898 | Optional argument to specify the WHERE part of the query. |
1899 | The argument is most often a hashref, but can also be |
9d48860e |
1900 | an arrayref or plain scalar -- |
96449e8e |
1901 | see section L<WHERE clause|/"WHERE CLAUSES"> for details. |
32eab2da |
1902 | |
96449e8e |
1903 | =item $order |
32eab2da |
1904 | |
96449e8e |
1905 | Optional argument to specify the ORDER BY part of the query. |
9d48860e |
1906 | The argument can be a scalar, a hashref or an arrayref |
96449e8e |
1907 | -- see section L<ORDER BY clause|/"ORDER BY CLAUSES"> |
1908 | for details. |
32eab2da |
1909 | |
96449e8e |
1910 | =back |
32eab2da |
1911 | |
32eab2da |
1912 | |
1913 | =head2 delete($table, \%where) |
1914 | |
86298391 |
1915 | This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>. |
32eab2da |
1916 | It returns an SQL DELETE statement and list of bind values. |
1917 | |
32eab2da |
1918 | =head2 where(\%where, \@order) |
1919 | |
1920 | This is used to generate just the WHERE clause. For example, |
1921 | if you have an arbitrary data structure and know what the |
1922 | rest of your SQL is going to look like, but want an easy way |
1923 | to produce a WHERE clause, use this. It returns an SQL WHERE |
1924 | clause and list of bind values. |
1925 | |
32eab2da |
1926 | |
1927 | =head2 values(\%data) |
1928 | |
1929 | This just returns the values from the hash C<%data>, in the same |
1930 | order that would be returned from any of the other above queries. |
1931 | Using this allows you to markedly speed up your queries if you |
1932 | are affecting lots of rows. See below under the L</"PERFORMANCE"> section. |
1933 | |
32eab2da |
1934 | =head2 generate($any, 'number', $of, \@data, $struct, \%types) |
1935 | |
1936 | Warning: This is an experimental method and subject to change. |
1937 | |
1938 | This returns arbitrarily generated SQL. It's a really basic shortcut. |
1939 | It will return two different things, depending on return context: |
1940 | |
1941 | my($stmt, @bind) = $sql->generate('create table', \$table, \@fields); |
1942 | my $stmt_and_val = $sql->generate('create table', \$table, \@fields); |
1943 | |
1944 | These would return the following: |
1945 | |
1946 | # First calling form |
1947 | $stmt = "CREATE TABLE test (?, ?)"; |
1948 | @bind = (field1, field2); |
1949 | |
1950 | # Second calling form |
1951 | $stmt_and_val = "CREATE TABLE test (field1, field2)"; |
1952 | |
1953 | Depending on what you're trying to do, it's up to you to choose the correct |
1954 | format. In this example, the second form is what you would want. |
1955 | |
1956 | By the same token: |
1957 | |
1958 | $sql->generate('alter session', { nls_date_format => 'MM/YY' }); |
1959 | |
1960 | Might give you: |
1961 | |
1962 | ALTER SESSION SET nls_date_format = 'MM/YY' |
1963 | |
1964 | You get the idea. Strings get their case twiddled, but everything |
1965 | else remains verbatim. |
1966 | |
32eab2da |
1967 | |
32eab2da |
1968 | |
32eab2da |
1969 | |
1970 | =head1 WHERE CLAUSES |
1971 | |
96449e8e |
1972 | =head2 Introduction |
1973 | |
32eab2da |
1974 | This module uses a variation on the idea from L<DBIx::Abstract>. It |
1975 | is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this |
1976 | module is that things in arrays are OR'ed, and things in hashes |
1977 | are AND'ed.> |
1978 | |
1979 | The easiest way to explain is to show lots of examples. After |
1980 | each C<%where> hash shown, it is assumed you used: |
1981 | |
1982 | my($stmt, @bind) = $sql->where(\%where); |
1983 | |
1984 | However, note that the C<%where> hash can be used directly in any |
1985 | of the other functions as well, as described above. |
1986 | |
96449e8e |
1987 | =head2 Key-value pairs |
1988 | |
32eab2da |
1989 | So, let's get started. To begin, a simple hash: |
1990 | |
1991 | my %where = ( |
1992 | user => 'nwiger', |
1993 | status => 'completed' |
1994 | ); |
1995 | |
1996 | Is converted to SQL C<key = val> statements: |
1997 | |
1998 | $stmt = "WHERE user = ? AND status = ?"; |
1999 | @bind = ('nwiger', 'completed'); |
2000 | |
2001 | One common thing I end up doing is having a list of values that |
2002 | a field can be in. To do this, simply specify a list inside of |
2003 | an arrayref: |
2004 | |
2005 | my %where = ( |
2006 | user => 'nwiger', |
2007 | status => ['assigned', 'in-progress', 'pending']; |
2008 | ); |
2009 | |
2010 | This simple code will create the following: |
9d48860e |
2011 | |
32eab2da |
2012 | $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )"; |
2013 | @bind = ('nwiger', 'assigned', 'in-progress', 'pending'); |
2014 | |
9d48860e |
2015 | A field associated to an empty arrayref will be considered a |
7cac25e6 |
2016 | logical false and will generate 0=1. |
8a68b5be |
2017 | |
b864ba9b |
2018 | =head2 Tests for NULL values |
2019 | |
2020 | If the value part is C<undef> then this is converted to SQL <IS NULL> |
2021 | |
2022 | my %where = ( |
2023 | user => 'nwiger', |
2024 | status => undef, |
2025 | ); |
2026 | |
2027 | becomes: |
2028 | |
2029 | $stmt = "WHERE user = ? AND status IS NULL"; |
2030 | @bind = ('nwiger'); |
2031 | |
e9614080 |
2032 | To test if a column IS NOT NULL: |
2033 | |
2034 | my %where = ( |
2035 | user => 'nwiger', |
2036 | status => { '!=', undef }, |
2037 | ); |
2038 | |
6e0c6552 |
2039 | =head2 Specific comparison operators |
96449e8e |
2040 | |
32eab2da |
2041 | If you want to specify a different type of operator for your comparison, |
2042 | you can use a hashref for a given column: |
2043 | |
2044 | my %where = ( |
2045 | user => 'nwiger', |
2046 | status => { '!=', 'completed' } |
2047 | ); |
2048 | |
2049 | Which would generate: |
2050 | |
2051 | $stmt = "WHERE user = ? AND status != ?"; |
2052 | @bind = ('nwiger', 'completed'); |
2053 | |
2054 | To test against multiple values, just enclose the values in an arrayref: |
2055 | |
96449e8e |
2056 | status => { '=', ['assigned', 'in-progress', 'pending'] }; |
2057 | |
f2d5020d |
2058 | Which would give you: |
96449e8e |
2059 | |
2060 | "WHERE status = ? OR status = ? OR status = ?" |
2061 | |
2062 | |
2063 | The hashref can also contain multiple pairs, in which case it is expanded |
32eab2da |
2064 | into an C<AND> of its elements: |
2065 | |
2066 | my %where = ( |
2067 | user => 'nwiger', |
2068 | status => { '!=', 'completed', -not_like => 'pending%' } |
2069 | ); |
2070 | |
2071 | # Or more dynamically, like from a form |
2072 | $where{user} = 'nwiger'; |
2073 | $where{status}{'!='} = 'completed'; |
2074 | $where{status}{'-not_like'} = 'pending%'; |
2075 | |
2076 | # Both generate this |
2077 | $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?"; |
2078 | @bind = ('nwiger', 'completed', 'pending%'); |
2079 | |
96449e8e |
2080 | |
32eab2da |
2081 | To get an OR instead, you can combine it with the arrayref idea: |
2082 | |
2083 | my %where => ( |
2084 | user => 'nwiger', |
1a6f2a03 |
2085 | priority => [ { '=', 2 }, { '>', 5 } ] |
32eab2da |
2086 | ); |
2087 | |
2088 | Which would generate: |
2089 | |
1a6f2a03 |
2090 | $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?"; |
2091 | @bind = ('2', '5', 'nwiger'); |
32eab2da |
2092 | |
44b9e502 |
2093 | If you want to include literal SQL (with or without bind values), just use a |
2094 | scalar reference or array reference as the value: |
2095 | |
2096 | my %where = ( |
2097 | date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] }, |
2098 | date_expires => { '<' => \"now()" } |
2099 | ); |
2100 | |
2101 | Which would generate: |
2102 | |
2103 | $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()"; |
2104 | @bind = ('11/26/2008'); |
2105 | |
96449e8e |
2106 | |
2107 | =head2 Logic and nesting operators |
2108 | |
2109 | In the example above, |
2110 | there is a subtle trap if you want to say something like |
32eab2da |
2111 | this (notice the C<AND>): |
2112 | |
2113 | WHERE priority != ? AND priority != ? |
2114 | |
2115 | Because, in Perl you I<can't> do this: |
2116 | |
2117 | priority => { '!=', 2, '!=', 1 } |
2118 | |
2119 | As the second C<!=> key will obliterate the first. The solution |
2120 | is to use the special C<-modifier> form inside an arrayref: |
2121 | |
9d48860e |
2122 | priority => [ -and => {'!=', 2}, |
96449e8e |
2123 | {'!=', 1} ] |
2124 | |
32eab2da |
2125 | |
2126 | Normally, these would be joined by C<OR>, but the modifier tells it |
2127 | to use C<AND> instead. (Hint: You can use this in conjunction with the |
2128 | C<logic> option to C<new()> in order to change the way your queries |
2129 | work by default.) B<Important:> Note that the C<-modifier> goes |
2130 | B<INSIDE> the arrayref, as an extra first element. This will |
2131 | B<NOT> do what you think it might: |
2132 | |
2133 | priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG! |
2134 | |
2135 | Here is a quick list of equivalencies, since there is some overlap: |
2136 | |
2137 | # Same |
2138 | status => {'!=', 'completed', 'not like', 'pending%' } |
2139 | status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}] |
2140 | |
2141 | # Same |
2142 | status => {'=', ['assigned', 'in-progress']} |
2143 | status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}] |
2144 | status => [ {'=', 'assigned'}, {'=', 'in-progress'} ] |
2145 | |
e3f9dff4 |
2146 | |
2147 | |
96449e8e |
2148 | =head2 Special operators : IN, BETWEEN, etc. |
2149 | |
32eab2da |
2150 | You can also use the hashref format to compare a list of fields using the |
2151 | C<IN> comparison operator, by specifying the list as an arrayref: |
2152 | |
2153 | my %where = ( |
2154 | status => 'completed', |
2155 | reportid => { -in => [567, 2335, 2] } |
2156 | ); |
2157 | |
2158 | Which would generate: |
2159 | |
2160 | $stmt = "WHERE status = ? AND reportid IN (?,?,?)"; |
2161 | @bind = ('completed', '567', '2335', '2'); |
2162 | |
9d48860e |
2163 | The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in |
96449e8e |
2164 | the same way. |
2165 | |
6e0c6552 |
2166 | If the argument to C<-in> is an empty array, 'sqlfalse' is generated |
2167 | (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates |
2168 | 'sqltrue' (by default : C<1=1>). |
2169 | |
e41c3bdd |
2170 | In addition to the array you can supply a chunk of literal sql or |
2171 | literal sql with bind: |
6e0c6552 |
2172 | |
e41c3bdd |
2173 | my %where = { |
2174 | customer => { -in => \[ |
2175 | 'SELECT cust_id FROM cust WHERE balance > ?', |
2176 | 2000, |
2177 | ], |
2178 | status => { -in => \'SELECT status_codes FROM states' }, |
2179 | }; |
6e0c6552 |
2180 | |
e41c3bdd |
2181 | would generate: |
2182 | |
2183 | $stmt = "WHERE ( |
2184 | customer IN ( SELECT cust_id FROM cust WHERE balance > ? ) |
2185 | AND status IN ( SELECT status_codes FROM states ) |
2186 | )"; |
2187 | @bind = ('2000'); |
2188 | |
2189 | |
2190 | |
2191 | Another pair of operators is C<-between> and C<-not_between>, |
96449e8e |
2192 | used with an arrayref of two values: |
32eab2da |
2193 | |
2194 | my %where = ( |
2195 | user => 'nwiger', |
2196 | completion_date => { |
2197 | -not_between => ['2002-10-01', '2003-02-06'] |
2198 | } |
2199 | ); |
2200 | |
2201 | Would give you: |
2202 | |
2203 | WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? ) |
2204 | |
e41c3bdd |
2205 | Just like with C<-in> all plausible combinations of literal SQL |
2206 | are possible: |
2207 | |
2208 | my %where = { |
2209 | start0 => { -between => [ 1, 2 ] }, |
2210 | start1 => { -between => \["? AND ?", 1, 2] }, |
2211 | start2 => { -between => \"lower(x) AND upper(y)" }, |
9d48860e |
2212 | start3 => { -between => [ |
e41c3bdd |
2213 | \"lower(x)", |
2214 | \["upper(?)", 'stuff' ], |
2215 | ] }, |
2216 | }; |
2217 | |
2218 | Would give you: |
2219 | |
2220 | $stmt = "WHERE ( |
2221 | ( start0 BETWEEN ? AND ? ) |
2222 | AND ( start1 BETWEEN ? AND ? ) |
2223 | AND ( start2 BETWEEN lower(x) AND upper(y) ) |
2224 | AND ( start3 BETWEEN lower(x) AND upper(?) ) |
2225 | )"; |
2226 | @bind = (1, 2, 1, 2, 'stuff'); |
2227 | |
2228 | |
9d48860e |
2229 | These are the two builtin "special operators"; but the |
96449e8e |
2230 | list can be expanded : see section L</"SPECIAL OPERATORS"> below. |
2231 | |
59f23b3d |
2232 | =head2 Unary operators: bool |
97a920ef |
2233 | |
2234 | If you wish to test against boolean columns or functions within your |
2235 | database you can use the C<-bool> and C<-not_bool> operators. For |
2236 | example to test the column C<is_user> being true and the column |
827bb0eb |
2237 | C<is_enabled> being false you would use:- |
97a920ef |
2238 | |
2239 | my %where = ( |
2240 | -bool => 'is_user', |
2241 | -not_bool => 'is_enabled', |
2242 | ); |
2243 | |
2244 | Would give you: |
2245 | |
277b5d3f |
2246 | WHERE is_user AND NOT is_enabled |
97a920ef |
2247 | |
0b604e9d |
2248 | If a more complex combination is required, testing more conditions, |
2249 | then you should use the and/or operators:- |
2250 | |
2251 | my %where = ( |
2252 | -and => [ |
2253 | -bool => 'one', |
2254 | -bool => 'two', |
2255 | -bool => 'three', |
2256 | -not_bool => 'four', |
2257 | ], |
2258 | ); |
2259 | |
2260 | Would give you: |
2261 | |
2262 | WHERE one AND two AND three AND NOT four |
97a920ef |
2263 | |
2264 | |
107b72f1 |
2265 | =head2 Nested conditions, -and/-or prefixes |
96449e8e |
2266 | |
32eab2da |
2267 | So far, we've seen how multiple conditions are joined with a top-level |
2268 | C<AND>. We can change this by putting the different conditions we want in |
2269 | hashes and then putting those hashes in an array. For example: |
2270 | |
2271 | my @where = ( |
2272 | { |
2273 | user => 'nwiger', |
2274 | status => { -like => ['pending%', 'dispatched'] }, |
2275 | }, |
2276 | { |
2277 | user => 'robot', |
2278 | status => 'unassigned', |
2279 | } |
2280 | ); |
2281 | |
2282 | This data structure would create the following: |
2283 | |
2284 | $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) ) |
2285 | OR ( user = ? AND status = ? ) )"; |
2286 | @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned'); |
2287 | |
107b72f1 |
2288 | |
48d9f5f8 |
2289 | Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or> |
2290 | to change the logic inside : |
32eab2da |
2291 | |
2292 | my @where = ( |
2293 | -and => [ |
2294 | user => 'nwiger', |
48d9f5f8 |
2295 | [ |
2296 | -and => [ workhrs => {'>', 20}, geo => 'ASIA' ], |
2297 | -or => { workhrs => {'<', 50}, geo => 'EURO' }, |
32eab2da |
2298 | ], |
2299 | ], |
2300 | ); |
2301 | |
2302 | That would yield: |
2303 | |
48d9f5f8 |
2304 | WHERE ( user = ? AND ( |
2305 | ( workhrs > ? AND geo = ? ) |
2306 | OR ( workhrs < ? OR geo = ? ) |
2307 | ) ) |
107b72f1 |
2308 | |
2309 | =head2 Algebraic inconsistency, for historical reasons |
2310 | |
7cac25e6 |
2311 | C<Important note>: when connecting several conditions, the C<-and->|C<-or> |
2312 | operator goes C<outside> of the nested structure; whereas when connecting |
2313 | several constraints on one column, the C<-and> operator goes |
2314 | C<inside> the arrayref. Here is an example combining both features : |
2315 | |
2316 | my @where = ( |
2317 | -and => [a => 1, b => 2], |
2318 | -or => [c => 3, d => 4], |
2319 | e => [-and => {-like => 'foo%'}, {-like => '%bar'} ] |
2320 | ) |
2321 | |
2322 | yielding |
2323 | |
9d48860e |
2324 | WHERE ( ( ( a = ? AND b = ? ) |
2325 | OR ( c = ? OR d = ? ) |
7cac25e6 |
2326 | OR ( e LIKE ? AND e LIKE ? ) ) ) |
2327 | |
107b72f1 |
2328 | This difference in syntax is unfortunate but must be preserved for |
2329 | historical reasons. So be careful : the two examples below would |
2330 | seem algebraically equivalent, but they are not |
2331 | |
9d48860e |
2332 | {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]} |
107b72f1 |
2333 | # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) ) |
2334 | |
9d48860e |
2335 | [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]] |
107b72f1 |
2336 | # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) ) |
2337 | |
7cac25e6 |
2338 | |
96449e8e |
2339 | =head2 Literal SQL |
2340 | |
e9614080 |
2341 | Finally, sometimes only literal SQL will do. |
2342 | To include literal SQL verbatim, you specify it as a scalar reference. |
2343 | Consider this only as a last resort. Usually there is a better way. |
2344 | |
2345 | Literal SQL is the only way to compare 2 columns to one another: |
32eab2da |
2346 | |
e9614080 |
2347 | my %where = ( |
2348 | priority => { '<', 2 }, |
2349 | requestor => \'= submittor' |
2350 | ); |
2351 | |
2352 | which creates: |
2353 | |
2354 | $stmt = "WHERE priority < ? AND requestor = submitter"; |
2355 | @bind = ('2'); |
2356 | |
2357 | |
2358 | There is a nicer way to test for NULL, but just for the sake of example: |
2359 | |
2360 | my $inn = 'IS NOT NULL'; |
32eab2da |
2361 | my %where = ( |
2362 | priority => { '<', 2 }, |
2363 | requestor => \$inn |
2364 | ); |
2365 | |
2366 | This would create: |
2367 | |
2368 | $stmt = "WHERE priority < ? AND requestor is Not Null"; |
2369 | @bind = ('2'); |
2370 | |
2371 | Note that in this example, you only get one bind parameter back, since |
2372 | the verbatim SQL is passed as part of the statement. |
2373 | |
2374 | Of course, just to prove a point, the above can also be accomplished |
2375 | with this: |
2376 | |
2377 | my %where = ( |
2378 | priority => { '<', 2 }, |
2379 | requestor => { '!=', undef }, |
2380 | ); |
2381 | |
96449e8e |
2382 | |
e9614080 |
2383 | Conditions on boolean columns can be expressed by passing |
0b604e9d |
2384 | a reference to an empty string, however using liternal SQL in this way |
2385 | is deprecated - the preferred method is to use the boolean operators - |
2386 | see L</"Unary operators: bool"> : |
96449e8e |
2387 | |
2388 | my %where = ( |
2389 | priority => { '<', 2 }, |
2390 | is_ready => \""; |
2391 | ); |
2392 | |
2393 | which yields |
2394 | |
2395 | $stmt = "WHERE priority < ? AND is_ready"; |
2396 | @bind = ('2'); |
2397 | |
96449e8e |
2398 | =head2 Literal SQL with placeholders and bind values (subqueries) |
2399 | |
2400 | If the literal SQL to be inserted has placeholders and bind values, |
2401 | use a reference to an arrayref (yes this is a double reference -- |
2402 | not so common, but perfectly legal Perl). For example, to find a date |
2403 | in Postgres you can use something like this: |
2404 | |
2405 | my %where = ( |
2406 | date_column => \[q/= date '2008-09-30' - ?::integer/, 10/] |
2407 | ) |
2408 | |
2409 | This would create: |
2410 | |
d2a8fe1a |
2411 | $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )" |
96449e8e |
2412 | @bind = ('10'); |
2413 | |
deb148a2 |
2414 | Note that you must pass the bind values in the same format as they are returned |
62552e7d |
2415 | by L</where>. That means that if you set L</bindtype> to C<columns>, you must |
26f2dca5 |
2416 | provide the bind values in the C<< [ column_meta => value ] >> format, where |
2417 | C<column_meta> is an opaque scalar value; most commonly the column name, but |
62552e7d |
2418 | you can use any scalar value (including references and blessed references), |
2419 | L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set |
2420 | to C<columns> the above example will look like: |
deb148a2 |
2421 | |
2422 | my %where = ( |
2423 | date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/] |
2424 | ) |
96449e8e |
2425 | |
2426 | Literal SQL is especially useful for nesting parenthesized clauses in the |
2427 | main SQL query. Here is a first example : |
2428 | |
2429 | my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?", |
2430 | 100, "foo%"); |
2431 | my %where = ( |
2432 | foo => 1234, |
2433 | bar => \["IN ($sub_stmt)" => @sub_bind], |
2434 | ); |
2435 | |
2436 | This yields : |
2437 | |
9d48860e |
2438 | $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1 |
96449e8e |
2439 | WHERE c2 < ? AND c3 LIKE ?))"; |
2440 | @bind = (1234, 100, "foo%"); |
2441 | |
9d48860e |
2442 | Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">, |
96449e8e |
2443 | are expressed in the same way. Of course the C<$sub_stmt> and |
9d48860e |
2444 | its associated bind values can be generated through a former call |
96449e8e |
2445 | to C<select()> : |
2446 | |
2447 | my ($sub_stmt, @sub_bind) |
9d48860e |
2448 | = $sql->select("t1", "c1", {c2 => {"<" => 100}, |
96449e8e |
2449 | c3 => {-like => "foo%"}}); |
2450 | my %where = ( |
2451 | foo => 1234, |
2452 | bar => \["> ALL ($sub_stmt)" => @sub_bind], |
2453 | ); |
2454 | |
2455 | In the examples above, the subquery was used as an operator on a column; |
9d48860e |
2456 | but the same principle also applies for a clause within the main C<%where> |
96449e8e |
2457 | hash, like an EXISTS subquery : |
2458 | |
9d48860e |
2459 | my ($sub_stmt, @sub_bind) |
96449e8e |
2460 | = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"}); |
48d9f5f8 |
2461 | my %where = ( -and => [ |
96449e8e |
2462 | foo => 1234, |
48d9f5f8 |
2463 | \["EXISTS ($sub_stmt)" => @sub_bind], |
2464 | ]); |
96449e8e |
2465 | |
2466 | which yields |
2467 | |
9d48860e |
2468 | $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1 |
96449e8e |
2469 | WHERE c1 = ? AND c2 > t0.c0))"; |
2470 | @bind = (1234, 1); |
2471 | |
2472 | |
9d48860e |
2473 | Observe that the condition on C<c2> in the subquery refers to |
2474 | column C<t0.c0> of the main query : this is I<not> a bind |
2475 | value, so we have to express it through a scalar ref. |
96449e8e |
2476 | Writing C<< c2 => {">" => "t0.c0"} >> would have generated |
2477 | C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly |
2478 | what we wanted here. |
2479 | |
96449e8e |
2480 | Finally, here is an example where a subquery is used |
2481 | for expressing unary negation: |
2482 | |
9d48860e |
2483 | my ($sub_stmt, @sub_bind) |
96449e8e |
2484 | = $sql->where({age => [{"<" => 10}, {">" => 20}]}); |
2485 | $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause |
2486 | my %where = ( |
2487 | lname => {like => '%son%'}, |
48d9f5f8 |
2488 | \["NOT ($sub_stmt)" => @sub_bind], |
96449e8e |
2489 | ); |
2490 | |
2491 | This yields |
2492 | |
2493 | $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )" |
2494 | @bind = ('%son%', 10, 20) |
2495 | |
2496 | |
2497 | |
2498 | =head2 Conclusion |
2499 | |
32eab2da |
2500 | These pages could go on for a while, since the nesting of the data |
2501 | structures this module can handle are pretty much unlimited (the |
2502 | module implements the C<WHERE> expansion as a recursive function |
2503 | internally). Your best bet is to "play around" with the module a |
2504 | little to see how the data structures behave, and choose the best |
2505 | format for your data based on that. |
2506 | |
2507 | And of course, all the values above will probably be replaced with |
2508 | variables gotten from forms or the command line. After all, if you |
2509 | knew everything ahead of time, you wouldn't have to worry about |
2510 | dynamically-generating SQL and could just hardwire it into your |
2511 | script. |
2512 | |
96449e8e |
2513 | |
2514 | |
2515 | |
86298391 |
2516 | =head1 ORDER BY CLAUSES |
2517 | |
9d48860e |
2518 | Some functions take an order by clause. This can either be a scalar (just a |
86298391 |
2519 | column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>, |
1cfa1db3 |
2520 | or an array of either of the two previous forms. Examples: |
2521 | |
952f9e2d |
2522 | Given | Will Generate |
1cfa1db3 |
2523 | ---------------------------------------------------------- |
952f9e2d |
2524 | | |
2525 | \'colA DESC' | ORDER BY colA DESC |
2526 | | |
2527 | 'colA' | ORDER BY colA |
2528 | | |
2529 | [qw/colA colB/] | ORDER BY colA, colB |
2530 | | |
2531 | {-asc => 'colA'} | ORDER BY colA ASC |
2532 | | |
2533 | {-desc => 'colB'} | ORDER BY colB DESC |
2534 | | |
2535 | ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC |
2536 | | |
855e6047 |
2537 | { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC |
952f9e2d |
2538 | | |
2539 | [ | |
2540 | { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC, |
2541 | { -desc => [qw/colB/], | colC ASC, colD ASC |
2542 | { -asc => [qw/colC colD/],| |
2543 | ] | |
2544 | =========================================================== |
86298391 |
2545 | |
96449e8e |
2546 | |
2547 | |
2548 | =head1 SPECIAL OPERATORS |
2549 | |
e3f9dff4 |
2550 | my $sqlmaker = SQL::Abstract->new(special_ops => [ |
3a2e1a5e |
2551 | { |
2552 | regex => qr/.../, |
e3f9dff4 |
2553 | handler => sub { |
2554 | my ($self, $field, $op, $arg) = @_; |
2555 | ... |
3a2e1a5e |
2556 | }, |
2557 | }, |
2558 | { |
2559 | regex => qr/.../, |
2560 | handler => 'method_name', |
e3f9dff4 |
2561 | }, |
2562 | ]); |
2563 | |
9d48860e |
2564 | A "special operator" is a SQL syntactic clause that can be |
e3f9dff4 |
2565 | applied to a field, instead of a usual binary operator. |
9d48860e |
2566 | For example : |
e3f9dff4 |
2567 | |
2568 | WHERE field IN (?, ?, ?) |
2569 | WHERE field BETWEEN ? AND ? |
2570 | WHERE MATCH(field) AGAINST (?, ?) |
96449e8e |
2571 | |
e3f9dff4 |
2572 | Special operators IN and BETWEEN are fairly standard and therefore |
3a2e1a5e |
2573 | are builtin within C<SQL::Abstract> (as the overridable methods |
2574 | C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators, |
2575 | like the MATCH .. AGAINST example above which is specific to MySQL, |
2576 | you can write your own operator handlers - supply a C<special_ops> |
2577 | argument to the C<new> method. That argument takes an arrayref of |
2578 | operator definitions; each operator definition is a hashref with two |
2579 | entries: |
96449e8e |
2580 | |
e3f9dff4 |
2581 | =over |
2582 | |
2583 | =item regex |
2584 | |
2585 | the regular expression to match the operator |
96449e8e |
2586 | |
e3f9dff4 |
2587 | =item handler |
2588 | |
3a2e1a5e |
2589 | Either a coderef or a plain scalar method name. In both cases |
2590 | the expected return is C<< ($sql, @bind) >>. |
2591 | |
2592 | When supplied with a method name, it is simply called on the |
2593 | L<SQL::Abstract/> object as: |
2594 | |
2595 | $self->$method_name ($field, $op, $arg) |
2596 | |
2597 | Where: |
2598 | |
2599 | $op is the part that matched the handler regex |
2600 | $field is the LHS of the operator |
2601 | $arg is the RHS |
2602 | |
2603 | When supplied with a coderef, it is called as: |
2604 | |
2605 | $coderef->($self, $field, $op, $arg) |
2606 | |
e3f9dff4 |
2607 | |
2608 | =back |
2609 | |
9d48860e |
2610 | For example, here is an implementation |
e3f9dff4 |
2611 | of the MATCH .. AGAINST syntax for MySQL |
2612 | |
2613 | my $sqlmaker = SQL::Abstract->new(special_ops => [ |
9d48860e |
2614 | |
e3f9dff4 |
2615 | # special op for MySql MATCH (field) AGAINST(word1, word2, ...) |
9d48860e |
2616 | {regex => qr/^match$/i, |
e3f9dff4 |
2617 | handler => sub { |
2618 | my ($self, $field, $op, $arg) = @_; |
2619 | $arg = [$arg] if not ref $arg; |
2620 | my $label = $self->_quote($field); |
2621 | my ($placeholder) = $self->_convert('?'); |
2622 | my $placeholders = join ", ", (($placeholder) x @$arg); |
2623 | my $sql = $self->_sqlcase('match') . " ($label) " |
2624 | . $self->_sqlcase('against') . " ($placeholders) "; |
2625 | my @bind = $self->_bindtype($field, @$arg); |
2626 | return ($sql, @bind); |
2627 | } |
2628 | }, |
9d48860e |
2629 | |
e3f9dff4 |
2630 | ]); |
96449e8e |
2631 | |
2632 | |
59f23b3d |
2633 | =head1 UNARY OPERATORS |
2634 | |
112b5232 |
2635 | my $sqlmaker = SQL::Abstract->new(unary_ops => [ |
59f23b3d |
2636 | { |
2637 | regex => qr/.../, |
2638 | handler => sub { |
2639 | my ($self, $op, $arg) = @_; |
2640 | ... |
2641 | }, |
2642 | }, |
2643 | { |
2644 | regex => qr/.../, |
2645 | handler => 'method_name', |
2646 | }, |
2647 | ]); |
2648 | |
9d48860e |
2649 | A "unary operator" is a SQL syntactic clause that can be |
59f23b3d |
2650 | applied to a field - the operator goes before the field |
2651 | |
2652 | You can write your own operator handlers - supply a C<unary_ops> |
2653 | argument to the C<new> method. That argument takes an arrayref of |
2654 | operator definitions; each operator definition is a hashref with two |
2655 | entries: |
2656 | |
2657 | =over |
2658 | |
2659 | =item regex |
2660 | |
2661 | the regular expression to match the operator |
2662 | |
2663 | =item handler |
2664 | |
2665 | Either a coderef or a plain scalar method name. In both cases |
2666 | the expected return is C<< $sql >>. |
2667 | |
2668 | When supplied with a method name, it is simply called on the |
2669 | L<SQL::Abstract/> object as: |
2670 | |
2671 | $self->$method_name ($op, $arg) |
2672 | |
2673 | Where: |
2674 | |
2675 | $op is the part that matched the handler regex |
2676 | $arg is the RHS or argument of the operator |
2677 | |
2678 | When supplied with a coderef, it is called as: |
2679 | |
2680 | $coderef->($self, $op, $arg) |
2681 | |
2682 | |
2683 | =back |
2684 | |
2685 | |
32eab2da |
2686 | =head1 PERFORMANCE |
2687 | |
2688 | Thanks to some benchmarking by Mark Stosberg, it turns out that |
2689 | this module is many orders of magnitude faster than using C<DBIx::Abstract>. |
2690 | I must admit this wasn't an intentional design issue, but it's a |
2691 | byproduct of the fact that you get to control your C<DBI> handles |
2692 | yourself. |
2693 | |
2694 | To maximize performance, use a code snippet like the following: |
2695 | |
2696 | # prepare a statement handle using the first row |
2697 | # and then reuse it for the rest of the rows |
2698 | my($sth, $stmt); |
2699 | for my $href (@array_of_hashrefs) { |
2700 | $stmt ||= $sql->insert('table', $href); |
2701 | $sth ||= $dbh->prepare($stmt); |
2702 | $sth->execute($sql->values($href)); |
2703 | } |
2704 | |
2705 | The reason this works is because the keys in your C<$href> are sorted |
2706 | internally by B<SQL::Abstract>. Thus, as long as your data retains |
2707 | the same structure, you only have to generate the SQL the first time |
2708 | around. On subsequent queries, simply use the C<values> function provided |
2709 | by this module to return your values in the correct order. |
2710 | |
b864ba9b |
2711 | However this depends on the values having the same type - if, for |
2712 | example, the values of a where clause may either have values |
2713 | (resulting in sql of the form C<column = ?> with a single bind |
2714 | value), or alternatively the values might be C<undef> (resulting in |
2715 | sql of the form C<column IS NULL> with no bind value) then the |
2716 | caching technique suggested will not work. |
96449e8e |
2717 | |
32eab2da |
2718 | =head1 FORMBUILDER |
2719 | |
2720 | If you use my C<CGI::FormBuilder> module at all, you'll hopefully |
2721 | really like this part (I do, at least). Building up a complex query |
2722 | can be as simple as the following: |
2723 | |
2724 | #!/usr/bin/perl |
2725 | |
2726 | use CGI::FormBuilder; |
2727 | use SQL::Abstract; |
2728 | |
2729 | my $form = CGI::FormBuilder->new(...); |
2730 | my $sql = SQL::Abstract->new; |
2731 | |
2732 | if ($form->submitted) { |
2733 | my $field = $form->field; |
2734 | my $id = delete $field->{id}; |
2735 | my($stmt, @bind) = $sql->update('table', $field, {id => $id}); |
2736 | } |
2737 | |
2738 | Of course, you would still have to connect using C<DBI> to run the |
2739 | query, but the point is that if you make your form look like your |
2740 | table, the actual query script can be extremely simplistic. |
2741 | |
2742 | If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for |
9d48860e |
2743 | a fast interface to returning and formatting data. I frequently |
32eab2da |
2744 | use these three modules together to write complex database query |
2745 | apps in under 50 lines. |
2746 | |
d8cc1792 |
2747 | =head1 REPO |
2748 | |
2749 | =over |
2750 | |
6d19fbf9 |
2751 | =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git> |
d8cc1792 |
2752 | |
6d19fbf9 |
2753 | =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git> |
d8cc1792 |
2754 | |
2755 | =back |
32eab2da |
2756 | |
96449e8e |
2757 | =head1 CHANGES |
2758 | |
2759 | Version 1.50 was a major internal refactoring of C<SQL::Abstract>. |
2760 | Great care has been taken to preserve the I<published> behavior |
2761 | documented in previous versions in the 1.* family; however, |
9d48860e |
2762 | some features that were previously undocumented, or behaved |
96449e8e |
2763 | differently from the documentation, had to be changed in order |
2764 | to clarify the semantics. Hence, client code that was relying |
9d48860e |
2765 | on some dark areas of C<SQL::Abstract> v1.* |
96449e8e |
2766 | B<might behave differently> in v1.50. |
32eab2da |
2767 | |
d2a8fe1a |
2768 | The main changes are : |
2769 | |
96449e8e |
2770 | =over |
32eab2da |
2771 | |
9d48860e |
2772 | =item * |
32eab2da |
2773 | |
96449e8e |
2774 | support for literal SQL through the C<< \ [$sql, bind] >> syntax. |
2775 | |
2776 | =item * |
2777 | |
145fbfc8 |
2778 | support for the { operator => \"..." } construct (to embed literal SQL) |
2779 | |
2780 | =item * |
2781 | |
9c37b9c0 |
2782 | support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values) |
2783 | |
2784 | =item * |
2785 | |
96449e8e |
2786 | optional support for L<array datatypes|/"Inserting and Updating Arrays"> |
2787 | |
9d48860e |
2788 | =item * |
96449e8e |
2789 | |
2790 | defensive programming : check arguments |
2791 | |
2792 | =item * |
2793 | |
2794 | fixed bug with global logic, which was previously implemented |
7cac25e6 |
2795 | through global variables yielding side-effects. Prior versions would |
96449e8e |
2796 | interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >> |
2797 | as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>. |
2798 | Now this is interpreted |
2799 | as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>. |
2800 | |
96449e8e |
2801 | |
2802 | =item * |
2803 | |
2804 | fixed semantics of _bindtype on array args |
2805 | |
9d48860e |
2806 | =item * |
96449e8e |
2807 | |
2808 | dropped the C<_anoncopy> of the %where tree. No longer necessary, |
2809 | we just avoid shifting arrays within that tree. |
2810 | |
2811 | =item * |
2812 | |
2813 | dropped the C<_modlogic> function |
2814 | |
2815 | =back |
32eab2da |
2816 | |
32eab2da |
2817 | |
32eab2da |
2818 | |
2819 | =head1 ACKNOWLEDGEMENTS |
2820 | |
2821 | There are a number of individuals that have really helped out with |
2822 | this module. Unfortunately, most of them submitted bugs via CPAN |
2823 | so I have no idea who they are! But the people I do know are: |
2824 | |
9d48860e |
2825 | Ash Berlin (order_by hash term support) |
b643abe1 |
2826 | Matt Trout (DBIx::Class support) |
32eab2da |
2827 | Mark Stosberg (benchmarking) |
2828 | Chas Owens (initial "IN" operator support) |
2829 | Philip Collins (per-field SQL functions) |
2830 | Eric Kolve (hashref "AND" support) |
2831 | Mike Fragassi (enhancements to "BETWEEN" and "LIKE") |
2832 | Dan Kubb (support for "quote_char" and "name_sep") |
f5aab26e |
2833 | Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by) |
48d9f5f8 |
2834 | Laurent Dami (internal refactoring, extensible list of special operators, literal SQL) |
dbdf7648 |
2835 | Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests) |
e96c510a |
2836 | Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests) |
02288357 |
2837 | Oliver Charles (support for "RETURNING" after "INSERT") |
32eab2da |
2838 | |
2839 | Thanks! |
2840 | |
32eab2da |
2841 | =head1 SEE ALSO |
2842 | |
86298391 |
2843 | L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>. |
32eab2da |
2844 | |
32eab2da |
2845 | =head1 AUTHOR |
2846 | |
b643abe1 |
2847 | Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved. |
2848 | |
2849 | This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk> |
32eab2da |
2850 | |
abe72f94 |
2851 | For support, your best bet is to try the C<DBIx::Class> users mailing list. |
2852 | While not an official support venue, C<DBIx::Class> makes heavy use of |
2853 | C<SQL::Abstract>, and as such list members there are very familiar with |
2854 | how to create queries. |
2855 | |
0d067ded |
2856 | =head1 LICENSE |
2857 | |
d988ab87 |
2858 | This module is free software; you may copy this under the same |
2859 | terms as perl itself (either the GNU General Public License or |
2860 | the Artistic License) |
32eab2da |
2861 | |
2862 | =cut |
2863 | |