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