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