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