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