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