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