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' },
35 { regex => qr/^or (\s? \d+)?$/xi, handler => '_where_op_ANDOR' },
36 { regex => qr/^nest (\s? \d+)?$/xi, handler => '_where_op_NEST' },
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/_/ /; # underscores become spaces
461 $op =~ s/^\s+//; # no initial space
462 $op =~ s/\s+$//; # no final space
463 $op =~ s/\s+/ /; # multiple spaces become one
465 $self->_debug("OP(-$op) within hashref, recursing...");
467 my $op_entry = first {$op =~ $_->{regex}} @{$self->{unary_ops}};
468 my $handler = $op_entry->{handler};
470 puke "unknown operator: -$op";
472 elsif (not ref $handler) {
473 return $self->$handler ($op, $v);
475 elsif (ref $handler eq 'CODE') {
476 return $handler->($self, $op, $v);
479 puke "Illegal handler for operator $op - expecting a method name or a coderef";
483 sub _where_op_ANDOR {
484 my ($self, $op, $v) = @_;
486 if ($op =~ s/\s?\d+$//) {
487 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
488 . "You probably wanted ...-and => [ $op => COND1, $op => COND2 ... ]";
491 $self->_SWITCH_refkind($v, {
493 return $self->_where_ARRAYREF($v, $op);
497 return ( $op =~ /^or/i )
498 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
499 : $self->_where_HASHREF($v);
503 puke "-$op => \\\$scalar not supported, use -nest => ...";
507 puke "-$op => \\[..] not supported, use -nest => ...";
510 SCALAR => sub { # permissively interpreted as SQL
511 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
515 puke "-$op => undef not supported";
521 my ($self, $op, $v) = @_;
523 if ($op =~ s/\s?\d+$//) {
524 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
525 . "You probably wanted ...-and => [ $op => COND1, $op => COND2 ... ]";
529 $self->_SWITCH_refkind($v, {
532 return $self->_where_ARRAYREF($v, '');
536 return $self->_where_HASHREF($v);
539 SCALARREF => sub { # literal SQL
543 ARRAYREFREF => sub { # literal SQL
547 SCALAR => sub { # permissively interpreted as SQL
548 belch "literal SQL should be -nest => \\'scalar' "
549 . "instead of -nest => 'scalar' ";
554 puke "-$op => undef not supported";
561 my ($self, $op, $v) = @_;
563 my $prefix = ($op =~ /\bnot\b/i) ? 'NOT ' : '';
564 $self->_SWITCH_refkind($v, {
565 SCALARREF => sub { # literal SQL
566 return ($prefix . $$v);
569 SCALAR => sub { # interpreted as SQL column
570 return ($prefix . $self->_convert($self->_quote($v)));
576 sub _where_hashpair_ARRAYREF {
577 my ($self, $k, $v) = @_;
580 my @v = @$v; # need copy because of shift below
581 $self->_debug("ARRAY($k) means distribute over elements");
583 # put apart first element if it is an operator (-and, -or)
585 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
589 my @distributed = map { {$k => $_} } @v;
592 $self->_debug("OP($op) reinjected into the distributed array");
593 unshift @distributed, $op;
596 my $logic = $op ? substr($op, 1) : '';
598 return $self->_recurse_where(\@distributed, $logic);
601 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
602 $self->_debug("empty ARRAY($k) means 0=1");
603 return ($self->{sqlfalse});
607 sub _where_hashpair_HASHREF {
608 my ($self, $k, $v, $logic) = @_;
611 my ($all_sql, @all_bind);
613 for my $op (sort keys %$v) {
616 # put the operator in canonical form
617 $op =~ s/^-//; # remove initial dash
618 $op =~ tr/_/ /; # underscores become spaces
619 $op =~ s/^\s+//; # no initial space
620 $op =~ s/\s+$//; # no final space
621 $op =~ s/\s+/ /; # multiple spaces become one
625 # CASE: special operators like -in or -between
626 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
628 my $handler = $special_op->{handler};
630 puke "No handler supplied for special operator matching $special_op->{regex}";
632 elsif (not ref $handler) {
633 ($sql, @bind) = $self->$handler ($k, $op, $val);
635 elsif (ref $handler eq 'CODE') {
636 ($sql, @bind) = $handler->($self, $k, $op, $val);
639 puke "Illegal handler for special operator matching $special_op->{regex} - expecting a method name or a coderef";
643 $self->_SWITCH_refkind($val, {
645 ARRAYREF => sub { # CASE: col => {op => \@vals}
646 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
649 SCALARREF => sub { # CASE: col => {op => \$scalar} (literal SQL without bind)
650 $sql = join ' ', $self->_convert($self->_quote($k)),
651 $self->_sqlcase($op),
655 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
656 my ($sub_sql, @sub_bind) = @$$val;
657 $self->_assert_bindval_matches_bindtype(@sub_bind);
658 $sql = join ' ', $self->_convert($self->_quote($k)),
659 $self->_sqlcase($op),
665 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $op);
668 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
669 my $is = ($op =~ $self->{equality_op}) ? 'is' :
670 ($op =~ $self->{inequality_op}) ? 'is not' :
671 puke "unexpected operator '$op' with undef operand";
672 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
675 FALLBACK => sub { # CASE: col => {op => $scalar}
676 $sql = join ' ', $self->_convert($self->_quote($k)),
677 $self->_sqlcase($op),
678 $self->_convert('?');
679 @bind = $self->_bindtype($k, $val);
684 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
685 push @all_bind, @bind;
687 return ($all_sql, @all_bind);
692 sub _where_field_op_ARRAYREF {
693 my ($self, $k, $op, $vals) = @_;
695 my @vals = @$vals; #always work on a copy
698 $self->_debug("ARRAY($vals) means multiple elements: [ @vals ]");
700 # see if the first element is an -and/-or op
702 if ($vals[0] =~ /^ - ( AND|OR ) $/ix) {
707 # distribute $op over each remaining member of @vals, append logic if exists
708 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
710 # LDNOTE : had planned to change the distribution logic when
711 # $op =~ $self->{inequality_op}, because of Morgan laws :
712 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
713 # WHERE field != 22 OR field != 33 : the user probably means
714 # WHERE field != 22 AND field != 33.
715 # To do this, replace the above to roughly :
716 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
717 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
721 # try to DWIM on equality operators
722 # LDNOTE : not 100% sure this is the correct thing to do ...
723 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
724 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
727 puke "operator '$op' applied on an empty array (field '$k')";
732 sub _where_hashpair_SCALARREF {
733 my ($self, $k, $v) = @_;
734 $self->_debug("SCALAR($k) means literal SQL: $$v");
735 my $sql = $self->_quote($k) . " " . $$v;
739 # literal SQL with bind
740 sub _where_hashpair_ARRAYREFREF {
741 my ($self, $k, $v) = @_;
742 $self->_debug("REF($k) means literal SQL: @${$v}");
743 my ($sql, @bind) = @${$v};
744 $self->_assert_bindval_matches_bindtype(@bind);
745 $sql = $self->_quote($k) . " " . $sql;
746 return ($sql, @bind );
749 # literal SQL without bind
750 sub _where_hashpair_SCALAR {
751 my ($self, $k, $v) = @_;
752 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
753 my $sql = join ' ', $self->_convert($self->_quote($k)),
754 $self->_sqlcase($self->{cmp}),
755 $self->_convert('?');
756 my @bind = $self->_bindtype($k, $v);
757 return ( $sql, @bind);
761 sub _where_hashpair_UNDEF {
762 my ($self, $k, $v) = @_;
763 $self->_debug("UNDEF($k) means IS NULL");
764 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
768 #======================================================================
769 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
770 #======================================================================
773 sub _where_SCALARREF {
774 my ($self, $where) = @_;
777 $self->_debug("SCALAR(*top) means literal SQL: $$where");
783 my ($self, $where) = @_;
786 $self->_debug("NOREF(*top) means literal SQL: $where");
797 #======================================================================
798 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
799 #======================================================================
802 sub _where_field_BETWEEN {
803 my ($self, $k, $op, $vals) = @_;
805 (ref $vals eq 'ARRAY' && @$vals == 2) or
806 (ref $vals eq 'REF' && (@$$vals == 1 || @$$vals == 2 || @$$vals == 3))
807 or puke "special op 'between' requires an arrayref of two values (or a scalarref or arrayrefref for literal SQL)";
809 my ($clause, @bind, $label, $and, $placeholder);
810 $label = $self->_convert($self->_quote($k));
811 $and = ' ' . $self->_sqlcase('and') . ' ';
812 $placeholder = $self->_convert('?');
813 $op = $self->_sqlcase($op);
815 if (ref $vals eq 'REF') {
816 ($clause, @bind) = @$$vals;
819 my (@all_sql, @all_bind);
821 foreach my $val (@$vals) {
822 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
824 return ($placeholder, ($val));
827 return ($self->_convert($$val), ());
831 push @all_bind, @bind;
834 $clause = (join $and, @all_sql);
835 @bind = $self->_bindtype($k, @all_bind);
837 my $sql = "( $label $op $clause )";
842 sub _where_field_IN {
843 my ($self, $k, $op, $vals) = @_;
845 # backwards compatibility : if scalar, force into an arrayref
846 $vals = [$vals] if defined $vals && ! ref $vals;
848 my ($label) = $self->_convert($self->_quote($k));
849 my ($placeholder) = $self->_convert('?');
850 $op = $self->_sqlcase($op);
852 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
853 ARRAYREF => sub { # list of choices
854 if (@$vals) { # nonempty list
855 my $placeholders = join ", ", (($placeholder) x @$vals);
856 my $sql = "$label $op ( $placeholders )";
857 my @bind = $self->_bindtype($k, @$vals);
859 return ($sql, @bind);
861 else { # empty list : some databases won't understand "IN ()", so DWIM
862 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
867 ARRAYREFREF => sub { # literal SQL with bind
868 my ($sql, @bind) = @$$vals;
869 $self->_assert_bindval_matches_bindtype(@bind);
870 return ("$label $op ( $sql )", @bind);
874 puke "special op 'in' requires an arrayref (or arrayref-ref)";
878 return ($sql, @bind);
884 #======================================================================
886 #======================================================================
889 my ($self, $arg) = @_;
892 for my $c ($self->_order_by_chunks ($arg) ) {
893 $self->_SWITCH_refkind ($c, {
894 SCALAR => sub { push @sql, $c },
895 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
901 $self->_sqlcase(' order by'),
907 return wantarray ? ($sql, @bind) : $sql;
910 sub _order_by_chunks {
911 my ($self, $arg) = @_;
913 return $self->_SWITCH_refkind($arg, {
916 map { $self->_order_by_chunks ($_ ) } @$arg;
919 ARRAYREFREF => sub { [ @$$arg ] },
921 SCALAR => sub {$self->_quote($arg)},
923 UNDEF => sub {return () },
925 SCALARREF => sub {$$arg}, # literal SQL, no quoting
928 # get first pair in hash
929 my ($key, $val) = each %$arg;
931 return () unless $key;
933 if ( (keys %$arg) > 1 or not $key =~ /^-(desc|asc)/i ) {
934 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
940 for my $c ($self->_order_by_chunks ($val)) {
943 $self->_SWITCH_refkind ($c, {
952 $sql = $sql . ' ' . $self->_sqlcase($direction);
954 push @ret, [ $sql, @bind];
963 #======================================================================
964 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
965 #======================================================================
970 $self->_SWITCH_refkind($from, {
971 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
972 SCALAR => sub {$self->_quote($from)},
973 SCALARREF => sub {$$from},
974 ARRAYREFREF => sub {join ', ', @$from;},
979 #======================================================================
981 #======================================================================
987 $label or puke "can't quote an empty label";
989 # left and right quote characters
990 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
991 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
992 ARRAYREF => sub {@{$self->{quote_char}}},
996 or puke "quote_char must be an arrayref of 2 values";
998 # no quoting if no quoting chars
999 $ql or return $label;
1001 # no quoting for literal SQL
1002 return $$label if ref($label) eq 'SCALAR';
1004 # separate table / column (if applicable)
1005 my $sep = $self->{name_sep} || '';
1006 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
1008 # do the quoting, except for "*" or for `table`.*
1009 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
1011 # reassemble and return.
1012 return join $sep, @quoted;
1016 # Conversion, if applicable
1018 my ($self, $arg) = @_;
1020 # LDNOTE : modified the previous implementation below because
1021 # it was not consistent : the first "return" is always an array,
1022 # the second "return" is context-dependent. Anyway, _convert
1023 # seems always used with just a single argument, so make it a
1025 # return @_ unless $self->{convert};
1026 # my $conv = $self->_sqlcase($self->{convert});
1027 # my @ret = map { $conv.'('.$_.')' } @_;
1028 # return wantarray ? @ret : $ret[0];
1029 if ($self->{convert}) {
1030 my $conv = $self->_sqlcase($self->{convert});
1031 $arg = $conv.'('.$arg.')';
1039 my($col, @vals) = @_;
1041 #LDNOTE : changed original implementation below because it did not make
1042 # sense when bindtype eq 'columns' and @vals > 1.
1043 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1045 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
1048 # Dies if any element of @bind is not in [colname => value] format
1049 # if bindtype is 'columns'.
1050 sub _assert_bindval_matches_bindtype {
1051 my ($self, @bind) = @_;
1053 if ($self->{bindtype} eq 'columns') {
1054 foreach my $val (@bind) {
1055 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1056 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1062 sub _join_sql_clauses {
1063 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1065 if (@$clauses_aref > 1) {
1066 my $join = " " . $self->_sqlcase($logic) . " ";
1067 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1068 return ($sql, @$bind_aref);
1070 elsif (@$clauses_aref) {
1071 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1074 return (); # if no SQL, ignore @$bind_aref
1079 # Fix SQL case, if so requested
1083 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1084 # don't touch the argument ... crooked logic, but let's not change it!
1085 return $self->{case} ? $_[0] : uc($_[0]);
1089 #======================================================================
1090 # DISPATCHING FROM REFKIND
1091 #======================================================================
1094 my ($self, $data) = @_;
1100 # blessed objects are treated like scalars
1101 $ref = (blessed $data) ? '' : ref $data;
1102 $n_steps += 1 if $ref;
1103 last if $ref ne 'REF';
1107 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
1109 return $base . ('REF' x $n_steps);
1115 my ($self, $data) = @_;
1116 my @try = ($self->_refkind($data));
1117 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1118 push @try, 'FALLBACK';
1122 sub _METHOD_FOR_refkind {
1123 my ($self, $meth_prefix, $data) = @_;
1124 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
1125 $self->_try_refkind($data)
1126 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1131 sub _SWITCH_refkind {
1132 my ($self, $data, $dispatch_table) = @_;
1134 my $coderef = first {$_} map {$dispatch_table->{$_}}
1135 $self->_try_refkind($data)
1136 or puke "no dispatch entry for ".$self->_refkind($data);
1143 #======================================================================
1144 # VALUES, GENERATE, AUTOLOAD
1145 #======================================================================
1147 # LDNOTE: original code from nwiger, didn't touch code in that section
1148 # I feel the AUTOLOAD stuff should not be the default, it should
1149 # only be activated on explicit demand by user.
1153 my $data = shift || return;
1154 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1155 unless ref $data eq 'HASH';
1158 foreach my $k ( sort keys %$data ) {
1159 my $v = $data->{$k};
1160 $self->_SWITCH_refkind($v, {
1162 if ($self->{array_datatypes}) { # array datatype
1163 push @all_bind, $self->_bindtype($k, $v);
1165 else { # literal SQL with bind
1166 my ($sql, @bind) = @$v;
1167 $self->_assert_bindval_matches_bindtype(@bind);
1168 push @all_bind, @bind;
1171 ARRAYREFREF => sub { # literal SQL with bind
1172 my ($sql, @bind) = @${$v};
1173 $self->_assert_bindval_matches_bindtype(@bind);
1174 push @all_bind, @bind;
1176 SCALARREF => sub { # literal SQL without bind
1178 SCALAR_or_UNDEF => sub {
1179 push @all_bind, $self->_bindtype($k, $v);
1190 my(@sql, @sqlq, @sqlv);
1194 if ($ref eq 'HASH') {
1195 for my $k (sort keys %$_) {
1198 my $label = $self->_quote($k);
1199 if ($r eq 'ARRAY') {
1200 # literal SQL with bind
1201 my ($sql, @bind) = @$v;
1202 $self->_assert_bindval_matches_bindtype(@bind);
1203 push @sqlq, "$label = $sql";
1205 } elsif ($r eq 'SCALAR') {
1206 # literal SQL without bind
1207 push @sqlq, "$label = $$v";
1209 push @sqlq, "$label = ?";
1210 push @sqlv, $self->_bindtype($k, $v);
1213 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1214 } elsif ($ref eq 'ARRAY') {
1215 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1218 if ($r eq 'ARRAY') { # literal SQL with bind
1219 my ($sql, @bind) = @$v;
1220 $self->_assert_bindval_matches_bindtype(@bind);
1223 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1224 # embedded literal SQL
1231 push @sql, '(' . join(', ', @sqlq) . ')';
1232 } elsif ($ref eq 'SCALAR') {
1236 # strings get case twiddled
1237 push @sql, $self->_sqlcase($_);
1241 my $sql = join ' ', @sql;
1243 # this is pretty tricky
1244 # if ask for an array, return ($stmt, @bind)
1245 # otherwise, s/?/shift @sqlv/ to put it inline
1247 return ($sql, @sqlv);
1249 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1250 ref $d ? $d->[1] : $d/e;
1259 # This allows us to check for a local, then _form, attr
1261 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1262 return $self->generate($name, @_);
1273 SQL::Abstract - Generate SQL from Perl data structures
1279 my $sql = SQL::Abstract->new;
1281 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1283 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1285 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1287 my($stmt, @bind) = $sql->delete($table, \%where);
1289 # Then, use these in your DBI statements
1290 my $sth = $dbh->prepare($stmt);
1291 $sth->execute(@bind);
1293 # Just generate the WHERE clause
1294 my($stmt, @bind) = $sql->where(\%where, \@order);
1296 # Return values in the same order, for hashed queries
1297 # See PERFORMANCE section for more details
1298 my @bind = $sql->values(\%fieldvals);
1302 This module was inspired by the excellent L<DBIx::Abstract>.
1303 However, in using that module I found that what I really wanted
1304 to do was generate SQL, but still retain complete control over my
1305 statement handles and use the DBI interface. So, I set out to
1306 create an abstract SQL generation module.
1308 While based on the concepts used by L<DBIx::Abstract>, there are
1309 several important differences, especially when it comes to WHERE
1310 clauses. I have modified the concepts used to make the SQL easier
1311 to generate from Perl data structures and, IMO, more intuitive.
1312 The underlying idea is for this module to do what you mean, based
1313 on the data structures you provide it. The big advantage is that
1314 you don't have to modify your code every time your data changes,
1315 as this module figures it out.
1317 To begin with, an SQL INSERT is as easy as just specifying a hash
1318 of C<key=value> pairs:
1321 name => 'Jimbo Bobson',
1322 phone => '123-456-7890',
1323 address => '42 Sister Lane',
1324 city => 'St. Louis',
1325 state => 'Louisiana',
1328 The SQL can then be generated with this:
1330 my($stmt, @bind) = $sql->insert('people', \%data);
1332 Which would give you something like this:
1334 $stmt = "INSERT INTO people
1335 (address, city, name, phone, state)
1336 VALUES (?, ?, ?, ?, ?)";
1337 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1338 '123-456-7890', 'Louisiana');
1340 These are then used directly in your DBI code:
1342 my $sth = $dbh->prepare($stmt);
1343 $sth->execute(@bind);
1345 =head2 Inserting and Updating Arrays
1347 If your database has array types (like for example Postgres),
1348 activate the special option C<< array_datatypes => 1 >>
1349 when creating the C<SQL::Abstract> object.
1350 Then you may use an arrayref to insert and update database array types:
1352 my $sql = SQL::Abstract->new(array_datatypes => 1);
1354 planets => [qw/Mercury Venus Earth Mars/]
1357 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1361 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1363 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1366 =head2 Inserting and Updating SQL
1368 In order to apply SQL functions to elements of your C<%data> you may
1369 specify a reference to an arrayref for the given hash value. For example,
1370 if you need to execute the Oracle C<to_date> function on a value, you can
1371 say something like this:
1375 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1378 The first value in the array is the actual SQL. Any other values are
1379 optional and would be included in the bind values array. This gives
1382 my($stmt, @bind) = $sql->insert('people', \%data);
1384 $stmt = "INSERT INTO people (name, date_entered)
1385 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1386 @bind = ('Bill', '03/02/2003');
1388 An UPDATE is just as easy, all you change is the name of the function:
1390 my($stmt, @bind) = $sql->update('people', \%data);
1392 Notice that your C<%data> isn't touched; the module will generate
1393 the appropriately quirky SQL for you automatically. Usually you'll
1394 want to specify a WHERE clause for your UPDATE, though, which is
1395 where handling C<%where> hashes comes in handy...
1397 =head2 Complex where statements
1399 This module can generate pretty complicated WHERE statements
1400 easily. For example, simple C<key=value> pairs are taken to mean
1401 equality, and if you want to see if a field is within a set
1402 of values, you can use an arrayref. Let's say we wanted to
1403 SELECT some data based on this criteria:
1406 requestor => 'inna',
1407 worker => ['nwiger', 'rcwe', 'sfz'],
1408 status => { '!=', 'completed' }
1411 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1413 The above would give you something like this:
1415 $stmt = "SELECT * FROM tickets WHERE
1416 ( requestor = ? ) AND ( status != ? )
1417 AND ( worker = ? OR worker = ? OR worker = ? )";
1418 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1420 Which you could then use in DBI code like so:
1422 my $sth = $dbh->prepare($stmt);
1423 $sth->execute(@bind);
1429 The functions are simple. There's one for each major SQL operation,
1430 and a constructor you use first. The arguments are specified in a
1431 similar order to each function (table, then fields, then a where
1432 clause) to try and simplify things.
1437 =head2 new(option => 'value')
1439 The C<new()> function takes a list of options and values, and returns
1440 a new B<SQL::Abstract> object which can then be used to generate SQL
1441 through the methods below. The options accepted are:
1447 If set to 'lower', then SQL will be generated in all lowercase. By
1448 default SQL is generated in "textbook" case meaning something like:
1450 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1452 Any setting other than 'lower' is ignored.
1456 This determines what the default comparison operator is. By default
1457 it is C<=>, meaning that a hash like this:
1459 %where = (name => 'nwiger', email => 'nate@wiger.org');
1461 Will generate SQL like this:
1463 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1465 However, you may want loose comparisons by default, so if you set
1466 C<cmp> to C<like> you would get SQL such as:
1468 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1470 You can also override the comparsion on an individual basis - see
1471 the huge section on L</"WHERE CLAUSES"> at the bottom.
1473 =item sqltrue, sqlfalse
1475 Expressions for inserting boolean values within SQL statements.
1476 By default these are C<1=1> and C<1=0>. They are used
1477 by the special operators C<-in> and C<-not_in> for generating
1478 correct SQL even when the argument is an empty array (see below).
1482 This determines the default logical operator for multiple WHERE
1483 statements in arrays or hashes. If absent, the default logic is "or"
1484 for arrays, and "and" for hashes. This means that a WHERE
1488 event_date => {'>=', '2/13/99'},
1489 event_date => {'<=', '4/24/03'},
1492 will generate SQL like this:
1494 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1496 This is probably not what you want given this query, though (look
1497 at the dates). To change the "OR" to an "AND", simply specify:
1499 my $sql = SQL::Abstract->new(logic => 'and');
1501 Which will change the above C<WHERE> to:
1503 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1505 The logic can also be changed locally by inserting
1506 a modifier in front of an arrayref :
1508 @where = (-and => [event_date => {'>=', '2/13/99'},
1509 event_date => {'<=', '4/24/03'} ]);
1511 See the L</"WHERE CLAUSES"> section for explanations.
1515 This will automatically convert comparisons using the specified SQL
1516 function for both column and value. This is mostly used with an argument
1517 of C<upper> or C<lower>, so that the SQL will have the effect of
1518 case-insensitive "searches". For example, this:
1520 $sql = SQL::Abstract->new(convert => 'upper');
1521 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1523 Will turn out the following SQL:
1525 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1527 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1528 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1529 not validate this option; it will just pass through what you specify verbatim).
1533 This is a kludge because many databases suck. For example, you can't
1534 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1535 Instead, you have to use C<bind_param()>:
1537 $sth->bind_param(1, 'reg data');
1538 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1540 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1541 which loses track of which field each slot refers to. Fear not.
1543 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1544 Currently, you can specify either C<normal> (default) or C<columns>. If you
1545 specify C<columns>, you will get an array that looks like this:
1547 my $sql = SQL::Abstract->new(bindtype => 'columns');
1548 my($stmt, @bind) = $sql->insert(...);
1551 [ 'column1', 'value1' ],
1552 [ 'column2', 'value2' ],
1553 [ 'column3', 'value3' ],
1556 You can then iterate through this manually, using DBI's C<bind_param()>.
1558 $sth->prepare($stmt);
1561 my($col, $data) = @$_;
1562 if ($col eq 'details' || $col eq 'comments') {
1563 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1564 } elsif ($col eq 'image') {
1565 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1567 $sth->bind_param($i, $data);
1571 $sth->execute; # execute without @bind now
1573 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1574 Basically, the advantage is still that you don't have to care which fields
1575 are or are not included. You could wrap that above C<for> loop in a simple
1576 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1577 get a layer of abstraction over manual SQL specification.
1579 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1580 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1581 will expect the bind values in this format.
1585 This is the character that a table or column name will be quoted
1586 with. By default this is an empty string, but you could set it to
1587 the character C<`>, to generate SQL like this:
1589 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1591 Alternatively, you can supply an array ref of two items, the first being the left
1592 hand quote character, and the second the right hand quote character. For
1593 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1594 that generates SQL like this:
1596 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1598 Quoting is useful if you have tables or columns names that are reserved
1599 words in your database's SQL dialect.
1603 This is the character that separates a table and column name. It is
1604 necessary to specify this when the C<quote_char> option is selected,
1605 so that tables and column names can be individually quoted like this:
1607 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1609 =item array_datatypes
1611 When this option is true, arrayrefs in INSERT or UPDATE are
1612 interpreted as array datatypes and are passed directly
1614 When this option is false, arrayrefs are interpreted
1615 as literal SQL, just like refs to arrayrefs
1616 (but this behavior is for backwards compatibility; when writing
1617 new queries, use the "reference to arrayref" syntax
1623 Takes a reference to a list of "special operators"
1624 to extend the syntax understood by L<SQL::Abstract>.
1625 See section L</"SPECIAL OPERATORS"> for details.
1629 Takes a reference to a list of "unary operators"
1630 to extend the syntax understood by L<SQL::Abstract>.
1631 See section L</"UNARY OPERATORS"> for details.
1637 =head2 insert($table, \@values || \%fieldvals)
1639 This is the simplest function. You simply give it a table name
1640 and either an arrayref of values or hashref of field/value pairs.
1641 It returns an SQL INSERT statement and a list of bind values.
1642 See the sections on L</"Inserting and Updating Arrays"> and
1643 L</"Inserting and Updating SQL"> for information on how to insert
1644 with those data types.
1646 =head2 update($table, \%fieldvals, \%where)
1648 This takes a table, hashref of field/value pairs, and an optional
1649 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1651 See the sections on L</"Inserting and Updating Arrays"> and
1652 L</"Inserting and Updating SQL"> for information on how to insert
1653 with those data types.
1655 =head2 select($source, $fields, $where, $order)
1657 This returns a SQL SELECT statement and associated list of bind values, as
1658 specified by the arguments :
1664 Specification of the 'FROM' part of the statement.
1665 The argument can be either a plain scalar (interpreted as a table
1666 name, will be quoted), or an arrayref (interpreted as a list
1667 of table names, joined by commas, quoted), or a scalarref
1668 (literal table name, not quoted), or a ref to an arrayref
1669 (list of literal table names, joined by commas, not quoted).
1673 Specification of the list of fields to retrieve from
1675 The argument can be either an arrayref (interpreted as a list
1676 of field names, will be joined by commas and quoted), or a
1677 plain scalar (literal SQL, not quoted).
1678 Please observe that this API is not as flexible as for
1679 the first argument C<$table>, for backwards compatibility reasons.
1683 Optional argument to specify the WHERE part of the query.
1684 The argument is most often a hashref, but can also be
1685 an arrayref or plain scalar --
1686 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1690 Optional argument to specify the ORDER BY part of the query.
1691 The argument can be a scalar, a hashref or an arrayref
1692 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1698 =head2 delete($table, \%where)
1700 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1701 It returns an SQL DELETE statement and list of bind values.
1703 =head2 where(\%where, \@order)
1705 This is used to generate just the WHERE clause. For example,
1706 if you have an arbitrary data structure and know what the
1707 rest of your SQL is going to look like, but want an easy way
1708 to produce a WHERE clause, use this. It returns an SQL WHERE
1709 clause and list of bind values.
1712 =head2 values(\%data)
1714 This just returns the values from the hash C<%data>, in the same
1715 order that would be returned from any of the other above queries.
1716 Using this allows you to markedly speed up your queries if you
1717 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1719 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1721 Warning: This is an experimental method and subject to change.
1723 This returns arbitrarily generated SQL. It's a really basic shortcut.
1724 It will return two different things, depending on return context:
1726 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1727 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1729 These would return the following:
1731 # First calling form
1732 $stmt = "CREATE TABLE test (?, ?)";
1733 @bind = (field1, field2);
1735 # Second calling form
1736 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1738 Depending on what you're trying to do, it's up to you to choose the correct
1739 format. In this example, the second form is what you would want.
1743 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1747 ALTER SESSION SET nls_date_format = 'MM/YY'
1749 You get the idea. Strings get their case twiddled, but everything
1750 else remains verbatim.
1755 =head1 WHERE CLAUSES
1759 This module uses a variation on the idea from L<DBIx::Abstract>. It
1760 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1761 module is that things in arrays are OR'ed, and things in hashes
1764 The easiest way to explain is to show lots of examples. After
1765 each C<%where> hash shown, it is assumed you used:
1767 my($stmt, @bind) = $sql->where(\%where);
1769 However, note that the C<%where> hash can be used directly in any
1770 of the other functions as well, as described above.
1772 =head2 Key-value pairs
1774 So, let's get started. To begin, a simple hash:
1778 status => 'completed'
1781 Is converted to SQL C<key = val> statements:
1783 $stmt = "WHERE user = ? AND status = ?";
1784 @bind = ('nwiger', 'completed');
1786 One common thing I end up doing is having a list of values that
1787 a field can be in. To do this, simply specify a list inside of
1792 status => ['assigned', 'in-progress', 'pending'];
1795 This simple code will create the following:
1797 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1798 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1800 A field associated to an empty arrayref will be considered a
1801 logical false and will generate 0=1.
1803 =head2 Specific comparison operators
1805 If you want to specify a different type of operator for your comparison,
1806 you can use a hashref for a given column:
1810 status => { '!=', 'completed' }
1813 Which would generate:
1815 $stmt = "WHERE user = ? AND status != ?";
1816 @bind = ('nwiger', 'completed');
1818 To test against multiple values, just enclose the values in an arrayref:
1820 status => { '=', ['assigned', 'in-progress', 'pending'] };
1822 Which would give you:
1824 "WHERE status = ? OR status = ? OR status = ?"
1827 The hashref can also contain multiple pairs, in which case it is expanded
1828 into an C<AND> of its elements:
1832 status => { '!=', 'completed', -not_like => 'pending%' }
1835 # Or more dynamically, like from a form
1836 $where{user} = 'nwiger';
1837 $where{status}{'!='} = 'completed';
1838 $where{status}{'-not_like'} = 'pending%';
1840 # Both generate this
1841 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1842 @bind = ('nwiger', 'completed', 'pending%');
1845 To get an OR instead, you can combine it with the arrayref idea:
1849 priority => [ {'=', 2}, {'!=', 1} ]
1852 Which would generate:
1854 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1855 @bind = ('nwiger', '2', '1');
1857 If you want to include literal SQL (with or without bind values), just use a
1858 scalar reference or array reference as the value:
1861 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1862 date_expires => { '<' => \"now()" }
1865 Which would generate:
1867 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1868 @bind = ('11/26/2008');
1871 =head2 Logic and nesting operators
1873 In the example above,
1874 there is a subtle trap if you want to say something like
1875 this (notice the C<AND>):
1877 WHERE priority != ? AND priority != ?
1879 Because, in Perl you I<can't> do this:
1881 priority => { '!=', 2, '!=', 1 }
1883 As the second C<!=> key will obliterate the first. The solution
1884 is to use the special C<-modifier> form inside an arrayref:
1886 priority => [ -and => {'!=', 2},
1890 Normally, these would be joined by C<OR>, but the modifier tells it
1891 to use C<AND> instead. (Hint: You can use this in conjunction with the
1892 C<logic> option to C<new()> in order to change the way your queries
1893 work by default.) B<Important:> Note that the C<-modifier> goes
1894 B<INSIDE> the arrayref, as an extra first element. This will
1895 B<NOT> do what you think it might:
1897 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1899 Here is a quick list of equivalencies, since there is some overlap:
1902 status => {'!=', 'completed', 'not like', 'pending%' }
1903 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1906 status => {'=', ['assigned', 'in-progress']}
1907 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1908 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1912 =head2 Special operators : IN, BETWEEN, etc.
1914 You can also use the hashref format to compare a list of fields using the
1915 C<IN> comparison operator, by specifying the list as an arrayref:
1918 status => 'completed',
1919 reportid => { -in => [567, 2335, 2] }
1922 Which would generate:
1924 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1925 @bind = ('completed', '567', '2335', '2');
1927 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1930 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1931 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1932 'sqltrue' (by default : C<1=1>).
1936 Another pair of operators is C<-between> and C<-not_between>,
1937 used with an arrayref of two values:
1941 completion_date => {
1942 -not_between => ['2002-10-01', '2003-02-06']
1948 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1950 These are the two builtin "special operators"; but the
1951 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1953 =head2 Unary operators: bool
1955 If you wish to test against boolean columns or functions within your
1956 database you can use the C<-bool> and C<-not_bool> operators. For
1957 example to test the column C<is_user> being true and the column
1958 <is_enabled> being false you would use:-
1962 -not_bool => 'is_enabled',
1967 WHERE is_user AND NOT is_enabledmv
1971 =head2 Nested conditions, -and/-or prefixes
1973 So far, we've seen how multiple conditions are joined with a top-level
1974 C<AND>. We can change this by putting the different conditions we want in
1975 hashes and then putting those hashes in an array. For example:
1980 status => { -like => ['pending%', 'dispatched'] },
1984 status => 'unassigned',
1988 This data structure would create the following:
1990 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1991 OR ( user = ? AND status = ? ) )";
1992 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1995 There is also a special C<-nest>
1996 operator which adds an additional set of parens, to create a subquery.
1997 For example, to get something like this:
1999 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2000 @bind = ('nwiger', '20', 'ASIA');
2006 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2010 Finally, clauses in hashrefs or arrayrefs can be
2011 prefixed with an C<-and> or C<-or> to change the logic
2018 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2019 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2026 WHERE ( user = ? AND
2027 ( ( workhrs > ? AND geo = ? )
2028 OR ( workhrs < ? AND geo = ? ) ) )
2031 =head2 Algebraic inconsistency, for historical reasons
2033 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2034 operator goes C<outside> of the nested structure; whereas when connecting
2035 several constraints on one column, the C<-and> operator goes
2036 C<inside> the arrayref. Here is an example combining both features :
2039 -and => [a => 1, b => 2],
2040 -or => [c => 3, d => 4],
2041 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2046 WHERE ( ( ( a = ? AND b = ? )
2047 OR ( c = ? OR d = ? )
2048 OR ( e LIKE ? AND e LIKE ? ) ) )
2050 This difference in syntax is unfortunate but must be preserved for
2051 historical reasons. So be careful : the two examples below would
2052 seem algebraically equivalent, but they are not
2054 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2055 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2057 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2058 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2063 Finally, sometimes only literal SQL will do. If you want to include
2064 literal SQL verbatim, you can specify it as a scalar reference, namely:
2066 my $inn = 'is Not Null';
2068 priority => { '<', 2 },
2074 $stmt = "WHERE priority < ? AND requestor is Not Null";
2077 Note that in this example, you only get one bind parameter back, since
2078 the verbatim SQL is passed as part of the statement.
2080 Of course, just to prove a point, the above can also be accomplished
2084 priority => { '<', 2 },
2085 requestor => { '!=', undef },
2091 Conditions on boolean columns can be expressed in the
2092 same way, passing a reference to an empty string :
2095 priority => { '<', 2 },
2101 $stmt = "WHERE priority < ? AND is_ready";
2105 =head2 Literal SQL with placeholders and bind values (subqueries)
2107 If the literal SQL to be inserted has placeholders and bind values,
2108 use a reference to an arrayref (yes this is a double reference --
2109 not so common, but perfectly legal Perl). For example, to find a date
2110 in Postgres you can use something like this:
2113 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2118 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2121 Note that you must pass the bind values in the same format as they are returned
2122 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2123 provide the bind values in the C<< [ column_meta => value ] >> format, where
2124 C<column_meta> is an opaque scalar value; most commonly the column name, but
2125 you can use any scalar value (including references and blessed references),
2126 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2127 to C<columns> the above example will look like:
2130 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2133 Literal SQL is especially useful for nesting parenthesized clauses in the
2134 main SQL query. Here is a first example :
2136 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2140 bar => \["IN ($sub_stmt)" => @sub_bind],
2145 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2146 WHERE c2 < ? AND c3 LIKE ?))";
2147 @bind = (1234, 100, "foo%");
2149 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2150 are expressed in the same way. Of course the C<$sub_stmt> and
2151 its associated bind values can be generated through a former call
2154 my ($sub_stmt, @sub_bind)
2155 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2156 c3 => {-like => "foo%"}});
2159 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2162 In the examples above, the subquery was used as an operator on a column;
2163 but the same principle also applies for a clause within the main C<%where>
2164 hash, like an EXISTS subquery :
2166 my ($sub_stmt, @sub_bind)
2167 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2170 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2175 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2176 WHERE c1 = ? AND c2 > t0.c0))";
2180 Observe that the condition on C<c2> in the subquery refers to
2181 column C<t0.c0> of the main query : this is I<not> a bind
2182 value, so we have to express it through a scalar ref.
2183 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2184 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2185 what we wanted here.
2187 Another use of the subquery technique is when some SQL clauses need
2188 parentheses, as it often occurs with some proprietary SQL extensions
2189 like for example fulltext expressions, geospatial expressions,
2190 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2193 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2196 Finally, here is an example where a subquery is used
2197 for expressing unary negation:
2199 my ($sub_stmt, @sub_bind)
2200 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2201 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2203 lname => {like => '%son%'},
2204 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2209 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2210 @bind = ('%son%', 10, 20)
2216 These pages could go on for a while, since the nesting of the data
2217 structures this module can handle are pretty much unlimited (the
2218 module implements the C<WHERE> expansion as a recursive function
2219 internally). Your best bet is to "play around" with the module a
2220 little to see how the data structures behave, and choose the best
2221 format for your data based on that.
2223 And of course, all the values above will probably be replaced with
2224 variables gotten from forms or the command line. After all, if you
2225 knew everything ahead of time, you wouldn't have to worry about
2226 dynamically-generating SQL and could just hardwire it into your
2232 =head1 ORDER BY CLAUSES
2234 Some functions take an order by clause. This can either be a scalar (just a
2235 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2236 or an array of either of the two previous forms. Examples:
2238 Given | Will Generate
2239 ----------------------------------------------------------
2241 \'colA DESC' | ORDER BY colA DESC
2243 'colA' | ORDER BY colA
2245 [qw/colA colB/] | ORDER BY colA, colB
2247 {-asc => 'colA'} | ORDER BY colA ASC
2249 {-desc => 'colB'} | ORDER BY colB DESC
2251 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2253 { -asc => [qw/colA colB] } | ORDER BY colA ASC, colB ASC
2256 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2257 { -desc => [qw/colB/], | colC ASC, colD ASC
2258 { -asc => [qw/colC colD/],|
2260 ===========================================================
2264 =head1 SPECIAL OPERATORS
2266 my $sqlmaker = SQL::Abstract->new(special_ops => [
2270 my ($self, $field, $op, $arg) = @_;
2276 handler => 'method_name',
2280 A "special operator" is a SQL syntactic clause that can be
2281 applied to a field, instead of a usual binary operator.
2284 WHERE field IN (?, ?, ?)
2285 WHERE field BETWEEN ? AND ?
2286 WHERE MATCH(field) AGAINST (?, ?)
2288 Special operators IN and BETWEEN are fairly standard and therefore
2289 are builtin within C<SQL::Abstract> (as the overridable methods
2290 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2291 like the MATCH .. AGAINST example above which is specific to MySQL,
2292 you can write your own operator handlers - supply a C<special_ops>
2293 argument to the C<new> method. That argument takes an arrayref of
2294 operator definitions; each operator definition is a hashref with two
2301 the regular expression to match the operator
2305 Either a coderef or a plain scalar method name. In both cases
2306 the expected return is C<< ($sql, @bind) >>.
2308 When supplied with a method name, it is simply called on the
2309 L<SQL::Abstract/> object as:
2311 $self->$method_name ($field, $op, $arg)
2315 $op is the part that matched the handler regex
2316 $field is the LHS of the operator
2319 When supplied with a coderef, it is called as:
2321 $coderef->($self, $field, $op, $arg)
2326 For example, here is an implementation
2327 of the MATCH .. AGAINST syntax for MySQL
2329 my $sqlmaker = SQL::Abstract->new(special_ops => [
2331 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2332 {regex => qr/^match$/i,
2334 my ($self, $field, $op, $arg) = @_;
2335 $arg = [$arg] if not ref $arg;
2336 my $label = $self->_quote($field);
2337 my ($placeholder) = $self->_convert('?');
2338 my $placeholders = join ", ", (($placeholder) x @$arg);
2339 my $sql = $self->_sqlcase('match') . " ($label) "
2340 . $self->_sqlcase('against') . " ($placeholders) ";
2341 my @bind = $self->_bindtype($field, @$arg);
2342 return ($sql, @bind);
2349 =head1 UNARY OPERATORS
2351 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2355 my ($self, $op, $arg) = @_;
2361 handler => 'method_name',
2365 A "unary operator" is a SQL syntactic clause that can be
2366 applied to a field - the operator goes before the field
2368 You can write your own operator handlers - supply a C<unary_ops>
2369 argument to the C<new> method. That argument takes an arrayref of
2370 operator definitions; each operator definition is a hashref with two
2377 the regular expression to match the operator
2381 Either a coderef or a plain scalar method name. In both cases
2382 the expected return is C<< $sql >>.
2384 When supplied with a method name, it is simply called on the
2385 L<SQL::Abstract/> object as:
2387 $self->$method_name ($op, $arg)
2391 $op is the part that matched the handler regex
2392 $arg is the RHS or argument of the operator
2394 When supplied with a coderef, it is called as:
2396 $coderef->($self, $op, $arg)
2404 Thanks to some benchmarking by Mark Stosberg, it turns out that
2405 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2406 I must admit this wasn't an intentional design issue, but it's a
2407 byproduct of the fact that you get to control your C<DBI> handles
2410 To maximize performance, use a code snippet like the following:
2412 # prepare a statement handle using the first row
2413 # and then reuse it for the rest of the rows
2415 for my $href (@array_of_hashrefs) {
2416 $stmt ||= $sql->insert('table', $href);
2417 $sth ||= $dbh->prepare($stmt);
2418 $sth->execute($sql->values($href));
2421 The reason this works is because the keys in your C<$href> are sorted
2422 internally by B<SQL::Abstract>. Thus, as long as your data retains
2423 the same structure, you only have to generate the SQL the first time
2424 around. On subsequent queries, simply use the C<values> function provided
2425 by this module to return your values in the correct order.
2430 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2431 really like this part (I do, at least). Building up a complex query
2432 can be as simple as the following:
2436 use CGI::FormBuilder;
2439 my $form = CGI::FormBuilder->new(...);
2440 my $sql = SQL::Abstract->new;
2442 if ($form->submitted) {
2443 my $field = $form->field;
2444 my $id = delete $field->{id};
2445 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2448 Of course, you would still have to connect using C<DBI> to run the
2449 query, but the point is that if you make your form look like your
2450 table, the actual query script can be extremely simplistic.
2452 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2453 a fast interface to returning and formatting data. I frequently
2454 use these three modules together to write complex database query
2455 apps in under 50 lines.
2460 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2461 Great care has been taken to preserve the I<published> behavior
2462 documented in previous versions in the 1.* family; however,
2463 some features that were previously undocumented, or behaved
2464 differently from the documentation, had to be changed in order
2465 to clarify the semantics. Hence, client code that was relying
2466 on some dark areas of C<SQL::Abstract> v1.*
2467 B<might behave differently> in v1.50.
2469 The main changes are :
2475 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2479 support for the { operator => \"..." } construct (to embed literal SQL)
2483 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2487 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2491 defensive programming : check arguments
2495 fixed bug with global logic, which was previously implemented
2496 through global variables yielding side-effects. Prior versions would
2497 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2498 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2499 Now this is interpreted
2500 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2505 fixed semantics of _bindtype on array args
2509 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2510 we just avoid shifting arrays within that tree.
2514 dropped the C<_modlogic> function
2520 =head1 ACKNOWLEDGEMENTS
2522 There are a number of individuals that have really helped out with
2523 this module. Unfortunately, most of them submitted bugs via CPAN
2524 so I have no idea who they are! But the people I do know are:
2526 Ash Berlin (order_by hash term support)
2527 Matt Trout (DBIx::Class support)
2528 Mark Stosberg (benchmarking)
2529 Chas Owens (initial "IN" operator support)
2530 Philip Collins (per-field SQL functions)
2531 Eric Kolve (hashref "AND" support)
2532 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2533 Dan Kubb (support for "quote_char" and "name_sep")
2534 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2535 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2536 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2537 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2543 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2547 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2549 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2551 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2552 While not an official support venue, C<DBIx::Class> makes heavy use of
2553 C<SQL::Abstract>, and as such list members there are very familiar with
2554 how to create queries.
2558 This module is free software; you may copy this under the terms of
2559 the GNU General Public License, or the Artistic License, copies of
2560 which should have accompanied your Perl kit.