refactor somewhat and convert order_by
[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 DQ_ORDER
15 );
16 use Data::Query::ExprHelpers qw(perl_scalar_value);
17
18 #======================================================================
19 # GLOBALS
20 #======================================================================
21
22 our $VERSION  = '1.72';
23
24 # This would confuse some packagers
25 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
26
27 our $AUTOLOAD;
28
29 # special operators (-in, -between). May be extended/overridden by user.
30 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
31 my @BUILTIN_SPECIAL_OPS = (
32   {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
33   {regex => qr/^ (?: not \s )? in      $/ix, handler => '_where_field_IN'},
34   {regex => qr/^ ident                 $/ix, handler => '_where_op_IDENT'},
35   {regex => qr/^ value                 $/ix, handler => '_where_op_VALUE'},
36 );
37
38 # unaryish operators - key maps to handler
39 my @BUILTIN_UNARY_OPS = (
40   # the digits are backcompat stuff
41   { regex => qr/^ and  (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
42   { regex => qr/^ or   (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
43   { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
44   { regex => qr/^ (?: not \s )? bool     $/xi, handler => '_where_op_BOOL' },
45   { regex => qr/^ ident                  $/xi, handler => '_where_op_IDENT' },
46   { regex => qr/^ value                  $/ix, handler => '_where_op_VALUE' },
47 );
48
49 #======================================================================
50 # DEBUGGING AND ERROR REPORTING
51 #======================================================================
52
53 sub _debug {
54   return unless $_[0]->{debug}; shift; # a little faster
55   my $func = (caller(1))[3];
56   warn "[$func] ", @_, "\n";
57 }
58
59 sub belch (@) {
60   my($func) = (caller(1))[3];
61   Carp::carp "[$func] Warning: ", @_;
62 }
63
64 sub puke (@) {
65   my($func) = (caller(1))[3];
66   Carp::croak "[$func] Fatal: ", @_;
67 }
68
69
70 #======================================================================
71 # NEW
72 #======================================================================
73
74 sub new {
75   my $self = shift;
76   my $class = ref($self) || $self;
77   my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
78
79   # choose our case by keeping an option around
80   delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
81
82   # default logic for interpreting arrayrefs
83   $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
84
85   # how to return bind vars
86   # LDNOTE: changed nwiger code : why this 'delete' ??
87   # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
88   $opt{bindtype} ||= 'normal';
89
90   # default comparison is "=", but can be overridden
91   $opt{cmp} ||= '=';
92
93   # try to recognize which are the 'equality' and 'unequality' ops
94   # (temporary quickfix, should go through a more seasoned API)
95   $opt{equality_op}   = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
96   $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
97
98   # SQL booleans
99   $opt{sqltrue}  ||= '1=1';
100   $opt{sqlfalse} ||= '0=1';
101
102   # special operators
103   $opt{special_ops} ||= [];
104   # regexes are applied in order, thus push after user-defines
105   push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
106
107   # unary operators
108   $opt{unary_ops} ||= [];
109   push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
110
111   # rudimentary saniy-check for user supplied bits treated as functions/operators
112   # If a purported  function matches this regular expression, an exception is thrown.
113   # Literal SQL is *NOT* subject to this check, only functions (and column names
114   # when quoting is not in effect)
115
116   # FIXME
117   # need to guard against ()'s in column names too, but this will break tons of
118   # hacks... ideas anyone?
119   $opt{injection_guard} ||= qr/
120     \;
121       |
122     ^ \s* go \s
123   /xmi;
124
125   $opt{name_sep} ||= '.';
126
127   $opt{renderer} ||= do {
128     require Data::Query::Renderer::SQL::Naive;
129     my ($always, $chars);
130     for ($opt{quote_char}) {
131       $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
132       $always = defined;
133     }
134     Data::Query::Renderer::SQL::Naive->new({
135       quote_chars => $chars, always_quote => $always,
136     });
137   };
138
139   return bless \%opt, $class;
140 }
141
142 sub _render_dq {
143   my ($self, $dq) = @_;
144   my ($sql, @bind) = @{$self->{renderer}->render($dq)};
145   wantarray ?
146     ($self->{bindtype} eq 'normal'
147       ? ($sql, map $_->{value}, @bind)
148       : ($sql, map [ $_->{meta}, $_->{value} ], @bind)
149     )
150     : $sql;
151 }
152
153 sub _bind_to_dq {
154   my ($self, @bind) = @_;
155   $self->{bindtype} eq 'normal'
156     ? map perl_scalar_value($_), @bind
157     : map perl_scalar_value(reverse @$_), @bind
158 }
159
160 sub _ident_to_dq {
161   my ($self, $ident) = @_;
162   +{
163     type => DQ_IDENTIFIER,
164     elements => [ split /\Q$self->{name_sep}/, $ident ],
165   };
166 }
167
168 sub _assert_pass_injection_guard {
169   if ($_[1] =~ $_[0]->{injection_guard}) {
170     my $class = ref $_[0];
171     puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
172      . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
173      . "{injection_guard} attribute to ${class}->new()"
174   }
175 }
176
177
178 #======================================================================
179 # INSERT methods
180 #======================================================================
181
182 sub insert {
183   my $self    = shift;
184   my $table   = $self->_table(shift);
185   my $data    = shift || return;
186   my $options = shift;
187
188   my $method       = $self->_METHOD_FOR_refkind("_insert", $data);
189   my ($sql, @bind) = $self->$method($data);
190   $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
191
192   if ($options->{returning}) {
193     my ($s, @b) = $self->_insert_returning ($options);
194     $sql .= $s;
195     push @bind, @b;
196   }
197
198   return wantarray ? ($sql, @bind) : $sql;
199 }
200
201 sub _insert_returning {
202   my ($self, $options) = @_;
203
204   my $f = $options->{returning};
205
206   my $fieldlist = $self->_SWITCH_refkind($f, {
207     ARRAYREF     => sub {join ', ', map { $self->_quote($_) } @$f;},
208     SCALAR       => sub {$self->_quote($f)},
209     SCALARREF    => sub {$$f},
210   });
211   return $self->_sqlcase(' returning ') . $fieldlist;
212 }
213
214 sub _insert_HASHREF { # explicit list of fields and then values
215   my ($self, $data) = @_;
216
217   my @fields = sort keys %$data;
218
219   my ($sql, @bind) = $self->_insert_values($data);
220
221   # assemble SQL
222   $_ = $self->_quote($_) foreach @fields;
223   $sql = "( ".join(", ", @fields).") ".$sql;
224
225   return ($sql, @bind);
226 }
227
228 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
229   my ($self, $data) = @_;
230
231   # no names (arrayref) so can't generate bindtype
232   $self->{bindtype} ne 'columns'
233     or belch "can't do 'columns' bindtype when called with arrayref";
234
235   # fold the list of values into a hash of column name - value pairs
236   # (where the column names are artificially generated, and their
237   # lexicographical ordering keep the ordering of the original list)
238   my $i = "a";  # incremented values will be in lexicographical order
239   my $data_in_hash = { map { ($i++ => $_) } @$data };
240
241   return $self->_insert_values($data_in_hash);
242 }
243
244 sub _insert_ARRAYREFREF { # literal SQL with bind
245   my ($self, $data) = @_;
246
247   my ($sql, @bind) = @${$data};
248   $self->_assert_bindval_matches_bindtype(@bind);
249
250   return ($sql, @bind);
251 }
252
253
254 sub _insert_SCALARREF { # literal SQL without bind
255   my ($self, $data) = @_;
256
257   return ($$data);
258 }
259
260 sub _insert_values {
261   my ($self, $data) = @_;
262
263   my (@values, @all_bind);
264   foreach my $column (sort keys %$data) {
265     my $v = $data->{$column};
266
267     $self->_SWITCH_refkind($v, {
268
269       ARRAYREF => sub {
270         if ($self->{array_datatypes}) { # if array datatype are activated
271           push @values, '?';
272           push @all_bind, $self->_bindtype($column, $v);
273         }
274         else {                          # else literal SQL with bind
275           my ($sql, @bind) = @$v;
276           $self->_assert_bindval_matches_bindtype(@bind);
277           push @values, $sql;
278           push @all_bind, @bind;
279         }
280       },
281
282       ARRAYREFREF => sub { # literal SQL with bind
283         my ($sql, @bind) = @${$v};
284         $self->_assert_bindval_matches_bindtype(@bind);
285         push @values, $sql;
286         push @all_bind, @bind;
287       },
288
289       # THINK : anything useful to do with a HASHREF ?
290       HASHREF => sub {  # (nothing, but old SQLA passed it through)
291         #TODO in SQLA >= 2.0 it will die instead
292         belch "HASH ref as bind value in insert is not supported";
293         push @values, '?';
294         push @all_bind, $self->_bindtype($column, $v);
295       },
296
297       SCALARREF => sub {  # literal SQL without bind
298         push @values, $$v;
299       },
300
301       SCALAR_or_UNDEF => sub {
302         push @values, '?';
303         push @all_bind, $self->_bindtype($column, $v);
304       },
305
306      });
307
308   }
309
310   my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
311   return ($sql, @all_bind);
312 }
313
314
315
316 #======================================================================
317 # UPDATE methods
318 #======================================================================
319
320
321 sub update {
322   my $self  = shift;
323   my $table = $self->_table(shift);
324   my $data  = shift || return;
325   my $where = shift;
326
327   # first build the 'SET' part of the sql statement
328   my (@set, @all_bind);
329   puke "Unsupported data type specified to \$sql->update"
330     unless ref $data eq 'HASH';
331
332   for my $k (sort keys %$data) {
333     my $v = $data->{$k};
334     my $r = ref $v;
335     my $label = $self->_quote($k);
336
337     $self->_SWITCH_refkind($v, {
338       ARRAYREF => sub {
339         if ($self->{array_datatypes}) { # array datatype
340           push @set, "$label = ?";
341           push @all_bind, $self->_bindtype($k, $v);
342         }
343         else {                          # literal SQL with bind
344           my ($sql, @bind) = @$v;
345           $self->_assert_bindval_matches_bindtype(@bind);
346           push @set, "$label = $sql";
347           push @all_bind, @bind;
348         }
349       },
350       ARRAYREFREF => sub { # literal SQL with bind
351         my ($sql, @bind) = @${$v};
352         $self->_assert_bindval_matches_bindtype(@bind);
353         push @set, "$label = $sql";
354         push @all_bind, @bind;
355       },
356       SCALARREF => sub {  # literal SQL without bind
357         push @set, "$label = $$v";
358       },
359       HASHREF => sub {
360         my ($op, $arg, @rest) = %$v;
361
362         puke 'Operator calls in update must be in the form { -op => $arg }'
363           if (@rest or not $op =~ /^\-(.+)/);
364
365         local $self->{_nested_func_lhs} = $k;
366         my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
367
368         push @set, "$label = $sql";
369         push @all_bind, @bind;
370       },
371       SCALAR_or_UNDEF => sub {
372         push @set, "$label = ?";
373         push @all_bind, $self->_bindtype($k, $v);
374       },
375     });
376   }
377
378   # generate sql
379   my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
380           . join ', ', @set;
381
382   if ($where) {
383     my($where_sql, @where_bind) = $self->where($where);
384     $sql .= $where_sql;
385     push @all_bind, @where_bind;
386   }
387
388   return wantarray ? ($sql, @all_bind) : $sql;
389 }
390
391
392
393
394 #======================================================================
395 # SELECT
396 #======================================================================
397
398
399 sub select {
400   my $self   = shift;
401   my $table  = shift;
402   my $fields = shift || '*';
403   my $where  = shift;
404   my $order  = shift;
405
406   my($where_sql, @bind) = $self->where($where, $order);
407
408   my $sql = $self->_render_dq({
409     type => DQ_SELECT,
410     select => [
411       map $self->_ident_to_dq($_),
412         ref($fields) eq 'ARRAY' ? @$fields : $fields
413     ],
414     from => $self->_table_to_dq($table),
415   });
416
417   $sql .= $where_sql;
418
419   return wantarray ? ($sql, @bind) : $sql;
420 }
421
422 #======================================================================
423 # DELETE
424 #======================================================================
425
426
427 sub delete {
428   my $self  = shift;
429   my $table = $self->_table(shift);
430   my $where = shift;
431
432
433   my($where_sql, @bind) = $self->where($where);
434   my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
435
436   return wantarray ? ($sql, @bind) : $sql;
437 }
438
439
440 #======================================================================
441 # WHERE: entry point
442 #======================================================================
443
444
445
446 # Finally, a separate routine just to handle WHERE clauses
447 sub where {
448   my ($self, $where, $order) = @_;
449
450   # where ?
451   my ($sql, @bind) = $self->_recurse_where($where);
452   $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
453
454   # order by?
455   if ($order) {
456     $sql .= $self->_order_by($order);
457   }
458
459   return wantarray ? ($sql, @bind) : $sql;
460 }
461
462
463 sub _recurse_where {
464   my ($self, $where, $logic) = @_;
465
466   # dispatch on appropriate method according to refkind of $where
467   my $method = $self->_METHOD_FOR_refkind("_where", $where);
468
469   my ($sql, @bind) =  $self->$method($where, $logic);
470
471   # DBIx::Class directly calls _recurse_where in scalar context, so
472   # we must implement it, even if not in the official API
473   return wantarray ? ($sql, @bind) : $sql;
474 }
475
476
477
478 #======================================================================
479 # WHERE: top-level ARRAYREF
480 #======================================================================
481
482
483 sub _where_ARRAYREF {
484   my ($self, $where, $logic) = @_;
485
486   $logic = uc($logic || $self->{logic});
487   $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
488
489   my @clauses = @$where;
490
491   my (@sql_clauses, @all_bind);
492   # need to use while() so can shift() for pairs
493   while (my $el = shift @clauses) {
494
495     # switch according to kind of $el and get corresponding ($sql, @bind)
496     my ($sql, @bind) = $self->_SWITCH_refkind($el, {
497
498       # skip empty elements, otherwise get invalid trailing AND stuff
499       ARRAYREF  => sub {$self->_recurse_where($el)        if @$el},
500
501       ARRAYREFREF => sub {
502         my ($s, @b) = @$$el;
503         $self->_assert_bindval_matches_bindtype(@b);
504         ($s, @b);
505       },
506
507       HASHREF   => sub {$self->_recurse_where($el, 'and') if %$el},
508            # LDNOTE : previous SQLA code for hashrefs was creating a dirty
509            # side-effect: the first hashref within an array would change
510            # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
511            # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
512            # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
513
514       SCALARREF => sub { ($$el);                                 },
515
516       SCALAR    => sub {# top-level arrayref with scalars, recurse in pairs
517                         $self->_recurse_where({$el => shift(@clauses)})},
518
519       UNDEF     => sub {puke "not supported : UNDEF in arrayref" },
520     });
521
522     if ($sql) {
523       push @sql_clauses, $sql;
524       push @all_bind, @bind;
525     }
526   }
527
528   return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
529 }
530
531 #======================================================================
532 # WHERE: top-level ARRAYREFREF
533 #======================================================================
534
535 sub _where_ARRAYREFREF {
536     my ($self, $where) = @_;
537     my ($sql, @bind) = @$$where;
538     $self->_assert_bindval_matches_bindtype(@bind);
539     return ($sql, @bind);
540 }
541
542 #======================================================================
543 # WHERE: top-level HASHREF
544 #======================================================================
545
546 sub _where_HASHREF {
547   my ($self, $where) = @_;
548   my (@sql_clauses, @all_bind);
549
550   for my $k (sort keys %$where) {
551     my $v = $where->{$k};
552
553     # ($k => $v) is either a special unary op or a regular hashpair
554     my ($sql, @bind) = do {
555       if ($k =~ /^-./) {
556         # put the operator in canonical form
557         my $op = $k;
558         $op = substr $op, 1;  # remove initial dash
559         $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
560         $op =~ s/\s+/ /g;     # compress whitespace
561
562         # so that -not_foo works correctly
563         $op =~ s/^not_/NOT /i;
564
565         $self->_debug("Unary OP(-$op) within hashref, recursing...");
566         my ($s, @b) = $self->_where_unary_op ($op, $v);
567
568         # top level vs nested
569         # we assume that handled unary ops will take care of their ()s
570         $s = "($s)" unless (
571           List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
572             or
573           defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
574         );
575         ($s, @b);
576       }
577       else {
578         my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
579         $self->$method($k, $v);
580       }
581     };
582
583     push @sql_clauses, $sql;
584     push @all_bind, @bind;
585   }
586
587   return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
588 }
589
590 sub _where_unary_op {
591   my ($self, $op, $rhs) = @_;
592
593   if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
594     my $handler = $op_entry->{handler};
595
596     if (not ref $handler) {
597       if ($op =~ s/ [_\s]? \d+ $//x ) {
598         belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
599             . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
600       }
601       return $self->$handler ($op, $rhs);
602     }
603     elsif (ref $handler eq 'CODE') {
604       return $handler->($self, $op, $rhs);
605     }
606     else {
607       puke "Illegal handler for operator $op - expecting a method name or a coderef";
608     }
609   }
610
611   $self->_debug("Generic unary OP: $op - recursing as function");
612
613   $self->_assert_pass_injection_guard($op);
614
615   my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
616     SCALAR =>   sub {
617       puke "Illegal use of top-level '$op'"
618         unless $self->{_nested_func_lhs};
619
620       return (
621         $self->_convert('?'),
622         $self->_bindtype($self->{_nested_func_lhs}, $rhs)
623       );
624     },
625     FALLBACK => sub {
626       $self->_recurse_where ($rhs)
627     },
628   });
629
630   $sql = sprintf ('%s %s',
631     $self->_sqlcase($op),
632     $sql,
633   );
634
635   return ($sql, @bind);
636 }
637
638 sub _where_op_ANDOR {
639   my ($self, $op, $v) = @_;
640
641   $self->_SWITCH_refkind($v, {
642     ARRAYREF => sub {
643       return $self->_where_ARRAYREF($v, $op);
644     },
645
646     HASHREF => sub {
647       return ( $op =~ /^or/i )
648         ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
649         : $self->_where_HASHREF($v);
650     },
651
652     SCALARREF  => sub {
653       puke "-$op => \\\$scalar makes little sense, use " .
654         ($op =~ /^or/i
655           ? '[ \$scalar, \%rest_of_conditions ] instead'
656           : '-and => [ \$scalar, \%rest_of_conditions ] instead'
657         );
658     },
659
660     ARRAYREFREF => sub {
661       puke "-$op => \\[...] makes little sense, use " .
662         ($op =~ /^or/i
663           ? '[ \[...], \%rest_of_conditions ] instead'
664           : '-and => [ \[...], \%rest_of_conditions ] instead'
665         );
666     },
667
668     SCALAR => sub { # permissively interpreted as SQL
669       puke "-$op => \$value makes little sense, use -bool => \$value instead";
670     },
671
672     UNDEF => sub {
673       puke "-$op => undef not supported";
674     },
675    });
676 }
677
678 sub _where_op_NEST {
679   my ($self, $op, $v) = @_;
680
681   $self->_SWITCH_refkind($v, {
682
683     SCALAR => sub { # permissively interpreted as SQL
684       belch "literal SQL should be -nest => \\'scalar' "
685           . "instead of -nest => 'scalar' ";
686       return ($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 }
699
700
701 sub _where_op_BOOL {
702   my ($self, $op, $v) = @_;
703
704   my ($s, @b) = $self->_SWITCH_refkind($v, {
705     SCALAR => sub { # interpreted as SQL column
706       $self->_convert($self->_quote($v));
707     },
708
709     UNDEF => sub {
710       puke "-$op => undef not supported";
711     },
712
713     FALLBACK => sub {
714       $self->_recurse_where ($v);
715     },
716   });
717
718   $s = "(NOT $s)" if $op =~ /^not/i;
719   ($s, @b);
720 }
721
722
723 sub _where_op_IDENT {
724   my $self = shift;
725   my ($op, $rhs) = splice @_, -2;
726   if (ref $rhs) {
727     puke "-$op takes a single scalar argument (a quotable identifier)";
728   }
729
730   # in case we are called as a top level special op (no '=')
731   my $lhs = shift;
732
733   $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
734
735   return $lhs
736     ? "$lhs = $rhs"
737     : $rhs
738   ;
739 }
740
741 sub _where_op_VALUE {
742   my $self = shift;
743   my ($op, $rhs) = splice @_, -2;
744
745   # in case we are called as a top level special op (no '=')
746   my $lhs = shift;
747
748   my @bind =
749     $self->_bindtype (
750       ($lhs || $self->{_nested_func_lhs}),
751       $rhs,
752     )
753   ;
754
755   return $lhs
756     ? (
757       $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
758       @bind
759     )
760     : (
761       $self->_convert('?'),
762       @bind,
763     )
764   ;
765 }
766
767 sub _where_hashpair_ARRAYREF {
768   my ($self, $k, $v) = @_;
769
770   if( @$v ) {
771     my @v = @$v; # need copy because of shift below
772     $self->_debug("ARRAY($k) means distribute over elements");
773
774     # put apart first element if it is an operator (-and, -or)
775     my $op = (
776        (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
777          ? shift @v
778          : ''
779     );
780     my @distributed = map { {$k =>  $_} } @v;
781
782     if ($op) {
783       $self->_debug("OP($op) reinjected into the distributed array");
784       unshift @distributed, $op;
785     }
786
787     my $logic = $op ? substr($op, 1) : '';
788
789     return $self->_recurse_where(\@distributed, $logic);
790   }
791   else {
792     # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
793     $self->_debug("empty ARRAY($k) means 0=1");
794     return ($self->{sqlfalse});
795   }
796 }
797
798 sub _where_hashpair_HASHREF {
799   my ($self, $k, $v, $logic) = @_;
800   $logic ||= 'and';
801
802   local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
803
804   my ($all_sql, @all_bind);
805
806   for my $orig_op (sort keys %$v) {
807     my $val = $v->{$orig_op};
808
809     # put the operator in canonical form
810     my $op = $orig_op;
811
812     # FIXME - we need to phase out dash-less ops
813     $op =~ s/^-//;        # remove possible initial dash
814     $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
815     $op =~ s/\s+/ /g;     # compress whitespace
816
817     $self->_assert_pass_injection_guard($op);
818
819     # so that -not_foo works correctly
820     $op =~ s/^not_/NOT /i;
821
822     my ($sql, @bind);
823
824     # CASE: col-value logic modifiers
825     if ( $orig_op =~ /^ \- (and|or) $/xi ) {
826       ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
827     }
828     # CASE: special operators like -in or -between
829     elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
830       my $handler = $special_op->{handler};
831       if (! $handler) {
832         puke "No handler supplied for special operator $orig_op";
833       }
834       elsif (not ref $handler) {
835         ($sql, @bind) = $self->$handler ($k, $op, $val);
836       }
837       elsif (ref $handler eq 'CODE') {
838         ($sql, @bind) = $handler->($self, $k, $op, $val);
839       }
840       else {
841         puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
842       }
843     }
844     else {
845       $self->_SWITCH_refkind($val, {
846
847         ARRAYREF => sub {       # CASE: col => {op => \@vals}
848           ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
849         },
850
851         ARRAYREFREF => sub {    # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
852           my ($sub_sql, @sub_bind) = @$$val;
853           $self->_assert_bindval_matches_bindtype(@sub_bind);
854           $sql  = join ' ', $self->_convert($self->_quote($k)),
855                             $self->_sqlcase($op),
856                             $sub_sql;
857           @bind = @sub_bind;
858         },
859
860         UNDEF => sub {          # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
861           my $is = ($op =~ $self->{equality_op})   ? 'is'     :
862                    ($op =~ $self->{inequality_op}) ? 'is not' :
863                puke "unexpected operator '$orig_op' with undef operand";
864           $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
865         },
866
867         FALLBACK => sub {       # CASE: col => {op/func => $stuff}
868
869           # retain for proper column type bind
870           $self->{_nested_func_lhs} ||= $k;
871
872           ($sql, @bind) = $self->_where_unary_op ($op, $val);
873
874           $sql = join (' ',
875             $self->_convert($self->_quote($k)),
876             $self->{_nested_func_lhs} eq $k ? $sql : "($sql)",  # top level vs nested
877           );
878         },
879       });
880     }
881
882     ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
883     push @all_bind, @bind;
884   }
885   return ($all_sql, @all_bind);
886 }
887
888
889
890 sub _where_field_op_ARRAYREF {
891   my ($self, $k, $op, $vals) = @_;
892
893   my @vals = @$vals;  #always work on a copy
894
895   if(@vals) {
896     $self->_debug(sprintf '%s means multiple elements: [ %s ]',
897       $vals,
898       join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
899     );
900
901     # see if the first element is an -and/-or op
902     my $logic;
903     if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
904       $logic = uc $1;
905       shift @vals;
906     }
907
908     # distribute $op over each remaining member of @vals, append logic if exists
909     return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
910
911     # LDNOTE : had planned to change the distribution logic when
912     # $op =~ $self->{inequality_op}, because of Morgan laws :
913     # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
914     # WHERE field != 22 OR  field != 33 : the user probably means
915     # WHERE field != 22 AND field != 33.
916     # To do this, replace the above to roughly :
917     # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
918     # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
919
920   }
921   else {
922     # try to DWIM on equality operators
923     # LDNOTE : not 100% sure this is the correct thing to do ...
924     return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
925     return ($self->{sqltrue})  if $op =~ $self->{inequality_op};
926
927     # otherwise
928     puke "operator '$op' applied on an empty array (field '$k')";
929   }
930 }
931
932
933 sub _where_hashpair_SCALARREF {
934   my ($self, $k, $v) = @_;
935   $self->_debug("SCALAR($k) means literal SQL: $$v");
936   my $sql = $self->_quote($k) . " " . $$v;
937   return ($sql);
938 }
939
940 # literal SQL with bind
941 sub _where_hashpair_ARRAYREFREF {
942   my ($self, $k, $v) = @_;
943   $self->_debug("REF($k) means literal SQL: @${$v}");
944   my ($sql, @bind) = @$$v;
945   $self->_assert_bindval_matches_bindtype(@bind);
946   $sql  = $self->_quote($k) . " " . $sql;
947   return ($sql, @bind );
948 }
949
950 # literal SQL without bind
951 sub _where_hashpair_SCALAR {
952   my ($self, $k, $v) = @_;
953   $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
954   my $sql = join ' ', $self->_convert($self->_quote($k)),
955                       $self->_sqlcase($self->{cmp}),
956                       $self->_convert('?');
957   my @bind =  $self->_bindtype($k, $v);
958   return ( $sql, @bind);
959 }
960
961
962 sub _where_hashpair_UNDEF {
963   my ($self, $k, $v) = @_;
964   $self->_debug("UNDEF($k) means IS NULL");
965   my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
966   return ($sql);
967 }
968
969 #======================================================================
970 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
971 #======================================================================
972
973
974 sub _where_SCALARREF {
975   my ($self, $where) = @_;
976
977   # literal sql
978   $self->_debug("SCALAR(*top) means literal SQL: $$where");
979   return ($$where);
980 }
981
982
983 sub _where_SCALAR {
984   my ($self, $where) = @_;
985
986   # literal sql
987   $self->_debug("NOREF(*top) means literal SQL: $where");
988   return ($where);
989 }
990
991
992 sub _where_UNDEF {
993   my ($self) = @_;
994   return ();
995 }
996
997
998 #======================================================================
999 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
1000 #======================================================================
1001
1002
1003 sub _where_field_BETWEEN {
1004   my ($self, $k, $op, $vals) = @_;
1005
1006   my ($label, $and, $placeholder);
1007   $label       = $self->_convert($self->_quote($k));
1008   $and         = ' ' . $self->_sqlcase('and') . ' ';
1009   $placeholder = $self->_convert('?');
1010   $op               = $self->_sqlcase($op);
1011
1012   my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
1013     ARRAYREFREF => sub {
1014       my ($s, @b) = @$$vals;
1015       $self->_assert_bindval_matches_bindtype(@b);
1016       ($s, @b);
1017     },
1018     SCALARREF => sub {
1019       return $$vals;
1020     },
1021     ARRAYREF => sub {
1022       puke "special op 'between' accepts an arrayref with exactly two values"
1023         if @$vals != 2;
1024
1025       my (@all_sql, @all_bind);
1026       foreach my $val (@$vals) {
1027         my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1028            SCALAR => sub {
1029              return ($placeholder, $self->_bindtype($k, $val) );
1030            },
1031            SCALARREF => sub {
1032              return $$val;
1033            },
1034            ARRAYREFREF => sub {
1035              my ($sql, @bind) = @$$val;
1036              $self->_assert_bindval_matches_bindtype(@bind);
1037              return ($sql, @bind);
1038            },
1039            HASHREF => sub {
1040              my ($func, $arg, @rest) = %$val;
1041              puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
1042                if (@rest or $func !~ /^ \- (.+)/x);
1043              local $self->{_nested_func_lhs} = $k;
1044              $self->_where_unary_op ($1 => $arg);
1045            }
1046         });
1047         push @all_sql, $sql;
1048         push @all_bind, @bind;
1049       }
1050
1051       return (
1052         (join $and, @all_sql),
1053         @all_bind
1054       );
1055     },
1056     FALLBACK => sub {
1057       puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
1058     },
1059   });
1060
1061   my $sql = "( $label $op $clause )";
1062   return ($sql, @bind)
1063 }
1064
1065
1066 sub _where_field_IN {
1067   my ($self, $k, $op, $vals) = @_;
1068
1069   # backwards compatibility : if scalar, force into an arrayref
1070   $vals = [$vals] if defined $vals && ! ref $vals;
1071
1072   my ($label)       = $self->_convert($self->_quote($k));
1073   my ($placeholder) = $self->_convert('?');
1074   $op               = $self->_sqlcase($op);
1075
1076   my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1077     ARRAYREF => sub {     # list of choices
1078       if (@$vals) { # nonempty list
1079         my (@all_sql, @all_bind);
1080
1081         for my $val (@$vals) {
1082           my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1083             SCALAR => sub {
1084               return ($placeholder, $val);
1085             },
1086             SCALARREF => sub {
1087               return $$val;
1088             },
1089             ARRAYREFREF => sub {
1090               my ($sql, @bind) = @$$val;
1091               $self->_assert_bindval_matches_bindtype(@bind);
1092               return ($sql, @bind);
1093             },
1094             HASHREF => sub {
1095               my ($func, $arg, @rest) = %$val;
1096               puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1097                 if (@rest or $func !~ /^ \- (.+)/x);
1098               local $self->{_nested_func_lhs} = $k;
1099               $self->_where_unary_op ($1 => $arg);
1100             },
1101             UNDEF => sub {
1102               return $self->_sqlcase('null');
1103             },
1104           });
1105           push @all_sql, $sql;
1106           push @all_bind, @bind;
1107         }
1108
1109         return (
1110           sprintf ('%s %s ( %s )',
1111             $label,
1112             $op,
1113             join (', ', @all_sql)
1114           ),
1115           $self->_bindtype($k, @all_bind),
1116         );
1117       }
1118       else { # empty list : some databases won't understand "IN ()", so DWIM
1119         my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1120         return ($sql);
1121       }
1122     },
1123
1124     SCALARREF => sub {  # literal SQL
1125       my $sql = $self->_open_outer_paren ($$vals);
1126       return ("$label $op ( $sql )");
1127     },
1128     ARRAYREFREF => sub {  # literal SQL with bind
1129       my ($sql, @bind) = @$$vals;
1130       $self->_assert_bindval_matches_bindtype(@bind);
1131       $sql = $self->_open_outer_paren ($sql);
1132       return ("$label $op ( $sql )", @bind);
1133     },
1134
1135     FALLBACK => sub {
1136       puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1137     },
1138   });
1139
1140   return ($sql, @bind);
1141 }
1142
1143 # Some databases (SQLite) treat col IN (1, 2) different from
1144 # col IN ( (1, 2) ). Use this to strip all outer parens while
1145 # adding them back in the corresponding method
1146 sub _open_outer_paren {
1147   my ($self, $sql) = @_;
1148   $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1149   return $sql;
1150 }
1151
1152
1153 #======================================================================
1154 # ORDER BY
1155 #======================================================================
1156
1157 sub _order_by {
1158   my ($self, $arg) = @_;
1159   if (my $dq = $self->_order_by_to_dq($arg)) {
1160     # SQLA generates ' ORDER BY foo'. The hilarity.
1161     wantarray
1162       ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
1163       : ' '.$self->_render_dq($dq);
1164   } else {
1165     '';
1166   }
1167 }
1168
1169 sub _order_by_to_dq {
1170   my ($self, $arg, $dir) = @_;
1171
1172   return unless $arg;
1173
1174   my $dq = {
1175     type => DQ_ORDER,
1176     ($dir ? (direction => $dir) : ()),
1177   };
1178
1179   if (!ref($arg)) {
1180     $dq->{by} = $self->_ident_to_dq($arg);
1181   } elsif (ref($arg) eq 'ARRAY') {
1182     return unless @$arg;
1183     local our $Order_Inner unless our $Order_Recursing;
1184     local $Order_Recursing = 1;
1185     my ($outer, $inner);
1186     foreach my $member (@$arg) {
1187       local $Order_Inner;
1188       my $next = $self->_order_by_to_dq($member, $dir);
1189       $outer ||= $next;
1190       $inner->{from} = $next if $inner;
1191       $inner = $Order_Inner || $next;
1192     }
1193     $Order_Inner = $inner;
1194     return $outer;
1195   } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
1196     my ($sql, @bind) = @{$$arg};
1197     $dq->{by} = {
1198       type => DQ_LITERAL,
1199       subtype => 'SQL',
1200       literal => $sql,
1201       values => [ $self->_bind_to_dq(@bind) ],
1202     };
1203   } elsif (ref($arg) eq 'SCALAR') {
1204     $dq->{by} = {
1205       type => DQ_LITERAL,
1206       subtype => 'SQL',
1207       literal => $$arg,
1208     };
1209   } elsif (ref($arg) eq 'HASH') {
1210     my ($key, $val, @rest) = %$arg;
1211
1212     return unless $key;
1213
1214     if (@rest or not $key =~ /^-(desc|asc)/i) {
1215       puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1216     }
1217     my $dir = uc $1;
1218     return $self->_order_by_to_dq($val, $dir);
1219   } else {
1220     die "Can't handle $arg in _order_by_to_dq";
1221   }
1222   return $dq;
1223 }
1224
1225 #======================================================================
1226 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1227 #======================================================================
1228
1229 sub _table  {
1230   my ($self, $from) = @_;
1231   $self->_render_dq($self->_table_to_dq($from));
1232 }
1233
1234 sub _table_to_dq {
1235   my ($self, $from) = @_;
1236   $self->_SWITCH_refkind($from, {
1237     ARRAYREF     => sub {
1238       die "Empty FROM list" unless my @f = @$from;
1239       my $dq = $self->_ident_to_dq(shift @f);
1240       while (my $x = shift @f) {
1241         $dq = {
1242           type => DQ_JOIN,
1243           join => [ $dq, $self->_ident_to_dq($x) ]
1244         };
1245       }
1246       $dq;
1247     },
1248     SCALAR       => sub { $self->_ident_to_dq($from) },
1249     SCALARREF    => sub {
1250       +{
1251         type => DQ_LITERAL,
1252         subtype => 'SQL',
1253         literal => $$from
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