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