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;
701 or puke "special op 'in' requires an arrayref";
703 my ($label) = $self->_convert($self->_quote($k));
704 my ($placeholder) = $self->_convert('?');
705 my $and = $self->_sqlcase('and');
706 $op = $self->_sqlcase($op);
708 if (@$vals) { # nonempty list
709 my $placeholders = join ", ", (($placeholder) x @$vals);
710 my $sql = "$label $op ( $placeholders )";
711 my @bind = $self->_bindtype($k, @$vals);
713 return ($sql, @bind);
715 else { # empty list : some databases won't understand "IN ()", so DWIM
716 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
726 #======================================================================
728 #======================================================================
731 my ($self, $arg) = @_;
733 # construct list of ordering instructions
734 my @order = $self->_SWITCH_refkind($arg, {
737 map {$self->_SWITCH_refkind($_, {
738 SCALAR => sub {$self->_quote($_)},
740 SCALARREF => sub {$$_}, # literal SQL, no quoting
741 HASHREF => sub {$self->_order_by_hash($_)}
745 SCALAR => sub {$self->_quote($arg)},
747 SCALARREF => sub {$$arg}, # literal SQL, no quoting
748 HASHREF => sub {$self->_order_by_hash($arg)},
753 my $order = join ', ', @order;
754 return $order ? $self->_sqlcase(' order by')." $order" : '';
759 my ($self, $hash) = @_;
761 # get first pair in hash
762 my ($key, $val) = each %$hash;
764 # check if one pair was found and no other pair in hash
765 $key && !(each %$hash)
766 or puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
768 my ($order) = ($key =~ /^-(desc|asc)/i)
769 or puke "invalid key in _order_by hash : $key";
771 return $self->_quote($val) ." ". $self->_sqlcase($order);
776 #======================================================================
777 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
778 #======================================================================
783 $self->_SWITCH_refkind($from, {
784 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
785 SCALAR => sub {$self->_quote($from)},
786 SCALARREF => sub {$$from},
787 ARRAYREFREF => sub {join ', ', @$from;},
792 #======================================================================
794 #======================================================================
800 $label or puke "can't quote an empty label";
802 # left and right quote characters
803 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
804 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
805 ARRAYREF => sub {@{$self->{quote_char}}},
809 or puke "quote_char must be an arrayref of 2 values";
811 # no quoting if no quoting chars
812 $ql or return $label;
814 # no quoting for literal SQL
815 return $$label if ref($label) eq 'SCALAR';
817 # separate table / column (if applicable)
818 my $sep = $self->{name_sep} || '';
819 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
821 # do the quoting, except for "*" or for `table`.*
822 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
824 # reassemble and return.
825 return join $sep, @quoted;
829 # Conversion, if applicable
831 my ($self, $arg) = @_;
833 # LDNOTE : modified the previous implementation below because
834 # it was not consistent : the first "return" is always an array,
835 # the second "return" is context-dependent. Anyway, _convert
836 # seems always used with just a single argument, so make it a
838 # return @_ unless $self->{convert};
839 # my $conv = $self->_sqlcase($self->{convert});
840 # my @ret = map { $conv.'('.$_.')' } @_;
841 # return wantarray ? @ret : $ret[0];
842 if ($self->{convert}) {
843 my $conv = $self->_sqlcase($self->{convert});
844 $arg = $conv.'('.$arg.')';
852 my($col, @vals) = @_;
854 #LDNOTE : changed original implementation below because it did not make
855 # sense when bindtype eq 'columns' and @vals > 1.
856 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
858 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
861 sub _join_sql_clauses {
862 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
864 if (@$clauses_aref > 1) {
865 my $join = " " . $self->_sqlcase($logic) . " ";
866 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
867 return ($sql, @$bind_aref);
869 elsif (@$clauses_aref) {
870 return ($clauses_aref->[0], @$bind_aref); # no parentheses
873 return (); # if no SQL, ignore @$bind_aref
878 # Fix SQL case, if so requested
882 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
883 # don't touch the argument ... crooked logic, but let's not change it!
884 return $self->{case} ? $_[0] : uc($_[0]);
888 #======================================================================
889 # DISPATCHING FROM REFKIND
890 #======================================================================
893 my ($self, $data) = @_;
899 # blessed objects are treated like scalars
900 $ref = (blessed $data) ? '' : ref $data;
901 $n_steps += 1 if $ref;
902 last if $ref ne 'REF';
906 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
908 return $base . ('REF' x $n_steps);
914 my ($self, $data) = @_;
915 my @try = ($self->_refkind($data));
916 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
917 push @try, 'FALLBACK';
921 sub _METHOD_FOR_refkind {
922 my ($self, $meth_prefix, $data) = @_;
923 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
924 $self->_try_refkind($data)
925 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
930 sub _SWITCH_refkind {
931 my ($self, $data, $dispatch_table) = @_;
933 my $coderef = first {$_} map {$dispatch_table->{$_}}
934 $self->_try_refkind($data)
935 or puke "no dispatch entry for ".$self->_refkind($data);
942 #======================================================================
943 # VALUES, GENERATE, AUTOLOAD
944 #======================================================================
946 # LDNOTE: original code from nwiger, didn't touch code in that section
947 # I feel the AUTOLOAD stuff should not be the default, it should
948 # only be activated on explicit demand by user.
952 my $data = shift || return;
953 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
954 unless ref $data eq 'HASH';
955 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
961 my(@sql, @sqlq, @sqlv);
965 if ($ref eq 'HASH') {
966 for my $k (sort keys %$_) {
969 my $label = $self->_quote($k);
971 # SQL included for values
973 my $sql = shift @bind;
974 push @sqlq, "$label = $sql";
975 push @sqlv, $self->_bindtype($k, @bind);
976 } elsif ($r eq 'SCALAR') {
977 # embedded literal SQL
978 push @sqlq, "$label = $$v";
980 push @sqlq, "$label = ?";
981 push @sqlv, $self->_bindtype($k, $v);
984 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
985 } elsif ($ref eq 'ARRAY') {
986 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
991 push @sqlq, shift @val;
993 } elsif ($r eq 'SCALAR') {
994 # embedded literal SQL
1001 push @sql, '(' . join(', ', @sqlq) . ')';
1002 } elsif ($ref eq 'SCALAR') {
1006 # strings get case twiddled
1007 push @sql, $self->_sqlcase($_);
1011 my $sql = join ' ', @sql;
1013 # this is pretty tricky
1014 # if ask for an array, return ($stmt, @bind)
1015 # otherwise, s/?/shift @sqlv/ to put it inline
1017 return ($sql, @sqlv);
1019 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1020 ref $d ? $d->[1] : $d/e;
1029 # This allows us to check for a local, then _form, attr
1031 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1032 return $self->generate($name, @_);
1043 SQL::Abstract - Generate SQL from Perl data structures
1049 my $sql = SQL::Abstract->new;
1051 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1053 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1055 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1057 my($stmt, @bind) = $sql->delete($table, \%where);
1059 # Then, use these in your DBI statements
1060 my $sth = $dbh->prepare($stmt);
1061 $sth->execute(@bind);
1063 # Just generate the WHERE clause
1064 my($stmt, @bind) = $sql->where(\%where, \@order);
1066 # Return values in the same order, for hashed queries
1067 # See PERFORMANCE section for more details
1068 my @bind = $sql->values(\%fieldvals);
1072 This module was inspired by the excellent L<DBIx::Abstract>.
1073 However, in using that module I found that what I really wanted
1074 to do was generate SQL, but still retain complete control over my
1075 statement handles and use the DBI interface. So, I set out to
1076 create an abstract SQL generation module.
1078 While based on the concepts used by L<DBIx::Abstract>, there are
1079 several important differences, especially when it comes to WHERE
1080 clauses. I have modified the concepts used to make the SQL easier
1081 to generate from Perl data structures and, IMO, more intuitive.
1082 The underlying idea is for this module to do what you mean, based
1083 on the data structures you provide it. The big advantage is that
1084 you don't have to modify your code every time your data changes,
1085 as this module figures it out.
1087 To begin with, an SQL INSERT is as easy as just specifying a hash
1088 of C<key=value> pairs:
1091 name => 'Jimbo Bobson',
1092 phone => '123-456-7890',
1093 address => '42 Sister Lane',
1094 city => 'St. Louis',
1095 state => 'Louisiana',
1098 The SQL can then be generated with this:
1100 my($stmt, @bind) = $sql->insert('people', \%data);
1102 Which would give you something like this:
1104 $stmt = "INSERT INTO people
1105 (address, city, name, phone, state)
1106 VALUES (?, ?, ?, ?, ?)";
1107 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1108 '123-456-7890', 'Louisiana');
1110 These are then used directly in your DBI code:
1112 my $sth = $dbh->prepare($stmt);
1113 $sth->execute(@bind);
1115 =head2 Inserting and Updating Arrays
1117 If your database has array types (like for example Postgres),
1118 activate the special option C<< array_datatypes => 1 >>
1119 when creating the C<SQL::Abstract> object.
1120 Then you may use an arrayref to insert and update database array types:
1122 my $sql = SQL::Abstract->new(array_datatypes => 1);
1124 planets => [qw/Mercury Venus Earth Mars/]
1127 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1131 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1133 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1136 =head2 Inserting and Updating SQL
1138 In order to apply SQL functions to elements of your C<%data> you may
1139 specify a reference to an arrayref for the given hash value. For example,
1140 if you need to execute the Oracle C<to_date> function on a value, you can
1141 say something like this:
1145 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1148 The first value in the array is the actual SQL. Any other values are
1149 optional and would be included in the bind values array. This gives
1152 my($stmt, @bind) = $sql->insert('people', \%data);
1154 $stmt = "INSERT INTO people (name, date_entered)
1155 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1156 @bind = ('Bill', '03/02/2003');
1158 An UPDATE is just as easy, all you change is the name of the function:
1160 my($stmt, @bind) = $sql->update('people', \%data);
1162 Notice that your C<%data> isn't touched; the module will generate
1163 the appropriately quirky SQL for you automatically. Usually you'll
1164 want to specify a WHERE clause for your UPDATE, though, which is
1165 where handling C<%where> hashes comes in handy...
1167 =head2 Complex where statements
1169 This module can generate pretty complicated WHERE statements
1170 easily. For example, simple C<key=value> pairs are taken to mean
1171 equality, and if you want to see if a field is within a set
1172 of values, you can use an arrayref. Let's say we wanted to
1173 SELECT some data based on this criteria:
1176 requestor => 'inna',
1177 worker => ['nwiger', 'rcwe', 'sfz'],
1178 status => { '!=', 'completed' }
1181 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1183 The above would give you something like this:
1185 $stmt = "SELECT * FROM tickets WHERE
1186 ( requestor = ? ) AND ( status != ? )
1187 AND ( worker = ? OR worker = ? OR worker = ? )";
1188 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1190 Which you could then use in DBI code like so:
1192 my $sth = $dbh->prepare($stmt);
1193 $sth->execute(@bind);
1199 The functions are simple. There's one for each major SQL operation,
1200 and a constructor you use first. The arguments are specified in a
1201 similar order to each function (table, then fields, then a where
1202 clause) to try and simplify things.
1207 =head2 new(option => 'value')
1209 The C<new()> function takes a list of options and values, and returns
1210 a new B<SQL::Abstract> object which can then be used to generate SQL
1211 through the methods below. The options accepted are:
1217 If set to 'lower', then SQL will be generated in all lowercase. By
1218 default SQL is generated in "textbook" case meaning something like:
1220 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1222 Any setting other than 'lower' is ignored.
1226 This determines what the default comparison operator is. By default
1227 it is C<=>, meaning that a hash like this:
1229 %where = (name => 'nwiger', email => 'nate@wiger.org');
1231 Will generate SQL like this:
1233 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1235 However, you may want loose comparisons by default, so if you set
1236 C<cmp> to C<like> you would get SQL such as:
1238 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1240 You can also override the comparsion on an individual basis - see
1241 the huge section on L</"WHERE CLAUSES"> at the bottom.
1243 =item sqltrue, sqlfalse
1245 Expressions for inserting boolean values within SQL statements.
1246 By default these are C<1=1> and C<1=0>.
1250 This determines the default logical operator for multiple WHERE
1251 statements in arrays. By default it is "or", meaning that a WHERE
1255 event_date => {'>=', '2/13/99'},
1256 event_date => {'<=', '4/24/03'},
1259 Will generate SQL like this:
1261 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1263 This is probably not what you want given this query, though (look
1264 at the dates). To change the "OR" to an "AND", simply specify:
1266 my $sql = SQL::Abstract->new(logic => 'and');
1268 Which will change the above C<WHERE> to:
1270 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1272 The logic can also be changed locally by inserting
1273 an extra first element in the array :
1275 @where = (-and => event_date => {'>=', '2/13/99'},
1276 event_date => {'<=', '4/24/03'} );
1278 See the L</"WHERE CLAUSES"> section for explanations.
1282 This will automatically convert comparisons using the specified SQL
1283 function for both column and value. This is mostly used with an argument
1284 of C<upper> or C<lower>, so that the SQL will have the effect of
1285 case-insensitive "searches". For example, this:
1287 $sql = SQL::Abstract->new(convert => 'upper');
1288 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1290 Will turn out the following SQL:
1292 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1294 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1295 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1296 not validate this option; it will just pass through what you specify verbatim).
1300 This is a kludge because many databases suck. For example, you can't
1301 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1302 Instead, you have to use C<bind_param()>:
1304 $sth->bind_param(1, 'reg data');
1305 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1307 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1308 which loses track of which field each slot refers to. Fear not.
1310 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1311 Currently, you can specify either C<normal> (default) or C<columns>. If you
1312 specify C<columns>, you will get an array that looks like this:
1314 my $sql = SQL::Abstract->new(bindtype => 'columns');
1315 my($stmt, @bind) = $sql->insert(...);
1318 [ 'column1', 'value1' ],
1319 [ 'column2', 'value2' ],
1320 [ 'column3', 'value3' ],
1323 You can then iterate through this manually, using DBI's C<bind_param()>.
1325 $sth->prepare($stmt);
1328 my($col, $data) = @$_;
1329 if ($col eq 'details' || $col eq 'comments') {
1330 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1331 } elsif ($col eq 'image') {
1332 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1334 $sth->bind_param($i, $data);
1338 $sth->execute; # execute without @bind now
1340 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1341 Basically, the advantage is still that you don't have to care which fields
1342 are or are not included. You could wrap that above C<for> loop in a simple
1343 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1344 get a layer of abstraction over manual SQL specification.
1348 This is the character that a table or column name will be quoted
1349 with. By default this is an empty string, but you could set it to
1350 the character C<`>, to generate SQL like this:
1352 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1354 Alternatively, you can supply an array ref of two items, the first being the left
1355 hand quote character, and the second the right hand quote character. For
1356 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1357 that generates SQL like this:
1359 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1361 Quoting is useful if you have tables or columns names that are reserved
1362 words in your database's SQL dialect.
1366 This is the character that separates a table and column name. It is
1367 necessary to specify this when the C<quote_char> option is selected,
1368 so that tables and column names can be individually quoted like this:
1370 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1372 =item array_datatypes
1374 When this option is true, arrayrefs in INSERT or UPDATE are
1375 interpreted as array datatypes and are passed directly
1377 When this option is false, arrayrefs are interpreted
1378 as literal SQL, just like refs to arrayrefs
1379 (but this behavior is for backwards compatibility; when writing
1380 new queries, use the "reference to arrayref" syntax
1386 Takes a reference to a list of "special operators"
1387 to extend the syntax understood by L<SQL::Abstract>.
1388 See section L</"SPECIAL OPERATORS"> for details.
1394 =head2 insert($table, \@values || \%fieldvals)
1396 This is the simplest function. You simply give it a table name
1397 and either an arrayref of values or hashref of field/value pairs.
1398 It returns an SQL INSERT statement and a list of bind values.
1399 See the sections on L</"Inserting and Updating Arrays"> and
1400 L</"Inserting and Updating SQL"> for information on how to insert
1401 with those data types.
1403 =head2 update($table, \%fieldvals, \%where)
1405 This takes a table, hashref of field/value pairs, and an optional
1406 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1408 See the sections on L</"Inserting and Updating Arrays"> and
1409 L</"Inserting and Updating SQL"> for information on how to insert
1410 with those data types.
1412 =head2 select($source, $fields, $where, $order)
1414 This returns a SQL SELECT statement and associated list of bind values, as
1415 specified by the arguments :
1421 Specification of the 'FROM' part of the statement.
1422 The argument can be either a plain scalar (interpreted as a table
1423 name, will be quoted), or an arrayref (interpreted as a list
1424 of table names, joined by commas, quoted), or a scalarref
1425 (literal table name, not quoted), or a ref to an arrayref
1426 (list of literal table names, joined by commas, not quoted).
1430 Specification of the list of fields to retrieve from
1432 The argument can be either an arrayref (interpreted as a list
1433 of field names, will be joined by commas and quoted), or a
1434 plain scalar (literal SQL, not quoted).
1435 Please observe that this API is not as flexible as for
1436 the first argument C<$table>, for backwards compatibility reasons.
1440 Optional argument to specify the WHERE part of the query.
1441 The argument is most often a hashref, but can also be
1442 an arrayref or plain scalar --
1443 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1447 Optional argument to specify the ORDER BY part of the query.
1448 The argument can be a scalar, a hashref or an arrayref
1449 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1455 =head2 delete($table, \%where)
1457 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1458 It returns an SQL DELETE statement and list of bind values.
1460 =head2 where(\%where, \@order)
1462 This is used to generate just the WHERE clause. For example,
1463 if you have an arbitrary data structure and know what the
1464 rest of your SQL is going to look like, but want an easy way
1465 to produce a WHERE clause, use this. It returns an SQL WHERE
1466 clause and list of bind values.
1469 =head2 values(\%data)
1471 This just returns the values from the hash C<%data>, in the same
1472 order that would be returned from any of the other above queries.
1473 Using this allows you to markedly speed up your queries if you
1474 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1476 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1478 Warning: This is an experimental method and subject to change.
1480 This returns arbitrarily generated SQL. It's a really basic shortcut.
1481 It will return two different things, depending on return context:
1483 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1484 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1486 These would return the following:
1488 # First calling form
1489 $stmt = "CREATE TABLE test (?, ?)";
1490 @bind = (field1, field2);
1492 # Second calling form
1493 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1495 Depending on what you're trying to do, it's up to you to choose the correct
1496 format. In this example, the second form is what you would want.
1500 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1504 ALTER SESSION SET nls_date_format = 'MM/YY'
1506 You get the idea. Strings get their case twiddled, but everything
1507 else remains verbatim.
1512 =head1 WHERE CLAUSES
1516 This module uses a variation on the idea from L<DBIx::Abstract>. It
1517 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1518 module is that things in arrays are OR'ed, and things in hashes
1521 The easiest way to explain is to show lots of examples. After
1522 each C<%where> hash shown, it is assumed you used:
1524 my($stmt, @bind) = $sql->where(\%where);
1526 However, note that the C<%where> hash can be used directly in any
1527 of the other functions as well, as described above.
1529 =head2 Key-value pairs
1531 So, let's get started. To begin, a simple hash:
1535 status => 'completed'
1538 Is converted to SQL C<key = val> statements:
1540 $stmt = "WHERE user = ? AND status = ?";
1541 @bind = ('nwiger', 'completed');
1543 One common thing I end up doing is having a list of values that
1544 a field can be in. To do this, simply specify a list inside of
1549 status => ['assigned', 'in-progress', 'pending'];
1552 This simple code will create the following:
1554 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1555 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1557 An empty arrayref will be considered a logical false and
1560 =head2 Key-value pairs
1562 If you want to specify a different type of operator for your comparison,
1563 you can use a hashref for a given column:
1567 status => { '!=', 'completed' }
1570 Which would generate:
1572 $stmt = "WHERE user = ? AND status != ?";
1573 @bind = ('nwiger', 'completed');
1575 To test against multiple values, just enclose the values in an arrayref:
1577 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1579 Which would give you:
1581 "WHERE status != ? AND status != ? AND status != ?"
1583 Notice that since the operator was recognized as being a 'negative'
1584 operator, the arrayref was interpreted with 'AND' logic (because
1585 of Morgan's laws). By contrast, the reverse
1587 status => { '=', ['assigned', 'in-progress', 'pending'] };
1591 "WHERE status = ? OR status = ? OR status = ?"
1594 The hashref can also contain multiple pairs, in which case it is expanded
1595 into an C<AND> of its elements:
1599 status => { '!=', 'completed', -not_like => 'pending%' }
1602 # Or more dynamically, like from a form
1603 $where{user} = 'nwiger';
1604 $where{status}{'!='} = 'completed';
1605 $where{status}{'-not_like'} = 'pending%';
1607 # Both generate this
1608 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1609 @bind = ('nwiger', 'completed', 'pending%');
1612 To get an OR instead, you can combine it with the arrayref idea:
1616 priority => [ {'=', 2}, {'!=', 1} ]
1619 Which would generate:
1621 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1622 @bind = ('nwiger', '2', '1');
1624 If you want to include literal SQL (with or without bind values), just use a
1625 scalar reference or array reference as the value:
1628 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1629 date_expires => { '<' => \"now()" }
1632 Which would generate:
1634 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1635 @bind = ('11/26/2008');
1638 =head2 Logic and nesting operators
1640 In the example above,
1641 there is a subtle trap if you want to say something like
1642 this (notice the C<AND>):
1644 WHERE priority != ? AND priority != ?
1646 Because, in Perl you I<can't> do this:
1648 priority => { '!=', 2, '!=', 1 }
1650 As the second C<!=> key will obliterate the first. The solution
1651 is to use the special C<-modifier> form inside an arrayref:
1653 priority => [ -and => {'!=', 2},
1657 Normally, these would be joined by C<OR>, but the modifier tells it
1658 to use C<AND> instead. (Hint: You can use this in conjunction with the
1659 C<logic> option to C<new()> in order to change the way your queries
1660 work by default.) B<Important:> Note that the C<-modifier> goes
1661 B<INSIDE> the arrayref, as an extra first element. This will
1662 B<NOT> do what you think it might:
1664 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1666 Here is a quick list of equivalencies, since there is some overlap:
1669 status => {'!=', 'completed', 'not like', 'pending%' }
1670 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1673 status => {'=', ['assigned', 'in-progress']}
1674 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1675 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1677 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1678 operator which adds an additional set of parens, to create a subquery.
1679 For example, to get something like this:
1681 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1682 @bind = ('nwiger', '20', 'ASIA');
1688 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1691 If you need several nested subexpressions, you can number
1692 the C<-nest> branches :
1702 =head2 Special operators : IN, BETWEEN, etc.
1704 You can also use the hashref format to compare a list of fields using the
1705 C<IN> comparison operator, by specifying the list as an arrayref:
1708 status => 'completed',
1709 reportid => { -in => [567, 2335, 2] }
1712 Which would generate:
1714 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1715 @bind = ('completed', '567', '2335', '2');
1717 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1720 Another pair of operators is C<-between> and C<-not_between>,
1721 used with an arrayref of two values:
1725 completion_date => {
1726 -not_between => ['2002-10-01', '2003-02-06']
1732 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1734 These are the two builtin "special operators"; but the
1735 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1737 =head2 Nested conditions
1739 So far, we've seen how multiple conditions are joined with a top-level
1740 C<AND>. We can change this by putting the different conditions we want in
1741 hashes and then putting those hashes in an array. For example:
1746 status => { -like => ['pending%', 'dispatched'] },
1750 status => 'unassigned',
1754 This data structure would create the following:
1756 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1757 OR ( user = ? AND status = ? ) )";
1758 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1760 This can be combined with the C<-nest> operator to properly group
1767 ["-and", workhrs => {'>', 20}, geo => 'ASIA' ],
1768 ["-and", workhrs => {'<', 50}, geo => 'EURO' ]
1775 WHERE ( user = ? AND
1776 ( ( workhrs > ? AND geo = ? )
1777 OR ( workhrs < ? AND geo = ? ) ) )
1781 Finally, sometimes only literal SQL will do. If you want to include
1782 literal SQL verbatim, you can specify it as a scalar reference, namely:
1784 my $inn = 'is Not Null';
1786 priority => { '<', 2 },
1792 $stmt = "WHERE priority < ? AND requestor is Not Null";
1795 Note that in this example, you only get one bind parameter back, since
1796 the verbatim SQL is passed as part of the statement.
1798 Of course, just to prove a point, the above can also be accomplished
1802 priority => { '<', 2 },
1803 requestor => { '!=', undef },
1809 Conditions on boolean columns can be expressed in the
1810 same way, passing a reference to an empty string :
1813 priority => { '<', 2 },
1819 $stmt = "WHERE priority < ? AND is_ready";
1823 =head2 Literal SQL with placeholders and bind values (subqueries)
1825 If the literal SQL to be inserted has placeholders and bind values,
1826 use a reference to an arrayref (yes this is a double reference --
1827 not so common, but perfectly legal Perl). For example, to find a date
1828 in Postgres you can use something like this:
1831 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1836 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1840 Literal SQL is especially useful for nesting parenthesized clauses in the
1841 main SQL query. Here is a first example :
1843 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1847 bar => \["IN ($sub_stmt)" => @sub_bind],
1852 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1853 WHERE c2 < ? AND c3 LIKE ?))";
1854 @bind = (1234, 100, "foo%");
1856 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
1857 are expressed in the same way. Of course the C<$sub_stmt> and
1858 its associated bind values can be generated through a former call
1861 my ($sub_stmt, @sub_bind)
1862 = $sql->select("t1", "c1", {c2 => {"<" => 100},
1863 c3 => {-like => "foo%"}});
1866 bar => \["> ALL ($sub_stmt)" => @sub_bind],
1869 In the examples above, the subquery was used as an operator on a column;
1870 but the same principle also applies for a clause within the main C<%where>
1871 hash, like an EXISTS subquery :
1873 my ($sub_stmt, @sub_bind)
1874 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1877 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
1882 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1883 WHERE c1 = ? AND c2 > t0.c0))";
1887 Observe that the condition on C<c2> in the subquery refers to
1888 column C<t0.c0> of the main query : this is I<not> a bind
1889 value, so we have to express it through a scalar ref.
1890 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
1891 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
1892 what we wanted here.
1894 Another use of the subquery technique is when some SQL clauses need
1895 parentheses, as it often occurs with some proprietary SQL extensions
1896 like for example fulltext expressions, geospatial expressions,
1897 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
1900 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
1903 Finally, here is an example where a subquery is used
1904 for expressing unary negation:
1906 my ($sub_stmt, @sub_bind)
1907 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
1908 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
1910 lname => {like => '%son%'},
1911 -nest => \["NOT ($sub_stmt)" => @sub_bind],
1916 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1917 @bind = ('%son%', 10, 20)
1923 These pages could go on for a while, since the nesting of the data
1924 structures this module can handle are pretty much unlimited (the
1925 module implements the C<WHERE> expansion as a recursive function
1926 internally). Your best bet is to "play around" with the module a
1927 little to see how the data structures behave, and choose the best
1928 format for your data based on that.
1930 And of course, all the values above will probably be replaced with
1931 variables gotten from forms or the command line. After all, if you
1932 knew everything ahead of time, you wouldn't have to worry about
1933 dynamically-generating SQL and could just hardwire it into your
1939 =head1 ORDER BY CLAUSES
1941 Some functions take an order by clause. This can either be a scalar (just a
1942 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1943 or an array of either of the two previous forms. Examples:
1945 Given | Will Generate
1946 ----------------------------------------------------------
1947 \'colA DESC' | ORDER BY colA DESC
1948 'colA' | ORDER BY colA
1949 [qw/colA colB/] | ORDER BY colA, colB
1950 {-asc => 'colA'} | ORDER BY colA ASC
1951 {-desc => 'colB'} | ORDER BY colB DESC
1953 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1956 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1957 ==========================================================
1961 =head1 SPECIAL OPERATORS
1963 my $sqlmaker = SQL::Abstract->new(special_ops => [
1966 my ($self, $field, $op, $arg) = @_;
1972 A "special operator" is a SQL syntactic clause that can be
1973 applied to a field, instead of a usual binary operator.
1976 WHERE field IN (?, ?, ?)
1977 WHERE field BETWEEN ? AND ?
1978 WHERE MATCH(field) AGAINST (?, ?)
1980 Special operators IN and BETWEEN are fairly standard and therefore
1981 are builtin within C<SQL::Abstract>. For other operators,
1982 like the MATCH .. AGAINST example above which is
1983 specific to MySQL, you can write your own operator handlers :
1984 supply a C<special_ops> argument to the C<new> method.
1985 That argument takes an arrayref of operator definitions;
1986 each operator definition is a hashref with two entries
1992 the regular expression to match the operator
1996 coderef that will be called when meeting that operator
1997 in the input tree. The coderef will be called with
1998 arguments C<< ($self, $field, $op, $arg) >>, and
1999 should return a C<< ($sql, @bind) >> structure.
2003 For example, here is an implementation
2004 of the MATCH .. AGAINST syntax for MySQL
2006 my $sqlmaker = SQL::Abstract->new(special_ops => [
2008 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2009 {regex => qr/^match$/i,
2011 my ($self, $field, $op, $arg) = @_;
2012 $arg = [$arg] if not ref $arg;
2013 my $label = $self->_quote($field);
2014 my ($placeholder) = $self->_convert('?');
2015 my $placeholders = join ", ", (($placeholder) x @$arg);
2016 my $sql = $self->_sqlcase('match') . " ($label) "
2017 . $self->_sqlcase('against') . " ($placeholders) ";
2018 my @bind = $self->_bindtype($field, @$arg);
2019 return ($sql, @bind);
2028 Thanks to some benchmarking by Mark Stosberg, it turns out that
2029 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2030 I must admit this wasn't an intentional design issue, but it's a
2031 byproduct of the fact that you get to control your C<DBI> handles
2034 To maximize performance, use a code snippet like the following:
2036 # prepare a statement handle using the first row
2037 # and then reuse it for the rest of the rows
2039 for my $href (@array_of_hashrefs) {
2040 $stmt ||= $sql->insert('table', $href);
2041 $sth ||= $dbh->prepare($stmt);
2042 $sth->execute($sql->values($href));
2045 The reason this works is because the keys in your C<$href> are sorted
2046 internally by B<SQL::Abstract>. Thus, as long as your data retains
2047 the same structure, you only have to generate the SQL the first time
2048 around. On subsequent queries, simply use the C<values> function provided
2049 by this module to return your values in the correct order.
2054 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2055 really like this part (I do, at least). Building up a complex query
2056 can be as simple as the following:
2060 use CGI::FormBuilder;
2063 my $form = CGI::FormBuilder->new(...);
2064 my $sql = SQL::Abstract->new;
2066 if ($form->submitted) {
2067 my $field = $form->field;
2068 my $id = delete $field->{id};
2069 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2072 Of course, you would still have to connect using C<DBI> to run the
2073 query, but the point is that if you make your form look like your
2074 table, the actual query script can be extremely simplistic.
2076 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2077 a fast interface to returning and formatting data. I frequently
2078 use these three modules together to write complex database query
2079 apps in under 50 lines.
2084 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2085 Great care has been taken to preserve the I<published> behavior
2086 documented in previous versions in the 1.* family; however,
2087 some features that were previously undocumented, or behaved
2088 differently from the documentation, had to be changed in order
2089 to clarify the semantics. Hence, client code that was relying
2090 on some dark areas of C<SQL::Abstract> v1.*
2091 B<might behave differently> in v1.50.
2093 The main changes are :
2099 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2103 support for the { operator => \"..." } construct (to embed literal SQL)
2107 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2111 added -nest1, -nest2 or -nest_1, -nest_2, ...
2115 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2119 defensive programming : check arguments
2123 fixed bug with global logic, which was previously implemented
2124 through global variables yielding side-effects. Prior versons would
2125 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2126 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2127 Now this is interpreted
2128 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2132 C<-and> / C<-or> operators are no longer accepted
2133 in the middle of an arrayref : they are
2134 only admitted if in first position.
2138 changed logic for distributing an op over arrayrefs
2142 fixed semantics of _bindtype on array args
2146 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2147 we just avoid shifting arrays within that tree.
2151 dropped the C<_modlogic> function
2157 =head1 ACKNOWLEDGEMENTS
2159 There are a number of individuals that have really helped out with
2160 this module. Unfortunately, most of them submitted bugs via CPAN
2161 so I have no idea who they are! But the people I do know are:
2163 Ash Berlin (order_by hash term support)
2164 Matt Trout (DBIx::Class support)
2165 Mark Stosberg (benchmarking)
2166 Chas Owens (initial "IN" operator support)
2167 Philip Collins (per-field SQL functions)
2168 Eric Kolve (hashref "AND" support)
2169 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2170 Dan Kubb (support for "quote_char" and "name_sep")
2171 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2172 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2173 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2179 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2183 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2185 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2187 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2188 While not an official support venue, C<DBIx::Class> makes heavy use of
2189 C<SQL::Abstract>, and as such list members there are very familiar with
2190 how to create queries.
2192 This module is free software; you may copy this under the terms of
2193 the GNU General Public License, or the Artistic License, copies of
2194 which should have accompanied your Perl kit.