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/;
12 use Scalar::Util qw/blessed/;
14 #======================================================================
16 #======================================================================
18 our $VERSION = '1.49_01';
19 $VERSION = eval $VERSION; # numify for warning-free dev releases
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},
31 #======================================================================
32 # DEBUGGING AND ERROR REPORTING
33 #======================================================================
36 return unless $_[0]->{debug}; shift; # a little faster
37 my $func = (caller(1))[3];
38 warn "[$func] ", @_, "\n";
42 my($func) = (caller(1))[3];
43 carp "[$func] Warning: ", @_;
47 my($func) = (caller(1))[3];
48 croak "[$func] Fatal: ", @_;
52 #======================================================================
54 #======================================================================
58 my $class = ref($self) || $self;
59 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
61 # choose our case by keeping an option around
62 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
64 # default logic for interpreting arrayrefs
65 $opt{logic} = uc $opt{logic} || 'OR';
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';
72 # default comparison is "=", but can be overridden
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;
81 $opt{sqltrue} ||= '1=1';
82 $opt{sqlfalse} ||= '0=1';
85 $opt{special_ops} ||= [];
86 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
88 return bless \%opt, $class;
93 #======================================================================
95 #======================================================================
99 my $table = $self->_table(shift);
100 my $data = shift || return;
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;
108 sub _insert_HASHREF { # explicit list of fields and then values
109 my ($self, $data) = @_;
111 my @fields = sort keys %$data;
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}]);
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]);
127 $_ = $self->_quote($_) foreach @fields;
128 $sql = "( ".join(", ", @fields).") ".$sql;
130 return ($sql, @bind);
133 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
134 my ($self, $data) = @_;
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";
140 my (@values, @all_bind);
143 $self->_SWITCH_refkind($v, {
146 if ($self->{array_datatypes}) { # if array datatype are activated
149 else { # else literal SQL with bind
150 my ($sql, @bind) = @$v;
152 push @all_bind, @bind;
156 ARRAYREFREF => sub { # literal SQL with bind
157 my ($sql, @bind) = @${$v};
159 push @all_bind, @bind;
162 # THINK : anything useful to do with a HASHREF ?
164 SCALARREF => sub { # literal SQL without bind
168 SCALAR_or_UNDEF => sub {
177 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
178 return ($sql, @all_bind);
182 sub _insert_ARRAYREFREF { # literal SQL with bind
183 my ($self, $data) = @_;
188 sub _insert_SCALARREF { # literal SQL without bind
189 my ($self, $data) = @_;
196 #======================================================================
198 #======================================================================
203 my $table = $self->_table(shift);
204 my $data = shift || return;
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';
212 for my $k (sort keys %$data) {
215 my $label = $self->_quote($k);
217 $self->_SWITCH_refkind($v, {
219 if ($self->{array_datatypes}) { # array datatype
220 push @set, "$label = ?";
221 push @all_bind, $self->_bindtype($k, $v);
223 else { # literal SQL with bind
224 my ($sql, @bind) = @$v;
225 push @set, "$label = $sql";
226 push @all_bind, $self->_bindtype($k, @bind);
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);
234 SCALARREF => sub { # literal SQL without bind
235 push @set, "$label = $$v";
237 SCALAR_or_UNDEF => sub {
238 push @set, "$label = ?";
239 push @all_bind, $self->_bindtype($k, $v);
245 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
249 my($where_sql, @where_bind) = $self->where($where);
251 push @all_bind, @where_bind;
254 return wantarray ? ($sql, @all_bind) : $sql;
260 #======================================================================
262 #======================================================================
267 my $table = $self->_table(shift);
268 my $fields = shift || '*';
272 my($where_sql, @bind) = $self->where($where, $order);
274 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
276 my $sql = join(' ', $self->_sqlcase('select'), $f,
277 $self->_sqlcase('from'), $table)
280 return wantarray ? ($sql, @bind) : $sql;
283 #======================================================================
285 #======================================================================
290 my $table = $self->_table(shift);
294 my($where_sql, @bind) = $self->where($where);
295 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
297 return wantarray ? ($sql, @bind) : $sql;
301 #======================================================================
303 #======================================================================
307 # Finally, a separate routine just to handle WHERE clauses
309 my ($self, $where, $order) = @_;
312 my ($sql, @bind) = $self->_recurse_where($where);
313 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
317 $sql .= $self->_order_by($order);
320 return wantarray ? ($sql, @bind) : $sql;
325 my ($self, $where, $logic) = @_;
327 # dispatch on appropriate method according to refkind of $where
328 my $method = $self->_METHOD_FOR_refkind("_where", $where);
329 $self->$method($where, $logic);
334 #======================================================================
335 # WHERE: top-level ARRAYREF
336 #======================================================================
339 sub _where_ARRAYREF {
340 my ($self, $where, $logic) = @_;
342 $logic = uc($logic || $self->{logic});
343 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
345 my @clauses = @$where;
347 # if the array starts with [-and|or => ...], recurse with that logic
348 my $first = $clauses[0] || '';
349 if ($first =~ /^-(and|or)/i) {
352 return $self->_where_ARRAYREF(\@clauses, $logic);
356 my (@sql_clauses, @all_bind);
358 # need to use while() so can shift() for pairs
359 while (my $el = shift @clauses) {
361 # switch according to kind of $el and get corresponding ($sql, @bind)
362 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
364 # skip empty elements, otherwise get invalid trailing AND stuff
365 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
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)".
374 SCALARREF => sub { ($$el); },
376 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
377 $self->_recurse_where({$el => shift(@clauses)})},
379 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
383 push @sql_clauses, $sql;
384 push @all_bind, @bind;
388 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
393 #======================================================================
394 # WHERE: top-level HASHREF
395 #======================================================================
398 my ($self, $where) = @_;
399 my (@sql_clauses, @all_bind);
401 # LDNOTE : don't really know why we need to sort keys
402 for my $k (sort keys %$where) {
403 my $v = $where->{$k};
405 # ($k => $v) is either a special op or a regular hashpair
406 my ($sql, @bind) = ($k =~ /^-(.+)/) ? $self->_where_op_in_hash($1, $v)
408 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
409 $self->$method($k, $v);
412 push @sql_clauses, $sql;
413 push @all_bind, @bind;
416 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
420 sub _where_op_in_hash {
421 my ($self, $op, $v) = @_;
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...");
428 $self->_SWITCH_refkind($v, {
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);
439 belch "-or => {...} should be -nest => [...]";
440 return $self->_where_ARRAYREF([%$v], 'OR');
443 return $self->_where_HASHREF($v);
447 SCALARREF => sub { # literal SQL
449 or puke "-$op => \\\$scalar not supported, use -nest => ...";
453 ARRAYREFREF => sub { # literal SQL
455 or puke "-$op => \\[..] not supported, use -nest => ...";
459 SCALAR => sub { # permissively interpreted as SQL
461 or puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
462 belch "literal SQL should be -nest => \\'scalar' "
463 . "instead of -nest => 'scalar' ";
468 puke "-$op => undef not supported";
474 sub _where_hashpair_ARRAYREF {
475 my ($self, $k, $v) = @_;
478 my @v = @$v; # need copy because of shift below
479 $self->_debug("ARRAY($k) means distribute over elements");
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;
485 my @distributed = map { {$k => $_} } @v;
486 unshift @distributed, $op if $op;
488 return $self->_recurse_where(\@distributed);
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});
497 sub _where_hashpair_HASHREF {
498 my ($self, $k, $v) = @_;
500 my (@all_sql, @all_bind);
502 for my $op (sort keys %$v) {
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
514 # CASE: special operators like -in or -between
515 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
517 ($sql, @bind) = $special_op->{handler}->($self, $k, $op, $val);
520 # CASE: col => {op => \@vals}
521 elsif (ref $val eq 'ARRAY') {
522 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
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");
533 # CASE: col => {op => $scalar}
535 $sql = join ' ', $self->_convert($self->_quote($k)),
536 $self->_sqlcase($op),
537 $self->_convert('?');
538 @bind = $self->_bindtype($k, $val);
542 push @all_bind, @bind;
545 return $self->_join_sql_clauses('and', \@all_sql, \@all_bind);
550 sub _where_field_op_ARRAYREF {
551 my ($self, $k, $op, $vals) = @_;
554 $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
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';
565 # distribute $op over each member of @$vals
566 return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
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};
576 puke "operator '$op' applied on an empty array (field '$k')";
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;
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 );
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);
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');
615 #======================================================================
616 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
617 #======================================================================
620 sub _where_SCALARREF {
621 my ($self, $where) = @_;
624 $self->_debug("SCALAR(*top) means literal SQL: $$where");
630 my ($self, $where) = @_;
633 $self->_debug("NOREF(*top) means literal SQL: $where");
644 #======================================================================
645 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
646 #======================================================================
649 sub _where_field_BETWEEN {
650 my ($self, $k, $op, $vals) = @_;
652 ref $vals eq 'ARRAY' && @$vals == 2
653 or puke "special op 'between' requires an arrayref of two values";
655 my ($label) = $self->_convert($self->_quote($k));
656 my ($placeholder) = $self->_convert('?');
657 my $and = $self->_sqlcase('and');
658 $op = $self->_sqlcase($op);
660 my $sql = "( $label $op $placeholder $and $placeholder )";
661 my @bind = $self->_bindtype($k, @$vals);
666 sub _where_field_IN {
667 my ($self, $k, $op, $vals) = @_;
669 # backwards compatibility : if scalar, force into an arrayref
670 $vals = [$vals] if defined $vals && ! ref $vals;
673 or puke "special op 'in' requires an arrayref";
675 my ($label) = $self->_convert($self->_quote($k));
676 my ($placeholder) = $self->_convert('?');
677 my $and = $self->_sqlcase('and');
678 $op = $self->_sqlcase($op);
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);
685 return ($sql, @bind);
687 else { # empty list : some databases won't understand "IN ()", so DWIM
688 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
698 #======================================================================
700 #======================================================================
703 my ($self, $arg) = @_;
705 # construct list of ordering instructions
706 my @order = $self->_SWITCH_refkind($arg, {
709 map {$self->_SWITCH_refkind($_, {
710 SCALAR => sub {$self->_quote($_)},
712 SCALARREF => sub {$$_}, # literal SQL, no quoting
713 HASHREF => sub {$self->_order_by_hash($_)}
717 SCALAR => sub {$self->_quote($arg)},
719 SCALARREF => sub {$$arg}, # literal SQL, no quoting
720 HASHREF => sub {$self->_order_by_hash($arg)},
725 my $order = join ', ', @order;
726 return $order ? $self->_sqlcase(' order by')." $order" : '';
731 my ($self, $hash) = @_;
733 # get first pair in hash
734 my ($key, $val) = each %$hash;
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)";
740 my ($order) = ($key =~ /^-(desc|asc)/i)
741 or puke "invalid key in _order_by hash : $key";
743 return $self->_quote($val) ." ". $self->_sqlcase($order);
748 #======================================================================
749 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
750 #======================================================================
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;},
764 #======================================================================
766 #======================================================================
772 $label or puke "can't quote an empty label";
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}}},
781 or puke "quote_char must be an arrayref of 2 values";
783 # no quoting if no quoting chars
784 $ql or return $label;
786 # no quoting for literal SQL
787 return $$label if ref($label) eq 'SCALAR';
789 # separate table / column (if applicable)
790 my $sep = $self->{name_sep} || '';
791 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
793 # do the quoting, except for "*" or for `table`.*
794 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
796 # reassemble and return.
797 return join $sep, @quoted;
801 # Conversion, if applicable
803 my ($self, $arg) = @_;
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
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.')';
824 my($col, @vals) = @_;
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;
830 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
833 sub _join_sql_clauses {
834 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
836 if (@$clauses_aref > 1) {
837 my $join = " " . $self->_sqlcase($logic) . " ";
838 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
839 return ($sql, @$bind_aref);
841 elsif (@$clauses_aref) {
842 return ($clauses_aref->[0], @$bind_aref); # no parentheses
845 return (); # if no SQL, ignore @$bind_aref
850 # Fix SQL case, if so requested
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]);
860 #======================================================================
861 # DISPATCHING FROM REFKIND
862 #======================================================================
865 my ($self, $data) = @_;
869 # $suffix = 'REF' x (length of ref chain, i. e. \\[] is REFREFREF)
873 # blessed references that can stringify are considered like scalars
874 $ref = (blessed $data && overload::Method($data, '""')) ? ''
876 last if $ref ne 'REF';
880 return $ref ? $ref.$suffix :
881 defined $data ? 'SCALAR' :
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';
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);
902 sub _SWITCH_refkind {
903 my ($self, $data, $dispatch_table) = @_;
905 my $coderef = first {$_} map {$dispatch_table->{$_}}
906 $self->_try_refkind($data)
907 or puke "no dispatch entry for ".$self->_refkind($data);
914 #======================================================================
915 # VALUES, GENERATE, AUTOLOAD
916 #======================================================================
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.
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;
933 my(@sql, @sqlq, @sqlv);
937 if ($ref eq 'HASH') {
938 for my $k (sort keys %$_) {
941 my $label = $self->_quote($k);
943 # SQL included for values
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";
952 push @sqlq, "$label = ?";
953 push @sqlv, $self->_bindtype($k, $v);
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
963 push @sqlq, shift @val;
965 } elsif ($r eq 'SCALAR') {
966 # embedded literal SQL
973 push @sql, '(' . join(', ', @sqlq) . ')';
974 } elsif ($ref eq 'SCALAR') {
978 # strings get case twiddled
979 push @sql, $self->_sqlcase($_);
983 my $sql = join ' ', @sql;
985 # this is pretty tricky
986 # if ask for an array, return ($stmt, @bind)
987 # otherwise, s/?/shift @sqlv/ to put it inline
989 return ($sql, @sqlv);
991 1 while $sql =~ s/\?/my $d = shift(@sqlv);
992 ref $d ? $d->[1] : $d/e;
1001 # This allows us to check for a local, then _form, attr
1003 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1004 return $self->generate($name, @_);
1015 SQL::Abstract - Generate SQL from Perl data structures
1021 my $sql = SQL::Abstract->new;
1023 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1025 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1027 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1029 my($stmt, @bind) = $sql->delete($table, \%where);
1031 # Then, use these in your DBI statements
1032 my $sth = $dbh->prepare($stmt);
1033 $sth->execute(@bind);
1035 # Just generate the WHERE clause
1036 my($stmt, @bind) = $sql->where(\%where, \@order);
1038 # Return values in the same order, for hashed queries
1039 # See PERFORMANCE section for more details
1040 my @bind = $sql->values(\%fieldvals);
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.
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.
1059 To begin with, an SQL INSERT is as easy as just specifying a hash
1060 of C<key=value> pairs:
1063 name => 'Jimbo Bobson',
1064 phone => '123-456-7890',
1065 address => '42 Sister Lane',
1066 city => 'St. Louis',
1067 state => 'Louisiana',
1070 The SQL can then be generated with this:
1072 my($stmt, @bind) = $sql->insert('people', \%data);
1074 Which would give you something like this:
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');
1082 These are then used directly in your DBI code:
1084 my $sth = $dbh->prepare($stmt);
1085 $sth->execute(@bind);
1087 =head2 Inserting and Updating Arrays
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:
1094 my $sql = SQL::Abstract->new(array_datatypes => 1);
1096 planets => [qw/Mercury Venus Earth Mars/]
1099 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1103 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1105 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1108 =head2 Inserting and Updating SQL
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:
1117 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
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
1124 my($stmt, @bind) = $sql->insert('people', \%data);
1126 $stmt = "INSERT INTO people (name, date_entered)
1127 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1128 @bind = ('Bill', '03/02/2003');
1130 An UPDATE is just as easy, all you change is the name of the function:
1132 my($stmt, @bind) = $sql->update('people', \%data);
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...
1139 =head2 Complex where statements
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:
1148 requestor => 'inna',
1149 worker => ['nwiger', 'rcwe', 'sfz'],
1150 status => { '!=', 'completed' }
1153 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1155 The above would give you something like this:
1157 $stmt = "SELECT * FROM tickets WHERE
1158 ( requestor = ? ) AND ( status != ? )
1159 AND ( worker = ? OR worker = ? OR worker = ? )";
1160 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1162 Which you could then use in DBI code like so:
1164 my $sth = $dbh->prepare($stmt);
1165 $sth->execute(@bind);
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.
1179 =head2 new(option => 'value')
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:
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:
1192 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1194 Any setting other than 'lower' is ignored.
1198 This determines what the default comparison operator is. By default
1199 it is C<=>, meaning that a hash like this:
1201 %where = (name => 'nwiger', email => 'nate@wiger.org');
1203 Will generate SQL like this:
1205 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
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:
1210 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1212 You can also override the comparsion on an individual basis - see
1213 the huge section on L</"WHERE CLAUSES"> at the bottom.
1215 =item sqltrue, sqlfalse
1217 Expressions for inserting boolean values within SQL statements.
1218 By default these are C<1=1> and C<1=0>.
1222 This determines the default logical operator for multiple WHERE
1223 statements in arrays. By default it is "or", meaning that a WHERE
1227 event_date => {'>=', '2/13/99'},
1228 event_date => {'<=', '4/24/03'},
1231 Will generate SQL like this:
1233 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
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:
1238 my $sql = SQL::Abstract->new(logic => 'and');
1240 Which will change the above C<WHERE> to:
1242 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1244 The logic can also be changed locally by inserting
1245 an extra first element in the array :
1247 @where = (-and => event_date => {'>=', '2/13/99'},
1248 event_date => {'<=', '4/24/03'} );
1250 See the L</"WHERE CLAUSES"> section for explanations.
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:
1259 $sql = SQL::Abstract->new(convert => 'upper');
1260 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1262 Will turn out the following SQL:
1264 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
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).
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()>:
1276 $sth->bind_param(1, 'reg data');
1277 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
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.
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:
1286 my $sql = SQL::Abstract->new(bindtype => 'columns');
1287 my($stmt, @bind) = $sql->insert(...);
1290 [ 'column1', 'value1' ],
1291 [ 'column2', 'value2' ],
1292 [ 'column3', 'value3' ],
1295 You can then iterate through this manually, using DBI's C<bind_param()>.
1297 $sth->prepare($stmt);
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});
1306 $sth->bind_param($i, $data);
1310 $sth->execute; # execute without @bind now
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.
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:
1324 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
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:
1331 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1333 Quoting is useful if you have tables or columns names that are reserved
1334 words in your database's SQL dialect.
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:
1342 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1344 =item array_datatypes
1346 When this option is true, arrayrefs in INSERT or UPDATE are
1347 interpreted as array datatypes and are passed directly
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
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.
1366 =head2 insert($table, \@values || \%fieldvals)
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.
1375 =head2 update($table, \%fieldvals, \%where)
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
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.
1384 =head2 select($source, $fields, $where, $order)
1386 This returns a SQL SELECT statement and associated list of bind values, as
1387 specified by the arguments :
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).
1402 Specification of the list of fields to retrieve from
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.
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.
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">
1427 =head2 delete($table, \%where)
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.
1432 =head2 where(\%where, \@order)
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.
1441 =head2 values(\%data)
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.
1448 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1450 Warning: This is an experimental method and subject to change.
1452 This returns arbitrarily generated SQL. It's a really basic shortcut.
1453 It will return two different things, depending on return context:
1455 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1456 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1458 These would return the following:
1460 # First calling form
1461 $stmt = "CREATE TABLE test (?, ?)";
1462 @bind = (field1, field2);
1464 # Second calling form
1465 $stmt_and_val = "CREATE TABLE test (field1, field2)";
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.
1472 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1476 ALTER SESSION SET nls_date_format = 'MM/YY'
1478 You get the idea. Strings get their case twiddled, but everything
1479 else remains verbatim.
1484 =head1 WHERE CLAUSES
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
1493 The easiest way to explain is to show lots of examples. After
1494 each C<%where> hash shown, it is assumed you used:
1496 my($stmt, @bind) = $sql->where(\%where);
1498 However, note that the C<%where> hash can be used directly in any
1499 of the other functions as well, as described above.
1501 =head2 Key-value pairs
1503 So, let's get started. To begin, a simple hash:
1507 status => 'completed'
1510 Is converted to SQL C<key = val> statements:
1512 $stmt = "WHERE user = ? AND status = ?";
1513 @bind = ('nwiger', 'completed');
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
1521 status => ['assigned', 'in-progress', 'pending'];
1524 This simple code will create the following:
1526 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1527 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1529 An empty arrayref will be considered a logical false and
1532 =head2 Key-value pairs
1534 If you want to specify a different type of operator for your comparison,
1535 you can use a hashref for a given column:
1539 status => { '!=', 'completed' }
1542 Which would generate:
1544 $stmt = "WHERE user = ? AND status != ?";
1545 @bind = ('nwiger', 'completed');
1547 To test against multiple values, just enclose the values in an arrayref:
1549 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1551 Which would give you:
1553 "WHERE status != ? AND status != ? AND status != ?"
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
1559 status => { '=', ['assigned', 'in-progress', 'pending'] };
1563 "WHERE status = ? OR status = ? OR status = ?"
1566 The hashref can also contain multiple pairs, in which case it is expanded
1567 into an C<AND> of its elements:
1571 status => { '!=', 'completed', -not_like => 'pending%' }
1574 # Or more dynamically, like from a form
1575 $where{user} = 'nwiger';
1576 $where{status}{'!='} = 'completed';
1577 $where{status}{'-not_like'} = 'pending%';
1579 # Both generate this
1580 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1581 @bind = ('nwiger', 'completed', 'pending%');
1584 To get an OR instead, you can combine it with the arrayref idea:
1588 priority => [ {'=', 2}, {'!=', 1} ]
1591 Which would generate:
1593 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1594 @bind = ('nwiger', '2', '1');
1597 =head2 Logic and nesting operators
1599 In the example above,
1600 there is a subtle trap if you want to say something like
1601 this (notice the C<AND>):
1603 WHERE priority != ? AND priority != ?
1605 Because, in Perl you I<can't> do this:
1607 priority => { '!=', 2, '!=', 1 }
1609 As the second C<!=> key will obliterate the first. The solution
1610 is to use the special C<-modifier> form inside an arrayref:
1612 priority => [ -and => {'!=', 2},
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:
1623 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1625 Here is a quick list of equivalencies, since there is some overlap:
1628 status => {'!=', 'completed', 'not like', 'pending%' }
1629 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1632 status => {'=', ['assigned', 'in-progress']}
1633 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1634 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
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:
1640 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1641 @bind = ('nwiger', '20', 'ASIA');
1647 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1650 If you need several nested subexpressions, you can number
1651 the C<-nest> branches :
1661 =head2 Special operators : IN, BETWEEN, etc.
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:
1667 status => 'completed',
1668 reportid => { -in => [567, 2335, 2] }
1671 Which would generate:
1673 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1674 @bind = ('completed', '567', '2335', '2');
1676 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1679 Another pair of operators is C<-between> and C<-not_between>,
1680 used with an arrayref of two values:
1684 completion_date => {
1685 -not_between => ['2002-10-01', '2003-02-06']
1691 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1693 These are the two builtin "special operators"; but the
1694 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1696 =head2 Nested conditions
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:
1705 status => { -like => ['pending%', 'dispatched'] },
1709 status => 'unassigned',
1713 This data structure would create the following:
1715 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1716 OR ( user = ? AND status = ? ) )";
1717 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1719 This can be combined with the C<-nest> operator to properly group
1726 ["-and", workhrs => {'>', 20}, geo => 'ASIA' ],
1727 ["-and", workhrs => {'<', 50}, geo => 'EURO' ]
1734 WHERE ( user = ? AND
1735 ( ( workhrs > ? AND geo = ? )
1736 OR ( workhrs < ? AND geo = ? ) ) )
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:
1743 my $inn = 'is Not Null';
1745 priority => { '<', 2 },
1751 $stmt = "WHERE priority < ? AND requestor is Not Null";
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.
1757 Of course, just to prove a point, the above can also be accomplished
1761 priority => { '<', 2 },
1762 requestor => { '!=', undef },
1768 Conditions on boolean columns can be expressed in the
1769 same way, passing a reference to an empty string :
1772 priority => { '<', 2 },
1778 $stmt = "WHERE priority < ? AND is_ready";
1782 =head2 Literal SQL with placeholders and bind values (subqueries)
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:
1790 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1795 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1799 Literal SQL is especially useful for nesting parenthesized clauses in the
1800 main SQL query. Here is a first example :
1802 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1806 bar => \["IN ($sub_stmt)" => @sub_bind],
1811 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1812 WHERE c2 < ? AND c3 LIKE ?))";
1813 @bind = (1234, 100, "foo%");
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
1820 my ($sub_stmt, @sub_bind)
1821 = $sql->select("t1", "c1", {c2 => {"<" => 100},
1822 c3 => {-like => "foo%"}});
1825 bar => \["> ALL ($sub_stmt)" => @sub_bind],
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 :
1832 my ($sub_stmt, @sub_bind)
1833 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1836 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
1841 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1842 WHERE c1 = ? AND c2 > t0.c0))";
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.
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 :
1859 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
1862 Finally, here is an example where a subquery is used
1863 for expressing unary negation:
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
1869 lname => {like => '%son%'},
1870 -nest => \["NOT ($sub_stmt)" => @sub_bind],
1875 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1876 @bind = ('%son%', 10, 20)
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.
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
1898 =head1 ORDER BY CLAUSES
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:
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
1912 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1915 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1916 ==========================================================
1920 =head1 SPECIAL OPERATORS
1922 my $sqlmaker = SQL::Abstract->new(special_ops => [
1925 my ($self, $field, $op, $arg) = @_;
1931 A "special operator" is a SQL syntactic clause that can be
1932 applied to a field, instead of a usual binary operator.
1935 WHERE field IN (?, ?, ?)
1936 WHERE field BETWEEN ? AND ?
1937 WHERE MATCH(field) AGAINST (?, ?)
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
1951 the regular expression to match the operator
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.
1962 For example, here is an implementation
1963 of the MATCH .. AGAINST syntax for MySQL
1965 my $sqlmaker = SQL::Abstract->new(special_ops => [
1967 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
1968 {regex => qr/^match$/i,
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);
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
1993 To maximize performance, use a code snippet like the following:
1995 # prepare a statement handle using the first row
1996 # and then reuse it for the rest of the rows
1998 for my $href (@array_of_hashrefs) {
1999 $stmt ||= $sql->insert('table', $href);
2000 $sth ||= $dbh->prepare($stmt);
2001 $sth->execute($sql->values($href));
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.
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:
2019 use CGI::FormBuilder;
2022 my $form = CGI::FormBuilder->new(...);
2023 my $sql = SQL::Abstract->new;
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});
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.
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.
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.
2052 The main changes are :
2058 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2062 added -nest1, -nest2 or -nest_1, -nest_2, ...
2066 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2070 defensive programming : check arguments
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)" >>.
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.
2089 changed logic for distributing an op over arrayrefs
2093 fixed semantics of _bindtype on array args
2097 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2098 we just avoid shifting arrays within that tree.
2102 dropped the C<_modlogic> function
2108 =head1 ACKNOWLEDGEMENTS
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:
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)
2129 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2133 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2135 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
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.
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.