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