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.56';
20 # This would confuse some packagers
21 #$VERSION = eval $VERSION; # numify for warning-free dev releases
25 # special operators (-in, -between). May be extended/overridden by user.
26 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
27 my @BUILTIN_SPECIAL_OPS = (
28 {regex => qr/^(not )?between$/i, handler => '_where_field_BETWEEN'},
29 {regex => qr/^(not )?in$/i, handler => '_where_field_IN'},
32 # unaryish operators - key maps to handler
33 my @BUILTIN_UNARY_OPS = (
34 { regex => qr/^and (\s? \d+)?$/xi, handler => '_where_op_ANDOR', numchk => 1 },
35 { regex => qr/^or (\s? \d+)?$/xi, handler => '_where_op_ANDOR', numchk => 1 },
36 { regex => qr/^nest (\s? \d+)?$/xi, handler => '_where_op_NEST', numchk => 1 },
37 { regex => qr/^(not \s?)? bool$/xi, handler => '_where_op_BOOL' },
40 #======================================================================
41 # DEBUGGING AND ERROR REPORTING
42 #======================================================================
45 return unless $_[0]->{debug}; shift; # a little faster
46 my $func = (caller(1))[3];
47 warn "[$func] ", @_, "\n";
51 my($func) = (caller(1))[3];
52 carp "[$func] Warning: ", @_;
56 my($func) = (caller(1))[3];
57 croak "[$func] Fatal: ", @_;
61 #======================================================================
63 #======================================================================
67 my $class = ref($self) || $self;
68 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
70 # choose our case by keeping an option around
71 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
73 # default logic for interpreting arrayrefs
74 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
76 # how to return bind vars
77 # LDNOTE: changed nwiger code : why this 'delete' ??
78 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
79 $opt{bindtype} ||= 'normal';
81 # default comparison is "=", but can be overridden
84 # try to recognize which are the 'equality' and 'unequality' ops
85 # (temporary quickfix, should go through a more seasoned API)
86 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
87 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
90 $opt{sqltrue} ||= '1=1';
91 $opt{sqlfalse} ||= '0=1';
94 $opt{special_ops} ||= [];
95 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
98 $opt{unary_ops} ||= [];
99 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
101 return bless \%opt, $class;
106 #======================================================================
108 #======================================================================
112 my $table = $self->_table(shift);
113 my $data = shift || return;
115 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
116 my ($sql, @bind) = $self->$method($data);
117 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
118 return wantarray ? ($sql, @bind) : $sql;
121 sub _insert_HASHREF { # explicit list of fields and then values
122 my ($self, $data) = @_;
124 my @fields = sort keys %$data;
126 my ($sql, @bind) = $self->_insert_values($data);
129 $_ = $self->_quote($_) foreach @fields;
130 $sql = "( ".join(", ", @fields).") ".$sql;
132 return ($sql, @bind);
135 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
136 my ($self, $data) = @_;
138 # no names (arrayref) so can't generate bindtype
139 $self->{bindtype} ne 'columns'
140 or belch "can't do 'columns' bindtype when called with arrayref";
142 # fold the list of values into a hash of column name - value pairs
143 # (where the column names are artificially generated, and their
144 # lexicographical ordering keep the ordering of the original list)
145 my $i = "a"; # incremented values will be in lexicographical order
146 my $data_in_hash = { map { ($i++ => $_) } @$data };
148 return $self->_insert_values($data_in_hash);
151 sub _insert_ARRAYREFREF { # literal SQL with bind
152 my ($self, $data) = @_;
154 my ($sql, @bind) = @${$data};
155 $self->_assert_bindval_matches_bindtype(@bind);
157 return ($sql, @bind);
161 sub _insert_SCALARREF { # literal SQL without bind
162 my ($self, $data) = @_;
168 my ($self, $data) = @_;
170 my (@values, @all_bind);
171 foreach my $column (sort keys %$data) {
172 my $v = $data->{$column};
174 $self->_SWITCH_refkind($v, {
177 if ($self->{array_datatypes}) { # if array datatype are activated
179 push @all_bind, $self->_bindtype($column, $v);
181 else { # else literal SQL with bind
182 my ($sql, @bind) = @$v;
183 $self->_assert_bindval_matches_bindtype(@bind);
185 push @all_bind, @bind;
189 ARRAYREFREF => sub { # literal SQL with bind
190 my ($sql, @bind) = @${$v};
191 $self->_assert_bindval_matches_bindtype(@bind);
193 push @all_bind, @bind;
196 # THINK : anything useful to do with a HASHREF ?
197 HASHREF => sub { # (nothing, but old SQLA passed it through)
198 #TODO in SQLA >= 2.0 it will die instead
199 belch "HASH ref as bind value in insert is not supported";
201 push @all_bind, $self->_bindtype($column, $v);
204 SCALARREF => sub { # literal SQL without bind
208 SCALAR_or_UNDEF => sub {
210 push @all_bind, $self->_bindtype($column, $v);
217 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
218 return ($sql, @all_bind);
223 #======================================================================
225 #======================================================================
230 my $table = $self->_table(shift);
231 my $data = shift || return;
234 # first build the 'SET' part of the sql statement
235 my (@set, @all_bind);
236 puke "Unsupported data type specified to \$sql->update"
237 unless ref $data eq 'HASH';
239 for my $k (sort keys %$data) {
242 my $label = $self->_quote($k);
244 $self->_SWITCH_refkind($v, {
246 if ($self->{array_datatypes}) { # array datatype
247 push @set, "$label = ?";
248 push @all_bind, $self->_bindtype($k, $v);
250 else { # literal SQL with bind
251 my ($sql, @bind) = @$v;
252 $self->_assert_bindval_matches_bindtype(@bind);
253 push @set, "$label = $sql";
254 push @all_bind, @bind;
257 ARRAYREFREF => sub { # literal SQL with bind
258 my ($sql, @bind) = @${$v};
259 $self->_assert_bindval_matches_bindtype(@bind);
260 push @set, "$label = $sql";
261 push @all_bind, @bind;
263 SCALARREF => sub { # literal SQL without bind
264 push @set, "$label = $$v";
266 SCALAR_or_UNDEF => sub {
267 push @set, "$label = ?";
268 push @all_bind, $self->_bindtype($k, $v);
274 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
278 my($where_sql, @where_bind) = $self->where($where);
280 push @all_bind, @where_bind;
283 return wantarray ? ($sql, @all_bind) : $sql;
289 #======================================================================
291 #======================================================================
296 my $table = $self->_table(shift);
297 my $fields = shift || '*';
301 my($where_sql, @bind) = $self->where($where, $order);
303 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
305 my $sql = join(' ', $self->_sqlcase('select'), $f,
306 $self->_sqlcase('from'), $table)
309 return wantarray ? ($sql, @bind) : $sql;
312 #======================================================================
314 #======================================================================
319 my $table = $self->_table(shift);
323 my($where_sql, @bind) = $self->where($where);
324 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
326 return wantarray ? ($sql, @bind) : $sql;
330 #======================================================================
332 #======================================================================
336 # Finally, a separate routine just to handle WHERE clauses
338 my ($self, $where, $order) = @_;
341 my ($sql, @bind) = $self->_recurse_where($where);
342 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
346 $sql .= $self->_order_by($order);
349 return wantarray ? ($sql, @bind) : $sql;
354 my ($self, $where, $logic) = @_;
356 # dispatch on appropriate method according to refkind of $where
357 my $method = $self->_METHOD_FOR_refkind("_where", $where);
360 my ($sql, @bind) = $self->$method($where, $logic);
362 # DBIx::Class directly calls _recurse_where in scalar context, so
363 # we must implement it, even if not in the official API
364 return wantarray ? ($sql, @bind) : $sql;
369 #======================================================================
370 # WHERE: top-level ARRAYREF
371 #======================================================================
374 sub _where_ARRAYREF {
375 my ($self, $where, $logic) = @_;
377 $logic = uc($logic || $self->{logic});
378 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
380 my @clauses = @$where;
382 my (@sql_clauses, @all_bind);
383 # need to use while() so can shift() for pairs
384 while (my $el = shift @clauses) {
386 # switch according to kind of $el and get corresponding ($sql, @bind)
387 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
389 # skip empty elements, otherwise get invalid trailing AND stuff
390 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
392 ARRAYREFREF => sub { @{${$el}} if @{${$el}}},
394 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
395 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
396 # side-effect: the first hashref within an array would change
397 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
398 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
399 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
401 SCALARREF => sub { ($$el); },
403 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
404 $self->_recurse_where({$el => shift(@clauses)})},
406 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
410 push @sql_clauses, $sql;
411 push @all_bind, @bind;
415 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
418 #======================================================================
419 # WHERE: top-level ARRAYREFREF
420 #======================================================================
422 sub _where_ARRAYREFREF {
423 my ($self, $where) = @_;
424 my ($sql, @bind) = @{${$where}};
426 return ($sql, @bind);
429 #======================================================================
430 # WHERE: top-level HASHREF
431 #======================================================================
434 my ($self, $where) = @_;
435 my (@sql_clauses, @all_bind);
437 for my $k (sort keys %$where) {
438 my $v = $where->{$k};
440 # ($k => $v) is either a special op or a regular hashpair
441 my ($sql, @bind) = ($k =~ /^-(.+)/) ? $self->_where_op_in_hash($1, $v)
443 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
444 $self->$method($k, $v);
447 push @sql_clauses, $sql;
448 push @all_bind, @bind;
451 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
455 sub _where_op_in_hash {
456 my ($self, $op, $v) = @_;
458 # put the operator in canonical form
459 $op =~ s/^-//; # remove initial dash
460 $op =~ tr/_ \t/ /s; # underscores and whitespace become single spaces
462 $self->_debug("OP(-$op) within hashref, recursing...");
464 my $op_entry = first {$op =~ $_->{regex}} @{$self->{unary_ops}};
465 my $handler = $op_entry->{handler};
467 puke "unknown operator: -$op";
469 elsif (not ref $handler) {
470 if ($op_entry->{numchk} && ($op =~ s/\s?\d+$//)) {
471 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
472 . "You probably wanted ...-and => [ $op => COND1, $op => COND2 ... ]";
474 return $self->$handler ($op, $v);
476 elsif (ref $handler eq 'CODE') {
477 return $handler->($self, $op, $v);
480 puke "Illegal handler for operator $op - expecting a method name or a coderef";
484 sub _where_op_ANDOR {
485 my ($self, $op, $v) = @_;
487 $self->_SWITCH_refkind($v, {
489 return $self->_where_ARRAYREF($v, $op);
493 return ( $op =~ /^or/i )
494 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
495 : $self->_where_HASHREF($v);
499 puke "-$op => \\\$scalar not supported, use -nest => ...";
503 puke "-$op => \\[..] not supported, use -nest => ...";
506 SCALAR => sub { # permissively interpreted as SQL
507 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
511 puke "-$op => undef not supported";
517 my ($self, $op, $v) = @_;
519 $self->_SWITCH_refkind($v, {
522 return $self->_where_ARRAYREF($v, '');
526 return $self->_where_HASHREF($v);
529 SCALARREF => sub { # literal SQL
533 ARRAYREFREF => sub { # literal SQL
537 SCALAR => sub { # permissively interpreted as SQL
538 belch "literal SQL should be -nest => \\'scalar' "
539 . "instead of -nest => 'scalar' ";
544 puke "-$op => undef not supported";
551 my ($self, $op, $v) = @_;
553 my $prefix = ($op =~ /\bnot\b/i) ? 'NOT ' : '';
554 $self->_SWITCH_refkind($v, {
555 SCALARREF => sub { # literal SQL
556 return ($prefix . $$v);
559 SCALAR => sub { # interpreted as SQL column
560 return ($prefix . $self->_convert($self->_quote($v)));
566 sub _where_hashpair_ARRAYREF {
567 my ($self, $k, $v) = @_;
570 my @v = @$v; # need copy because of shift below
571 $self->_debug("ARRAY($k) means distribute over elements");
573 # put apart first element if it is an operator (-and, -or)
575 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
579 my @distributed = map { {$k => $_} } @v;
582 $self->_debug("OP($op) reinjected into the distributed array");
583 unshift @distributed, $op;
586 my $logic = $op ? substr($op, 1) : '';
588 return $self->_recurse_where(\@distributed, $logic);
591 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
592 $self->_debug("empty ARRAY($k) means 0=1");
593 return ($self->{sqlfalse});
597 sub _where_hashpair_HASHREF {
598 my ($self, $k, $v, $logic) = @_;
601 my ($all_sql, @all_bind);
603 for my $op (sort keys %$v) {
606 # put the operator in canonical form
607 $op =~ s/^-//; # remove initial dash
608 $op =~ tr/_/ /; # underscores become spaces
609 $op =~ s/^\s+//; # no initial space
610 $op =~ s/\s+$//; # no final space
611 $op =~ s/\s+/ /; # multiple spaces become one
615 # CASE: special operators like -in or -between
616 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
618 my $handler = $special_op->{handler};
620 puke "No handler supplied for special operator matching $special_op->{regex}";
622 elsif (not ref $handler) {
623 ($sql, @bind) = $self->$handler ($k, $op, $val);
625 elsif (ref $handler eq 'CODE') {
626 ($sql, @bind) = $handler->($self, $k, $op, $val);
629 puke "Illegal handler for special operator matching $special_op->{regex} - expecting a method name or a coderef";
633 $self->_SWITCH_refkind($val, {
635 ARRAYREF => sub { # CASE: col => {op => \@vals}
636 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
639 SCALARREF => sub { # CASE: col => {op => \$scalar} (literal SQL without bind)
640 $sql = join ' ', $self->_convert($self->_quote($k)),
641 $self->_sqlcase($op),
645 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
646 my ($sub_sql, @sub_bind) = @$$val;
647 $self->_assert_bindval_matches_bindtype(@sub_bind);
648 $sql = join ' ', $self->_convert($self->_quote($k)),
649 $self->_sqlcase($op),
655 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $op);
658 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
659 my $is = ($op =~ $self->{equality_op}) ? 'is' :
660 ($op =~ $self->{inequality_op}) ? 'is not' :
661 puke "unexpected operator '$op' with undef operand";
662 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
665 FALLBACK => sub { # CASE: col => {op => $scalar}
666 $sql = join ' ', $self->_convert($self->_quote($k)),
667 $self->_sqlcase($op),
668 $self->_convert('?');
669 @bind = $self->_bindtype($k, $val);
674 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
675 push @all_bind, @bind;
677 return ($all_sql, @all_bind);
682 sub _where_field_op_ARRAYREF {
683 my ($self, $k, $op, $vals) = @_;
685 my @vals = @$vals; #always work on a copy
688 $self->_debug("ARRAY($vals) means multiple elements: [ @vals ]");
690 # see if the first element is an -and/-or op
692 if ($vals[0] =~ /^ - ( AND|OR ) $/ix) {
697 # distribute $op over each remaining member of @vals, append logic if exists
698 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
700 # LDNOTE : had planned to change the distribution logic when
701 # $op =~ $self->{inequality_op}, because of Morgan laws :
702 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
703 # WHERE field != 22 OR field != 33 : the user probably means
704 # WHERE field != 22 AND field != 33.
705 # To do this, replace the above to roughly :
706 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
707 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
711 # try to DWIM on equality operators
712 # LDNOTE : not 100% sure this is the correct thing to do ...
713 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
714 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
717 puke "operator '$op' applied on an empty array (field '$k')";
722 sub _where_hashpair_SCALARREF {
723 my ($self, $k, $v) = @_;
724 $self->_debug("SCALAR($k) means literal SQL: $$v");
725 my $sql = $self->_quote($k) . " " . $$v;
729 # literal SQL with bind
730 sub _where_hashpair_ARRAYREFREF {
731 my ($self, $k, $v) = @_;
732 $self->_debug("REF($k) means literal SQL: @${$v}");
733 my ($sql, @bind) = @${$v};
734 $self->_assert_bindval_matches_bindtype(@bind);
735 $sql = $self->_quote($k) . " " . $sql;
736 return ($sql, @bind );
739 # literal SQL without bind
740 sub _where_hashpair_SCALAR {
741 my ($self, $k, $v) = @_;
742 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
743 my $sql = join ' ', $self->_convert($self->_quote($k)),
744 $self->_sqlcase($self->{cmp}),
745 $self->_convert('?');
746 my @bind = $self->_bindtype($k, $v);
747 return ( $sql, @bind);
751 sub _where_hashpair_UNDEF {
752 my ($self, $k, $v) = @_;
753 $self->_debug("UNDEF($k) means IS NULL");
754 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
758 #======================================================================
759 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
760 #======================================================================
763 sub _where_SCALARREF {
764 my ($self, $where) = @_;
767 $self->_debug("SCALAR(*top) means literal SQL: $$where");
773 my ($self, $where) = @_;
776 $self->_debug("NOREF(*top) means literal SQL: $where");
787 #======================================================================
788 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
789 #======================================================================
792 sub _where_field_BETWEEN {
793 my ($self, $k, $op, $vals) = @_;
795 (ref $vals eq 'ARRAY' && @$vals == 2) or
796 (ref $vals eq 'REF' && (@$$vals == 1 || @$$vals == 2 || @$$vals == 3))
797 or puke "special op 'between' requires an arrayref of two values (or a scalarref or arrayrefref for literal SQL)";
799 my ($clause, @bind, $label, $and, $placeholder);
800 $label = $self->_convert($self->_quote($k));
801 $and = ' ' . $self->_sqlcase('and') . ' ';
802 $placeholder = $self->_convert('?');
803 $op = $self->_sqlcase($op);
805 if (ref $vals eq 'REF') {
806 ($clause, @bind) = @$$vals;
809 my (@all_sql, @all_bind);
811 foreach my $val (@$vals) {
812 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
814 return ($placeholder, ($val));
817 return ($self->_convert($$val), ());
821 push @all_bind, @bind;
824 $clause = (join $and, @all_sql);
825 @bind = $self->_bindtype($k, @all_bind);
827 my $sql = "( $label $op $clause )";
832 sub _where_field_IN {
833 my ($self, $k, $op, $vals) = @_;
835 # backwards compatibility : if scalar, force into an arrayref
836 $vals = [$vals] if defined $vals && ! ref $vals;
838 my ($label) = $self->_convert($self->_quote($k));
839 my ($placeholder) = $self->_convert('?');
840 $op = $self->_sqlcase($op);
842 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
843 ARRAYREF => sub { # list of choices
844 if (@$vals) { # nonempty list
845 my $placeholders = join ", ", (($placeholder) x @$vals);
846 my $sql = "$label $op ( $placeholders )";
847 my @bind = $self->_bindtype($k, @$vals);
849 return ($sql, @bind);
851 else { # empty list : some databases won't understand "IN ()", so DWIM
852 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
857 ARRAYREFREF => sub { # literal SQL with bind
858 my ($sql, @bind) = @$$vals;
859 $self->_assert_bindval_matches_bindtype(@bind);
860 return ("$label $op ( $sql )", @bind);
864 puke "special op 'in' requires an arrayref (or arrayref-ref)";
868 return ($sql, @bind);
874 #======================================================================
876 #======================================================================
879 my ($self, $arg) = @_;
882 for my $c ($self->_order_by_chunks ($arg) ) {
883 $self->_SWITCH_refkind ($c, {
884 SCALAR => sub { push @sql, $c },
885 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
891 $self->_sqlcase(' order by'),
897 return wantarray ? ($sql, @bind) : $sql;
900 sub _order_by_chunks {
901 my ($self, $arg) = @_;
903 return $self->_SWITCH_refkind($arg, {
906 map { $self->_order_by_chunks ($_ ) } @$arg;
909 ARRAYREFREF => sub { [ @$$arg ] },
911 SCALAR => sub {$self->_quote($arg)},
913 UNDEF => sub {return () },
915 SCALARREF => sub {$$arg}, # literal SQL, no quoting
918 # get first pair in hash
919 my ($key, $val) = each %$arg;
921 return () unless $key;
923 if ( (keys %$arg) > 1 or not $key =~ /^-(desc|asc)/i ) {
924 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
930 for my $c ($self->_order_by_chunks ($val)) {
933 $self->_SWITCH_refkind ($c, {
942 $sql = $sql . ' ' . $self->_sqlcase($direction);
944 push @ret, [ $sql, @bind];
953 #======================================================================
954 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
955 #======================================================================
960 $self->_SWITCH_refkind($from, {
961 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
962 SCALAR => sub {$self->_quote($from)},
963 SCALARREF => sub {$$from},
964 ARRAYREFREF => sub {join ', ', @$from;},
969 #======================================================================
971 #======================================================================
977 $label or puke "can't quote an empty label";
979 # left and right quote characters
980 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
981 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
982 ARRAYREF => sub {@{$self->{quote_char}}},
986 or puke "quote_char must be an arrayref of 2 values";
988 # no quoting if no quoting chars
989 $ql or return $label;
991 # no quoting for literal SQL
992 return $$label if ref($label) eq 'SCALAR';
994 # separate table / column (if applicable)
995 my $sep = $self->{name_sep} || '';
996 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
998 # do the quoting, except for "*" or for `table`.*
999 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
1001 # reassemble and return.
1002 return join $sep, @quoted;
1006 # Conversion, if applicable
1008 my ($self, $arg) = @_;
1010 # LDNOTE : modified the previous implementation below because
1011 # it was not consistent : the first "return" is always an array,
1012 # the second "return" is context-dependent. Anyway, _convert
1013 # seems always used with just a single argument, so make it a
1015 # return @_ unless $self->{convert};
1016 # my $conv = $self->_sqlcase($self->{convert});
1017 # my @ret = map { $conv.'('.$_.')' } @_;
1018 # return wantarray ? @ret : $ret[0];
1019 if ($self->{convert}) {
1020 my $conv = $self->_sqlcase($self->{convert});
1021 $arg = $conv.'('.$arg.')';
1029 my($col, @vals) = @_;
1031 #LDNOTE : changed original implementation below because it did not make
1032 # sense when bindtype eq 'columns' and @vals > 1.
1033 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1035 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
1038 # Dies if any element of @bind is not in [colname => value] format
1039 # if bindtype is 'columns'.
1040 sub _assert_bindval_matches_bindtype {
1041 my ($self, @bind) = @_;
1043 if ($self->{bindtype} eq 'columns') {
1044 foreach my $val (@bind) {
1045 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1046 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1052 sub _join_sql_clauses {
1053 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1055 if (@$clauses_aref > 1) {
1056 my $join = " " . $self->_sqlcase($logic) . " ";
1057 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1058 return ($sql, @$bind_aref);
1060 elsif (@$clauses_aref) {
1061 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1064 return (); # if no SQL, ignore @$bind_aref
1069 # Fix SQL case, if so requested
1073 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1074 # don't touch the argument ... crooked logic, but let's not change it!
1075 return $self->{case} ? $_[0] : uc($_[0]);
1079 #======================================================================
1080 # DISPATCHING FROM REFKIND
1081 #======================================================================
1084 my ($self, $data) = @_;
1090 # blessed objects are treated like scalars
1091 $ref = (blessed $data) ? '' : ref $data;
1092 $n_steps += 1 if $ref;
1093 last if $ref ne 'REF';
1097 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
1099 return $base . ('REF' x $n_steps);
1105 my ($self, $data) = @_;
1106 my @try = ($self->_refkind($data));
1107 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1108 push @try, 'FALLBACK';
1112 sub _METHOD_FOR_refkind {
1113 my ($self, $meth_prefix, $data) = @_;
1114 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
1115 $self->_try_refkind($data)
1116 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1121 sub _SWITCH_refkind {
1122 my ($self, $data, $dispatch_table) = @_;
1124 my $coderef = first {$_} map {$dispatch_table->{$_}}
1125 $self->_try_refkind($data)
1126 or puke "no dispatch entry for ".$self->_refkind($data);
1133 #======================================================================
1134 # VALUES, GENERATE, AUTOLOAD
1135 #======================================================================
1137 # LDNOTE: original code from nwiger, didn't touch code in that section
1138 # I feel the AUTOLOAD stuff should not be the default, it should
1139 # only be activated on explicit demand by user.
1143 my $data = shift || return;
1144 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1145 unless ref $data eq 'HASH';
1148 foreach my $k ( sort keys %$data ) {
1149 my $v = $data->{$k};
1150 $self->_SWITCH_refkind($v, {
1152 if ($self->{array_datatypes}) { # array datatype
1153 push @all_bind, $self->_bindtype($k, $v);
1155 else { # literal SQL with bind
1156 my ($sql, @bind) = @$v;
1157 $self->_assert_bindval_matches_bindtype(@bind);
1158 push @all_bind, @bind;
1161 ARRAYREFREF => sub { # literal SQL with bind
1162 my ($sql, @bind) = @${$v};
1163 $self->_assert_bindval_matches_bindtype(@bind);
1164 push @all_bind, @bind;
1166 SCALARREF => sub { # literal SQL without bind
1168 SCALAR_or_UNDEF => sub {
1169 push @all_bind, $self->_bindtype($k, $v);
1180 my(@sql, @sqlq, @sqlv);
1184 if ($ref eq 'HASH') {
1185 for my $k (sort keys %$_) {
1188 my $label = $self->_quote($k);
1189 if ($r eq 'ARRAY') {
1190 # literal SQL with bind
1191 my ($sql, @bind) = @$v;
1192 $self->_assert_bindval_matches_bindtype(@bind);
1193 push @sqlq, "$label = $sql";
1195 } elsif ($r eq 'SCALAR') {
1196 # literal SQL without bind
1197 push @sqlq, "$label = $$v";
1199 push @sqlq, "$label = ?";
1200 push @sqlv, $self->_bindtype($k, $v);
1203 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1204 } elsif ($ref eq 'ARRAY') {
1205 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1208 if ($r eq 'ARRAY') { # literal SQL with bind
1209 my ($sql, @bind) = @$v;
1210 $self->_assert_bindval_matches_bindtype(@bind);
1213 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1214 # embedded literal SQL
1221 push @sql, '(' . join(', ', @sqlq) . ')';
1222 } elsif ($ref eq 'SCALAR') {
1226 # strings get case twiddled
1227 push @sql, $self->_sqlcase($_);
1231 my $sql = join ' ', @sql;
1233 # this is pretty tricky
1234 # if ask for an array, return ($stmt, @bind)
1235 # otherwise, s/?/shift @sqlv/ to put it inline
1237 return ($sql, @sqlv);
1239 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1240 ref $d ? $d->[1] : $d/e;
1249 # This allows us to check for a local, then _form, attr
1251 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1252 return $self->generate($name, @_);
1263 SQL::Abstract - Generate SQL from Perl data structures
1269 my $sql = SQL::Abstract->new;
1271 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1273 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1275 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1277 my($stmt, @bind) = $sql->delete($table, \%where);
1279 # Then, use these in your DBI statements
1280 my $sth = $dbh->prepare($stmt);
1281 $sth->execute(@bind);
1283 # Just generate the WHERE clause
1284 my($stmt, @bind) = $sql->where(\%where, \@order);
1286 # Return values in the same order, for hashed queries
1287 # See PERFORMANCE section for more details
1288 my @bind = $sql->values(\%fieldvals);
1292 This module was inspired by the excellent L<DBIx::Abstract>.
1293 However, in using that module I found that what I really wanted
1294 to do was generate SQL, but still retain complete control over my
1295 statement handles and use the DBI interface. So, I set out to
1296 create an abstract SQL generation module.
1298 While based on the concepts used by L<DBIx::Abstract>, there are
1299 several important differences, especially when it comes to WHERE
1300 clauses. I have modified the concepts used to make the SQL easier
1301 to generate from Perl data structures and, IMO, more intuitive.
1302 The underlying idea is for this module to do what you mean, based
1303 on the data structures you provide it. The big advantage is that
1304 you don't have to modify your code every time your data changes,
1305 as this module figures it out.
1307 To begin with, an SQL INSERT is as easy as just specifying a hash
1308 of C<key=value> pairs:
1311 name => 'Jimbo Bobson',
1312 phone => '123-456-7890',
1313 address => '42 Sister Lane',
1314 city => 'St. Louis',
1315 state => 'Louisiana',
1318 The SQL can then be generated with this:
1320 my($stmt, @bind) = $sql->insert('people', \%data);
1322 Which would give you something like this:
1324 $stmt = "INSERT INTO people
1325 (address, city, name, phone, state)
1326 VALUES (?, ?, ?, ?, ?)";
1327 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1328 '123-456-7890', 'Louisiana');
1330 These are then used directly in your DBI code:
1332 my $sth = $dbh->prepare($stmt);
1333 $sth->execute(@bind);
1335 =head2 Inserting and Updating Arrays
1337 If your database has array types (like for example Postgres),
1338 activate the special option C<< array_datatypes => 1 >>
1339 when creating the C<SQL::Abstract> object.
1340 Then you may use an arrayref to insert and update database array types:
1342 my $sql = SQL::Abstract->new(array_datatypes => 1);
1344 planets => [qw/Mercury Venus Earth Mars/]
1347 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1351 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1353 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1356 =head2 Inserting and Updating SQL
1358 In order to apply SQL functions to elements of your C<%data> you may
1359 specify a reference to an arrayref for the given hash value. For example,
1360 if you need to execute the Oracle C<to_date> function on a value, you can
1361 say something like this:
1365 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1368 The first value in the array is the actual SQL. Any other values are
1369 optional and would be included in the bind values array. This gives
1372 my($stmt, @bind) = $sql->insert('people', \%data);
1374 $stmt = "INSERT INTO people (name, date_entered)
1375 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1376 @bind = ('Bill', '03/02/2003');
1378 An UPDATE is just as easy, all you change is the name of the function:
1380 my($stmt, @bind) = $sql->update('people', \%data);
1382 Notice that your C<%data> isn't touched; the module will generate
1383 the appropriately quirky SQL for you automatically. Usually you'll
1384 want to specify a WHERE clause for your UPDATE, though, which is
1385 where handling C<%where> hashes comes in handy...
1387 =head2 Complex where statements
1389 This module can generate pretty complicated WHERE statements
1390 easily. For example, simple C<key=value> pairs are taken to mean
1391 equality, and if you want to see if a field is within a set
1392 of values, you can use an arrayref. Let's say we wanted to
1393 SELECT some data based on this criteria:
1396 requestor => 'inna',
1397 worker => ['nwiger', 'rcwe', 'sfz'],
1398 status => { '!=', 'completed' }
1401 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1403 The above would give you something like this:
1405 $stmt = "SELECT * FROM tickets WHERE
1406 ( requestor = ? ) AND ( status != ? )
1407 AND ( worker = ? OR worker = ? OR worker = ? )";
1408 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1410 Which you could then use in DBI code like so:
1412 my $sth = $dbh->prepare($stmt);
1413 $sth->execute(@bind);
1419 The functions are simple. There's one for each major SQL operation,
1420 and a constructor you use first. The arguments are specified in a
1421 similar order to each function (table, then fields, then a where
1422 clause) to try and simplify things.
1427 =head2 new(option => 'value')
1429 The C<new()> function takes a list of options and values, and returns
1430 a new B<SQL::Abstract> object which can then be used to generate SQL
1431 through the methods below. The options accepted are:
1437 If set to 'lower', then SQL will be generated in all lowercase. By
1438 default SQL is generated in "textbook" case meaning something like:
1440 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1442 Any setting other than 'lower' is ignored.
1446 This determines what the default comparison operator is. By default
1447 it is C<=>, meaning that a hash like this:
1449 %where = (name => 'nwiger', email => 'nate@wiger.org');
1451 Will generate SQL like this:
1453 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1455 However, you may want loose comparisons by default, so if you set
1456 C<cmp> to C<like> you would get SQL such as:
1458 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1460 You can also override the comparsion on an individual basis - see
1461 the huge section on L</"WHERE CLAUSES"> at the bottom.
1463 =item sqltrue, sqlfalse
1465 Expressions for inserting boolean values within SQL statements.
1466 By default these are C<1=1> and C<1=0>. They are used
1467 by the special operators C<-in> and C<-not_in> for generating
1468 correct SQL even when the argument is an empty array (see below).
1472 This determines the default logical operator for multiple WHERE
1473 statements in arrays or hashes. If absent, the default logic is "or"
1474 for arrays, and "and" for hashes. This means that a WHERE
1478 event_date => {'>=', '2/13/99'},
1479 event_date => {'<=', '4/24/03'},
1482 will generate SQL like this:
1484 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1486 This is probably not what you want given this query, though (look
1487 at the dates). To change the "OR" to an "AND", simply specify:
1489 my $sql = SQL::Abstract->new(logic => 'and');
1491 Which will change the above C<WHERE> to:
1493 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1495 The logic can also be changed locally by inserting
1496 a modifier in front of an arrayref :
1498 @where = (-and => [event_date => {'>=', '2/13/99'},
1499 event_date => {'<=', '4/24/03'} ]);
1501 See the L</"WHERE CLAUSES"> section for explanations.
1505 This will automatically convert comparisons using the specified SQL
1506 function for both column and value. This is mostly used with an argument
1507 of C<upper> or C<lower>, so that the SQL will have the effect of
1508 case-insensitive "searches". For example, this:
1510 $sql = SQL::Abstract->new(convert => 'upper');
1511 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1513 Will turn out the following SQL:
1515 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1517 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1518 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1519 not validate this option; it will just pass through what you specify verbatim).
1523 This is a kludge because many databases suck. For example, you can't
1524 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1525 Instead, you have to use C<bind_param()>:
1527 $sth->bind_param(1, 'reg data');
1528 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1530 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1531 which loses track of which field each slot refers to. Fear not.
1533 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1534 Currently, you can specify either C<normal> (default) or C<columns>. If you
1535 specify C<columns>, you will get an array that looks like this:
1537 my $sql = SQL::Abstract->new(bindtype => 'columns');
1538 my($stmt, @bind) = $sql->insert(...);
1541 [ 'column1', 'value1' ],
1542 [ 'column2', 'value2' ],
1543 [ 'column3', 'value3' ],
1546 You can then iterate through this manually, using DBI's C<bind_param()>.
1548 $sth->prepare($stmt);
1551 my($col, $data) = @$_;
1552 if ($col eq 'details' || $col eq 'comments') {
1553 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1554 } elsif ($col eq 'image') {
1555 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1557 $sth->bind_param($i, $data);
1561 $sth->execute; # execute without @bind now
1563 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1564 Basically, the advantage is still that you don't have to care which fields
1565 are or are not included. You could wrap that above C<for> loop in a simple
1566 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1567 get a layer of abstraction over manual SQL specification.
1569 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1570 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1571 will expect the bind values in this format.
1575 This is the character that a table or column name will be quoted
1576 with. By default this is an empty string, but you could set it to
1577 the character C<`>, to generate SQL like this:
1579 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1581 Alternatively, you can supply an array ref of two items, the first being the left
1582 hand quote character, and the second the right hand quote character. For
1583 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1584 that generates SQL like this:
1586 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1588 Quoting is useful if you have tables or columns names that are reserved
1589 words in your database's SQL dialect.
1593 This is the character that separates a table and column name. It is
1594 necessary to specify this when the C<quote_char> option is selected,
1595 so that tables and column names can be individually quoted like this:
1597 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1599 =item array_datatypes
1601 When this option is true, arrayrefs in INSERT or UPDATE are
1602 interpreted as array datatypes and are passed directly
1604 When this option is false, arrayrefs are interpreted
1605 as literal SQL, just like refs to arrayrefs
1606 (but this behavior is for backwards compatibility; when writing
1607 new queries, use the "reference to arrayref" syntax
1613 Takes a reference to a list of "special operators"
1614 to extend the syntax understood by L<SQL::Abstract>.
1615 See section L</"SPECIAL OPERATORS"> for details.
1619 Takes a reference to a list of "unary operators"
1620 to extend the syntax understood by L<SQL::Abstract>.
1621 See section L</"UNARY OPERATORS"> for details.
1627 =head2 insert($table, \@values || \%fieldvals)
1629 This is the simplest function. You simply give it a table name
1630 and either an arrayref of values or hashref of field/value pairs.
1631 It returns an SQL INSERT statement and a list of bind values.
1632 See the sections on L</"Inserting and Updating Arrays"> and
1633 L</"Inserting and Updating SQL"> for information on how to insert
1634 with those data types.
1636 =head2 update($table, \%fieldvals, \%where)
1638 This takes a table, hashref of field/value pairs, and an optional
1639 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1641 See the sections on L</"Inserting and Updating Arrays"> and
1642 L</"Inserting and Updating SQL"> for information on how to insert
1643 with those data types.
1645 =head2 select($source, $fields, $where, $order)
1647 This returns a SQL SELECT statement and associated list of bind values, as
1648 specified by the arguments :
1654 Specification of the 'FROM' part of the statement.
1655 The argument can be either a plain scalar (interpreted as a table
1656 name, will be quoted), or an arrayref (interpreted as a list
1657 of table names, joined by commas, quoted), or a scalarref
1658 (literal table name, not quoted), or a ref to an arrayref
1659 (list of literal table names, joined by commas, not quoted).
1663 Specification of the list of fields to retrieve from
1665 The argument can be either an arrayref (interpreted as a list
1666 of field names, will be joined by commas and quoted), or a
1667 plain scalar (literal SQL, not quoted).
1668 Please observe that this API is not as flexible as for
1669 the first argument C<$table>, for backwards compatibility reasons.
1673 Optional argument to specify the WHERE part of the query.
1674 The argument is most often a hashref, but can also be
1675 an arrayref or plain scalar --
1676 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1680 Optional argument to specify the ORDER BY part of the query.
1681 The argument can be a scalar, a hashref or an arrayref
1682 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1688 =head2 delete($table, \%where)
1690 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1691 It returns an SQL DELETE statement and list of bind values.
1693 =head2 where(\%where, \@order)
1695 This is used to generate just the WHERE clause. For example,
1696 if you have an arbitrary data structure and know what the
1697 rest of your SQL is going to look like, but want an easy way
1698 to produce a WHERE clause, use this. It returns an SQL WHERE
1699 clause and list of bind values.
1702 =head2 values(\%data)
1704 This just returns the values from the hash C<%data>, in the same
1705 order that would be returned from any of the other above queries.
1706 Using this allows you to markedly speed up your queries if you
1707 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1709 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1711 Warning: This is an experimental method and subject to change.
1713 This returns arbitrarily generated SQL. It's a really basic shortcut.
1714 It will return two different things, depending on return context:
1716 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1717 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1719 These would return the following:
1721 # First calling form
1722 $stmt = "CREATE TABLE test (?, ?)";
1723 @bind = (field1, field2);
1725 # Second calling form
1726 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1728 Depending on what you're trying to do, it's up to you to choose the correct
1729 format. In this example, the second form is what you would want.
1733 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1737 ALTER SESSION SET nls_date_format = 'MM/YY'
1739 You get the idea. Strings get their case twiddled, but everything
1740 else remains verbatim.
1745 =head1 WHERE CLAUSES
1749 This module uses a variation on the idea from L<DBIx::Abstract>. It
1750 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1751 module is that things in arrays are OR'ed, and things in hashes
1754 The easiest way to explain is to show lots of examples. After
1755 each C<%where> hash shown, it is assumed you used:
1757 my($stmt, @bind) = $sql->where(\%where);
1759 However, note that the C<%where> hash can be used directly in any
1760 of the other functions as well, as described above.
1762 =head2 Key-value pairs
1764 So, let's get started. To begin, a simple hash:
1768 status => 'completed'
1771 Is converted to SQL C<key = val> statements:
1773 $stmt = "WHERE user = ? AND status = ?";
1774 @bind = ('nwiger', 'completed');
1776 One common thing I end up doing is having a list of values that
1777 a field can be in. To do this, simply specify a list inside of
1782 status => ['assigned', 'in-progress', 'pending'];
1785 This simple code will create the following:
1787 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1788 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1790 A field associated to an empty arrayref will be considered a
1791 logical false and will generate 0=1.
1793 =head2 Specific comparison operators
1795 If you want to specify a different type of operator for your comparison,
1796 you can use a hashref for a given column:
1800 status => { '!=', 'completed' }
1803 Which would generate:
1805 $stmt = "WHERE user = ? AND status != ?";
1806 @bind = ('nwiger', 'completed');
1808 To test against multiple values, just enclose the values in an arrayref:
1810 status => { '=', ['assigned', 'in-progress', 'pending'] };
1812 Which would give you:
1814 "WHERE status = ? OR status = ? OR status = ?"
1817 The hashref can also contain multiple pairs, in which case it is expanded
1818 into an C<AND> of its elements:
1822 status => { '!=', 'completed', -not_like => 'pending%' }
1825 # Or more dynamically, like from a form
1826 $where{user} = 'nwiger';
1827 $where{status}{'!='} = 'completed';
1828 $where{status}{'-not_like'} = 'pending%';
1830 # Both generate this
1831 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1832 @bind = ('nwiger', 'completed', 'pending%');
1835 To get an OR instead, you can combine it with the arrayref idea:
1839 priority => [ {'=', 2}, {'!=', 1} ]
1842 Which would generate:
1844 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1845 @bind = ('nwiger', '2', '1');
1847 If you want to include literal SQL (with or without bind values), just use a
1848 scalar reference or array reference as the value:
1851 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1852 date_expires => { '<' => \"now()" }
1855 Which would generate:
1857 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1858 @bind = ('11/26/2008');
1861 =head2 Logic and nesting operators
1863 In the example above,
1864 there is a subtle trap if you want to say something like
1865 this (notice the C<AND>):
1867 WHERE priority != ? AND priority != ?
1869 Because, in Perl you I<can't> do this:
1871 priority => { '!=', 2, '!=', 1 }
1873 As the second C<!=> key will obliterate the first. The solution
1874 is to use the special C<-modifier> form inside an arrayref:
1876 priority => [ -and => {'!=', 2},
1880 Normally, these would be joined by C<OR>, but the modifier tells it
1881 to use C<AND> instead. (Hint: You can use this in conjunction with the
1882 C<logic> option to C<new()> in order to change the way your queries
1883 work by default.) B<Important:> Note that the C<-modifier> goes
1884 B<INSIDE> the arrayref, as an extra first element. This will
1885 B<NOT> do what you think it might:
1887 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1889 Here is a quick list of equivalencies, since there is some overlap:
1892 status => {'!=', 'completed', 'not like', 'pending%' }
1893 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1896 status => {'=', ['assigned', 'in-progress']}
1897 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1898 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1902 =head2 Special operators : IN, BETWEEN, etc.
1904 You can also use the hashref format to compare a list of fields using the
1905 C<IN> comparison operator, by specifying the list as an arrayref:
1908 status => 'completed',
1909 reportid => { -in => [567, 2335, 2] }
1912 Which would generate:
1914 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1915 @bind = ('completed', '567', '2335', '2');
1917 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1920 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1921 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1922 'sqltrue' (by default : C<1=1>).
1926 Another pair of operators is C<-between> and C<-not_between>,
1927 used with an arrayref of two values:
1931 completion_date => {
1932 -not_between => ['2002-10-01', '2003-02-06']
1938 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1940 These are the two builtin "special operators"; but the
1941 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1943 =head2 Unary operators: bool
1945 If you wish to test against boolean columns or functions within your
1946 database you can use the C<-bool> and C<-not_bool> operators. For
1947 example to test the column C<is_user> being true and the column
1948 <is_enabled> being false you would use:-
1952 -not_bool => 'is_enabled',
1957 WHERE is_user AND NOT is_enabledmv
1961 =head2 Nested conditions, -and/-or prefixes
1963 So far, we've seen how multiple conditions are joined with a top-level
1964 C<AND>. We can change this by putting the different conditions we want in
1965 hashes and then putting those hashes in an array. For example:
1970 status => { -like => ['pending%', 'dispatched'] },
1974 status => 'unassigned',
1978 This data structure would create the following:
1980 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1981 OR ( user = ? AND status = ? ) )";
1982 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1985 There is also a special C<-nest>
1986 operator which adds an additional set of parens, to create a subquery.
1987 For example, to get something like this:
1989 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1990 @bind = ('nwiger', '20', 'ASIA');
1996 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2000 Finally, clauses in hashrefs or arrayrefs can be
2001 prefixed with an C<-and> or C<-or> to change the logic
2008 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2009 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2016 WHERE ( user = ? AND
2017 ( ( workhrs > ? AND geo = ? )
2018 OR ( workhrs < ? AND geo = ? ) ) )
2021 =head2 Algebraic inconsistency, for historical reasons
2023 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2024 operator goes C<outside> of the nested structure; whereas when connecting
2025 several constraints on one column, the C<-and> operator goes
2026 C<inside> the arrayref. Here is an example combining both features :
2029 -and => [a => 1, b => 2],
2030 -or => [c => 3, d => 4],
2031 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2036 WHERE ( ( ( a = ? AND b = ? )
2037 OR ( c = ? OR d = ? )
2038 OR ( e LIKE ? AND e LIKE ? ) ) )
2040 This difference in syntax is unfortunate but must be preserved for
2041 historical reasons. So be careful : the two examples below would
2042 seem algebraically equivalent, but they are not
2044 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2045 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2047 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2048 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2053 Finally, sometimes only literal SQL will do. If you want to include
2054 literal SQL verbatim, you can specify it as a scalar reference, namely:
2056 my $inn = 'is Not Null';
2058 priority => { '<', 2 },
2064 $stmt = "WHERE priority < ? AND requestor is Not Null";
2067 Note that in this example, you only get one bind parameter back, since
2068 the verbatim SQL is passed as part of the statement.
2070 Of course, just to prove a point, the above can also be accomplished
2074 priority => { '<', 2 },
2075 requestor => { '!=', undef },
2081 Conditions on boolean columns can be expressed in the
2082 same way, passing a reference to an empty string :
2085 priority => { '<', 2 },
2091 $stmt = "WHERE priority < ? AND is_ready";
2095 =head2 Literal SQL with placeholders and bind values (subqueries)
2097 If the literal SQL to be inserted has placeholders and bind values,
2098 use a reference to an arrayref (yes this is a double reference --
2099 not so common, but perfectly legal Perl). For example, to find a date
2100 in Postgres you can use something like this:
2103 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2108 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2111 Note that you must pass the bind values in the same format as they are returned
2112 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2113 provide the bind values in the C<< [ column_meta => value ] >> format, where
2114 C<column_meta> is an opaque scalar value; most commonly the column name, but
2115 you can use any scalar value (including references and blessed references),
2116 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2117 to C<columns> the above example will look like:
2120 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2123 Literal SQL is especially useful for nesting parenthesized clauses in the
2124 main SQL query. Here is a first example :
2126 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2130 bar => \["IN ($sub_stmt)" => @sub_bind],
2135 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2136 WHERE c2 < ? AND c3 LIKE ?))";
2137 @bind = (1234, 100, "foo%");
2139 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2140 are expressed in the same way. Of course the C<$sub_stmt> and
2141 its associated bind values can be generated through a former call
2144 my ($sub_stmt, @sub_bind)
2145 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2146 c3 => {-like => "foo%"}});
2149 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2152 In the examples above, the subquery was used as an operator on a column;
2153 but the same principle also applies for a clause within the main C<%where>
2154 hash, like an EXISTS subquery :
2156 my ($sub_stmt, @sub_bind)
2157 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2160 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2165 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2166 WHERE c1 = ? AND c2 > t0.c0))";
2170 Observe that the condition on C<c2> in the subquery refers to
2171 column C<t0.c0> of the main query : this is I<not> a bind
2172 value, so we have to express it through a scalar ref.
2173 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2174 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2175 what we wanted here.
2177 Another use of the subquery technique is when some SQL clauses need
2178 parentheses, as it often occurs with some proprietary SQL extensions
2179 like for example fulltext expressions, geospatial expressions,
2180 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2183 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2186 Finally, here is an example where a subquery is used
2187 for expressing unary negation:
2189 my ($sub_stmt, @sub_bind)
2190 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2191 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2193 lname => {like => '%son%'},
2194 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2199 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2200 @bind = ('%son%', 10, 20)
2206 These pages could go on for a while, since the nesting of the data
2207 structures this module can handle are pretty much unlimited (the
2208 module implements the C<WHERE> expansion as a recursive function
2209 internally). Your best bet is to "play around" with the module a
2210 little to see how the data structures behave, and choose the best
2211 format for your data based on that.
2213 And of course, all the values above will probably be replaced with
2214 variables gotten from forms or the command line. After all, if you
2215 knew everything ahead of time, you wouldn't have to worry about
2216 dynamically-generating SQL and could just hardwire it into your
2222 =head1 ORDER BY CLAUSES
2224 Some functions take an order by clause. This can either be a scalar (just a
2225 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2226 or an array of either of the two previous forms. Examples:
2228 Given | Will Generate
2229 ----------------------------------------------------------
2231 \'colA DESC' | ORDER BY colA DESC
2233 'colA' | ORDER BY colA
2235 [qw/colA colB/] | ORDER BY colA, colB
2237 {-asc => 'colA'} | ORDER BY colA ASC
2239 {-desc => 'colB'} | ORDER BY colB DESC
2241 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2243 { -asc => [qw/colA colB] } | ORDER BY colA ASC, colB ASC
2246 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2247 { -desc => [qw/colB/], | colC ASC, colD ASC
2248 { -asc => [qw/colC colD/],|
2250 ===========================================================
2254 =head1 SPECIAL OPERATORS
2256 my $sqlmaker = SQL::Abstract->new(special_ops => [
2260 my ($self, $field, $op, $arg) = @_;
2266 handler => 'method_name',
2270 A "special operator" is a SQL syntactic clause that can be
2271 applied to a field, instead of a usual binary operator.
2274 WHERE field IN (?, ?, ?)
2275 WHERE field BETWEEN ? AND ?
2276 WHERE MATCH(field) AGAINST (?, ?)
2278 Special operators IN and BETWEEN are fairly standard and therefore
2279 are builtin within C<SQL::Abstract> (as the overridable methods
2280 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2281 like the MATCH .. AGAINST example above which is specific to MySQL,
2282 you can write your own operator handlers - supply a C<special_ops>
2283 argument to the C<new> method. That argument takes an arrayref of
2284 operator definitions; each operator definition is a hashref with two
2291 the regular expression to match the operator
2295 Either a coderef or a plain scalar method name. In both cases
2296 the expected return is C<< ($sql, @bind) >>.
2298 When supplied with a method name, it is simply called on the
2299 L<SQL::Abstract/> object as:
2301 $self->$method_name ($field, $op, $arg)
2305 $op is the part that matched the handler regex
2306 $field is the LHS of the operator
2309 When supplied with a coderef, it is called as:
2311 $coderef->($self, $field, $op, $arg)
2316 For example, here is an implementation
2317 of the MATCH .. AGAINST syntax for MySQL
2319 my $sqlmaker = SQL::Abstract->new(special_ops => [
2321 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2322 {regex => qr/^match$/i,
2324 my ($self, $field, $op, $arg) = @_;
2325 $arg = [$arg] if not ref $arg;
2326 my $label = $self->_quote($field);
2327 my ($placeholder) = $self->_convert('?');
2328 my $placeholders = join ", ", (($placeholder) x @$arg);
2329 my $sql = $self->_sqlcase('match') . " ($label) "
2330 . $self->_sqlcase('against') . " ($placeholders) ";
2331 my @bind = $self->_bindtype($field, @$arg);
2332 return ($sql, @bind);
2339 =head1 UNARY OPERATORS
2341 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2345 my ($self, $op, $arg) = @_;
2351 handler => 'method_name',
2355 A "unary operator" is a SQL syntactic clause that can be
2356 applied to a field - the operator goes before the field
2358 You can write your own operator handlers - supply a C<unary_ops>
2359 argument to the C<new> method. That argument takes an arrayref of
2360 operator definitions; each operator definition is a hashref with two
2367 the regular expression to match the operator
2371 Either a coderef or a plain scalar method name. In both cases
2372 the expected return is C<< $sql >>.
2374 When supplied with a method name, it is simply called on the
2375 L<SQL::Abstract/> object as:
2377 $self->$method_name ($op, $arg)
2381 $op is the part that matched the handler regex
2382 $arg is the RHS or argument of the operator
2384 When supplied with a coderef, it is called as:
2386 $coderef->($self, $op, $arg)
2394 Thanks to some benchmarking by Mark Stosberg, it turns out that
2395 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2396 I must admit this wasn't an intentional design issue, but it's a
2397 byproduct of the fact that you get to control your C<DBI> handles
2400 To maximize performance, use a code snippet like the following:
2402 # prepare a statement handle using the first row
2403 # and then reuse it for the rest of the rows
2405 for my $href (@array_of_hashrefs) {
2406 $stmt ||= $sql->insert('table', $href);
2407 $sth ||= $dbh->prepare($stmt);
2408 $sth->execute($sql->values($href));
2411 The reason this works is because the keys in your C<$href> are sorted
2412 internally by B<SQL::Abstract>. Thus, as long as your data retains
2413 the same structure, you only have to generate the SQL the first time
2414 around. On subsequent queries, simply use the C<values> function provided
2415 by this module to return your values in the correct order.
2420 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2421 really like this part (I do, at least). Building up a complex query
2422 can be as simple as the following:
2426 use CGI::FormBuilder;
2429 my $form = CGI::FormBuilder->new(...);
2430 my $sql = SQL::Abstract->new;
2432 if ($form->submitted) {
2433 my $field = $form->field;
2434 my $id = delete $field->{id};
2435 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2438 Of course, you would still have to connect using C<DBI> to run the
2439 query, but the point is that if you make your form look like your
2440 table, the actual query script can be extremely simplistic.
2442 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2443 a fast interface to returning and formatting data. I frequently
2444 use these three modules together to write complex database query
2445 apps in under 50 lines.
2450 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2451 Great care has been taken to preserve the I<published> behavior
2452 documented in previous versions in the 1.* family; however,
2453 some features that were previously undocumented, or behaved
2454 differently from the documentation, had to be changed in order
2455 to clarify the semantics. Hence, client code that was relying
2456 on some dark areas of C<SQL::Abstract> v1.*
2457 B<might behave differently> in v1.50.
2459 The main changes are :
2465 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2469 support for the { operator => \"..." } construct (to embed literal SQL)
2473 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2477 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2481 defensive programming : check arguments
2485 fixed bug with global logic, which was previously implemented
2486 through global variables yielding side-effects. Prior versions would
2487 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2488 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2489 Now this is interpreted
2490 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2495 fixed semantics of _bindtype on array args
2499 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2500 we just avoid shifting arrays within that tree.
2504 dropped the C<_modlogic> function
2510 =head1 ACKNOWLEDGEMENTS
2512 There are a number of individuals that have really helped out with
2513 this module. Unfortunately, most of them submitted bugs via CPAN
2514 so I have no idea who they are! But the people I do know are:
2516 Ash Berlin (order_by hash term support)
2517 Matt Trout (DBIx::Class support)
2518 Mark Stosberg (benchmarking)
2519 Chas Owens (initial "IN" operator support)
2520 Philip Collins (per-field SQL functions)
2521 Eric Kolve (hashref "AND" support)
2522 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2523 Dan Kubb (support for "quote_char" and "name_sep")
2524 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2525 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2526 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2527 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2533 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2537 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2539 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2541 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2542 While not an official support venue, C<DBIx::Class> makes heavy use of
2543 C<SQL::Abstract>, and as such list members there are very familiar with
2544 how to create queries.
2548 This module is free software; you may copy this under the terms of
2549 the GNU General Public License, or the Artistic License, copies of
2550 which should have accompanied your Perl kit.