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