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