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
150 else { # else literal SQL with bind
151 my ($sql, @bind) = @$v;
153 push @all_bind, @bind;
157 ARRAYREFREF => sub { # literal SQL with bind
158 my ($sql, @bind) = @${$v};
160 push @all_bind, @bind;
163 # THINK : anything useful to do with a HASHREF ?
164 HASHREF => sub { # (nothing, but old SQLA passed it through)
165 #TODO in SQLA >= 2.0 it will die instead
166 belch "HASH ref as bind value in insert is not supported";
171 SCALARREF => sub { # literal SQL without bind
175 SCALAR_or_UNDEF => sub {
184 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
185 return ($sql, @all_bind);
189 sub _insert_ARRAYREFREF { # literal SQL with bind
190 my ($self, $data) = @_;
195 sub _insert_SCALARREF { # literal SQL without bind
196 my ($self, $data) = @_;
203 #======================================================================
205 #======================================================================
210 my $table = $self->_table(shift);
211 my $data = shift || return;
214 # first build the 'SET' part of the sql statement
215 my (@set, @all_bind);
216 puke "Unsupported data type specified to \$sql->update"
217 unless ref $data eq 'HASH';
219 for my $k (sort keys %$data) {
222 my $label = $self->_quote($k);
224 $self->_SWITCH_refkind($v, {
226 if ($self->{array_datatypes}) { # array datatype
227 push @set, "$label = ?";
228 push @all_bind, $self->_bindtype($k, $v);
230 else { # literal SQL with bind
231 my ($sql, @bind) = @$v;
232 push @set, "$label = $sql";
233 push @all_bind, $self->_bindtype($k, @bind);
236 ARRAYREFREF => sub { # literal SQL with bind
237 my ($sql, @bind) = @${$v};
238 push @set, "$label = $sql";
239 push @all_bind, $self->_bindtype($k, @bind);
241 SCALARREF => sub { # literal SQL without bind
242 push @set, "$label = $$v";
244 SCALAR_or_UNDEF => sub {
245 push @set, "$label = ?";
246 push @all_bind, $self->_bindtype($k, $v);
252 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
256 my($where_sql, @where_bind) = $self->where($where);
258 push @all_bind, @where_bind;
261 return wantarray ? ($sql, @all_bind) : $sql;
267 #======================================================================
269 #======================================================================
274 my $table = $self->_table(shift);
275 my $fields = shift || '*';
279 my($where_sql, @bind) = $self->where($where, $order);
281 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
283 my $sql = join(' ', $self->_sqlcase('select'), $f,
284 $self->_sqlcase('from'), $table)
287 return wantarray ? ($sql, @bind) : $sql;
290 #======================================================================
292 #======================================================================
297 my $table = $self->_table(shift);
301 my($where_sql, @bind) = $self->where($where);
302 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
304 return wantarray ? ($sql, @bind) : $sql;
308 #======================================================================
310 #======================================================================
314 # Finally, a separate routine just to handle WHERE clauses
316 my ($self, $where, $order) = @_;
319 my ($sql, @bind) = $self->_recurse_where($where);
320 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
324 $sql .= $self->_order_by($order);
327 return wantarray ? ($sql, @bind) : $sql;
332 my ($self, $where, $logic) = @_;
334 # dispatch on appropriate method according to refkind of $where
335 my $method = $self->_METHOD_FOR_refkind("_where", $where);
338 my ($sql, @bind) = $self->$method($where, $logic);
340 # DBIx::Class directly calls _recurse_where in scalar context, so
341 # we must implement it, even if not in the official API
342 return wantarray ? ($sql, @bind) : $sql;
347 #======================================================================
348 # WHERE: top-level ARRAYREF
349 #======================================================================
352 sub _where_ARRAYREF {
353 my ($self, $where, $logic) = @_;
355 $logic = uc($logic || $self->{logic});
356 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
358 my @clauses = @$where;
360 # if the array starts with [-and|or => ...], recurse with that logic
361 my $first = $clauses[0] || '';
362 if ($first =~ /^-(and|or)/i) {
365 return $self->_where_ARRAYREF(\@clauses, $logic);
369 my (@sql_clauses, @all_bind);
371 # need to use while() so can shift() for pairs
372 while (my $el = shift @clauses) {
374 # switch according to kind of $el and get corresponding ($sql, @bind)
375 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
377 # skip empty elements, otherwise get invalid trailing AND stuff
378 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
380 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
381 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
382 # side-effect: the first hashref within an array would change
383 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
384 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
385 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
387 SCALARREF => sub { ($$el); },
389 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
390 $self->_recurse_where({$el => shift(@clauses)})},
392 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
396 push @sql_clauses, $sql;
397 push @all_bind, @bind;
401 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
406 #======================================================================
407 # WHERE: top-level HASHREF
408 #======================================================================
411 my ($self, $where) = @_;
412 my (@sql_clauses, @all_bind);
414 # LDNOTE : don't really know why we need to sort keys
415 for my $k (sort keys %$where) {
416 my $v = $where->{$k};
418 # ($k => $v) is either a special op or a regular hashpair
419 my ($sql, @bind) = ($k =~ /^-(.+)/) ? $self->_where_op_in_hash($1, $v)
421 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
422 $self->$method($k, $v);
425 push @sql_clauses, $sql;
426 push @all_bind, @bind;
429 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
433 sub _where_op_in_hash {
434 my ($self, $op, $v) = @_;
436 $op =~ /^(AND|OR|NEST)[_\d]*/i
437 or puke "unknown operator: -$op";
438 $op = uc($1); # uppercase, remove trailing digits
439 $self->_debug("OP(-$op) within hashref, recursing...");
441 $self->_SWITCH_refkind($v, {
444 # LDNOTE : should deprecate {-or => [...]} and {-and => [...]}
445 # because they are misleading; the only proper way would be
446 # -nest => [-or => ...], -nest => [-and ...]
447 return $self->_where_ARRAYREF($v, $op eq 'NEST' ? '' : $op);
452 belch "-or => {...} should be -nest => [...]";
453 return $self->_where_ARRAYREF([%$v], 'OR');
456 return $self->_where_HASHREF($v);
460 SCALARREF => sub { # literal SQL
462 or puke "-$op => \\\$scalar not supported, use -nest => ...";
466 ARRAYREFREF => sub { # literal SQL
468 or puke "-$op => \\[..] not supported, use -nest => ...";
472 SCALAR => sub { # permissively interpreted as SQL
474 or puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
475 belch "literal SQL should be -nest => \\'scalar' "
476 . "instead of -nest => 'scalar' ";
481 puke "-$op => undef not supported";
487 sub _where_hashpair_ARRAYREF {
488 my ($self, $k, $v) = @_;
491 my @v = @$v; # need copy because of shift below
492 $self->_debug("ARRAY($k) means distribute over elements");
494 # put apart first element if it is an operator (-and, -or)
495 my $op = $v[0] =~ /^-/ ? shift @v : undef;
496 $self->_debug("OP($op) reinjected into the distributed array") if $op;
498 my @distributed = map { {$k => $_} } @v;
499 unshift @distributed, $op if $op;
501 return $self->_recurse_where(\@distributed);
504 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
505 $self->_debug("empty ARRAY($k) means 0=1");
506 return ($self->{sqlfalse});
510 sub _where_hashpair_HASHREF {
511 my ($self, $k, $v) = @_;
513 my (@all_sql, @all_bind);
515 for my $op (sort keys %$v) {
518 # put the operator in canonical form
519 $op =~ s/^-//; # remove initial dash
520 $op =~ tr/_/ /; # underscores become spaces
521 $op =~ s/^\s+//; # no initial space
522 $op =~ s/\s+$//; # no final space
523 $op =~ s/\s+/ /; # multiple spaces become one
527 # CASE: special operators like -in or -between
528 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
530 ($sql, @bind) = $special_op->{handler}->($self, $k, $op, $val);
533 $self->_SWITCH_refkind($val, {
535 ARRAYREF => sub { # CASE: col => {op => \@vals}
536 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
539 SCALARREF => sub { # CASE: col => {op => \$scalar}
540 $sql = join ' ', $self->_convert($self->_quote($k)),
541 $self->_sqlcase($op),
545 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]}
546 my ($sub_sql, @sub_bind) = @$$val;
547 $sql = join ' ', $self->_convert($self->_quote($k)),
548 $self->_sqlcase($op),
550 @bind = $self->_bindtype($k, @sub_bind);
553 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
554 my $is = ($op =~ $self->{equality_op}) ? 'is' :
555 ($op =~ $self->{inequality_op}) ? 'is not' :
556 puke "unexpected operator '$op' with undef operand";
557 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
560 FALLBACK => sub { # CASE: col => {op => $scalar}
561 $sql = join ' ', $self->_convert($self->_quote($k)),
562 $self->_sqlcase($op),
563 $self->_convert('?');
564 @bind = $self->_bindtype($k, $val);
570 push @all_bind, @bind;
573 return $self->_join_sql_clauses('and', \@all_sql, \@all_bind);
578 sub _where_field_op_ARRAYREF {
579 my ($self, $k, $op, $vals) = @_;
582 $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
586 # LDNOTE : change the distribution logic when
587 # $op =~ $self->{inequality_op}, because of Morgan laws :
588 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
589 # WHERE field != 22 OR field != 33 : the user probably means
590 # WHERE field != 22 AND field != 33.
591 my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
593 # distribute $op over each member of @$vals
594 return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
598 # try to DWIM on equality operators
599 # LDNOTE : not 100% sure this is the correct thing to do ...
600 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
601 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
604 puke "operator '$op' applied on an empty array (field '$k')";
609 sub _where_hashpair_SCALARREF {
610 my ($self, $k, $v) = @_;
611 $self->_debug("SCALAR($k) means literal SQL: $$v");
612 my $sql = $self->_quote($k) . " " . $$v;
616 sub _where_hashpair_ARRAYREFREF {
617 my ($self, $k, $v) = @_;
618 $self->_debug("REF($k) means literal SQL: @${$v}");
619 my ($sql, @bind) = @${$v};
620 $sql = $self->_quote($k) . " " . $sql;
621 @bind = $self->_bindtype($k, @bind);
622 return ($sql, @bind );
625 sub _where_hashpair_SCALAR {
626 my ($self, $k, $v) = @_;
627 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
628 my $sql = join ' ', $self->_convert($self->_quote($k)),
629 $self->_sqlcase($self->{cmp}),
630 $self->_convert('?');
631 my @bind = $self->_bindtype($k, $v);
632 return ( $sql, @bind);
636 sub _where_hashpair_UNDEF {
637 my ($self, $k, $v) = @_;
638 $self->_debug("UNDEF($k) means IS NULL");
639 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
643 #======================================================================
644 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
645 #======================================================================
648 sub _where_SCALARREF {
649 my ($self, $where) = @_;
652 $self->_debug("SCALAR(*top) means literal SQL: $$where");
658 my ($self, $where) = @_;
661 $self->_debug("NOREF(*top) means literal SQL: $where");
672 #======================================================================
673 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
674 #======================================================================
677 sub _where_field_BETWEEN {
678 my ($self, $k, $op, $vals) = @_;
680 ref $vals eq 'ARRAY' && @$vals == 2
681 or puke "special op 'between' requires an arrayref of two values";
683 my ($label) = $self->_convert($self->_quote($k));
684 my ($placeholder) = $self->_convert('?');
685 my $and = $self->_sqlcase('and');
686 $op = $self->_sqlcase($op);
688 my $sql = "( $label $op $placeholder $and $placeholder )";
689 my @bind = $self->_bindtype($k, @$vals);
694 sub _where_field_IN {
695 my ($self, $k, $op, $vals) = @_;
697 # backwards compatibility : if scalar, force into an arrayref
698 $vals = [$vals] if defined $vals && ! ref $vals;
700 my ($label) = $self->_convert($self->_quote($k));
701 my ($placeholder) = $self->_convert('?');
702 $op = $self->_sqlcase($op);
704 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
705 ARRAYREF => sub { # list of choices
706 if (@$vals) { # nonempty list
707 my $placeholders = join ", ", (($placeholder) x @$vals);
708 my $sql = "$label $op ( $placeholders )";
709 my @bind = $self->_bindtype($k, @$vals);
711 return ($sql, @bind);
713 else { # empty list : some databases won't understand "IN ()", so DWIM
714 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
719 ARRAYREFREF => sub { # literal SQL with bind
720 my ($sql, @bind) = @$$vals;
721 return ("$label $op ( $sql )", @bind);
725 puke "special op 'in' requires an arrayref (or arrayref-ref)";
729 return ($sql, @bind);
737 #======================================================================
739 #======================================================================
742 my ($self, $arg) = @_;
744 # construct list of ordering instructions
745 my @order = $self->_SWITCH_refkind($arg, {
748 map {$self->_SWITCH_refkind($_, {
749 SCALAR => sub {$self->_quote($_)},
751 SCALARREF => sub {$$_}, # literal SQL, no quoting
752 HASHREF => sub {$self->_order_by_hash($_)}
756 SCALAR => sub {$self->_quote($arg)},
758 SCALARREF => sub {$$arg}, # literal SQL, no quoting
759 HASHREF => sub {$self->_order_by_hash($arg)},
764 my $order = join ', ', @order;
765 return $order ? $self->_sqlcase(' order by')." $order" : '';
770 my ($self, $hash) = @_;
772 # get first pair in hash
773 my ($key, $val) = each %$hash;
775 # check if one pair was found and no other pair in hash
776 $key && !(each %$hash)
777 or puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
779 my ($order) = ($key =~ /^-(desc|asc)/i)
780 or puke "invalid key in _order_by hash : $key";
782 return $self->_quote($val) ." ". $self->_sqlcase($order);
787 #======================================================================
788 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
789 #======================================================================
794 $self->_SWITCH_refkind($from, {
795 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
796 SCALAR => sub {$self->_quote($from)},
797 SCALARREF => sub {$$from},
798 ARRAYREFREF => sub {join ', ', @$from;},
803 #======================================================================
805 #======================================================================
811 $label or puke "can't quote an empty label";
813 # left and right quote characters
814 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
815 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
816 ARRAYREF => sub {@{$self->{quote_char}}},
820 or puke "quote_char must be an arrayref of 2 values";
822 # no quoting if no quoting chars
823 $ql or return $label;
825 # no quoting for literal SQL
826 return $$label if ref($label) eq 'SCALAR';
828 # separate table / column (if applicable)
829 my $sep = $self->{name_sep} || '';
830 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
832 # do the quoting, except for "*" or for `table`.*
833 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
835 # reassemble and return.
836 return join $sep, @quoted;
840 # Conversion, if applicable
842 my ($self, $arg) = @_;
844 # LDNOTE : modified the previous implementation below because
845 # it was not consistent : the first "return" is always an array,
846 # the second "return" is context-dependent. Anyway, _convert
847 # seems always used with just a single argument, so make it a
849 # return @_ unless $self->{convert};
850 # my $conv = $self->_sqlcase($self->{convert});
851 # my @ret = map { $conv.'('.$_.')' } @_;
852 # return wantarray ? @ret : $ret[0];
853 if ($self->{convert}) {
854 my $conv = $self->_sqlcase($self->{convert});
855 $arg = $conv.'('.$arg.')';
863 my($col, @vals) = @_;
865 #LDNOTE : changed original implementation below because it did not make
866 # sense when bindtype eq 'columns' and @vals > 1.
867 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
869 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
872 sub _join_sql_clauses {
873 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
875 if (@$clauses_aref > 1) {
876 my $join = " " . $self->_sqlcase($logic) . " ";
877 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
878 return ($sql, @$bind_aref);
880 elsif (@$clauses_aref) {
881 return ($clauses_aref->[0], @$bind_aref); # no parentheses
884 return (); # if no SQL, ignore @$bind_aref
889 # Fix SQL case, if so requested
893 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
894 # don't touch the argument ... crooked logic, but let's not change it!
895 return $self->{case} ? $_[0] : uc($_[0]);
899 #======================================================================
900 # DISPATCHING FROM REFKIND
901 #======================================================================
904 my ($self, $data) = @_;
910 # blessed objects are treated like scalars
911 $ref = (blessed $data) ? '' : ref $data;
912 $n_steps += 1 if $ref;
913 last if $ref ne 'REF';
917 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
919 return $base . ('REF' x $n_steps);
925 my ($self, $data) = @_;
926 my @try = ($self->_refkind($data));
927 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
928 push @try, 'FALLBACK';
932 sub _METHOD_FOR_refkind {
933 my ($self, $meth_prefix, $data) = @_;
934 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
935 $self->_try_refkind($data)
936 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
941 sub _SWITCH_refkind {
942 my ($self, $data, $dispatch_table) = @_;
944 my $coderef = first {$_} map {$dispatch_table->{$_}}
945 $self->_try_refkind($data)
946 or puke "no dispatch entry for ".$self->_refkind($data);
953 #======================================================================
954 # VALUES, GENERATE, AUTOLOAD
955 #======================================================================
957 # LDNOTE: original code from nwiger, didn't touch code in that section
958 # I feel the AUTOLOAD stuff should not be the default, it should
959 # only be activated on explicit demand by user.
963 my $data = shift || return;
964 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
965 unless ref $data eq 'HASH';
966 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
972 my(@sql, @sqlq, @sqlv);
976 if ($ref eq 'HASH') {
977 for my $k (sort keys %$_) {
980 my $label = $self->_quote($k);
982 # SQL included for values
984 my $sql = shift @bind;
985 push @sqlq, "$label = $sql";
986 push @sqlv, $self->_bindtype($k, @bind);
987 } elsif ($r eq 'SCALAR') {
988 # embedded literal SQL
989 push @sqlq, "$label = $$v";
991 push @sqlq, "$label = ?";
992 push @sqlv, $self->_bindtype($k, $v);
995 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
996 } elsif ($ref eq 'ARRAY') {
997 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1000 if ($r eq 'ARRAY') {
1002 push @sqlq, shift @val;
1004 } elsif ($r eq 'SCALAR') {
1005 # embedded literal SQL
1012 push @sql, '(' . join(', ', @sqlq) . ')';
1013 } elsif ($ref eq 'SCALAR') {
1017 # strings get case twiddled
1018 push @sql, $self->_sqlcase($_);
1022 my $sql = join ' ', @sql;
1024 # this is pretty tricky
1025 # if ask for an array, return ($stmt, @bind)
1026 # otherwise, s/?/shift @sqlv/ to put it inline
1028 return ($sql, @sqlv);
1030 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1031 ref $d ? $d->[1] : $d/e;
1040 # This allows us to check for a local, then _form, attr
1042 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1043 return $self->generate($name, @_);
1054 SQL::Abstract - Generate SQL from Perl data structures
1060 my $sql = SQL::Abstract->new;
1062 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1064 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1066 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1068 my($stmt, @bind) = $sql->delete($table, \%where);
1070 # Then, use these in your DBI statements
1071 my $sth = $dbh->prepare($stmt);
1072 $sth->execute(@bind);
1074 # Just generate the WHERE clause
1075 my($stmt, @bind) = $sql->where(\%where, \@order);
1077 # Return values in the same order, for hashed queries
1078 # See PERFORMANCE section for more details
1079 my @bind = $sql->values(\%fieldvals);
1083 This module was inspired by the excellent L<DBIx::Abstract>.
1084 However, in using that module I found that what I really wanted
1085 to do was generate SQL, but still retain complete control over my
1086 statement handles and use the DBI interface. So, I set out to
1087 create an abstract SQL generation module.
1089 While based on the concepts used by L<DBIx::Abstract>, there are
1090 several important differences, especially when it comes to WHERE
1091 clauses. I have modified the concepts used to make the SQL easier
1092 to generate from Perl data structures and, IMO, more intuitive.
1093 The underlying idea is for this module to do what you mean, based
1094 on the data structures you provide it. The big advantage is that
1095 you don't have to modify your code every time your data changes,
1096 as this module figures it out.
1098 To begin with, an SQL INSERT is as easy as just specifying a hash
1099 of C<key=value> pairs:
1102 name => 'Jimbo Bobson',
1103 phone => '123-456-7890',
1104 address => '42 Sister Lane',
1105 city => 'St. Louis',
1106 state => 'Louisiana',
1109 The SQL can then be generated with this:
1111 my($stmt, @bind) = $sql->insert('people', \%data);
1113 Which would give you something like this:
1115 $stmt = "INSERT INTO people
1116 (address, city, name, phone, state)
1117 VALUES (?, ?, ?, ?, ?)";
1118 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1119 '123-456-7890', 'Louisiana');
1121 These are then used directly in your DBI code:
1123 my $sth = $dbh->prepare($stmt);
1124 $sth->execute(@bind);
1126 =head2 Inserting and Updating Arrays
1128 If your database has array types (like for example Postgres),
1129 activate the special option C<< array_datatypes => 1 >>
1130 when creating the C<SQL::Abstract> object.
1131 Then you may use an arrayref to insert and update database array types:
1133 my $sql = SQL::Abstract->new(array_datatypes => 1);
1135 planets => [qw/Mercury Venus Earth Mars/]
1138 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1142 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1144 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1147 =head2 Inserting and Updating SQL
1149 In order to apply SQL functions to elements of your C<%data> you may
1150 specify a reference to an arrayref for the given hash value. For example,
1151 if you need to execute the Oracle C<to_date> function on a value, you can
1152 say something like this:
1156 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1159 The first value in the array is the actual SQL. Any other values are
1160 optional and would be included in the bind values array. This gives
1163 my($stmt, @bind) = $sql->insert('people', \%data);
1165 $stmt = "INSERT INTO people (name, date_entered)
1166 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1167 @bind = ('Bill', '03/02/2003');
1169 An UPDATE is just as easy, all you change is the name of the function:
1171 my($stmt, @bind) = $sql->update('people', \%data);
1173 Notice that your C<%data> isn't touched; the module will generate
1174 the appropriately quirky SQL for you automatically. Usually you'll
1175 want to specify a WHERE clause for your UPDATE, though, which is
1176 where handling C<%where> hashes comes in handy...
1178 =head2 Complex where statements
1180 This module can generate pretty complicated WHERE statements
1181 easily. For example, simple C<key=value> pairs are taken to mean
1182 equality, and if you want to see if a field is within a set
1183 of values, you can use an arrayref. Let's say we wanted to
1184 SELECT some data based on this criteria:
1187 requestor => 'inna',
1188 worker => ['nwiger', 'rcwe', 'sfz'],
1189 status => { '!=', 'completed' }
1192 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1194 The above would give you something like this:
1196 $stmt = "SELECT * FROM tickets WHERE
1197 ( requestor = ? ) AND ( status != ? )
1198 AND ( worker = ? OR worker = ? OR worker = ? )";
1199 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1201 Which you could then use in DBI code like so:
1203 my $sth = $dbh->prepare($stmt);
1204 $sth->execute(@bind);
1210 The functions are simple. There's one for each major SQL operation,
1211 and a constructor you use first. The arguments are specified in a
1212 similar order to each function (table, then fields, then a where
1213 clause) to try and simplify things.
1218 =head2 new(option => 'value')
1220 The C<new()> function takes a list of options and values, and returns
1221 a new B<SQL::Abstract> object which can then be used to generate SQL
1222 through the methods below. The options accepted are:
1228 If set to 'lower', then SQL will be generated in all lowercase. By
1229 default SQL is generated in "textbook" case meaning something like:
1231 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1233 Any setting other than 'lower' is ignored.
1237 This determines what the default comparison operator is. By default
1238 it is C<=>, meaning that a hash like this:
1240 %where = (name => 'nwiger', email => 'nate@wiger.org');
1242 Will generate SQL like this:
1244 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1246 However, you may want loose comparisons by default, so if you set
1247 C<cmp> to C<like> you would get SQL such as:
1249 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1251 You can also override the comparsion on an individual basis - see
1252 the huge section on L</"WHERE CLAUSES"> at the bottom.
1254 =item sqltrue, sqlfalse
1256 Expressions for inserting boolean values within SQL statements.
1257 By default these are C<1=1> and C<1=0>.
1261 This determines the default logical operator for multiple WHERE
1262 statements in arrays. By default it is "or", meaning that a WHERE
1266 event_date => {'>=', '2/13/99'},
1267 event_date => {'<=', '4/24/03'},
1270 Will generate SQL like this:
1272 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1274 This is probably not what you want given this query, though (look
1275 at the dates). To change the "OR" to an "AND", simply specify:
1277 my $sql = SQL::Abstract->new(logic => 'and');
1279 Which will change the above C<WHERE> to:
1281 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1283 The logic can also be changed locally by inserting
1284 an extra first element in the array :
1286 @where = (-and => event_date => {'>=', '2/13/99'},
1287 event_date => {'<=', '4/24/03'} );
1289 See the L</"WHERE CLAUSES"> section for explanations.
1293 This will automatically convert comparisons using the specified SQL
1294 function for both column and value. This is mostly used with an argument
1295 of C<upper> or C<lower>, so that the SQL will have the effect of
1296 case-insensitive "searches". For example, this:
1298 $sql = SQL::Abstract->new(convert => 'upper');
1299 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1301 Will turn out the following SQL:
1303 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1305 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1306 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1307 not validate this option; it will just pass through what you specify verbatim).
1311 This is a kludge because many databases suck. For example, you can't
1312 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1313 Instead, you have to use C<bind_param()>:
1315 $sth->bind_param(1, 'reg data');
1316 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1318 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1319 which loses track of which field each slot refers to. Fear not.
1321 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1322 Currently, you can specify either C<normal> (default) or C<columns>. If you
1323 specify C<columns>, you will get an array that looks like this:
1325 my $sql = SQL::Abstract->new(bindtype => 'columns');
1326 my($stmt, @bind) = $sql->insert(...);
1329 [ 'column1', 'value1' ],
1330 [ 'column2', 'value2' ],
1331 [ 'column3', 'value3' ],
1334 You can then iterate through this manually, using DBI's C<bind_param()>.
1336 $sth->prepare($stmt);
1339 my($col, $data) = @$_;
1340 if ($col eq 'details' || $col eq 'comments') {
1341 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1342 } elsif ($col eq 'image') {
1343 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1345 $sth->bind_param($i, $data);
1349 $sth->execute; # execute without @bind now
1351 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1352 Basically, the advantage is still that you don't have to care which fields
1353 are or are not included. You could wrap that above C<for> loop in a simple
1354 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1355 get a layer of abstraction over manual SQL specification.
1359 This is the character that a table or column name will be quoted
1360 with. By default this is an empty string, but you could set it to
1361 the character C<`>, to generate SQL like this:
1363 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1365 Alternatively, you can supply an array ref of two items, the first being the left
1366 hand quote character, and the second the right hand quote character. For
1367 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1368 that generates SQL like this:
1370 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1372 Quoting is useful if you have tables or columns names that are reserved
1373 words in your database's SQL dialect.
1377 This is the character that separates a table and column name. It is
1378 necessary to specify this when the C<quote_char> option is selected,
1379 so that tables and column names can be individually quoted like this:
1381 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1383 =item array_datatypes
1385 When this option is true, arrayrefs in INSERT or UPDATE are
1386 interpreted as array datatypes and are passed directly
1388 When this option is false, arrayrefs are interpreted
1389 as literal SQL, just like refs to arrayrefs
1390 (but this behavior is for backwards compatibility; when writing
1391 new queries, use the "reference to arrayref" syntax
1397 Takes a reference to a list of "special operators"
1398 to extend the syntax understood by L<SQL::Abstract>.
1399 See section L</"SPECIAL OPERATORS"> for details.
1405 =head2 insert($table, \@values || \%fieldvals)
1407 This is the simplest function. You simply give it a table name
1408 and either an arrayref of values or hashref of field/value pairs.
1409 It returns an SQL INSERT statement and a list of bind values.
1410 See the sections on L</"Inserting and Updating Arrays"> and
1411 L</"Inserting and Updating SQL"> for information on how to insert
1412 with those data types.
1414 =head2 update($table, \%fieldvals, \%where)
1416 This takes a table, hashref of field/value pairs, and an optional
1417 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1419 See the sections on L</"Inserting and Updating Arrays"> and
1420 L</"Inserting and Updating SQL"> for information on how to insert
1421 with those data types.
1423 =head2 select($source, $fields, $where, $order)
1425 This returns a SQL SELECT statement and associated list of bind values, as
1426 specified by the arguments :
1432 Specification of the 'FROM' part of the statement.
1433 The argument can be either a plain scalar (interpreted as a table
1434 name, will be quoted), or an arrayref (interpreted as a list
1435 of table names, joined by commas, quoted), or a scalarref
1436 (literal table name, not quoted), or a ref to an arrayref
1437 (list of literal table names, joined by commas, not quoted).
1441 Specification of the list of fields to retrieve from
1443 The argument can be either an arrayref (interpreted as a list
1444 of field names, will be joined by commas and quoted), or a
1445 plain scalar (literal SQL, not quoted).
1446 Please observe that this API is not as flexible as for
1447 the first argument C<$table>, for backwards compatibility reasons.
1451 Optional argument to specify the WHERE part of the query.
1452 The argument is most often a hashref, but can also be
1453 an arrayref or plain scalar --
1454 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1458 Optional argument to specify the ORDER BY part of the query.
1459 The argument can be a scalar, a hashref or an arrayref
1460 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1466 =head2 delete($table, \%where)
1468 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1469 It returns an SQL DELETE statement and list of bind values.
1471 =head2 where(\%where, \@order)
1473 This is used to generate just the WHERE clause. For example,
1474 if you have an arbitrary data structure and know what the
1475 rest of your SQL is going to look like, but want an easy way
1476 to produce a WHERE clause, use this. It returns an SQL WHERE
1477 clause and list of bind values.
1480 =head2 values(\%data)
1482 This just returns the values from the hash C<%data>, in the same
1483 order that would be returned from any of the other above queries.
1484 Using this allows you to markedly speed up your queries if you
1485 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1487 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1489 Warning: This is an experimental method and subject to change.
1491 This returns arbitrarily generated SQL. It's a really basic shortcut.
1492 It will return two different things, depending on return context:
1494 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1495 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1497 These would return the following:
1499 # First calling form
1500 $stmt = "CREATE TABLE test (?, ?)";
1501 @bind = (field1, field2);
1503 # Second calling form
1504 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1506 Depending on what you're trying to do, it's up to you to choose the correct
1507 format. In this example, the second form is what you would want.
1511 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1515 ALTER SESSION SET nls_date_format = 'MM/YY'
1517 You get the idea. Strings get their case twiddled, but everything
1518 else remains verbatim.
1523 =head1 WHERE CLAUSES
1527 This module uses a variation on the idea from L<DBIx::Abstract>. It
1528 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1529 module is that things in arrays are OR'ed, and things in hashes
1532 The easiest way to explain is to show lots of examples. After
1533 each C<%where> hash shown, it is assumed you used:
1535 my($stmt, @bind) = $sql->where(\%where);
1537 However, note that the C<%where> hash can be used directly in any
1538 of the other functions as well, as described above.
1540 =head2 Key-value pairs
1542 So, let's get started. To begin, a simple hash:
1546 status => 'completed'
1549 Is converted to SQL C<key = val> statements:
1551 $stmt = "WHERE user = ? AND status = ?";
1552 @bind = ('nwiger', 'completed');
1554 One common thing I end up doing is having a list of values that
1555 a field can be in. To do this, simply specify a list inside of
1560 status => ['assigned', 'in-progress', 'pending'];
1563 This simple code will create the following:
1565 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1566 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1568 An empty arrayref will be considered a logical false and
1571 =head2 Key-value pairs
1573 If you want to specify a different type of operator for your comparison,
1574 you can use a hashref for a given column:
1578 status => { '!=', 'completed' }
1581 Which would generate:
1583 $stmt = "WHERE user = ? AND status != ?";
1584 @bind = ('nwiger', 'completed');
1586 To test against multiple values, just enclose the values in an arrayref:
1588 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1590 Which would give you:
1592 "WHERE status != ? AND status != ? AND status != ?"
1594 Notice that since the operator was recognized as being a 'negative'
1595 operator, the arrayref was interpreted with 'AND' logic (because
1596 of Morgan's laws). By contrast, the reverse
1598 status => { '=', ['assigned', 'in-progress', 'pending'] };
1602 "WHERE status = ? OR status = ? OR status = ?"
1605 The hashref can also contain multiple pairs, in which case it is expanded
1606 into an C<AND> of its elements:
1610 status => { '!=', 'completed', -not_like => 'pending%' }
1613 # Or more dynamically, like from a form
1614 $where{user} = 'nwiger';
1615 $where{status}{'!='} = 'completed';
1616 $where{status}{'-not_like'} = 'pending%';
1618 # Both generate this
1619 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1620 @bind = ('nwiger', 'completed', 'pending%');
1623 To get an OR instead, you can combine it with the arrayref idea:
1627 priority => [ {'=', 2}, {'!=', 1} ]
1630 Which would generate:
1632 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1633 @bind = ('nwiger', '2', '1');
1635 If you want to include literal SQL (with or without bind values), just use a
1636 scalar reference or array reference as the value:
1639 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1640 date_expires => { '<' => \"now()" }
1643 Which would generate:
1645 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1646 @bind = ('11/26/2008');
1649 =head2 Logic and nesting operators
1651 In the example above,
1652 there is a subtle trap if you want to say something like
1653 this (notice the C<AND>):
1655 WHERE priority != ? AND priority != ?
1657 Because, in Perl you I<can't> do this:
1659 priority => { '!=', 2, '!=', 1 }
1661 As the second C<!=> key will obliterate the first. The solution
1662 is to use the special C<-modifier> form inside an arrayref:
1664 priority => [ -and => {'!=', 2},
1668 Normally, these would be joined by C<OR>, but the modifier tells it
1669 to use C<AND> instead. (Hint: You can use this in conjunction with the
1670 C<logic> option to C<new()> in order to change the way your queries
1671 work by default.) B<Important:> Note that the C<-modifier> goes
1672 B<INSIDE> the arrayref, as an extra first element. This will
1673 B<NOT> do what you think it might:
1675 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1677 Here is a quick list of equivalencies, since there is some overlap:
1680 status => {'!=', 'completed', 'not like', 'pending%' }
1681 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1684 status => {'=', ['assigned', 'in-progress']}
1685 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1686 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1688 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1689 operator which adds an additional set of parens, to create a subquery.
1690 For example, to get something like this:
1692 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1693 @bind = ('nwiger', '20', 'ASIA');
1699 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1702 If you need several nested subexpressions, you can number
1703 the C<-nest> branches :
1713 =head2 Special operators : IN, BETWEEN, etc.
1715 You can also use the hashref format to compare a list of fields using the
1716 C<IN> comparison operator, by specifying the list as an arrayref:
1719 status => 'completed',
1720 reportid => { -in => [567, 2335, 2] }
1723 Which would generate:
1725 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1726 @bind = ('completed', '567', '2335', '2');
1728 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1731 Another pair of operators is C<-between> and C<-not_between>,
1732 used with an arrayref of two values:
1736 completion_date => {
1737 -not_between => ['2002-10-01', '2003-02-06']
1743 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1745 These are the two builtin "special operators"; but the
1746 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1748 =head2 Nested conditions
1750 So far, we've seen how multiple conditions are joined with a top-level
1751 C<AND>. We can change this by putting the different conditions we want in
1752 hashes and then putting those hashes in an array. For example:
1757 status => { -like => ['pending%', 'dispatched'] },
1761 status => 'unassigned',
1765 This data structure would create the following:
1767 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1768 OR ( user = ? AND status = ? ) )";
1769 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1771 This can be combined with the C<-nest> operator to properly group
1778 ["-and", workhrs => {'>', 20}, geo => 'ASIA' ],
1779 ["-and", workhrs => {'<', 50}, geo => 'EURO' ]
1786 WHERE ( user = ? AND
1787 ( ( workhrs > ? AND geo = ? )
1788 OR ( workhrs < ? AND geo = ? ) ) )
1792 Finally, sometimes only literal SQL will do. If you want to include
1793 literal SQL verbatim, you can specify it as a scalar reference, namely:
1795 my $inn = 'is Not Null';
1797 priority => { '<', 2 },
1803 $stmt = "WHERE priority < ? AND requestor is Not Null";
1806 Note that in this example, you only get one bind parameter back, since
1807 the verbatim SQL is passed as part of the statement.
1809 Of course, just to prove a point, the above can also be accomplished
1813 priority => { '<', 2 },
1814 requestor => { '!=', undef },
1820 Conditions on boolean columns can be expressed in the
1821 same way, passing a reference to an empty string :
1824 priority => { '<', 2 },
1830 $stmt = "WHERE priority < ? AND is_ready";
1834 =head2 Literal SQL with placeholders and bind values (subqueries)
1836 If the literal SQL to be inserted has placeholders and bind values,
1837 use a reference to an arrayref (yes this is a double reference --
1838 not so common, but perfectly legal Perl). For example, to find a date
1839 in Postgres you can use something like this:
1842 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1847 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1851 Literal SQL is especially useful for nesting parenthesized clauses in the
1852 main SQL query. Here is a first example :
1854 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1858 bar => \["IN ($sub_stmt)" => @sub_bind],
1863 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1864 WHERE c2 < ? AND c3 LIKE ?))";
1865 @bind = (1234, 100, "foo%");
1867 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
1868 are expressed in the same way. Of course the C<$sub_stmt> and
1869 its associated bind values can be generated through a former call
1872 my ($sub_stmt, @sub_bind)
1873 = $sql->select("t1", "c1", {c2 => {"<" => 100},
1874 c3 => {-like => "foo%"}});
1877 bar => \["> ALL ($sub_stmt)" => @sub_bind],
1880 In the examples above, the subquery was used as an operator on a column;
1881 but the same principle also applies for a clause within the main C<%where>
1882 hash, like an EXISTS subquery :
1884 my ($sub_stmt, @sub_bind)
1885 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1888 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
1893 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1894 WHERE c1 = ? AND c2 > t0.c0))";
1898 Observe that the condition on C<c2> in the subquery refers to
1899 column C<t0.c0> of the main query : this is I<not> a bind
1900 value, so we have to express it through a scalar ref.
1901 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
1902 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
1903 what we wanted here.
1905 Another use of the subquery technique is when some SQL clauses need
1906 parentheses, as it often occurs with some proprietary SQL extensions
1907 like for example fulltext expressions, geospatial expressions,
1908 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
1911 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
1914 Finally, here is an example where a subquery is used
1915 for expressing unary negation:
1917 my ($sub_stmt, @sub_bind)
1918 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
1919 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
1921 lname => {like => '%son%'},
1922 -nest => \["NOT ($sub_stmt)" => @sub_bind],
1927 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1928 @bind = ('%son%', 10, 20)
1934 These pages could go on for a while, since the nesting of the data
1935 structures this module can handle are pretty much unlimited (the
1936 module implements the C<WHERE> expansion as a recursive function
1937 internally). Your best bet is to "play around" with the module a
1938 little to see how the data structures behave, and choose the best
1939 format for your data based on that.
1941 And of course, all the values above will probably be replaced with
1942 variables gotten from forms or the command line. After all, if you
1943 knew everything ahead of time, you wouldn't have to worry about
1944 dynamically-generating SQL and could just hardwire it into your
1950 =head1 ORDER BY CLAUSES
1952 Some functions take an order by clause. This can either be a scalar (just a
1953 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1954 or an array of either of the two previous forms. Examples:
1956 Given | Will Generate
1957 ----------------------------------------------------------
1958 \'colA DESC' | ORDER BY colA DESC
1959 'colA' | ORDER BY colA
1960 [qw/colA colB/] | ORDER BY colA, colB
1961 {-asc => 'colA'} | ORDER BY colA ASC
1962 {-desc => 'colB'} | ORDER BY colB DESC
1964 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1967 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1968 ==========================================================
1972 =head1 SPECIAL OPERATORS
1974 my $sqlmaker = SQL::Abstract->new(special_ops => [
1977 my ($self, $field, $op, $arg) = @_;
1983 A "special operator" is a SQL syntactic clause that can be
1984 applied to a field, instead of a usual binary operator.
1987 WHERE field IN (?, ?, ?)
1988 WHERE field BETWEEN ? AND ?
1989 WHERE MATCH(field) AGAINST (?, ?)
1991 Special operators IN and BETWEEN are fairly standard and therefore
1992 are builtin within C<SQL::Abstract>. For other operators,
1993 like the MATCH .. AGAINST example above which is
1994 specific to MySQL, you can write your own operator handlers :
1995 supply a C<special_ops> argument to the C<new> method.
1996 That argument takes an arrayref of operator definitions;
1997 each operator definition is a hashref with two entries
2003 the regular expression to match the operator
2007 coderef that will be called when meeting that operator
2008 in the input tree. The coderef will be called with
2009 arguments C<< ($self, $field, $op, $arg) >>, and
2010 should return a C<< ($sql, @bind) >> structure.
2014 For example, here is an implementation
2015 of the MATCH .. AGAINST syntax for MySQL
2017 my $sqlmaker = SQL::Abstract->new(special_ops => [
2019 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2020 {regex => qr/^match$/i,
2022 my ($self, $field, $op, $arg) = @_;
2023 $arg = [$arg] if not ref $arg;
2024 my $label = $self->_quote($field);
2025 my ($placeholder) = $self->_convert('?');
2026 my $placeholders = join ", ", (($placeholder) x @$arg);
2027 my $sql = $self->_sqlcase('match') . " ($label) "
2028 . $self->_sqlcase('against') . " ($placeholders) ";
2029 my @bind = $self->_bindtype($field, @$arg);
2030 return ($sql, @bind);
2039 Thanks to some benchmarking by Mark Stosberg, it turns out that
2040 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2041 I must admit this wasn't an intentional design issue, but it's a
2042 byproduct of the fact that you get to control your C<DBI> handles
2045 To maximize performance, use a code snippet like the following:
2047 # prepare a statement handle using the first row
2048 # and then reuse it for the rest of the rows
2050 for my $href (@array_of_hashrefs) {
2051 $stmt ||= $sql->insert('table', $href);
2052 $sth ||= $dbh->prepare($stmt);
2053 $sth->execute($sql->values($href));
2056 The reason this works is because the keys in your C<$href> are sorted
2057 internally by B<SQL::Abstract>. Thus, as long as your data retains
2058 the same structure, you only have to generate the SQL the first time
2059 around. On subsequent queries, simply use the C<values> function provided
2060 by this module to return your values in the correct order.
2065 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2066 really like this part (I do, at least). Building up a complex query
2067 can be as simple as the following:
2071 use CGI::FormBuilder;
2074 my $form = CGI::FormBuilder->new(...);
2075 my $sql = SQL::Abstract->new;
2077 if ($form->submitted) {
2078 my $field = $form->field;
2079 my $id = delete $field->{id};
2080 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2083 Of course, you would still have to connect using C<DBI> to run the
2084 query, but the point is that if you make your form look like your
2085 table, the actual query script can be extremely simplistic.
2087 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2088 a fast interface to returning and formatting data. I frequently
2089 use these three modules together to write complex database query
2090 apps in under 50 lines.
2095 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2096 Great care has been taken to preserve the I<published> behavior
2097 documented in previous versions in the 1.* family; however,
2098 some features that were previously undocumented, or behaved
2099 differently from the documentation, had to be changed in order
2100 to clarify the semantics. Hence, client code that was relying
2101 on some dark areas of C<SQL::Abstract> v1.*
2102 B<might behave differently> in v1.50.
2104 The main changes are :
2110 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2114 support for the { operator => \"..." } construct (to embed literal SQL)
2118 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2122 added -nest1, -nest2 or -nest_1, -nest_2, ...
2126 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2130 defensive programming : check arguments
2134 fixed bug with global logic, which was previously implemented
2135 through global variables yielding side-effects. Prior versons would
2136 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2137 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2138 Now this is interpreted
2139 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2143 C<-and> / C<-or> operators are no longer accepted
2144 in the middle of an arrayref : they are
2145 only admitted if in first position.
2149 changed logic for distributing an op over arrayrefs
2153 fixed semantics of _bindtype on array args
2157 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2158 we just avoid shifting arrays within that tree.
2162 dropped the C<_modlogic> function
2168 =head1 ACKNOWLEDGEMENTS
2170 There are a number of individuals that have really helped out with
2171 this module. Unfortunately, most of them submitted bugs via CPAN
2172 so I have no idea who they are! But the people I do know are:
2174 Ash Berlin (order_by hash term support)
2175 Matt Trout (DBIx::Class support)
2176 Mark Stosberg (benchmarking)
2177 Chas Owens (initial "IN" operator support)
2178 Philip Collins (per-field SQL functions)
2179 Eric Kolve (hashref "AND" support)
2180 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2181 Dan Kubb (support for "quote_char" and "name_sep")
2182 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2183 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2184 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2190 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2194 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2196 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2198 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2199 While not an official support venue, C<DBIx::Class> makes heavy use of
2200 C<SQL::Abstract>, and as such list members there are very familiar with
2201 how to create queries.
2203 This module is free software; you may copy this under the terms of
2204 the GNU General Public License, or the Artistic License, copies of
2205 which should have accompanied your Perl kit.