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