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