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