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