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