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