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