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