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