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