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