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