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