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);
331 my ($sql, @bind) = $self->$method($where, $logic);
333 # DBIx::Class directly calls _recurse_where in scalar context, so
334 # we must implement it, even if not in the official API
335 return wantarray ? ($sql, @bind) : $sql;
340 #======================================================================
341 # WHERE: top-level ARRAYREF
342 #======================================================================
345 sub _where_ARRAYREF {
346 my ($self, $where, $logic) = @_;
348 $logic = uc($logic || $self->{logic});
349 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
351 my @clauses = @$where;
353 # if the array starts with [-and|or => ...], recurse with that logic
354 my $first = $clauses[0] || '';
355 if ($first =~ /^-(and|or)/i) {
358 return $self->_where_ARRAYREF(\@clauses, $logic);
362 my (@sql_clauses, @all_bind);
364 # need to use while() so can shift() for pairs
365 while (my $el = shift @clauses) {
367 # switch according to kind of $el and get corresponding ($sql, @bind)
368 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
370 # skip empty elements, otherwise get invalid trailing AND stuff
371 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
373 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
374 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
375 # side-effect: the first hashref within an array would change
376 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
377 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
378 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
380 SCALARREF => sub { ($$el); },
382 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
383 $self->_recurse_where({$el => shift(@clauses)})},
385 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
389 push @sql_clauses, $sql;
390 push @all_bind, @bind;
394 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
399 #======================================================================
400 # WHERE: top-level HASHREF
401 #======================================================================
404 my ($self, $where) = @_;
405 my (@sql_clauses, @all_bind);
407 # LDNOTE : don't really know why we need to sort keys
408 for my $k (sort keys %$where) {
409 my $v = $where->{$k};
411 # ($k => $v) is either a special op or a regular hashpair
412 my ($sql, @bind) = ($k =~ /^-(.+)/) ? $self->_where_op_in_hash($1, $v)
414 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
415 $self->$method($k, $v);
418 push @sql_clauses, $sql;
419 push @all_bind, @bind;
422 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
426 sub _where_op_in_hash {
427 my ($self, $op, $v) = @_;
429 $op =~ /^(AND|OR|NEST)[_\d]*/i
430 or puke "unknown operator: -$op";
431 $op = uc($1); # uppercase, remove trailing digits
432 $self->_debug("OP(-$op) within hashref, recursing...");
434 $self->_SWITCH_refkind($v, {
437 # LDNOTE : should deprecate {-or => [...]} and {-and => [...]}
438 # because they are misleading; the only proper way would be
439 # -nest => [-or => ...], -nest => [-and ...]
440 return $self->_where_ARRAYREF($v, $op eq 'NEST' ? '' : $op);
445 belch "-or => {...} should be -nest => [...]";
446 return $self->_where_ARRAYREF([%$v], 'OR');
449 return $self->_where_HASHREF($v);
453 SCALARREF => sub { # literal SQL
455 or puke "-$op => \\\$scalar not supported, use -nest => ...";
459 ARRAYREFREF => sub { # literal SQL
461 or puke "-$op => \\[..] not supported, use -nest => ...";
465 SCALAR => sub { # permissively interpreted as SQL
467 or puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
468 belch "literal SQL should be -nest => \\'scalar' "
469 . "instead of -nest => 'scalar' ";
474 puke "-$op => undef not supported";
480 sub _where_hashpair_ARRAYREF {
481 my ($self, $k, $v) = @_;
484 my @v = @$v; # need copy because of shift below
485 $self->_debug("ARRAY($k) means distribute over elements");
487 # put apart first element if it is an operator (-and, -or)
488 my $op = $v[0] =~ /^-/ ? shift @v : undef;
489 $self->_debug("OP($op) reinjected into the distributed array") if $op;
491 my @distributed = map { {$k => $_} } @v;
492 unshift @distributed, $op if $op;
494 return $self->_recurse_where(\@distributed);
497 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
498 $self->_debug("empty ARRAY($k) means 0=1");
499 return ($self->{sqlfalse});
503 sub _where_hashpair_HASHREF {
504 my ($self, $k, $v) = @_;
506 my (@all_sql, @all_bind);
508 for my $op (sort keys %$v) {
511 # put the operator in canonical form
512 $op =~ s/^-//; # remove initial dash
513 $op =~ tr/_/ /; # underscores become spaces
514 $op =~ s/^\s+//; # no initial space
515 $op =~ s/\s+$//; # no final space
516 $op =~ s/\s+/ /; # multiple spaces become one
520 # CASE: special operators like -in or -between
521 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
523 ($sql, @bind) = $special_op->{handler}->($self, $k, $op, $val);
526 # CASE: col => {op => \@vals}
527 elsif (ref $val eq 'ARRAY') {
528 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
531 # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
532 elsif (! defined($val)) {
533 my $is = ($op =~ $self->{equality_op}) ? 'is' :
534 ($op =~ $self->{inequality_op}) ? 'is not' :
535 puke "unexpected operator '$op' with undef operand";
536 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
539 # CASE: col => {op => $scalar}
541 $sql = join ' ', $self->_convert($self->_quote($k)),
542 $self->_sqlcase($op),
543 $self->_convert('?');
544 @bind = $self->_bindtype($k, $val);
548 push @all_bind, @bind;
551 return $self->_join_sql_clauses('and', \@all_sql, \@all_bind);
556 sub _where_field_op_ARRAYREF {
557 my ($self, $k, $op, $vals) = @_;
560 $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
564 # LDNOTE : change the distribution logic when
565 # $op =~ $self->{inequality_op}, because of Morgan laws :
566 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
567 # WHERE field != 22 OR field != 33 : the user probably means
568 # WHERE field != 22 AND field != 33.
569 my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
571 # distribute $op over each member of @$vals
572 return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
576 # try to DWIM on equality operators
577 # LDNOTE : not 100% sure this is the correct thing to do ...
578 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
579 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
582 puke "operator '$op' applied on an empty array (field '$k')";
587 sub _where_hashpair_SCALARREF {
588 my ($self, $k, $v) = @_;
589 $self->_debug("SCALAR($k) means literal SQL: $$v");
590 my $sql = $self->_quote($k) . " " . $$v;
594 sub _where_hashpair_ARRAYREFREF {
595 my ($self, $k, $v) = @_;
596 $self->_debug("REF($k) means literal SQL: @${$v}");
597 my ($sql, @bind) = @${$v};
598 $sql = $self->_quote($k) . " " . $sql;
599 @bind = $self->_bindtype($k, @bind);
600 return ($sql, @bind );
603 sub _where_hashpair_SCALAR {
604 my ($self, $k, $v) = @_;
605 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
606 my $sql = join ' ', $self->_convert($self->_quote($k)),
607 $self->_sqlcase($self->{cmp}),
608 $self->_convert('?');
609 my @bind = $self->_bindtype($k, $v);
610 return ( $sql, @bind);
614 sub _where_hashpair_UNDEF {
615 my ($self, $k, $v) = @_;
616 $self->_debug("UNDEF($k) means IS NULL");
617 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
621 #======================================================================
622 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
623 #======================================================================
626 sub _where_SCALARREF {
627 my ($self, $where) = @_;
630 $self->_debug("SCALAR(*top) means literal SQL: $$where");
636 my ($self, $where) = @_;
639 $self->_debug("NOREF(*top) means literal SQL: $where");
650 #======================================================================
651 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
652 #======================================================================
655 sub _where_field_BETWEEN {
656 my ($self, $k, $op, $vals) = @_;
658 ref $vals eq 'ARRAY' && @$vals == 2
659 or puke "special op 'between' requires an arrayref of two values";
661 my ($label) = $self->_convert($self->_quote($k));
662 my ($placeholder) = $self->_convert('?');
663 my $and = $self->_sqlcase('and');
664 $op = $self->_sqlcase($op);
666 my $sql = "( $label $op $placeholder $and $placeholder )";
667 my @bind = $self->_bindtype($k, @$vals);
672 sub _where_field_IN {
673 my ($self, $k, $op, $vals) = @_;
675 # backwards compatibility : if scalar, force into an arrayref
676 $vals = [$vals] if defined $vals && ! ref $vals;
679 or puke "special op 'in' requires an arrayref";
681 my ($label) = $self->_convert($self->_quote($k));
682 my ($placeholder) = $self->_convert('?');
683 my $and = $self->_sqlcase('and');
684 $op = $self->_sqlcase($op);
686 if (@$vals) { # nonempty list
687 my $placeholders = join ", ", (($placeholder) x @$vals);
688 my $sql = "$label $op ( $placeholders )";
689 my @bind = $self->_bindtype($k, @$vals);
691 return ($sql, @bind);
693 else { # empty list : some databases won't understand "IN ()", so DWIM
694 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
704 #======================================================================
706 #======================================================================
709 my ($self, $arg) = @_;
711 # construct list of ordering instructions
712 my @order = $self->_SWITCH_refkind($arg, {
715 map {$self->_SWITCH_refkind($_, {
716 SCALAR => sub {$self->_quote($_)},
718 SCALARREF => sub {$$_}, # literal SQL, no quoting
719 HASHREF => sub {$self->_order_by_hash($_)}
723 SCALAR => sub {$self->_quote($arg)},
725 SCALARREF => sub {$$arg}, # literal SQL, no quoting
726 HASHREF => sub {$self->_order_by_hash($arg)},
731 my $order = join ', ', @order;
732 return $order ? $self->_sqlcase(' order by')." $order" : '';
737 my ($self, $hash) = @_;
739 # get first pair in hash
740 my ($key, $val) = each %$hash;
742 # check if one pair was found and no other pair in hash
743 $key && !(each %$hash)
744 or puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
746 my ($order) = ($key =~ /^-(desc|asc)/i)
747 or puke "invalid key in _order_by hash : $key";
749 return $self->_quote($val) ." ". $self->_sqlcase($order);
754 #======================================================================
755 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
756 #======================================================================
761 $self->_SWITCH_refkind($from, {
762 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
763 SCALAR => sub {$self->_quote($from)},
764 SCALARREF => sub {$$from},
765 ARRAYREFREF => sub {join ', ', @$from;},
770 #======================================================================
772 #======================================================================
778 $label or puke "can't quote an empty label";
780 # left and right quote characters
781 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
782 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
783 ARRAYREF => sub {@{$self->{quote_char}}},
787 or puke "quote_char must be an arrayref of 2 values";
789 # no quoting if no quoting chars
790 $ql or return $label;
792 # no quoting for literal SQL
793 return $$label if ref($label) eq 'SCALAR';
795 # separate table / column (if applicable)
796 my $sep = $self->{name_sep} || '';
797 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
799 # do the quoting, except for "*" or for `table`.*
800 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
802 # reassemble and return.
803 return join $sep, @quoted;
807 # Conversion, if applicable
809 my ($self, $arg) = @_;
811 # LDNOTE : modified the previous implementation below because
812 # it was not consistent : the first "return" is always an array,
813 # the second "return" is context-dependent. Anyway, _convert
814 # seems always used with just a single argument, so make it a
816 # return @_ unless $self->{convert};
817 # my $conv = $self->_sqlcase($self->{convert});
818 # my @ret = map { $conv.'('.$_.')' } @_;
819 # return wantarray ? @ret : $ret[0];
820 if ($self->{convert}) {
821 my $conv = $self->_sqlcase($self->{convert});
822 $arg = $conv.'('.$arg.')';
830 my($col, @vals) = @_;
832 #LDNOTE : changed original implementation below because it did not make
833 # sense when bindtype eq 'columns' and @vals > 1.
834 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
836 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
839 sub _join_sql_clauses {
840 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
842 if (@$clauses_aref > 1) {
843 my $join = " " . $self->_sqlcase($logic) . " ";
844 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
845 return ($sql, @$bind_aref);
847 elsif (@$clauses_aref) {
848 return ($clauses_aref->[0], @$bind_aref); # no parentheses
851 return (); # if no SQL, ignore @$bind_aref
856 # Fix SQL case, if so requested
860 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
861 # don't touch the argument ... crooked logic, but let's not change it!
862 return $self->{case} ? $_[0] : uc($_[0]);
866 #======================================================================
867 # DISPATCHING FROM REFKIND
868 #======================================================================
871 my ($self, $data) = @_;
877 # blessed objects are treated like scalars
878 $ref = (blessed $data) ? '' : ref $data;
879 $n_steps += 1 if $ref;
880 last if $ref ne 'REF';
884 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
886 return $base . ('REF' x $n_steps);
892 my ($self, $data) = @_;
893 my @try = ($self->_refkind($data));
894 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
895 push @try, 'FALLBACK';
899 sub _METHOD_FOR_refkind {
900 my ($self, $meth_prefix, $data) = @_;
901 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
902 $self->_try_refkind($data)
903 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
908 sub _SWITCH_refkind {
909 my ($self, $data, $dispatch_table) = @_;
911 my $coderef = first {$_} map {$dispatch_table->{$_}}
912 $self->_try_refkind($data)
913 or puke "no dispatch entry for ".$self->_refkind($data);
920 #======================================================================
921 # VALUES, GENERATE, AUTOLOAD
922 #======================================================================
924 # LDNOTE: original code from nwiger, didn't touch code in that section
925 # I feel the AUTOLOAD stuff should not be the default, it should
926 # only be activated on explicit demand by user.
930 my $data = shift || return;
931 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
932 unless ref $data eq 'HASH';
933 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
939 my(@sql, @sqlq, @sqlv);
943 if ($ref eq 'HASH') {
944 for my $k (sort keys %$_) {
947 my $label = $self->_quote($k);
949 # SQL included for values
951 my $sql = shift @bind;
952 push @sqlq, "$label = $sql";
953 push @sqlv, $self->_bindtype($k, @bind);
954 } elsif ($r eq 'SCALAR') {
955 # embedded literal SQL
956 push @sqlq, "$label = $$v";
958 push @sqlq, "$label = ?";
959 push @sqlv, $self->_bindtype($k, $v);
962 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
963 } elsif ($ref eq 'ARRAY') {
964 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
969 push @sqlq, shift @val;
971 } elsif ($r eq 'SCALAR') {
972 # embedded literal SQL
979 push @sql, '(' . join(', ', @sqlq) . ')';
980 } elsif ($ref eq 'SCALAR') {
984 # strings get case twiddled
985 push @sql, $self->_sqlcase($_);
989 my $sql = join ' ', @sql;
991 # this is pretty tricky
992 # if ask for an array, return ($stmt, @bind)
993 # otherwise, s/?/shift @sqlv/ to put it inline
995 return ($sql, @sqlv);
997 1 while $sql =~ s/\?/my $d = shift(@sqlv);
998 ref $d ? $d->[1] : $d/e;
1007 # This allows us to check for a local, then _form, attr
1009 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1010 return $self->generate($name, @_);
1021 SQL::Abstract - Generate SQL from Perl data structures
1027 my $sql = SQL::Abstract->new;
1029 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1031 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1033 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1035 my($stmt, @bind) = $sql->delete($table, \%where);
1037 # Then, use these in your DBI statements
1038 my $sth = $dbh->prepare($stmt);
1039 $sth->execute(@bind);
1041 # Just generate the WHERE clause
1042 my($stmt, @bind) = $sql->where(\%where, \@order);
1044 # Return values in the same order, for hashed queries
1045 # See PERFORMANCE section for more details
1046 my @bind = $sql->values(\%fieldvals);
1050 This module was inspired by the excellent L<DBIx::Abstract>.
1051 However, in using that module I found that what I really wanted
1052 to do was generate SQL, but still retain complete control over my
1053 statement handles and use the DBI interface. So, I set out to
1054 create an abstract SQL generation module.
1056 While based on the concepts used by L<DBIx::Abstract>, there are
1057 several important differences, especially when it comes to WHERE
1058 clauses. I have modified the concepts used to make the SQL easier
1059 to generate from Perl data structures and, IMO, more intuitive.
1060 The underlying idea is for this module to do what you mean, based
1061 on the data structures you provide it. The big advantage is that
1062 you don't have to modify your code every time your data changes,
1063 as this module figures it out.
1065 To begin with, an SQL INSERT is as easy as just specifying a hash
1066 of C<key=value> pairs:
1069 name => 'Jimbo Bobson',
1070 phone => '123-456-7890',
1071 address => '42 Sister Lane',
1072 city => 'St. Louis',
1073 state => 'Louisiana',
1076 The SQL can then be generated with this:
1078 my($stmt, @bind) = $sql->insert('people', \%data);
1080 Which would give you something like this:
1082 $stmt = "INSERT INTO people
1083 (address, city, name, phone, state)
1084 VALUES (?, ?, ?, ?, ?)";
1085 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1086 '123-456-7890', 'Louisiana');
1088 These are then used directly in your DBI code:
1090 my $sth = $dbh->prepare($stmt);
1091 $sth->execute(@bind);
1093 =head2 Inserting and Updating Arrays
1095 If your database has array types (like for example Postgres),
1096 activate the special option C<< array_datatypes => 1 >>
1097 when creating the C<SQL::Abstract> object.
1098 Then you may use an arrayref to insert and update database array types:
1100 my $sql = SQL::Abstract->new(array_datatypes => 1);
1102 planets => [qw/Mercury Venus Earth Mars/]
1105 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1109 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1111 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1114 =head2 Inserting and Updating SQL
1116 In order to apply SQL functions to elements of your C<%data> you may
1117 specify a reference to an arrayref for the given hash value. For example,
1118 if you need to execute the Oracle C<to_date> function on a value, you can
1119 say something like this:
1123 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1126 The first value in the array is the actual SQL. Any other values are
1127 optional and would be included in the bind values array. This gives
1130 my($stmt, @bind) = $sql->insert('people', \%data);
1132 $stmt = "INSERT INTO people (name, date_entered)
1133 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1134 @bind = ('Bill', '03/02/2003');
1136 An UPDATE is just as easy, all you change is the name of the function:
1138 my($stmt, @bind) = $sql->update('people', \%data);
1140 Notice that your C<%data> isn't touched; the module will generate
1141 the appropriately quirky SQL for you automatically. Usually you'll
1142 want to specify a WHERE clause for your UPDATE, though, which is
1143 where handling C<%where> hashes comes in handy...
1145 =head2 Complex where statements
1147 This module can generate pretty complicated WHERE statements
1148 easily. For example, simple C<key=value> pairs are taken to mean
1149 equality, and if you want to see if a field is within a set
1150 of values, you can use an arrayref. Let's say we wanted to
1151 SELECT some data based on this criteria:
1154 requestor => 'inna',
1155 worker => ['nwiger', 'rcwe', 'sfz'],
1156 status => { '!=', 'completed' }
1159 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1161 The above would give you something like this:
1163 $stmt = "SELECT * FROM tickets WHERE
1164 ( requestor = ? ) AND ( status != ? )
1165 AND ( worker = ? OR worker = ? OR worker = ? )";
1166 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1168 Which you could then use in DBI code like so:
1170 my $sth = $dbh->prepare($stmt);
1171 $sth->execute(@bind);
1177 The functions are simple. There's one for each major SQL operation,
1178 and a constructor you use first. The arguments are specified in a
1179 similar order to each function (table, then fields, then a where
1180 clause) to try and simplify things.
1185 =head2 new(option => 'value')
1187 The C<new()> function takes a list of options and values, and returns
1188 a new B<SQL::Abstract> object which can then be used to generate SQL
1189 through the methods below. The options accepted are:
1195 If set to 'lower', then SQL will be generated in all lowercase. By
1196 default SQL is generated in "textbook" case meaning something like:
1198 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1200 Any setting other than 'lower' is ignored.
1204 This determines what the default comparison operator is. By default
1205 it is C<=>, meaning that a hash like this:
1207 %where = (name => 'nwiger', email => 'nate@wiger.org');
1209 Will generate SQL like this:
1211 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1213 However, you may want loose comparisons by default, so if you set
1214 C<cmp> to C<like> you would get SQL such as:
1216 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1218 You can also override the comparsion on an individual basis - see
1219 the huge section on L</"WHERE CLAUSES"> at the bottom.
1221 =item sqltrue, sqlfalse
1223 Expressions for inserting boolean values within SQL statements.
1224 By default these are C<1=1> and C<1=0>.
1228 This determines the default logical operator for multiple WHERE
1229 statements in arrays. By default it is "or", meaning that a WHERE
1233 event_date => {'>=', '2/13/99'},
1234 event_date => {'<=', '4/24/03'},
1237 Will generate SQL like this:
1239 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1241 This is probably not what you want given this query, though (look
1242 at the dates). To change the "OR" to an "AND", simply specify:
1244 my $sql = SQL::Abstract->new(logic => 'and');
1246 Which will change the above C<WHERE> to:
1248 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1250 The logic can also be changed locally by inserting
1251 an extra first element in the array :
1253 @where = (-and => event_date => {'>=', '2/13/99'},
1254 event_date => {'<=', '4/24/03'} );
1256 See the L</"WHERE CLAUSES"> section for explanations.
1260 This will automatically convert comparisons using the specified SQL
1261 function for both column and value. This is mostly used with an argument
1262 of C<upper> or C<lower>, so that the SQL will have the effect of
1263 case-insensitive "searches". For example, this:
1265 $sql = SQL::Abstract->new(convert => 'upper');
1266 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1268 Will turn out the following SQL:
1270 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1272 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1273 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1274 not validate this option; it will just pass through what you specify verbatim).
1278 This is a kludge because many databases suck. For example, you can't
1279 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1280 Instead, you have to use C<bind_param()>:
1282 $sth->bind_param(1, 'reg data');
1283 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1285 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1286 which loses track of which field each slot refers to. Fear not.
1288 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1289 Currently, you can specify either C<normal> (default) or C<columns>. If you
1290 specify C<columns>, you will get an array that looks like this:
1292 my $sql = SQL::Abstract->new(bindtype => 'columns');
1293 my($stmt, @bind) = $sql->insert(...);
1296 [ 'column1', 'value1' ],
1297 [ 'column2', 'value2' ],
1298 [ 'column3', 'value3' ],
1301 You can then iterate through this manually, using DBI's C<bind_param()>.
1303 $sth->prepare($stmt);
1306 my($col, $data) = @$_;
1307 if ($col eq 'details' || $col eq 'comments') {
1308 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1309 } elsif ($col eq 'image') {
1310 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1312 $sth->bind_param($i, $data);
1316 $sth->execute; # execute without @bind now
1318 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1319 Basically, the advantage is still that you don't have to care which fields
1320 are or are not included. You could wrap that above C<for> loop in a simple
1321 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1322 get a layer of abstraction over manual SQL specification.
1326 This is the character that a table or column name will be quoted
1327 with. By default this is an empty string, but you could set it to
1328 the character C<`>, to generate SQL like this:
1330 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1332 Alternatively, you can supply an array ref of two items, the first being the left
1333 hand quote character, and the second the right hand quote character. For
1334 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1335 that generates SQL like this:
1337 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1339 Quoting is useful if you have tables or columns names that are reserved
1340 words in your database's SQL dialect.
1344 This is the character that separates a table and column name. It is
1345 necessary to specify this when the C<quote_char> option is selected,
1346 so that tables and column names can be individually quoted like this:
1348 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1350 =item array_datatypes
1352 When this option is true, arrayrefs in INSERT or UPDATE are
1353 interpreted as array datatypes and are passed directly
1355 When this option is false, arrayrefs are interpreted
1356 as literal SQL, just like refs to arrayrefs
1357 (but this behavior is for backwards compatibility; when writing
1358 new queries, use the "reference to arrayref" syntax
1364 Takes a reference to a list of "special operators"
1365 to extend the syntax understood by L<SQL::Abstract>.
1366 See section L</"SPECIAL OPERATORS"> for details.
1372 =head2 insert($table, \@values || \%fieldvals)
1374 This is the simplest function. You simply give it a table name
1375 and either an arrayref of values or hashref of field/value pairs.
1376 It returns an SQL INSERT statement and a list of bind values.
1377 See the sections on L</"Inserting and Updating Arrays"> and
1378 L</"Inserting and Updating SQL"> for information on how to insert
1379 with those data types.
1381 =head2 update($table, \%fieldvals, \%where)
1383 This takes a table, hashref of field/value pairs, and an optional
1384 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1386 See the sections on L</"Inserting and Updating Arrays"> and
1387 L</"Inserting and Updating SQL"> for information on how to insert
1388 with those data types.
1390 =head2 select($source, $fields, $where, $order)
1392 This returns a SQL SELECT statement and associated list of bind values, as
1393 specified by the arguments :
1399 Specification of the 'FROM' part of the statement.
1400 The argument can be either a plain scalar (interpreted as a table
1401 name, will be quoted), or an arrayref (interpreted as a list
1402 of table names, joined by commas, quoted), or a scalarref
1403 (literal table name, not quoted), or a ref to an arrayref
1404 (list of literal table names, joined by commas, not quoted).
1408 Specification of the list of fields to retrieve from
1410 The argument can be either an arrayref (interpreted as a list
1411 of field names, will be joined by commas and quoted), or a
1412 plain scalar (literal SQL, not quoted).
1413 Please observe that this API is not as flexible as for
1414 the first argument C<$table>, for backwards compatibility reasons.
1418 Optional argument to specify the WHERE part of the query.
1419 The argument is most often a hashref, but can also be
1420 an arrayref or plain scalar --
1421 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1425 Optional argument to specify the ORDER BY part of the query.
1426 The argument can be a scalar, a hashref or an arrayref
1427 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1433 =head2 delete($table, \%where)
1435 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1436 It returns an SQL DELETE statement and list of bind values.
1438 =head2 where(\%where, \@order)
1440 This is used to generate just the WHERE clause. For example,
1441 if you have an arbitrary data structure and know what the
1442 rest of your SQL is going to look like, but want an easy way
1443 to produce a WHERE clause, use this. It returns an SQL WHERE
1444 clause and list of bind values.
1447 =head2 values(\%data)
1449 This just returns the values from the hash C<%data>, in the same
1450 order that would be returned from any of the other above queries.
1451 Using this allows you to markedly speed up your queries if you
1452 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1454 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1456 Warning: This is an experimental method and subject to change.
1458 This returns arbitrarily generated SQL. It's a really basic shortcut.
1459 It will return two different things, depending on return context:
1461 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1462 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1464 These would return the following:
1466 # First calling form
1467 $stmt = "CREATE TABLE test (?, ?)";
1468 @bind = (field1, field2);
1470 # Second calling form
1471 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1473 Depending on what you're trying to do, it's up to you to choose the correct
1474 format. In this example, the second form is what you would want.
1478 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1482 ALTER SESSION SET nls_date_format = 'MM/YY'
1484 You get the idea. Strings get their case twiddled, but everything
1485 else remains verbatim.
1490 =head1 WHERE CLAUSES
1494 This module uses a variation on the idea from L<DBIx::Abstract>. It
1495 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1496 module is that things in arrays are OR'ed, and things in hashes
1499 The easiest way to explain is to show lots of examples. After
1500 each C<%where> hash shown, it is assumed you used:
1502 my($stmt, @bind) = $sql->where(\%where);
1504 However, note that the C<%where> hash can be used directly in any
1505 of the other functions as well, as described above.
1507 =head2 Key-value pairs
1509 So, let's get started. To begin, a simple hash:
1513 status => 'completed'
1516 Is converted to SQL C<key = val> statements:
1518 $stmt = "WHERE user = ? AND status = ?";
1519 @bind = ('nwiger', 'completed');
1521 One common thing I end up doing is having a list of values that
1522 a field can be in. To do this, simply specify a list inside of
1527 status => ['assigned', 'in-progress', 'pending'];
1530 This simple code will create the following:
1532 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1533 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1535 An empty arrayref will be considered a logical false and
1538 =head2 Key-value pairs
1540 If you want to specify a different type of operator for your comparison,
1541 you can use a hashref for a given column:
1545 status => { '!=', 'completed' }
1548 Which would generate:
1550 $stmt = "WHERE user = ? AND status != ?";
1551 @bind = ('nwiger', 'completed');
1553 To test against multiple values, just enclose the values in an arrayref:
1555 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1557 Which would give you:
1559 "WHERE status != ? AND status != ? AND status != ?"
1561 Notice that since the operator was recognized as being a 'negative'
1562 operator, the arrayref was interpreted with 'AND' logic (because
1563 of Morgan's laws). By contrast, the reverse
1565 status => { '=', ['assigned', 'in-progress', 'pending'] };
1569 "WHERE status = ? OR status = ? OR status = ?"
1572 The hashref can also contain multiple pairs, in which case it is expanded
1573 into an C<AND> of its elements:
1577 status => { '!=', 'completed', -not_like => 'pending%' }
1580 # Or more dynamically, like from a form
1581 $where{user} = 'nwiger';
1582 $where{status}{'!='} = 'completed';
1583 $where{status}{'-not_like'} = 'pending%';
1585 # Both generate this
1586 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1587 @bind = ('nwiger', 'completed', 'pending%');
1590 To get an OR instead, you can combine it with the arrayref idea:
1594 priority => [ {'=', 2}, {'!=', 1} ]
1597 Which would generate:
1599 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1600 @bind = ('nwiger', '2', '1');
1603 =head2 Logic and nesting operators
1605 In the example above,
1606 there is a subtle trap if you want to say something like
1607 this (notice the C<AND>):
1609 WHERE priority != ? AND priority != ?
1611 Because, in Perl you I<can't> do this:
1613 priority => { '!=', 2, '!=', 1 }
1615 As the second C<!=> key will obliterate the first. The solution
1616 is to use the special C<-modifier> form inside an arrayref:
1618 priority => [ -and => {'!=', 2},
1622 Normally, these would be joined by C<OR>, but the modifier tells it
1623 to use C<AND> instead. (Hint: You can use this in conjunction with the
1624 C<logic> option to C<new()> in order to change the way your queries
1625 work by default.) B<Important:> Note that the C<-modifier> goes
1626 B<INSIDE> the arrayref, as an extra first element. This will
1627 B<NOT> do what you think it might:
1629 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1631 Here is a quick list of equivalencies, since there is some overlap:
1634 status => {'!=', 'completed', 'not like', 'pending%' }
1635 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1638 status => {'=', ['assigned', 'in-progress']}
1639 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1640 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1642 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1643 operator which adds an additional set of parens, to create a subquery.
1644 For example, to get something like this:
1646 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1647 @bind = ('nwiger', '20', 'ASIA');
1653 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1656 If you need several nested subexpressions, you can number
1657 the C<-nest> branches :
1667 =head2 Special operators : IN, BETWEEN, etc.
1669 You can also use the hashref format to compare a list of fields using the
1670 C<IN> comparison operator, by specifying the list as an arrayref:
1673 status => 'completed',
1674 reportid => { -in => [567, 2335, 2] }
1677 Which would generate:
1679 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1680 @bind = ('completed', '567', '2335', '2');
1682 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1685 Another pair of operators is C<-between> and C<-not_between>,
1686 used with an arrayref of two values:
1690 completion_date => {
1691 -not_between => ['2002-10-01', '2003-02-06']
1697 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1699 These are the two builtin "special operators"; but the
1700 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1702 =head2 Nested conditions
1704 So far, we've seen how multiple conditions are joined with a top-level
1705 C<AND>. We can change this by putting the different conditions we want in
1706 hashes and then putting those hashes in an array. For example:
1711 status => { -like => ['pending%', 'dispatched'] },
1715 status => 'unassigned',
1719 This data structure would create the following:
1721 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1722 OR ( user = ? AND status = ? ) )";
1723 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1725 This can be combined with the C<-nest> operator to properly group
1732 ["-and", workhrs => {'>', 20}, geo => 'ASIA' ],
1733 ["-and", workhrs => {'<', 50}, geo => 'EURO' ]
1740 WHERE ( user = ? AND
1741 ( ( workhrs > ? AND geo = ? )
1742 OR ( workhrs < ? AND geo = ? ) ) )
1746 Finally, sometimes only literal SQL will do. If you want to include
1747 literal SQL verbatim, you can specify it as a scalar reference, namely:
1749 my $inn = 'is Not Null';
1751 priority => { '<', 2 },
1757 $stmt = "WHERE priority < ? AND requestor is Not Null";
1760 Note that in this example, you only get one bind parameter back, since
1761 the verbatim SQL is passed as part of the statement.
1763 Of course, just to prove a point, the above can also be accomplished
1767 priority => { '<', 2 },
1768 requestor => { '!=', undef },
1774 Conditions on boolean columns can be expressed in the
1775 same way, passing a reference to an empty string :
1778 priority => { '<', 2 },
1784 $stmt = "WHERE priority < ? AND is_ready";
1788 =head2 Literal SQL with placeholders and bind values (subqueries)
1790 If the literal SQL to be inserted has placeholders and bind values,
1791 use a reference to an arrayref (yes this is a double reference --
1792 not so common, but perfectly legal Perl). For example, to find a date
1793 in Postgres you can use something like this:
1796 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1801 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1805 Literal SQL is especially useful for nesting parenthesized clauses in the
1806 main SQL query. Here is a first example :
1808 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1812 bar => \["IN ($sub_stmt)" => @sub_bind],
1817 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1818 WHERE c2 < ? AND c3 LIKE ?))";
1819 @bind = (1234, 100, "foo%");
1821 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
1822 are expressed in the same way. Of course the C<$sub_stmt> and
1823 its associated bind values can be generated through a former call
1826 my ($sub_stmt, @sub_bind)
1827 = $sql->select("t1", "c1", {c2 => {"<" => 100},
1828 c3 => {-like => "foo%"}});
1831 bar => \["> ALL ($sub_stmt)" => @sub_bind],
1834 In the examples above, the subquery was used as an operator on a column;
1835 but the same principle also applies for a clause within the main C<%where>
1836 hash, like an EXISTS subquery :
1838 my ($sub_stmt, @sub_bind)
1839 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1842 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
1847 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1848 WHERE c1 = ? AND c2 > t0.c0))";
1852 Observe that the condition on C<c2> in the subquery refers to
1853 column C<t0.c0> of the main query : this is I<not> a bind
1854 value, so we have to express it through a scalar ref.
1855 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
1856 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
1857 what we wanted here.
1859 Another use of the subquery technique is when some SQL clauses need
1860 parentheses, as it often occurs with some proprietary SQL extensions
1861 like for example fulltext expressions, geospatial expressions,
1862 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
1865 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
1868 Finally, here is an example where a subquery is used
1869 for expressing unary negation:
1871 my ($sub_stmt, @sub_bind)
1872 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
1873 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
1875 lname => {like => '%son%'},
1876 -nest => \["NOT ($sub_stmt)" => @sub_bind],
1881 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1882 @bind = ('%son%', 10, 20)
1888 These pages could go on for a while, since the nesting of the data
1889 structures this module can handle are pretty much unlimited (the
1890 module implements the C<WHERE> expansion as a recursive function
1891 internally). Your best bet is to "play around" with the module a
1892 little to see how the data structures behave, and choose the best
1893 format for your data based on that.
1895 And of course, all the values above will probably be replaced with
1896 variables gotten from forms or the command line. After all, if you
1897 knew everything ahead of time, you wouldn't have to worry about
1898 dynamically-generating SQL and could just hardwire it into your
1904 =head1 ORDER BY CLAUSES
1906 Some functions take an order by clause. This can either be a scalar (just a
1907 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1908 or an array of either of the two previous forms. Examples:
1910 Given | Will Generate
1911 ----------------------------------------------------------
1912 \'colA DESC' | ORDER BY colA DESC
1913 'colA' | ORDER BY colA
1914 [qw/colA colB/] | ORDER BY colA, colB
1915 {-asc => 'colA'} | ORDER BY colA ASC
1916 {-desc => 'colB'} | ORDER BY colB DESC
1918 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1921 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1922 ==========================================================
1926 =head1 SPECIAL OPERATORS
1928 my $sqlmaker = SQL::Abstract->new(special_ops => [
1931 my ($self, $field, $op, $arg) = @_;
1937 A "special operator" is a SQL syntactic clause that can be
1938 applied to a field, instead of a usual binary operator.
1941 WHERE field IN (?, ?, ?)
1942 WHERE field BETWEEN ? AND ?
1943 WHERE MATCH(field) AGAINST (?, ?)
1945 Special operators IN and BETWEEN are fairly standard and therefore
1946 are builtin within C<SQL::Abstract>. For other operators,
1947 like the MATCH .. AGAINST example above which is
1948 specific to MySQL, you can write your own operator handlers :
1949 supply a C<special_ops> argument to the C<new> method.
1950 That argument takes an arrayref of operator definitions;
1951 each operator definition is a hashref with two entries
1957 the regular expression to match the operator
1961 coderef that will be called when meeting that operator
1962 in the input tree. The coderef will be called with
1963 arguments C<< ($self, $field, $op, $arg) >>, and
1964 should return a C<< ($sql, @bind) >> structure.
1968 For example, here is an implementation
1969 of the MATCH .. AGAINST syntax for MySQL
1971 my $sqlmaker = SQL::Abstract->new(special_ops => [
1973 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
1974 {regex => qr/^match$/i,
1976 my ($self, $field, $op, $arg) = @_;
1977 $arg = [$arg] if not ref $arg;
1978 my $label = $self->_quote($field);
1979 my ($placeholder) = $self->_convert('?');
1980 my $placeholders = join ", ", (($placeholder) x @$arg);
1981 my $sql = $self->_sqlcase('match') . " ($label) "
1982 . $self->_sqlcase('against') . " ($placeholders) ";
1983 my @bind = $self->_bindtype($field, @$arg);
1984 return ($sql, @bind);
1993 Thanks to some benchmarking by Mark Stosberg, it turns out that
1994 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
1995 I must admit this wasn't an intentional design issue, but it's a
1996 byproduct of the fact that you get to control your C<DBI> handles
1999 To maximize performance, use a code snippet like the following:
2001 # prepare a statement handle using the first row
2002 # and then reuse it for the rest of the rows
2004 for my $href (@array_of_hashrefs) {
2005 $stmt ||= $sql->insert('table', $href);
2006 $sth ||= $dbh->prepare($stmt);
2007 $sth->execute($sql->values($href));
2010 The reason this works is because the keys in your C<$href> are sorted
2011 internally by B<SQL::Abstract>. Thus, as long as your data retains
2012 the same structure, you only have to generate the SQL the first time
2013 around. On subsequent queries, simply use the C<values> function provided
2014 by this module to return your values in the correct order.
2019 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2020 really like this part (I do, at least). Building up a complex query
2021 can be as simple as the following:
2025 use CGI::FormBuilder;
2028 my $form = CGI::FormBuilder->new(...);
2029 my $sql = SQL::Abstract->new;
2031 if ($form->submitted) {
2032 my $field = $form->field;
2033 my $id = delete $field->{id};
2034 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2037 Of course, you would still have to connect using C<DBI> to run the
2038 query, but the point is that if you make your form look like your
2039 table, the actual query script can be extremely simplistic.
2041 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2042 a fast interface to returning and formatting data. I frequently
2043 use these three modules together to write complex database query
2044 apps in under 50 lines.
2049 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2050 Great care has been taken to preserve the I<published> behavior
2051 documented in previous versions in the 1.* family; however,
2052 some features that were previously undocumented, or behaved
2053 differently from the documentation, had to be changed in order
2054 to clarify the semantics. Hence, client code that was relying
2055 on some dark areas of C<SQL::Abstract> v1.*
2056 B<might behave differently> in v1.50.
2058 The main changes are :
2064 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2068 added -nest1, -nest2 or -nest_1, -nest_2, ...
2072 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2076 defensive programming : check arguments
2080 fixed bug with global logic, which was previously implemented
2081 through global variables yielding side-effects. Prior versons would
2082 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2083 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2084 Now this is interpreted
2085 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2089 C<-and> / C<-or> operators are no longer accepted
2090 in the middle of an arrayref : they are
2091 only admitted if in first position.
2095 changed logic for distributing an op over arrayrefs
2099 fixed semantics of _bindtype on array args
2103 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2104 we just avoid shifting arrays within that tree.
2108 dropped the C<_modlogic> function
2114 =head1 ACKNOWLEDGEMENTS
2116 There are a number of individuals that have really helped out with
2117 this module. Unfortunately, most of them submitted bugs via CPAN
2118 so I have no idea who they are! But the people I do know are:
2120 Ash Berlin (order_by hash term support)
2121 Matt Trout (DBIx::Class support)
2122 Mark Stosberg (benchmarking)
2123 Chas Owens (initial "IN" operator support)
2124 Philip Collins (per-field SQL functions)
2125 Eric Kolve (hashref "AND" support)
2126 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2127 Dan Kubb (support for "quote_char" and "name_sep")
2128 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2129 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2135 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2139 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2141 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2143 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2144 While not an official support venue, C<DBIx::Class> makes heavy use of
2145 C<SQL::Abstract>, and as such list members there are very familiar with
2146 how to create queries.
2148 This module is free software; you may copy this under the terms of
2149 the GNU General Public License, or the Artistic License, copies of
2150 which should have accompanied your Perl kit.