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