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