1 package SQL::Abstract; # see doc at end of file
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)
11 use List::Util qw/first/;
13 #======================================================================
15 #======================================================================
17 our $VERSION = '1.49_01';
21 # special operators (-in, -between). May be extended/overridden by user.
22 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
23 my @BUILTIN_SPECIAL_OPS = (
24 {regex => qr/^(not )?between$/i, handler => \&_where_field_BETWEEN},
25 {regex => qr/^(not )?in$/i, handler => \&_where_field_IN},
28 #======================================================================
29 # DEBUGGING AND ERROR REPORTING
30 #======================================================================
33 return unless $_[0]->{debug}; shift; # a little faster
34 my $func = (caller(1))[3];
35 warn "[$func] ", @_, "\n";
39 my($func) = (caller(1))[3];
40 carp "[$func] Warning: ", @_;
44 my($func) = (caller(1))[3];
45 croak "[$func] Fatal: ", @_;
49 #======================================================================
51 #======================================================================
55 my $class = ref($self) || $self;
56 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
58 # choose our case by keeping an option around
59 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
61 # default logic for interpreting arrayrefs
62 $opt{logic} = uc $opt{logic} || 'OR';
64 # how to return bind vars
65 # LDNOTE: changed nwiger code : why this 'delete' ??
66 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
67 $opt{bindtype} ||= 'normal';
69 # default comparison is "=", but can be overridden
72 # try to recognize which are the 'equality' and 'unequality' ops
73 # (temporary quickfix, should go through a more seasoned API)
74 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
75 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
78 $opt{sqltrue} ||= '1=1';
79 $opt{sqlfalse} ||= '0=1';
82 $opt{special_ops} ||= [];
83 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
85 return bless \%opt, $class;
90 #======================================================================
92 #======================================================================
96 my $table = $self->_table(shift);
97 my $data = shift || return;
99 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
100 my ($sql, @bind) = $self->$method($data);
101 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
102 return wantarray ? ($sql, @bind) : $sql;
105 sub _insert_HASHREF { # explicit list of fields and then values
106 my ($self, $data) = @_;
108 my @fields = sort keys %$data;
111 { # get values (need temporary override of bindtype to avoid an error)
112 local $self->{bindtype} = 'normal';
113 ($sql, @bind) = $self->_insert_ARRAYREF([@{$data}{@fields}]);
116 # if necessary, transform values according to 'bindtype'
117 if ($self->{bindtype} eq 'columns') {
118 for my $i (0 .. $#fields) {
119 ($bind[$i]) = $self->_bindtype($fields[$i], $bind[$i]);
124 $_ = $self->_quote($_) foreach @fields;
125 $sql = "( ".join(", ", @fields).") ".$sql;
127 return ($sql, @bind);
130 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
131 my ($self, $data) = @_;
133 # no names (arrayref) so can't generate bindtype
134 $self->{bindtype} ne 'columns'
135 or belch "can't do 'columns' bindtype when called with arrayref";
137 my (@values, @all_bind);
140 $self->_SWITCH_refkind($v, {
143 if ($self->{array_datatypes}) { # if array datatype are activated
146 else { # else literal SQL with bind
147 my ($sql, @bind) = @$v;
149 push @all_bind, @bind;
153 ARRAYREFREF => sub { # literal SQL with bind
154 my ($sql, @bind) = @${$v};
156 push @all_bind, @bind;
159 # THINK : anything useful to do with a HASHREF ?
161 SCALARREF => sub { # literal SQL without bind
165 SCALAR_or_UNDEF => sub {
174 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
175 return ($sql, @all_bind);
179 sub _insert_ARRAYREFREF { # literal SQL with bind
180 my ($self, $data) = @_;
185 sub _insert_SCALARREF { # literal SQL without bind
186 my ($self, $data) = @_;
193 #======================================================================
195 #======================================================================
200 my $table = $self->_table(shift);
201 my $data = shift || return;
204 # first build the 'SET' part of the sql statement
205 my (@set, @all_bind);
206 puke "Unsupported data type specified to \$sql->update"
207 unless ref $data eq 'HASH';
209 for my $k (sort keys %$data) {
212 my $label = $self->_quote($k);
214 $self->_SWITCH_refkind($v, {
216 if ($self->{array_datatypes}) { # array datatype
217 push @set, "$label = ?";
218 push @all_bind, $self->_bindtype($k, $v);
220 else { # literal SQL with bind
221 my ($sql, @bind) = @$v;
222 push @set, "$label = $sql";
223 push @all_bind, $self->_bindtype($k, @bind);
226 ARRAYREFREF => sub { # literal SQL with bind
227 my ($sql, @bind) = @${$v};
228 push @set, "$label = $sql";
229 push @all_bind, $self->_bindtype($k, @bind);
231 SCALARREF => sub { # literal SQL without bind
232 push @set, "$label = $$v";
234 SCALAR_or_UNDEF => sub {
235 push @set, "$label = ?";
236 push @all_bind, $self->_bindtype($k, $v);
242 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
246 my($where_sql, @where_bind) = $self->where($where);
248 push @all_bind, @where_bind;
251 return wantarray ? ($sql, @all_bind) : $sql;
257 #======================================================================
259 #======================================================================
264 my $table = $self->_table(shift);
265 my $fields = shift || '*';
269 my($where_sql, @bind) = $self->where($where, $order);
271 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
273 my $sql = join(' ', $self->_sqlcase('select'), $f,
274 $self->_sqlcase('from'), $table)
277 return wantarray ? ($sql, @bind) : $sql;
280 #======================================================================
282 #======================================================================
287 my $table = $self->_table(shift);
291 my($where_sql, @bind) = $self->where($where);
292 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
294 return wantarray ? ($sql, @bind) : $sql;
298 #======================================================================
300 #======================================================================
304 # Finally, a separate routine just to handle WHERE clauses
306 my ($self, $where, $order) = @_;
309 my ($sql, @bind) = $self->_recurse_where($where);
310 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
314 $sql .= $self->_order_by($order);
317 return wantarray ? ($sql, @bind) : $sql;
322 my ($self, $where, $logic) = @_;
324 # dispatch on appropriate method according to refkind of $where
325 my $method = $self->_METHOD_FOR_refkind("_where", $where);
326 $self->$method($where, $logic);
331 #======================================================================
332 # WHERE: top-level ARRAYREF
333 #======================================================================
336 sub _where_ARRAYREF {
337 my ($self, $where, $logic) = @_;
339 $logic = uc($logic || $self->{logic});
340 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
342 my @clauses = @$where;
344 # if the array starts with [-and|or => ...], recurse with that logic
345 my $first = $clauses[0] || '';
346 if ($first =~ /^-(and|or)/i) {
349 return $self->_where_ARRAYREF(\@clauses, $logic);
353 my (@sql_clauses, @all_bind);
355 # need to use while() so can shift() for pairs
356 while (my $el = shift @clauses) {
358 # switch according to kind of $el and get corresponding ($sql, @bind)
359 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
361 # skip empty elements, otherwise get invalid trailing AND stuff
362 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
364 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
365 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
366 # side-effect: the first hashref within an array would change
367 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
368 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
369 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
371 SCALARREF => sub { ($$el); },
373 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
374 $self->_recurse_where({$el => shift(@clauses)})},
376 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
380 push @sql_clauses, $sql;
381 push @all_bind, @bind;
385 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
390 #======================================================================
391 # WHERE: top-level HASHREF
392 #======================================================================
395 my ($self, $where) = @_;
396 my (@sql_clauses, @all_bind);
398 # LDNOTE : don't really know why we need to sort keys
399 for my $k (sort keys %$where) {
400 my $v = $where->{$k};
402 # ($k => $v) is either a special op or a regular hashpair
403 my ($sql, @bind) = ($k =~ /^-(.+)/) ? $self->_where_op_in_hash($1, $v)
405 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
406 $self->$method($k, $v);
409 push @sql_clauses, $sql;
410 push @all_bind, @bind;
413 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
417 sub _where_op_in_hash {
418 my ($self, $op, $v) = @_;
420 $op =~ /^(AND|OR|NEST)[_\d]*/i
421 or puke "unknown operator: -$op";
422 $op = uc($1); # uppercase, remove trailing digits
423 $self->_debug("OP(-$op) within hashref, recursing...");
425 $self->_SWITCH_refkind($v, {
428 # LDNOTE : should deprecate {-or => [...]} and {-and => [...]}
429 # because they are misleading; the only proper way would be
430 # -nest => [-or => ...], -nest => [-and ...]
431 return $self->_where_ARRAYREF($v, $op eq 'NEST' ? '' : $op);
436 belch "-or => {...} should be -nest => [...]";
437 return $self->_where_ARRAYREF([%$v], 'OR');
440 return $self->_where_HASHREF($v);
444 SCALARREF => sub { # literal SQL
446 or puke "-$op => \\\$scalar not supported, use -nest => ...";
450 ARRAYREFREF => sub { # literal SQL
452 or puke "-$op => \\[..] not supported, use -nest => ...";
456 SCALAR => sub { # permissively interpreted as SQL
458 or puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
459 belch "literal SQL should be -nest => \\'scalar' "
460 . "instead of -nest => 'scalar' ";
465 puke "-$op => undef not supported";
471 sub _where_hashpair_ARRAYREF {
472 my ($self, $k, $v) = @_;
475 my @v = @$v; # need copy because of shift below
476 $self->_debug("ARRAY($k) means distribute over elements");
478 # put apart first element if it is an operator (-and, -or)
479 my $op = $v[0] =~ /^-/ ? shift @v : undef;
480 $self->_debug("OP($op) reinjected into the distributed array") if $op;
482 my @distributed = map { {$k => $_} } @v;
483 unshift @distributed, $op if $op;
485 return $self->_recurse_where(\@distributed);
488 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
489 $self->_debug("empty ARRAY($k) means 0=1");
490 return ($self->{sqlfalse});
494 sub _where_hashpair_HASHREF {
495 my ($self, $k, $v) = @_;
497 my (@all_sql, @all_bind);
499 for my $op (sort keys %$v) {
502 # put the operator in canonical form
503 $op =~ s/^-//; # remove initial dash
504 $op =~ tr/_/ /; # underscores become spaces
505 $op =~ s/^\s+//; # no initial space
506 $op =~ s/\s+$//; # no final space
507 $op =~ s/\s+/ /; # multiple spaces become one
511 # CASE: special operators like -in or -between
512 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
514 ($sql, @bind) = $special_op->{handler}->($self, $k, $op, $val);
517 # CASE: col => {op => \@vals}
518 elsif (ref $val eq 'ARRAY') {
519 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
522 # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
523 elsif (! defined($val)) {
524 my $is = ($op =~ $self->{equality_op}) ? 'is' :
525 ($op =~ $self->{inequality_op}) ? 'is not' :
526 puke "unexpected operator '$op' with undef operand";
527 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
530 # CASE: col => {op => $scalar}
532 $sql = join ' ', $self->_convert($self->_quote($k)),
533 $self->_sqlcase($op),
534 $self->_convert('?');
535 @bind = $self->_bindtype($k, $val);
539 push @all_bind, @bind;
542 return $self->_join_sql_clauses('and', \@all_sql, \@all_bind);
547 sub _where_field_op_ARRAYREF {
548 my ($self, $k, $op, $vals) = @_;
551 $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
555 # LDNOTE : change the distribution logic when
556 # $op =~ $self->{inequality_op}, because of Morgan laws :
557 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
558 # WHERE field != 22 OR field != 33 : the user probably means
559 # WHERE field != 22 AND field != 33.
560 my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
562 # distribute $op over each member of @$vals
563 return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
567 # try to DWIM on equality operators
568 # LDNOTE : not 100% sure this is the correct thing to do ...
569 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
570 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
573 puke "operator '$op' applied on an empty array (field '$k')";
578 sub _where_hashpair_SCALARREF {
579 my ($self, $k, $v) = @_;
580 $self->_debug("SCALAR($k) means literal SQL: $$v");
581 my $sql = $self->_quote($k) . " " . $$v;
585 sub _where_hashpair_ARRAYREFREF {
586 my ($self, $k, $v) = @_;
587 $self->_debug("REF($k) means literal SQL: @${$v}");
588 my ($sql, @bind) = @${$v};
589 $sql = $self->_quote($k) . " " . $sql;
590 @bind = $self->_bindtype($k, @bind);
591 return ($sql, @bind );
594 sub _where_hashpair_SCALAR {
595 my ($self, $k, $v) = @_;
596 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
597 my $sql = join ' ', $self->_convert($self->_quote($k)),
598 $self->_sqlcase($self->{cmp}),
599 $self->_convert('?');
600 my @bind = $self->_bindtype($k, $v);
601 return ( $sql, @bind);
605 sub _where_hashpair_UNDEF {
606 my ($self, $k, $v) = @_;
607 $self->_debug("UNDEF($k) means IS NULL");
608 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
612 #======================================================================
613 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
614 #======================================================================
617 sub _where_SCALARREF {
618 my ($self, $where) = @_;
621 $self->_debug("SCALAR(*top) means literal SQL: $$where");
627 my ($self, $where) = @_;
630 $self->_debug("NOREF(*top) means literal SQL: $where");
641 #======================================================================
642 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
643 #======================================================================
646 sub _where_field_BETWEEN {
647 my ($self, $k, $op, $vals) = @_;
649 ref $vals eq 'ARRAY' && @$vals == 2
650 or puke "special op 'between' requires an arrayref of two values";
652 my ($label) = $self->_convert($self->_quote($k));
653 my ($placeholder) = $self->_convert('?');
654 my $and = $self->_sqlcase('and');
655 $op = $self->_sqlcase($op);
657 my $sql = "( $label $op $placeholder $and $placeholder )";
658 my @bind = $self->_bindtype($k, @$vals);
663 sub _where_field_IN {
664 my ($self, $k, $op, $vals) = @_;
666 # backwards compatibility : if scalar, force into an arrayref
667 $vals = [$vals] if defined $vals && ! ref $vals;
670 or puke "special op 'in' requires an arrayref";
672 my ($label) = $self->_convert($self->_quote($k));
673 my ($placeholder) = $self->_convert('?');
674 my $and = $self->_sqlcase('and');
675 $op = $self->_sqlcase($op);
677 if (@$vals) { # nonempty list
678 my $placeholders = join ", ", (($placeholder) x @$vals);
679 my $sql = "$label $op ( $placeholders )";
680 my @bind = $self->_bindtype($k, @$vals);
682 return ($sql, @bind);
684 else { # empty list : some databases won't understand "IN ()", so DWIM
685 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
695 #======================================================================
697 #======================================================================
700 my ($self, $arg) = @_;
702 # construct list of ordering instructions
703 my @order = $self->_SWITCH_refkind($arg, {
706 map {$self->_SWITCH_refkind($_, {
707 SCALAR => sub {$self->_quote($_)},
708 SCALARREF => sub {$$_}, # literal SQL, no quoting
709 HASHREF => sub {$self->_order_by_hash($_)}
713 SCALAR => sub {$self->_quote($arg)},
714 SCALARREF => sub {$$arg}, # literal SQL, no quoting
715 HASHREF => sub {$self->_order_by_hash($arg)},
720 my $order = join ', ', @order;
721 return $order ? $self->_sqlcase(' order by')." $order" : '';
726 my ($self, $hash) = @_;
728 # get first pair in hash
729 my ($key, $val) = each %$hash;
731 # check if one pair was found and no other pair in hash
732 $key && !(each %$hash)
733 or puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
735 my ($order) = ($key =~ /^-(desc|asc)/i)
736 or puke "invalid key in _order_by hash : $key";
738 return $self->_quote($val) ." ". $self->_sqlcase($order);
743 #======================================================================
744 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
745 #======================================================================
750 $self->_SWITCH_refkind($from, {
751 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
752 SCALAR => sub {$self->_quote($from)},
753 SCALARREF => sub {$$from},
754 ARRAYREFREF => sub {join ', ', @$from;},
759 #======================================================================
761 #======================================================================
767 $label or puke "can't quote an empty label";
769 # left and right quote characters
770 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
771 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
772 ARRAYREF => sub {@{$self->{quote_char}}},
776 or puke "quote_char must be an arrayref of 2 values";
778 # no quoting if no quoting chars
779 $ql or return $label;
781 # no quoting for literal SQL
782 return $$label if ref($label) eq 'SCALAR';
784 # separate table / column (if applicable)
785 my $sep = $self->{name_sep} || '';
786 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
788 # do the quoting, except for "*" or for `table`.*
789 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
791 # reassemble and return.
792 return join $sep, @quoted;
796 # Conversion, if applicable
798 my ($self, $arg) = @_;
800 # LDNOTE : modified the previous implementation below because
801 # it was not consistent : the first "return" is always an array,
802 # the second "return" is context-dependent. Anyway, _convert
803 # seems always used with just a single argument, so make it a
805 # return @_ unless $self->{convert};
806 # my $conv = $self->_sqlcase($self->{convert});
807 # my @ret = map { $conv.'('.$_.')' } @_;
808 # return wantarray ? @ret : $ret[0];
809 if ($self->{convert}) {
810 my $conv = $self->_sqlcase($self->{convert});
811 $arg = $conv.'('.$arg.')';
819 my($col, @vals) = @_;
821 #LDNOTE : changed original implementation below because it did not make
822 # sense when bindtype eq 'columns' and @vals > 1.
823 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
825 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
828 sub _join_sql_clauses {
829 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
831 if (@$clauses_aref > 1) {
832 my $join = " " . $self->_sqlcase($logic) . " ";
833 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
834 return ($sql, @$bind_aref);
836 elsif (@$clauses_aref) {
837 return ($clauses_aref->[0], @$bind_aref); # no parentheses
840 return (); # if no SQL, ignore @$bind_aref
845 # Fix SQL case, if so requested
849 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
850 # don't touch the argument ... crooked logic, but let's not change it!
851 return $self->{case} ? $_[0] : uc($_[0]);
855 #======================================================================
856 # DISPATCHING FROM REFKIND
857 #======================================================================
860 my ($self, $data) = @_;
864 # $suffix = 'REF' x (length of ref chain, i. e. \\[] is REFREFREF)
868 last if $ref ne 'REF';
872 return $ref ? $ref.$suffix :
873 defined $data ? 'SCALAR' :
878 my ($self, $data) = @_;
879 my @try = ($self->_refkind($data));
880 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
881 push @try, 'FALLBACK';
885 sub _METHOD_FOR_refkind {
886 my ($self, $meth_prefix, $data) = @_;
887 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
888 $self->_try_refkind($data)
889 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
894 sub _SWITCH_refkind {
895 my ($self, $data, $dispatch_table) = @_;
897 my $coderef = first {$_} map {$dispatch_table->{$_}}
898 $self->_try_refkind($data)
899 or puke "no dispatch entry for ".$self->_refkind($data);
906 #======================================================================
907 # VALUES, GENERATE, AUTOLOAD
908 #======================================================================
910 # LDNOTE: original code from nwiger, didn't touch code in that section
911 # I feel the AUTOLOAD stuff should not be the default, it should
912 # only be activated on explicit demand by user.
916 my $data = shift || return;
917 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
918 unless ref $data eq 'HASH';
919 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
925 my(@sql, @sqlq, @sqlv);
929 if ($ref eq 'HASH') {
930 for my $k (sort keys %$_) {
933 my $label = $self->_quote($k);
935 # SQL included for values
937 my $sql = shift @bind;
938 push @sqlq, "$label = $sql";
939 push @sqlv, $self->_bindtype($k, @bind);
940 } elsif ($r eq 'SCALAR') {
941 # embedded literal SQL
942 push @sqlq, "$label = $$v";
944 push @sqlq, "$label = ?";
945 push @sqlv, $self->_bindtype($k, $v);
948 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
949 } elsif ($ref eq 'ARRAY') {
950 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
955 push @sqlq, shift @val;
957 } elsif ($r eq 'SCALAR') {
958 # embedded literal SQL
965 push @sql, '(' . join(', ', @sqlq) . ')';
966 } elsif ($ref eq 'SCALAR') {
970 # strings get case twiddled
971 push @sql, $self->_sqlcase($_);
975 my $sql = join ' ', @sql;
977 # this is pretty tricky
978 # if ask for an array, return ($stmt, @bind)
979 # otherwise, s/?/shift @sqlv/ to put it inline
981 return ($sql, @sqlv);
983 1 while $sql =~ s/\?/my $d = shift(@sqlv);
984 ref $d ? $d->[1] : $d/e;
993 # This allows us to check for a local, then _form, attr
995 my($name) = $AUTOLOAD =~ /.*::(.+)/;
996 return $self->generate($name, @_);
1007 SQL::Abstract - Generate SQL from Perl data structures
1013 my $sql = SQL::Abstract->new;
1015 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1017 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1019 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1021 my($stmt, @bind) = $sql->delete($table, \%where);
1023 # Then, use these in your DBI statements
1024 my $sth = $dbh->prepare($stmt);
1025 $sth->execute(@bind);
1027 # Just generate the WHERE clause
1028 my($stmt, @bind) = $sql->where(\%where, \@order);
1030 # Return values in the same order, for hashed queries
1031 # See PERFORMANCE section for more details
1032 my @bind = $sql->values(\%fieldvals);
1036 This module was inspired by the excellent L<DBIx::Abstract>.
1037 However, in using that module I found that what I really wanted
1038 to do was generate SQL, but still retain complete control over my
1039 statement handles and use the DBI interface. So, I set out to
1040 create an abstract SQL generation module.
1042 While based on the concepts used by L<DBIx::Abstract>, there are
1043 several important differences, especially when it comes to WHERE
1044 clauses. I have modified the concepts used to make the SQL easier
1045 to generate from Perl data structures and, IMO, more intuitive.
1046 The underlying idea is for this module to do what you mean, based
1047 on the data structures you provide it. The big advantage is that
1048 you don't have to modify your code every time your data changes,
1049 as this module figures it out.
1051 To begin with, an SQL INSERT is as easy as just specifying a hash
1052 of C<key=value> pairs:
1055 name => 'Jimbo Bobson',
1056 phone => '123-456-7890',
1057 address => '42 Sister Lane',
1058 city => 'St. Louis',
1059 state => 'Louisiana',
1062 The SQL can then be generated with this:
1064 my($stmt, @bind) = $sql->insert('people', \%data);
1066 Which would give you something like this:
1068 $stmt = "INSERT INTO people
1069 (address, city, name, phone, state)
1070 VALUES (?, ?, ?, ?, ?)";
1071 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1072 '123-456-7890', 'Louisiana');
1074 These are then used directly in your DBI code:
1076 my $sth = $dbh->prepare($stmt);
1077 $sth->execute(@bind);
1079 =head2 Inserting and Updating Arrays
1081 If your database has array types (like for example Postgres),
1082 activate the special option C<< array_datatypes => 1 >>
1083 when creating the C<SQL::Abstract> object.
1084 Then you may use an arrayref to insert and update database array types:
1086 my $sql = SQL::Abstract->new(array_datatypes => 1);
1088 planets => [qw/Mercury Venus Earth Mars/]
1091 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1095 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1097 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1100 =head2 Inserting and Updating SQL
1102 In order to apply SQL functions to elements of your C<%data> you may
1103 specify a reference to an arrayref for the given hash value. For example,
1104 if you need to execute the Oracle C<to_date> function on a value, you can
1105 say something like this:
1109 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1112 The first value in the array is the actual SQL. Any other values are
1113 optional and would be included in the bind values array. This gives
1116 my($stmt, @bind) = $sql->insert('people', \%data);
1118 $stmt = "INSERT INTO people (name, date_entered)
1119 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1120 @bind = ('Bill', '03/02/2003');
1122 An UPDATE is just as easy, all you change is the name of the function:
1124 my($stmt, @bind) = $sql->update('people', \%data);
1126 Notice that your C<%data> isn't touched; the module will generate
1127 the appropriately quirky SQL for you automatically. Usually you'll
1128 want to specify a WHERE clause for your UPDATE, though, which is
1129 where handling C<%where> hashes comes in handy...
1131 =head2 Complex where statements
1133 This module can generate pretty complicated WHERE statements
1134 easily. For example, simple C<key=value> pairs are taken to mean
1135 equality, and if you want to see if a field is within a set
1136 of values, you can use an arrayref. Let's say we wanted to
1137 SELECT some data based on this criteria:
1140 requestor => 'inna',
1141 worker => ['nwiger', 'rcwe', 'sfz'],
1142 status => { '!=', 'completed' }
1145 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1147 The above would give you something like this:
1149 $stmt = "SELECT * FROM tickets WHERE
1150 ( requestor = ? ) AND ( status != ? )
1151 AND ( worker = ? OR worker = ? OR worker = ? )";
1152 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1154 Which you could then use in DBI code like so:
1156 my $sth = $dbh->prepare($stmt);
1157 $sth->execute(@bind);
1163 The functions are simple. There's one for each major SQL operation,
1164 and a constructor you use first. The arguments are specified in a
1165 similar order to each function (table, then fields, then a where
1166 clause) to try and simplify things.
1171 =head2 new(option => 'value')
1173 The C<new()> function takes a list of options and values, and returns
1174 a new B<SQL::Abstract> object which can then be used to generate SQL
1175 through the methods below. The options accepted are:
1181 If set to 'lower', then SQL will be generated in all lowercase. By
1182 default SQL is generated in "textbook" case meaning something like:
1184 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1186 Any setting other than 'lower' is ignored.
1190 This determines what the default comparison operator is. By default
1191 it is C<=>, meaning that a hash like this:
1193 %where = (name => 'nwiger', email => 'nate@wiger.org');
1195 Will generate SQL like this:
1197 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1199 However, you may want loose comparisons by default, so if you set
1200 C<cmp> to C<like> you would get SQL such as:
1202 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1204 You can also override the comparsion on an individual basis - see
1205 the huge section on L</"WHERE CLAUSES"> at the bottom.
1207 =item sqltrue, sqlfalse
1209 Expressions for inserting boolean values within SQL statements.
1210 By default these are C<1=1> and C<1=0>.
1214 This determines the default logical operator for multiple WHERE
1215 statements in arrays. By default it is "or", meaning that a WHERE
1219 event_date => {'>=', '2/13/99'},
1220 event_date => {'<=', '4/24/03'},
1223 Will generate SQL like this:
1225 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1227 This is probably not what you want given this query, though (look
1228 at the dates). To change the "OR" to an "AND", simply specify:
1230 my $sql = SQL::Abstract->new(logic => 'and');
1232 Which will change the above C<WHERE> to:
1234 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1236 The logic can also be changed locally by inserting
1237 an extra first element in the array :
1239 @where = (-and => event_date => {'>=', '2/13/99'},
1240 event_date => {'<=', '4/24/03'} );
1242 See the L</"WHERE CLAUSES"> section for explanations.
1246 This will automatically convert comparisons using the specified SQL
1247 function for both column and value. This is mostly used with an argument
1248 of C<upper> or C<lower>, so that the SQL will have the effect of
1249 case-insensitive "searches". For example, this:
1251 $sql = SQL::Abstract->new(convert => 'upper');
1252 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1254 Will turn out the following SQL:
1256 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1258 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1259 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1260 not validate this option; it will just pass through what you specify verbatim).
1264 This is a kludge because many databases suck. For example, you can't
1265 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1266 Instead, you have to use C<bind_param()>:
1268 $sth->bind_param(1, 'reg data');
1269 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1271 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1272 which loses track of which field each slot refers to. Fear not.
1274 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1275 Currently, you can specify either C<normal> (default) or C<columns>. If you
1276 specify C<columns>, you will get an array that looks like this:
1278 my $sql = SQL::Abstract->new(bindtype => 'columns');
1279 my($stmt, @bind) = $sql->insert(...);
1282 [ 'column1', 'value1' ],
1283 [ 'column2', 'value2' ],
1284 [ 'column3', 'value3' ],
1287 You can then iterate through this manually, using DBI's C<bind_param()>.
1289 $sth->prepare($stmt);
1292 my($col, $data) = @$_;
1293 if ($col eq 'details' || $col eq 'comments') {
1294 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1295 } elsif ($col eq 'image') {
1296 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1298 $sth->bind_param($i, $data);
1302 $sth->execute; # execute without @bind now
1304 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1305 Basically, the advantage is still that you don't have to care which fields
1306 are or are not included. You could wrap that above C<for> loop in a simple
1307 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1308 get a layer of abstraction over manual SQL specification.
1312 This is the character that a table or column name will be quoted
1313 with. By default this is an empty string, but you could set it to
1314 the character C<`>, to generate SQL like this:
1316 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1318 Alternatively, you can supply an array ref of two items, the first being the left
1319 hand quote character, and the second the right hand quote character. For
1320 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1321 that generates SQL like this:
1323 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1325 Quoting is useful if you have tables or columns names that are reserved
1326 words in your database's SQL dialect.
1330 This is the character that separates a table and column name. It is
1331 necessary to specify this when the C<quote_char> option is selected,
1332 so that tables and column names can be individually quoted like this:
1334 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1336 =item array_datatypes
1338 When this option is true, arrayrefs in INSERT or UPDATE are
1339 interpreted as array datatypes and are passed directly
1341 When this option is false, arrayrefs are interpreted
1342 as literal SQL, just like refs to arrayrefs
1343 (but this behavior is for backwards compatibility; when writing
1344 new queries, use the "reference to arrayref" syntax
1350 Takes a reference to a list of "special operators"
1351 to extend the syntax understood by L<SQL::Abstract>.
1352 See section L</"SPECIAL OPERATORS"> for details.
1358 =head2 insert($table, \@values || \%fieldvals)
1360 This is the simplest function. You simply give it a table name
1361 and either an arrayref of values or hashref of field/value pairs.
1362 It returns an SQL INSERT statement and a list of bind values.
1363 See the sections on L</"Inserting and Updating Arrays"> and
1364 L</"Inserting and Updating SQL"> for information on how to insert
1365 with those data types.
1367 =head2 update($table, \%fieldvals, \%where)
1369 This takes a table, hashref of field/value pairs, and an optional
1370 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1372 See the sections on L</"Inserting and Updating Arrays"> and
1373 L</"Inserting and Updating SQL"> for information on how to insert
1374 with those data types.
1376 =head2 select($source, $fields, $where, $order)
1378 This returns a SQL SELECT statement and associated list of bind values, as
1379 specified by the arguments :
1385 Specification of the 'FROM' part of the statement.
1386 The argument can be either a plain scalar (interpreted as a table
1387 name, will be quoted), or an arrayref (interpreted as a list
1388 of table names, joined by commas, quoted), or a scalarref
1389 (literal table name, not quoted), or a ref to an arrayref
1390 (list of literal table names, joined by commas, not quoted).
1394 Specification of the list of fields to retrieve from
1396 The argument can be either an arrayref (interpreted as a list
1397 of field names, will be joined by commas and quoted), or a
1398 plain scalar (literal SQL, not quoted).
1399 Please observe that this API is not as flexible as for
1400 the first argument C<$table>, for backwards compatibility reasons.
1404 Optional argument to specify the WHERE part of the query.
1405 The argument is most often a hashref, but can also be
1406 an arrayref or plain scalar --
1407 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1411 Optional argument to specify the ORDER BY part of the query.
1412 The argument can be a scalar, a hashref or an arrayref
1413 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1419 =head2 delete($table, \%where)
1421 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1422 It returns an SQL DELETE statement and list of bind values.
1424 =head2 where(\%where, \@order)
1426 This is used to generate just the WHERE clause. For example,
1427 if you have an arbitrary data structure and know what the
1428 rest of your SQL is going to look like, but want an easy way
1429 to produce a WHERE clause, use this. It returns an SQL WHERE
1430 clause and list of bind values.
1433 =head2 values(\%data)
1435 This just returns the values from the hash C<%data>, in the same
1436 order that would be returned from any of the other above queries.
1437 Using this allows you to markedly speed up your queries if you
1438 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1440 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1442 Warning: This is an experimental method and subject to change.
1444 This returns arbitrarily generated SQL. It's a really basic shortcut.
1445 It will return two different things, depending on return context:
1447 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1448 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1450 These would return the following:
1452 # First calling form
1453 $stmt = "CREATE TABLE test (?, ?)";
1454 @bind = (field1, field2);
1456 # Second calling form
1457 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1459 Depending on what you're trying to do, it's up to you to choose the correct
1460 format. In this example, the second form is what you would want.
1464 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1468 ALTER SESSION SET nls_date_format = 'MM/YY'
1470 You get the idea. Strings get their case twiddled, but everything
1471 else remains verbatim.
1476 =head1 WHERE CLAUSES
1480 This module uses a variation on the idea from L<DBIx::Abstract>. It
1481 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1482 module is that things in arrays are OR'ed, and things in hashes
1485 The easiest way to explain is to show lots of examples. After
1486 each C<%where> hash shown, it is assumed you used:
1488 my($stmt, @bind) = $sql->where(\%where);
1490 However, note that the C<%where> hash can be used directly in any
1491 of the other functions as well, as described above.
1493 =head2 Key-value pairs
1495 So, let's get started. To begin, a simple hash:
1499 status => 'completed'
1502 Is converted to SQL C<key = val> statements:
1504 $stmt = "WHERE user = ? AND status = ?";
1505 @bind = ('nwiger', 'completed');
1507 One common thing I end up doing is having a list of values that
1508 a field can be in. To do this, simply specify a list inside of
1513 status => ['assigned', 'in-progress', 'pending'];
1516 This simple code will create the following:
1518 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1519 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1521 An empty arrayref will be considered a logical false and
1524 =head2 Key-value pairs
1526 If you want to specify a different type of operator for your comparison,
1527 you can use a hashref for a given column:
1531 status => { '!=', 'completed' }
1534 Which would generate:
1536 $stmt = "WHERE user = ? AND status != ?";
1537 @bind = ('nwiger', 'completed');
1539 To test against multiple values, just enclose the values in an arrayref:
1541 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1543 Which would give you:
1545 "WHERE status != ? AND status != ? AND status != ?"
1547 Notice that since the operator was recognized as being a 'negative'
1548 operator, the arrayref was interpreted with 'AND' logic (because
1549 of Morgan's laws). By contrast, the reverse
1551 status => { '=', ['assigned', 'in-progress', 'pending'] };
1555 "WHERE status = ? OR status = ? OR status = ?"
1558 The hashref can also contain multiple pairs, in which case it is expanded
1559 into an C<AND> of its elements:
1563 status => { '!=', 'completed', -not_like => 'pending%' }
1566 # Or more dynamically, like from a form
1567 $where{user} = 'nwiger';
1568 $where{status}{'!='} = 'completed';
1569 $where{status}{'-not_like'} = 'pending%';
1571 # Both generate this
1572 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1573 @bind = ('nwiger', 'completed', 'pending%');
1576 To get an OR instead, you can combine it with the arrayref idea:
1580 priority => [ {'=', 2}, {'!=', 1} ]
1583 Which would generate:
1585 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1586 @bind = ('nwiger', '2', '1');
1589 =head2 Logic and nesting operators
1591 In the example above,
1592 there is a subtle trap if you want to say something like
1593 this (notice the C<AND>):
1595 WHERE priority != ? AND priority != ?
1597 Because, in Perl you I<can't> do this:
1599 priority => { '!=', 2, '!=', 1 }
1601 As the second C<!=> key will obliterate the first. The solution
1602 is to use the special C<-modifier> form inside an arrayref:
1604 priority => [ -and => {'!=', 2},
1608 Normally, these would be joined by C<OR>, but the modifier tells it
1609 to use C<AND> instead. (Hint: You can use this in conjunction with the
1610 C<logic> option to C<new()> in order to change the way your queries
1611 work by default.) B<Important:> Note that the C<-modifier> goes
1612 B<INSIDE> the arrayref, as an extra first element. This will
1613 B<NOT> do what you think it might:
1615 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1617 Here is a quick list of equivalencies, since there is some overlap:
1620 status => {'!=', 'completed', 'not like', 'pending%' }
1621 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1624 status => {'=', ['assigned', 'in-progress']}
1625 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1626 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1628 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1629 operator which adds an additional set of parens, to create a subquery.
1630 For example, to get something like this:
1632 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1633 @bind = ('nwiger', '20', 'ASIA');
1639 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1642 If you need several nested subexpressions, you can number
1643 the C<-nest> branches :
1653 =head2 Special operators : IN, BETWEEN, etc.
1655 You can also use the hashref format to compare a list of fields using the
1656 C<IN> comparison operator, by specifying the list as an arrayref:
1659 status => 'completed',
1660 reportid => { -in => [567, 2335, 2] }
1663 Which would generate:
1665 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1666 @bind = ('completed', '567', '2335', '2');
1668 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1671 Another pair of operators is C<-between> and C<-not_between>,
1672 used with an arrayref of two values:
1676 completion_date => {
1677 -not_between => ['2002-10-01', '2003-02-06']
1683 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1685 These are the two builtin "special operators"; but the
1686 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1688 =head2 Nested conditions
1690 So far, we've seen how multiple conditions are joined with a top-level
1691 C<AND>. We can change this by putting the different conditions we want in
1692 hashes and then putting those hashes in an array. For example:
1697 status => { -like => ['pending%', 'dispatched'] },
1701 status => 'unassigned',
1705 This data structure would create the following:
1707 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1708 OR ( user = ? AND status = ? ) )";
1709 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1711 This can be combined with the C<-nest> operator to properly group
1718 ["-and", workhrs => {'>', 20}, geo => 'ASIA' ],
1719 ["-and", workhrs => {'<', 50}, geo => 'EURO' ]
1726 WHERE ( user = ? AND
1727 ( ( workhrs > ? AND geo = ? )
1728 OR ( workhrs < ? AND geo = ? ) ) )
1732 Finally, sometimes only literal SQL will do. If you want to include
1733 literal SQL verbatim, you can specify it as a scalar reference, namely:
1735 my $inn = 'is Not Null';
1737 priority => { '<', 2 },
1743 $stmt = "WHERE priority < ? AND requestor is Not Null";
1746 Note that in this example, you only get one bind parameter back, since
1747 the verbatim SQL is passed as part of the statement.
1749 Of course, just to prove a point, the above can also be accomplished
1753 priority => { '<', 2 },
1754 requestor => { '!=', undef },
1760 Conditions on boolean columns can be expressed in the
1761 same way, passing a reference to an empty string :
1764 priority => { '<', 2 },
1770 $stmt = "WHERE priority < ? AND is_ready";
1774 =head2 Literal SQL with placeholders and bind values (subqueries)
1776 If the literal SQL to be inserted has placeholders and bind values,
1777 use a reference to an arrayref (yes this is a double reference --
1778 not so common, but perfectly legal Perl). For example, to find a date
1779 in Postgres you can use something like this:
1782 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1787 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1791 Literal SQL is especially useful for nesting parenthesized clauses in the
1792 main SQL query. Here is a first example :
1794 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1798 bar => \["IN ($sub_stmt)" => @sub_bind],
1803 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1804 WHERE c2 < ? AND c3 LIKE ?))";
1805 @bind = (1234, 100, "foo%");
1807 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
1808 are expressed in the same way. Of course the C<$sub_stmt> and
1809 its associated bind values can be generated through a former call
1812 my ($sub_stmt, @sub_bind)
1813 = $sql->select("t1", "c1", {c2 => {"<" => 100},
1814 c3 => {-like => "foo%"}});
1817 bar => \["> ALL ($sub_stmt)" => @sub_bind],
1820 In the examples above, the subquery was used as an operator on a column;
1821 but the same principle also applies for a clause within the main C<%where>
1822 hash, like an EXISTS subquery :
1824 my ($sub_stmt, @sub_bind)
1825 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1828 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
1833 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1834 WHERE c1 = ? AND c2 > t0.c0))";
1838 Observe that the condition on C<c2> in the subquery refers to
1839 column C<t0.c0> of the main query : this is I<not> a bind
1840 value, so we have to express it through a scalar ref.
1841 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
1842 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
1843 what we wanted here.
1845 Another use of the subquery technique is when some SQL clauses need
1846 parentheses, as it often occurs with some proprietary SQL extensions
1847 like for example fulltext expressions, geospatial expressions,
1848 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
1851 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
1854 Finally, here is an example where a subquery is used
1855 for expressing unary negation:
1857 my ($sub_stmt, @sub_bind)
1858 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
1859 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
1861 lname => {like => '%son%'},
1862 -nest => \["NOT ($sub_stmt)" => @sub_bind],
1867 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1868 @bind = ('%son%', 10, 20)
1874 These pages could go on for a while, since the nesting of the data
1875 structures this module can handle are pretty much unlimited (the
1876 module implements the C<WHERE> expansion as a recursive function
1877 internally). Your best bet is to "play around" with the module a
1878 little to see how the data structures behave, and choose the best
1879 format for your data based on that.
1881 And of course, all the values above will probably be replaced with
1882 variables gotten from forms or the command line. After all, if you
1883 knew everything ahead of time, you wouldn't have to worry about
1884 dynamically-generating SQL and could just hardwire it into your
1890 =head1 ORDER BY CLAUSES
1892 Some functions take an order by clause. This can either be a scalar (just a
1893 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1894 or an array of either of the two previous forms. Examples:
1896 Given | Will Generate
1897 ----------------------------------------------------------
1898 \'colA DESC' | ORDER BY colA DESC
1899 'colA' | ORDER BY colA
1900 [qw/colA colB/] | ORDER BY colA, colB
1901 {-asc => 'colA'} | ORDER BY colA ASC
1902 {-desc => 'colB'} | ORDER BY colB DESC
1904 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1907 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1908 ==========================================================
1912 =head1 SPECIAL OPERATORS
1914 my $sqlmaker = SQL::Abstract->new(special_ops => [
1917 my ($self, $field, $op, $arg) = @_;
1923 A "special operator" is a SQL syntactic clause that can be
1924 applied to a field, instead of a usual binary operator.
1927 WHERE field IN (?, ?, ?)
1928 WHERE field BETWEEN ? AND ?
1929 WHERE MATCH(field) AGAINST (?, ?)
1931 Special operators IN and BETWEEN are fairly standard and therefore
1932 are builtin within C<SQL::Abstract>. For other operators,
1933 like the MATCH .. AGAINST example above which is
1934 specific to MySQL, you can write your own operator handlers :
1935 supply a C<special_ops> argument to the C<new> method.
1936 That argument takes an arrayref of operator definitions;
1937 each operator definition is a hashref with two entries
1943 the regular expression to match the operator
1947 coderef that will be called when meeting that operator
1948 in the input tree. The coderef will be called with
1949 arguments C<< ($self, $field, $op, $arg) >>, and
1950 should return a C<< ($sql, @bind) >> structure.
1954 For example, here is an implementation
1955 of the MATCH .. AGAINST syntax for MySQL
1957 my $sqlmaker = SQL::Abstract->new(special_ops => [
1959 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
1960 {regex => qr/^match$/i,
1962 my ($self, $field, $op, $arg) = @_;
1963 $arg = [$arg] if not ref $arg;
1964 my $label = $self->_quote($field);
1965 my ($placeholder) = $self->_convert('?');
1966 my $placeholders = join ", ", (($placeholder) x @$arg);
1967 my $sql = $self->_sqlcase('match') . " ($label) "
1968 . $self->_sqlcase('against') . " ($placeholders) ";
1969 my @bind = $self->_bindtype($field, @$arg);
1970 return ($sql, @bind);
1979 Thanks to some benchmarking by Mark Stosberg, it turns out that
1980 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
1981 I must admit this wasn't an intentional design issue, but it's a
1982 byproduct of the fact that you get to control your C<DBI> handles
1985 To maximize performance, use a code snippet like the following:
1987 # prepare a statement handle using the first row
1988 # and then reuse it for the rest of the rows
1990 for my $href (@array_of_hashrefs) {
1991 $stmt ||= $sql->insert('table', $href);
1992 $sth ||= $dbh->prepare($stmt);
1993 $sth->execute($sql->values($href));
1996 The reason this works is because the keys in your C<$href> are sorted
1997 internally by B<SQL::Abstract>. Thus, as long as your data retains
1998 the same structure, you only have to generate the SQL the first time
1999 around. On subsequent queries, simply use the C<values> function provided
2000 by this module to return your values in the correct order.
2005 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2006 really like this part (I do, at least). Building up a complex query
2007 can be as simple as the following:
2011 use CGI::FormBuilder;
2014 my $form = CGI::FormBuilder->new(...);
2015 my $sql = SQL::Abstract->new;
2017 if ($form->submitted) {
2018 my $field = $form->field;
2019 my $id = delete $field->{id};
2020 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2023 Of course, you would still have to connect using C<DBI> to run the
2024 query, but the point is that if you make your form look like your
2025 table, the actual query script can be extremely simplistic.
2027 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2028 a fast interface to returning and formatting data. I frequently
2029 use these three modules together to write complex database query
2030 apps in under 50 lines.
2035 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2036 Great care has been taken to preserve the I<published> behavior
2037 documented in previous versions in the 1.* family; however,
2038 some features that were previously undocumented, or behaved
2039 differently from the documentation, had to be changed in order
2040 to clarify the semantics. Hence, client code that was relying
2041 on some dark areas of C<SQL::Abstract> v1.*
2042 B<might behave differently> in v1.50.
2044 The main changes are :
2050 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2054 added -nest1, -nest2 or -nest_1, -nest_2, ...
2058 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2062 defensive programming : check arguments
2066 fixed bug with global logic, which was previously implemented
2067 through global variables yielding side-effects. Prior versons would
2068 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2069 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2070 Now this is interpreted
2071 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2075 C<-and> / C<-or> operators are no longer accepted
2076 in the middle of an arrayref : they are
2077 only admitted if in first position.
2081 changed logic for distributing an op over arrayrefs
2085 fixed semantics of _bindtype on array args
2089 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2090 we just avoid shifting arrays within that tree.
2094 dropped the C<_modlogic> function
2100 =head1 ACKNOWLEDGEMENTS
2102 There are a number of individuals that have really helped out with
2103 this module. Unfortunately, most of them submitted bugs via CPAN
2104 so I have no idea who they are! But the people I do know are:
2106 Ash Berlin (order_by hash term support)
2107 Matt Trout (DBIx::Class support)
2108 Mark Stosberg (benchmarking)
2109 Chas Owens (initial "IN" operator support)
2110 Philip Collins (per-field SQL functions)
2111 Eric Kolve (hashref "AND" support)
2112 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2113 Dan Kubb (support for "quote_char" and "name_sep")
2114 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2115 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2121 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2125 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2127 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2129 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2130 While not an official support venue, C<DBIx::Class> makes heavy use of
2131 C<SQL::Abstract>, and as such list members there are very familiar with
2132 how to create queries.
2134 This module is free software; you may copy this under the terms of
2135 the GNU General Public License, or the Artistic License, copies of
2136 which should have accompanied your Perl kit.