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