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