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