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