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