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.58';
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 # the digits are backcompat stuff
35 { regex => qr/^and (?: \s? \d+ )? $/xi, handler => '_where_op_ANDOR' },
36 { regex => qr/^or (?: \s? \d+ )? $/xi, handler => '_where_op_ANDOR' },
37 { regex => qr/^nest (?: \s? \d+ )? $/xi, handler => '_where_op_NEST' },
38 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
41 #======================================================================
42 # DEBUGGING AND ERROR REPORTING
43 #======================================================================
46 return unless $_[0]->{debug}; shift; # a little faster
47 my $func = (caller(1))[3];
48 warn "[$func] ", @_, "\n";
52 my($func) = (caller(1))[3];
53 carp "[$func] Warning: ", @_;
57 my($func) = (caller(1))[3];
58 croak "[$func] Fatal: ", @_;
62 #======================================================================
64 #======================================================================
68 my $class = ref($self) || $self;
69 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
71 # choose our case by keeping an option around
72 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
74 # default logic for interpreting arrayrefs
75 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
77 # how to return bind vars
78 # LDNOTE: changed nwiger code : why this 'delete' ??
79 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
80 $opt{bindtype} ||= 'normal';
82 # default comparison is "=", but can be overridden
85 # try to recognize which are the 'equality' and 'unequality' ops
86 # (temporary quickfix, should go through a more seasoned API)
87 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
88 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
91 $opt{sqltrue} ||= '1=1';
92 $opt{sqlfalse} ||= '0=1';
95 $opt{special_ops} ||= [];
96 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
99 $opt{unary_ops} ||= [];
100 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
102 return bless \%opt, $class;
107 #======================================================================
109 #======================================================================
113 my $table = $self->_table(shift);
114 my $data = shift || return;
116 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
117 my ($sql, @bind) = $self->$method($data);
118 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
119 return wantarray ? ($sql, @bind) : $sql;
122 sub _insert_HASHREF { # explicit list of fields and then values
123 my ($self, $data) = @_;
125 my @fields = sort keys %$data;
127 my ($sql, @bind) = $self->_insert_values($data);
130 $_ = $self->_quote($_) foreach @fields;
131 $sql = "( ".join(", ", @fields).") ".$sql;
133 return ($sql, @bind);
136 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
137 my ($self, $data) = @_;
139 # no names (arrayref) so can't generate bindtype
140 $self->{bindtype} ne 'columns'
141 or belch "can't do 'columns' bindtype when called with arrayref";
143 # fold the list of values into a hash of column name - value pairs
144 # (where the column names are artificially generated, and their
145 # lexicographical ordering keep the ordering of the original list)
146 my $i = "a"; # incremented values will be in lexicographical order
147 my $data_in_hash = { map { ($i++ => $_) } @$data };
149 return $self->_insert_values($data_in_hash);
152 sub _insert_ARRAYREFREF { # literal SQL with bind
153 my ($self, $data) = @_;
155 my ($sql, @bind) = @${$data};
156 $self->_assert_bindval_matches_bindtype(@bind);
158 return ($sql, @bind);
162 sub _insert_SCALARREF { # literal SQL without bind
163 my ($self, $data) = @_;
169 my ($self, $data) = @_;
171 my (@values, @all_bind);
172 foreach my $column (sort keys %$data) {
173 my $v = $data->{$column};
175 $self->_SWITCH_refkind($v, {
178 if ($self->{array_datatypes}) { # if array datatype are activated
180 push @all_bind, $self->_bindtype($column, $v);
182 else { # else literal SQL with bind
183 my ($sql, @bind) = @$v;
184 $self->_assert_bindval_matches_bindtype(@bind);
186 push @all_bind, @bind;
190 ARRAYREFREF => sub { # literal SQL with bind
191 my ($sql, @bind) = @${$v};
192 $self->_assert_bindval_matches_bindtype(@bind);
194 push @all_bind, @bind;
197 # THINK : anything useful to do with a HASHREF ?
198 HASHREF => sub { # (nothing, but old SQLA passed it through)
199 #TODO in SQLA >= 2.0 it will die instead
200 belch "HASH ref as bind value in insert is not supported";
202 push @all_bind, $self->_bindtype($column, $v);
205 SCALARREF => sub { # literal SQL without bind
209 SCALAR_or_UNDEF => sub {
211 push @all_bind, $self->_bindtype($column, $v);
218 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
219 return ($sql, @all_bind);
224 #======================================================================
226 #======================================================================
231 my $table = $self->_table(shift);
232 my $data = shift || return;
235 # first build the 'SET' part of the sql statement
236 my (@set, @all_bind);
237 puke "Unsupported data type specified to \$sql->update"
238 unless ref $data eq 'HASH';
240 for my $k (sort keys %$data) {
243 my $label = $self->_quote($k);
245 $self->_SWITCH_refkind($v, {
247 if ($self->{array_datatypes}) { # array datatype
248 push @set, "$label = ?";
249 push @all_bind, $self->_bindtype($k, $v);
251 else { # literal SQL with bind
252 my ($sql, @bind) = @$v;
253 $self->_assert_bindval_matches_bindtype(@bind);
254 push @set, "$label = $sql";
255 push @all_bind, @bind;
258 ARRAYREFREF => sub { # literal SQL with bind
259 my ($sql, @bind) = @${$v};
260 $self->_assert_bindval_matches_bindtype(@bind);
261 push @set, "$label = $sql";
262 push @all_bind, @bind;
264 SCALARREF => sub { # literal SQL without bind
265 push @set, "$label = $$v";
267 SCALAR_or_UNDEF => sub {
268 push @set, "$label = ?";
269 push @all_bind, $self->_bindtype($k, $v);
275 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
279 my($where_sql, @where_bind) = $self->where($where);
281 push @all_bind, @where_bind;
284 return wantarray ? ($sql, @all_bind) : $sql;
290 #======================================================================
292 #======================================================================
297 my $table = $self->_table(shift);
298 my $fields = shift || '*';
302 my($where_sql, @bind) = $self->where($where, $order);
304 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
306 my $sql = join(' ', $self->_sqlcase('select'), $f,
307 $self->_sqlcase('from'), $table)
310 return wantarray ? ($sql, @bind) : $sql;
313 #======================================================================
315 #======================================================================
320 my $table = $self->_table(shift);
324 my($where_sql, @bind) = $self->where($where);
325 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
327 return wantarray ? ($sql, @bind) : $sql;
331 #======================================================================
333 #======================================================================
337 # Finally, a separate routine just to handle WHERE clauses
339 my ($self, $where, $order) = @_;
342 my ($sql, @bind) = $self->_recurse_where($where);
343 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
347 $sql .= $self->_order_by($order);
350 return wantarray ? ($sql, @bind) : $sql;
355 my ($self, $where, $logic) = @_;
357 # dispatch on appropriate method according to refkind of $where
358 my $method = $self->_METHOD_FOR_refkind("_where", $where);
361 my ($sql, @bind) = $self->$method($where, $logic);
363 # DBIx::Class directly calls _recurse_where in scalar context, so
364 # we must implement it, even if not in the official API
365 return wantarray ? ($sql, @bind) : $sql;
370 #======================================================================
371 # WHERE: top-level ARRAYREF
372 #======================================================================
375 sub _where_ARRAYREF {
376 my ($self, $where, $logic) = @_;
378 $logic = uc($logic || $self->{logic});
379 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
381 my @clauses = @$where;
383 my (@sql_clauses, @all_bind);
384 # need to use while() so can shift() for pairs
385 while (my $el = shift @clauses) {
387 # switch according to kind of $el and get corresponding ($sql, @bind)
388 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
390 # skip empty elements, otherwise get invalid trailing AND stuff
391 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
393 ARRAYREFREF => sub { @{${$el}} if @{${$el}}},
395 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
396 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
397 # side-effect: the first hashref within an array would change
398 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
399 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
400 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
402 SCALARREF => sub { ($$el); },
404 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
405 $self->_recurse_where({$el => shift(@clauses)})},
407 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
411 push @sql_clauses, $sql;
412 push @all_bind, @bind;
416 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
419 #======================================================================
420 # WHERE: top-level ARRAYREFREF
421 #======================================================================
423 sub _where_ARRAYREFREF {
424 my ($self, $where) = @_;
425 my ($sql, @bind) = @{${$where}};
427 return ($sql, @bind);
430 #======================================================================
431 # WHERE: top-level HASHREF
432 #======================================================================
435 my ($self, $where) = @_;
436 my (@sql_clauses, @all_bind);
438 for my $k (sort keys %$where) {
439 my $v = $where->{$k};
441 # ($k => $v) is either a special op or a regular hashpair
442 my ($sql, @bind) = ($k =~ /^(-.+)/) ? $self->_where_op_in_hash($1, $v)
444 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
445 $self->$method($k, $v);
448 push @sql_clauses, $sql;
449 push @all_bind, @bind;
452 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
456 sub _where_op_in_hash {
457 my ($self, $orig_op, $v) = @_;
459 # put the operator in canonical form
461 $op =~ s/^-//; # remove initial dash
462 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
463 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
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: $orig_op";
472 elsif (not ref $handler) {
473 if ($op =~ s/\s?\d+$//) {
474 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
475 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
477 return $self->$handler ($op, $v);
479 elsif (ref $handler eq 'CODE') {
480 return $handler->($self, $op, $v);
483 puke "Illegal handler for operator $orig_op - expecting a method name or a coderef";
487 sub _where_op_ANDOR {
488 my ($self, $op, $v) = @_;
490 $self->_SWITCH_refkind($v, {
492 return $self->_where_ARRAYREF($v, $op);
496 return ( $op =~ /^or/i )
497 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
498 : $self->_where_HASHREF($v);
502 puke "-$op => \\\$scalar not supported, use -nest => ...";
506 puke "-$op => \\[..] not supported, use -nest => ...";
509 SCALAR => sub { # permissively interpreted as SQL
510 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
514 puke "-$op => undef not supported";
520 my ($self, $op, $v) = @_;
522 $self->_SWITCH_refkind($v, {
525 return $self->_where_ARRAYREF($v, '');
529 return $self->_where_HASHREF($v);
532 SCALARREF => sub { # literal SQL
536 ARRAYREFREF => sub { # literal SQL
540 SCALAR => sub { # permissively interpreted as SQL
541 belch "literal SQL should be -nest => \\'scalar' "
542 . "instead of -nest => 'scalar' ";
547 puke "-$op => undef not supported";
554 my ($self, $op, $v) = @_;
556 my ( $prefix, $suffix ) = ( $op =~ /\bnot\b/i )
559 $self->_SWITCH_refkind($v, {
561 my ( $sql, @bind ) = $self->_where_ARRAYREF($v, '');
562 return ( ($prefix . $sql . $suffix), @bind );
566 my ( $sql, @bind ) = @{ ${$v} };
567 return ( ($prefix . $sql . $suffix), @bind );
571 my ( $sql, @bind ) = $self->_where_HASHREF($v);
572 return ( ($prefix . $sql . $suffix), @bind );
575 SCALARREF => sub { # literal SQL
576 return ($prefix . $$v . $suffix);
579 SCALAR => sub { # interpreted as SQL column
580 return ($prefix . $self->_convert($self->_quote($v)) . $suffix);
584 puke "-$op => undef not supported";
590 sub _where_hashpair_ARRAYREF {
591 my ($self, $k, $v) = @_;
594 my @v = @$v; # need copy because of shift below
595 $self->_debug("ARRAY($k) means distribute over elements");
597 # put apart first element if it is an operator (-and, -or)
599 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
603 my @distributed = map { {$k => $_} } @v;
606 $self->_debug("OP($op) reinjected into the distributed array");
607 unshift @distributed, $op;
610 my $logic = $op ? substr($op, 1) : '';
612 return $self->_recurse_where(\@distributed, $logic);
615 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
616 $self->_debug("empty ARRAY($k) means 0=1");
617 return ($self->{sqlfalse});
621 sub _where_hashpair_HASHREF {
622 my ($self, $k, $v, $logic) = @_;
625 my ($all_sql, @all_bind);
627 for my $orig_op (sort keys %$v) {
628 my $val = $v->{$orig_op};
630 # put the operator in canonical form
632 $op =~ s/^-//; # remove initial dash
633 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
634 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
638 # CASE: special operators like -in or -between
639 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
641 my $handler = $special_op->{handler};
643 puke "No handler supplied for special operator $orig_op";
645 elsif (not ref $handler) {
646 ($sql, @bind) = $self->$handler ($k, $op, $val);
648 elsif (ref $handler eq 'CODE') {
649 ($sql, @bind) = $handler->($self, $k, $op, $val);
652 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
656 $self->_SWITCH_refkind($val, {
658 ARRAYREF => sub { # CASE: col => {op => \@vals}
659 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
662 SCALARREF => sub { # CASE: col => {op => \$scalar} (literal SQL without bind)
663 $sql = join ' ', $self->_convert($self->_quote($k)),
664 $self->_sqlcase($op),
668 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
669 my ($sub_sql, @sub_bind) = @$$val;
670 $self->_assert_bindval_matches_bindtype(@sub_bind);
671 $sql = join ' ', $self->_convert($self->_quote($k)),
672 $self->_sqlcase($op),
678 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $op);
681 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
682 my $is = ($op =~ $self->{equality_op}) ? 'is' :
683 ($op =~ $self->{inequality_op}) ? 'is not' :
684 puke "unexpected operator '$orig_op' with undef operand";
685 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
688 FALLBACK => sub { # CASE: col => {op => $scalar}
689 $sql = join ' ', $self->_convert($self->_quote($k)),
690 $self->_sqlcase($op),
691 $self->_convert('?');
692 @bind = $self->_bindtype($k, $val);
697 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
698 push @all_bind, @bind;
700 return ($all_sql, @all_bind);
705 sub _where_field_op_ARRAYREF {
706 my ($self, $k, $op, $vals) = @_;
708 my @vals = @$vals; #always work on a copy
711 $self->_debug("ARRAY($vals) means multiple elements: [ @vals ]");
713 # see if the first element is an -and/-or op
715 if ($vals[0] =~ /^ - ( AND|OR ) $/ix) {
720 # distribute $op over each remaining member of @vals, append logic if exists
721 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
723 # LDNOTE : had planned to change the distribution logic when
724 # $op =~ $self->{inequality_op}, because of Morgan laws :
725 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
726 # WHERE field != 22 OR field != 33 : the user probably means
727 # WHERE field != 22 AND field != 33.
728 # To do this, replace the above to roughly :
729 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
730 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
734 # try to DWIM on equality operators
735 # LDNOTE : not 100% sure this is the correct thing to do ...
736 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
737 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
740 puke "operator '$op' applied on an empty array (field '$k')";
745 sub _where_hashpair_SCALARREF {
746 my ($self, $k, $v) = @_;
747 $self->_debug("SCALAR($k) means literal SQL: $$v");
748 my $sql = $self->_quote($k) . " " . $$v;
752 # literal SQL with bind
753 sub _where_hashpair_ARRAYREFREF {
754 my ($self, $k, $v) = @_;
755 $self->_debug("REF($k) means literal SQL: @${$v}");
756 my ($sql, @bind) = @${$v};
757 $self->_assert_bindval_matches_bindtype(@bind);
758 $sql = $self->_quote($k) . " " . $sql;
759 return ($sql, @bind );
762 # literal SQL without bind
763 sub _where_hashpair_SCALAR {
764 my ($self, $k, $v) = @_;
765 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
766 my $sql = join ' ', $self->_convert($self->_quote($k)),
767 $self->_sqlcase($self->{cmp}),
768 $self->_convert('?');
769 my @bind = $self->_bindtype($k, $v);
770 return ( $sql, @bind);
774 sub _where_hashpair_UNDEF {
775 my ($self, $k, $v) = @_;
776 $self->_debug("UNDEF($k) means IS NULL");
777 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
781 #======================================================================
782 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
783 #======================================================================
786 sub _where_SCALARREF {
787 my ($self, $where) = @_;
790 $self->_debug("SCALAR(*top) means literal SQL: $$where");
796 my ($self, $where) = @_;
799 $self->_debug("NOREF(*top) means literal SQL: $where");
810 #======================================================================
811 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
812 #======================================================================
815 sub _where_field_BETWEEN {
816 my ($self, $k, $op, $vals) = @_;
818 (ref $vals eq 'ARRAY' && @$vals == 2) or
819 (ref $vals eq 'REF' && (@$$vals == 1 || @$$vals == 2 || @$$vals == 3))
820 or puke "special op 'between' requires an arrayref of two values (or a scalarref or arrayrefref for literal SQL)";
822 my ($clause, @bind, $label, $and, $placeholder);
823 $label = $self->_convert($self->_quote($k));
824 $and = ' ' . $self->_sqlcase('and') . ' ';
825 $placeholder = $self->_convert('?');
826 $op = $self->_sqlcase($op);
828 if (ref $vals eq 'REF') {
829 ($clause, @bind) = @$$vals;
832 my (@all_sql, @all_bind);
834 foreach my $val (@$vals) {
835 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
837 return ($placeholder, ($val));
840 return ($self->_convert($$val), ());
844 push @all_bind, @bind;
847 $clause = (join $and, @all_sql);
848 @bind = $self->_bindtype($k, @all_bind);
850 my $sql = "( $label $op $clause )";
855 sub _where_field_IN {
856 my ($self, $k, $op, $vals) = @_;
858 # backwards compatibility : if scalar, force into an arrayref
859 $vals = [$vals] if defined $vals && ! ref $vals;
861 my ($label) = $self->_convert($self->_quote($k));
862 my ($placeholder) = $self->_convert('?');
863 $op = $self->_sqlcase($op);
865 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
866 ARRAYREF => sub { # list of choices
867 if (@$vals) { # nonempty list
868 my $placeholders = join ", ", (($placeholder) x @$vals);
869 my $sql = "$label $op ( $placeholders )";
870 my @bind = $self->_bindtype($k, @$vals);
872 return ($sql, @bind);
874 else { # empty list : some databases won't understand "IN ()", so DWIM
875 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
880 ARRAYREFREF => sub { # literal SQL with bind
881 my ($sql, @bind) = @$$vals;
882 $self->_assert_bindval_matches_bindtype(@bind);
883 return ("$label $op ( $sql )", @bind);
887 puke "special op 'in' requires an arrayref (or arrayref-ref)";
891 return ($sql, @bind);
897 #======================================================================
899 #======================================================================
902 my ($self, $arg) = @_;
905 for my $c ($self->_order_by_chunks ($arg) ) {
906 $self->_SWITCH_refkind ($c, {
907 SCALAR => sub { push @sql, $c },
908 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
914 $self->_sqlcase(' order by'),
920 return wantarray ? ($sql, @bind) : $sql;
923 sub _order_by_chunks {
924 my ($self, $arg) = @_;
926 return $self->_SWITCH_refkind($arg, {
929 map { $self->_order_by_chunks ($_ ) } @$arg;
932 ARRAYREFREF => sub { [ @$$arg ] },
934 SCALAR => sub {$self->_quote($arg)},
936 UNDEF => sub {return () },
938 SCALARREF => sub {$$arg}, # literal SQL, no quoting
941 # get first pair in hash
942 my ($key, $val) = each %$arg;
944 return () unless $key;
946 if ( (keys %$arg) > 1 or not $key =~ /^-(desc|asc)/i ) {
947 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
953 for my $c ($self->_order_by_chunks ($val)) {
956 $self->_SWITCH_refkind ($c, {
965 $sql = $sql . ' ' . $self->_sqlcase($direction);
967 push @ret, [ $sql, @bind];
976 #======================================================================
977 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
978 #======================================================================
983 $self->_SWITCH_refkind($from, {
984 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
985 SCALAR => sub {$self->_quote($from)},
986 SCALARREF => sub {$$from},
987 ARRAYREFREF => sub {join ', ', @$from;},
992 #======================================================================
994 #======================================================================
1000 $label or puke "can't quote an empty label";
1002 # left and right quote characters
1003 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
1004 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
1005 ARRAYREF => sub {@{$self->{quote_char}}},
1009 or puke "quote_char must be an arrayref of 2 values";
1011 # no quoting if no quoting chars
1012 $ql or return $label;
1014 # no quoting for literal SQL
1015 return $$label if ref($label) eq 'SCALAR';
1017 # separate table / column (if applicable)
1018 my $sep = $self->{name_sep} || '';
1019 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
1021 # do the quoting, except for "*" or for `table`.*
1022 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
1024 # reassemble and return.
1025 return join $sep, @quoted;
1029 # Conversion, if applicable
1031 my ($self, $arg) = @_;
1033 # LDNOTE : modified the previous implementation below because
1034 # it was not consistent : the first "return" is always an array,
1035 # the second "return" is context-dependent. Anyway, _convert
1036 # seems always used with just a single argument, so make it a
1038 # return @_ unless $self->{convert};
1039 # my $conv = $self->_sqlcase($self->{convert});
1040 # my @ret = map { $conv.'('.$_.')' } @_;
1041 # return wantarray ? @ret : $ret[0];
1042 if ($self->{convert}) {
1043 my $conv = $self->_sqlcase($self->{convert});
1044 $arg = $conv.'('.$arg.')';
1052 my($col, @vals) = @_;
1054 #LDNOTE : changed original implementation below because it did not make
1055 # sense when bindtype eq 'columns' and @vals > 1.
1056 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1058 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
1061 # Dies if any element of @bind is not in [colname => value] format
1062 # if bindtype is 'columns'.
1063 sub _assert_bindval_matches_bindtype {
1064 my ($self, @bind) = @_;
1066 if ($self->{bindtype} eq 'columns') {
1067 foreach my $val (@bind) {
1068 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1069 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1075 sub _join_sql_clauses {
1076 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1078 if (@$clauses_aref > 1) {
1079 my $join = " " . $self->_sqlcase($logic) . " ";
1080 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1081 return ($sql, @$bind_aref);
1083 elsif (@$clauses_aref) {
1084 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1087 return (); # if no SQL, ignore @$bind_aref
1092 # Fix SQL case, if so requested
1096 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1097 # don't touch the argument ... crooked logic, but let's not change it!
1098 return $self->{case} ? $_[0] : uc($_[0]);
1102 #======================================================================
1103 # DISPATCHING FROM REFKIND
1104 #======================================================================
1107 my ($self, $data) = @_;
1113 # blessed objects are treated like scalars
1114 $ref = (blessed $data) ? '' : ref $data;
1115 $n_steps += 1 if $ref;
1116 last if $ref ne 'REF';
1120 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
1122 return $base . ('REF' x $n_steps);
1128 my ($self, $data) = @_;
1129 my @try = ($self->_refkind($data));
1130 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1131 push @try, 'FALLBACK';
1135 sub _METHOD_FOR_refkind {
1136 my ($self, $meth_prefix, $data) = @_;
1137 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
1138 $self->_try_refkind($data)
1139 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1144 sub _SWITCH_refkind {
1145 my ($self, $data, $dispatch_table) = @_;
1147 my $coderef = first {$_} map {$dispatch_table->{$_}}
1148 $self->_try_refkind($data)
1149 or puke "no dispatch entry for ".$self->_refkind($data);
1156 #======================================================================
1157 # VALUES, GENERATE, AUTOLOAD
1158 #======================================================================
1160 # LDNOTE: original code from nwiger, didn't touch code in that section
1161 # I feel the AUTOLOAD stuff should not be the default, it should
1162 # only be activated on explicit demand by user.
1166 my $data = shift || return;
1167 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1168 unless ref $data eq 'HASH';
1171 foreach my $k ( sort keys %$data ) {
1172 my $v = $data->{$k};
1173 $self->_SWITCH_refkind($v, {
1175 if ($self->{array_datatypes}) { # array datatype
1176 push @all_bind, $self->_bindtype($k, $v);
1178 else { # literal SQL with bind
1179 my ($sql, @bind) = @$v;
1180 $self->_assert_bindval_matches_bindtype(@bind);
1181 push @all_bind, @bind;
1184 ARRAYREFREF => sub { # literal SQL with bind
1185 my ($sql, @bind) = @${$v};
1186 $self->_assert_bindval_matches_bindtype(@bind);
1187 push @all_bind, @bind;
1189 SCALARREF => sub { # literal SQL without bind
1191 SCALAR_or_UNDEF => sub {
1192 push @all_bind, $self->_bindtype($k, $v);
1203 my(@sql, @sqlq, @sqlv);
1207 if ($ref eq 'HASH') {
1208 for my $k (sort keys %$_) {
1211 my $label = $self->_quote($k);
1212 if ($r eq 'ARRAY') {
1213 # literal SQL with bind
1214 my ($sql, @bind) = @$v;
1215 $self->_assert_bindval_matches_bindtype(@bind);
1216 push @sqlq, "$label = $sql";
1218 } elsif ($r eq 'SCALAR') {
1219 # literal SQL without bind
1220 push @sqlq, "$label = $$v";
1222 push @sqlq, "$label = ?";
1223 push @sqlv, $self->_bindtype($k, $v);
1226 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1227 } elsif ($ref eq 'ARRAY') {
1228 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1231 if ($r eq 'ARRAY') { # literal SQL with bind
1232 my ($sql, @bind) = @$v;
1233 $self->_assert_bindval_matches_bindtype(@bind);
1236 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1237 # embedded literal SQL
1244 push @sql, '(' . join(', ', @sqlq) . ')';
1245 } elsif ($ref eq 'SCALAR') {
1249 # strings get case twiddled
1250 push @sql, $self->_sqlcase($_);
1254 my $sql = join ' ', @sql;
1256 # this is pretty tricky
1257 # if ask for an array, return ($stmt, @bind)
1258 # otherwise, s/?/shift @sqlv/ to put it inline
1260 return ($sql, @sqlv);
1262 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1263 ref $d ? $d->[1] : $d/e;
1272 # This allows us to check for a local, then _form, attr
1274 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1275 return $self->generate($name, @_);
1286 SQL::Abstract - Generate SQL from Perl data structures
1292 my $sql = SQL::Abstract->new;
1294 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1296 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1298 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1300 my($stmt, @bind) = $sql->delete($table, \%where);
1302 # Then, use these in your DBI statements
1303 my $sth = $dbh->prepare($stmt);
1304 $sth->execute(@bind);
1306 # Just generate the WHERE clause
1307 my($stmt, @bind) = $sql->where(\%where, \@order);
1309 # Return values in the same order, for hashed queries
1310 # See PERFORMANCE section for more details
1311 my @bind = $sql->values(\%fieldvals);
1315 This module was inspired by the excellent L<DBIx::Abstract>.
1316 However, in using that module I found that what I really wanted
1317 to do was generate SQL, but still retain complete control over my
1318 statement handles and use the DBI interface. So, I set out to
1319 create an abstract SQL generation module.
1321 While based on the concepts used by L<DBIx::Abstract>, there are
1322 several important differences, especially when it comes to WHERE
1323 clauses. I have modified the concepts used to make the SQL easier
1324 to generate from Perl data structures and, IMO, more intuitive.
1325 The underlying idea is for this module to do what you mean, based
1326 on the data structures you provide it. The big advantage is that
1327 you don't have to modify your code every time your data changes,
1328 as this module figures it out.
1330 To begin with, an SQL INSERT is as easy as just specifying a hash
1331 of C<key=value> pairs:
1334 name => 'Jimbo Bobson',
1335 phone => '123-456-7890',
1336 address => '42 Sister Lane',
1337 city => 'St. Louis',
1338 state => 'Louisiana',
1341 The SQL can then be generated with this:
1343 my($stmt, @bind) = $sql->insert('people', \%data);
1345 Which would give you something like this:
1347 $stmt = "INSERT INTO people
1348 (address, city, name, phone, state)
1349 VALUES (?, ?, ?, ?, ?)";
1350 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1351 '123-456-7890', 'Louisiana');
1353 These are then used directly in your DBI code:
1355 my $sth = $dbh->prepare($stmt);
1356 $sth->execute(@bind);
1358 =head2 Inserting and Updating Arrays
1360 If your database has array types (like for example Postgres),
1361 activate the special option C<< array_datatypes => 1 >>
1362 when creating the C<SQL::Abstract> object.
1363 Then you may use an arrayref to insert and update database array types:
1365 my $sql = SQL::Abstract->new(array_datatypes => 1);
1367 planets => [qw/Mercury Venus Earth Mars/]
1370 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1374 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1376 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1379 =head2 Inserting and Updating SQL
1381 In order to apply SQL functions to elements of your C<%data> you may
1382 specify a reference to an arrayref for the given hash value. For example,
1383 if you need to execute the Oracle C<to_date> function on a value, you can
1384 say something like this:
1388 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1391 The first value in the array is the actual SQL. Any other values are
1392 optional and would be included in the bind values array. This gives
1395 my($stmt, @bind) = $sql->insert('people', \%data);
1397 $stmt = "INSERT INTO people (name, date_entered)
1398 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1399 @bind = ('Bill', '03/02/2003');
1401 An UPDATE is just as easy, all you change is the name of the function:
1403 my($stmt, @bind) = $sql->update('people', \%data);
1405 Notice that your C<%data> isn't touched; the module will generate
1406 the appropriately quirky SQL for you automatically. Usually you'll
1407 want to specify a WHERE clause for your UPDATE, though, which is
1408 where handling C<%where> hashes comes in handy...
1410 =head2 Complex where statements
1412 This module can generate pretty complicated WHERE statements
1413 easily. For example, simple C<key=value> pairs are taken to mean
1414 equality, and if you want to see if a field is within a set
1415 of values, you can use an arrayref. Let's say we wanted to
1416 SELECT some data based on this criteria:
1419 requestor => 'inna',
1420 worker => ['nwiger', 'rcwe', 'sfz'],
1421 status => { '!=', 'completed' }
1424 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1426 The above would give you something like this:
1428 $stmt = "SELECT * FROM tickets WHERE
1429 ( requestor = ? ) AND ( status != ? )
1430 AND ( worker = ? OR worker = ? OR worker = ? )";
1431 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1433 Which you could then use in DBI code like so:
1435 my $sth = $dbh->prepare($stmt);
1436 $sth->execute(@bind);
1442 The functions are simple. There's one for each major SQL operation,
1443 and a constructor you use first. The arguments are specified in a
1444 similar order to each function (table, then fields, then a where
1445 clause) to try and simplify things.
1450 =head2 new(option => 'value')
1452 The C<new()> function takes a list of options and values, and returns
1453 a new B<SQL::Abstract> object which can then be used to generate SQL
1454 through the methods below. The options accepted are:
1460 If set to 'lower', then SQL will be generated in all lowercase. By
1461 default SQL is generated in "textbook" case meaning something like:
1463 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1465 Any setting other than 'lower' is ignored.
1469 This determines what the default comparison operator is. By default
1470 it is C<=>, meaning that a hash like this:
1472 %where = (name => 'nwiger', email => 'nate@wiger.org');
1474 Will generate SQL like this:
1476 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1478 However, you may want loose comparisons by default, so if you set
1479 C<cmp> to C<like> you would get SQL such as:
1481 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1483 You can also override the comparsion on an individual basis - see
1484 the huge section on L</"WHERE CLAUSES"> at the bottom.
1486 =item sqltrue, sqlfalse
1488 Expressions for inserting boolean values within SQL statements.
1489 By default these are C<1=1> and C<1=0>. They are used
1490 by the special operators C<-in> and C<-not_in> for generating
1491 correct SQL even when the argument is an empty array (see below).
1495 This determines the default logical operator for multiple WHERE
1496 statements in arrays or hashes. If absent, the default logic is "or"
1497 for arrays, and "and" for hashes. This means that a WHERE
1501 event_date => {'>=', '2/13/99'},
1502 event_date => {'<=', '4/24/03'},
1505 will generate SQL like this:
1507 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1509 This is probably not what you want given this query, though (look
1510 at the dates). To change the "OR" to an "AND", simply specify:
1512 my $sql = SQL::Abstract->new(logic => 'and');
1514 Which will change the above C<WHERE> to:
1516 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1518 The logic can also be changed locally by inserting
1519 a modifier in front of an arrayref :
1521 @where = (-and => [event_date => {'>=', '2/13/99'},
1522 event_date => {'<=', '4/24/03'} ]);
1524 See the L</"WHERE CLAUSES"> section for explanations.
1528 This will automatically convert comparisons using the specified SQL
1529 function for both column and value. This is mostly used with an argument
1530 of C<upper> or C<lower>, so that the SQL will have the effect of
1531 case-insensitive "searches". For example, this:
1533 $sql = SQL::Abstract->new(convert => 'upper');
1534 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1536 Will turn out the following SQL:
1538 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1540 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1541 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1542 not validate this option; it will just pass through what you specify verbatim).
1546 This is a kludge because many databases suck. For example, you can't
1547 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1548 Instead, you have to use C<bind_param()>:
1550 $sth->bind_param(1, 'reg data');
1551 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1553 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1554 which loses track of which field each slot refers to. Fear not.
1556 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1557 Currently, you can specify either C<normal> (default) or C<columns>. If you
1558 specify C<columns>, you will get an array that looks like this:
1560 my $sql = SQL::Abstract->new(bindtype => 'columns');
1561 my($stmt, @bind) = $sql->insert(...);
1564 [ 'column1', 'value1' ],
1565 [ 'column2', 'value2' ],
1566 [ 'column3', 'value3' ],
1569 You can then iterate through this manually, using DBI's C<bind_param()>.
1571 $sth->prepare($stmt);
1574 my($col, $data) = @$_;
1575 if ($col eq 'details' || $col eq 'comments') {
1576 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1577 } elsif ($col eq 'image') {
1578 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1580 $sth->bind_param($i, $data);
1584 $sth->execute; # execute without @bind now
1586 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1587 Basically, the advantage is still that you don't have to care which fields
1588 are or are not included. You could wrap that above C<for> loop in a simple
1589 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1590 get a layer of abstraction over manual SQL specification.
1592 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1593 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1594 will expect the bind values in this format.
1598 This is the character that a table or column name will be quoted
1599 with. By default this is an empty string, but you could set it to
1600 the character C<`>, to generate SQL like this:
1602 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1604 Alternatively, you can supply an array ref of two items, the first being the left
1605 hand quote character, and the second the right hand quote character. For
1606 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1607 that generates SQL like this:
1609 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1611 Quoting is useful if you have tables or columns names that are reserved
1612 words in your database's SQL dialect.
1616 This is the character that separates a table and column name. It is
1617 necessary to specify this when the C<quote_char> option is selected,
1618 so that tables and column names can be individually quoted like this:
1620 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1622 =item array_datatypes
1624 When this option is true, arrayrefs in INSERT or UPDATE are
1625 interpreted as array datatypes and are passed directly
1627 When this option is false, arrayrefs are interpreted
1628 as literal SQL, just like refs to arrayrefs
1629 (but this behavior is for backwards compatibility; when writing
1630 new queries, use the "reference to arrayref" syntax
1636 Takes a reference to a list of "special operators"
1637 to extend the syntax understood by L<SQL::Abstract>.
1638 See section L</"SPECIAL OPERATORS"> for details.
1642 Takes a reference to a list of "unary operators"
1643 to extend the syntax understood by L<SQL::Abstract>.
1644 See section L</"UNARY OPERATORS"> for details.
1650 =head2 insert($table, \@values || \%fieldvals)
1652 This is the simplest function. You simply give it a table name
1653 and either an arrayref of values or hashref of field/value pairs.
1654 It returns an SQL INSERT statement and a list of bind values.
1655 See the sections on L</"Inserting and Updating Arrays"> and
1656 L</"Inserting and Updating SQL"> for information on how to insert
1657 with those data types.
1659 =head2 update($table, \%fieldvals, \%where)
1661 This takes a table, hashref of field/value pairs, and an optional
1662 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1664 See the sections on L</"Inserting and Updating Arrays"> and
1665 L</"Inserting and Updating SQL"> for information on how to insert
1666 with those data types.
1668 =head2 select($source, $fields, $where, $order)
1670 This returns a SQL SELECT statement and associated list of bind values, as
1671 specified by the arguments :
1677 Specification of the 'FROM' part of the statement.
1678 The argument can be either a plain scalar (interpreted as a table
1679 name, will be quoted), or an arrayref (interpreted as a list
1680 of table names, joined by commas, quoted), or a scalarref
1681 (literal table name, not quoted), or a ref to an arrayref
1682 (list of literal table names, joined by commas, not quoted).
1686 Specification of the list of fields to retrieve from
1688 The argument can be either an arrayref (interpreted as a list
1689 of field names, will be joined by commas and quoted), or a
1690 plain scalar (literal SQL, not quoted).
1691 Please observe that this API is not as flexible as for
1692 the first argument C<$table>, for backwards compatibility reasons.
1696 Optional argument to specify the WHERE part of the query.
1697 The argument is most often a hashref, but can also be
1698 an arrayref or plain scalar --
1699 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1703 Optional argument to specify the ORDER BY part of the query.
1704 The argument can be a scalar, a hashref or an arrayref
1705 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1711 =head2 delete($table, \%where)
1713 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1714 It returns an SQL DELETE statement and list of bind values.
1716 =head2 where(\%where, \@order)
1718 This is used to generate just the WHERE clause. For example,
1719 if you have an arbitrary data structure and know what the
1720 rest of your SQL is going to look like, but want an easy way
1721 to produce a WHERE clause, use this. It returns an SQL WHERE
1722 clause and list of bind values.
1725 =head2 values(\%data)
1727 This just returns the values from the hash C<%data>, in the same
1728 order that would be returned from any of the other above queries.
1729 Using this allows you to markedly speed up your queries if you
1730 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1732 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1734 Warning: This is an experimental method and subject to change.
1736 This returns arbitrarily generated SQL. It's a really basic shortcut.
1737 It will return two different things, depending on return context:
1739 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1740 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1742 These would return the following:
1744 # First calling form
1745 $stmt = "CREATE TABLE test (?, ?)";
1746 @bind = (field1, field2);
1748 # Second calling form
1749 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1751 Depending on what you're trying to do, it's up to you to choose the correct
1752 format. In this example, the second form is what you would want.
1756 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1760 ALTER SESSION SET nls_date_format = 'MM/YY'
1762 You get the idea. Strings get their case twiddled, but everything
1763 else remains verbatim.
1768 =head1 WHERE CLAUSES
1772 This module uses a variation on the idea from L<DBIx::Abstract>. It
1773 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1774 module is that things in arrays are OR'ed, and things in hashes
1777 The easiest way to explain is to show lots of examples. After
1778 each C<%where> hash shown, it is assumed you used:
1780 my($stmt, @bind) = $sql->where(\%where);
1782 However, note that the C<%where> hash can be used directly in any
1783 of the other functions as well, as described above.
1785 =head2 Key-value pairs
1787 So, let's get started. To begin, a simple hash:
1791 status => 'completed'
1794 Is converted to SQL C<key = val> statements:
1796 $stmt = "WHERE user = ? AND status = ?";
1797 @bind = ('nwiger', 'completed');
1799 One common thing I end up doing is having a list of values that
1800 a field can be in. To do this, simply specify a list inside of
1805 status => ['assigned', 'in-progress', 'pending'];
1808 This simple code will create the following:
1810 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1811 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1813 A field associated to an empty arrayref will be considered a
1814 logical false and will generate 0=1.
1816 =head2 Specific comparison operators
1818 If you want to specify a different type of operator for your comparison,
1819 you can use a hashref for a given column:
1823 status => { '!=', 'completed' }
1826 Which would generate:
1828 $stmt = "WHERE user = ? AND status != ?";
1829 @bind = ('nwiger', 'completed');
1831 To test against multiple values, just enclose the values in an arrayref:
1833 status => { '=', ['assigned', 'in-progress', 'pending'] };
1835 Which would give you:
1837 "WHERE status = ? OR status = ? OR status = ?"
1840 The hashref can also contain multiple pairs, in which case it is expanded
1841 into an C<AND> of its elements:
1845 status => { '!=', 'completed', -not_like => 'pending%' }
1848 # Or more dynamically, like from a form
1849 $where{user} = 'nwiger';
1850 $where{status}{'!='} = 'completed';
1851 $where{status}{'-not_like'} = 'pending%';
1853 # Both generate this
1854 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1855 @bind = ('nwiger', 'completed', 'pending%');
1858 To get an OR instead, you can combine it with the arrayref idea:
1862 priority => [ {'=', 2}, {'!=', 1} ]
1865 Which would generate:
1867 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1868 @bind = ('nwiger', '2', '1');
1870 If you want to include literal SQL (with or without bind values), just use a
1871 scalar reference or array reference as the value:
1874 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1875 date_expires => { '<' => \"now()" }
1878 Which would generate:
1880 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1881 @bind = ('11/26/2008');
1884 =head2 Logic and nesting operators
1886 In the example above,
1887 there is a subtle trap if you want to say something like
1888 this (notice the C<AND>):
1890 WHERE priority != ? AND priority != ?
1892 Because, in Perl you I<can't> do this:
1894 priority => { '!=', 2, '!=', 1 }
1896 As the second C<!=> key will obliterate the first. The solution
1897 is to use the special C<-modifier> form inside an arrayref:
1899 priority => [ -and => {'!=', 2},
1903 Normally, these would be joined by C<OR>, but the modifier tells it
1904 to use C<AND> instead. (Hint: You can use this in conjunction with the
1905 C<logic> option to C<new()> in order to change the way your queries
1906 work by default.) B<Important:> Note that the C<-modifier> goes
1907 B<INSIDE> the arrayref, as an extra first element. This will
1908 B<NOT> do what you think it might:
1910 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1912 Here is a quick list of equivalencies, since there is some overlap:
1915 status => {'!=', 'completed', 'not like', 'pending%' }
1916 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1919 status => {'=', ['assigned', 'in-progress']}
1920 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1921 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1925 =head2 Special operators : IN, BETWEEN, etc.
1927 You can also use the hashref format to compare a list of fields using the
1928 C<IN> comparison operator, by specifying the list as an arrayref:
1931 status => 'completed',
1932 reportid => { -in => [567, 2335, 2] }
1935 Which would generate:
1937 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1938 @bind = ('completed', '567', '2335', '2');
1940 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1943 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1944 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1945 'sqltrue' (by default : C<1=1>).
1949 Another pair of operators is C<-between> and C<-not_between>,
1950 used with an arrayref of two values:
1954 completion_date => {
1955 -not_between => ['2002-10-01', '2003-02-06']
1961 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1963 These are the two builtin "special operators"; but the
1964 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1966 =head2 Unary operators: bool
1968 If you wish to test against boolean columns or functions within your
1969 database you can use the C<-bool> and C<-not_bool> operators. For
1970 example to test the column C<is_user> being true and the column
1971 <is_enabled> being false you would use:-
1975 -not_bool => 'is_enabled',
1980 WHERE is_user AND NOT is_enabled
1982 If a more complex combination is required, testing more conditions,
1983 then you should use the and/or operators:-
1990 -not_bool => 'four',
1996 WHERE one AND two AND three AND NOT four
1999 =head2 Nested conditions, -and/-or prefixes
2001 So far, we've seen how multiple conditions are joined with a top-level
2002 C<AND>. We can change this by putting the different conditions we want in
2003 hashes and then putting those hashes in an array. For example:
2008 status => { -like => ['pending%', 'dispatched'] },
2012 status => 'unassigned',
2016 This data structure would create the following:
2018 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2019 OR ( user = ? AND status = ? ) )";
2020 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2023 There is also a special C<-nest>
2024 operator which adds an additional set of parens, to create a subquery.
2025 For example, to get something like this:
2027 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2028 @bind = ('nwiger', '20', 'ASIA');
2034 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2038 Finally, clauses in hashrefs or arrayrefs can be
2039 prefixed with an C<-and> or C<-or> to change the logic
2046 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2047 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2054 WHERE ( user = ? AND
2055 ( ( workhrs > ? AND geo = ? )
2056 OR ( workhrs < ? AND geo = ? ) ) )
2059 =head2 Algebraic inconsistency, for historical reasons
2061 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2062 operator goes C<outside> of the nested structure; whereas when connecting
2063 several constraints on one column, the C<-and> operator goes
2064 C<inside> the arrayref. Here is an example combining both features :
2067 -and => [a => 1, b => 2],
2068 -or => [c => 3, d => 4],
2069 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2074 WHERE ( ( ( a = ? AND b = ? )
2075 OR ( c = ? OR d = ? )
2076 OR ( e LIKE ? AND e LIKE ? ) ) )
2078 This difference in syntax is unfortunate but must be preserved for
2079 historical reasons. So be careful : the two examples below would
2080 seem algebraically equivalent, but they are not
2082 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2083 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2085 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2086 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2091 Finally, sometimes only literal SQL will do. If you want to include
2092 literal SQL verbatim, you can specify it as a scalar reference, namely:
2094 my $inn = 'is Not Null';
2096 priority => { '<', 2 },
2102 $stmt = "WHERE priority < ? AND requestor is Not Null";
2105 Note that in this example, you only get one bind parameter back, since
2106 the verbatim SQL is passed as part of the statement.
2108 Of course, just to prove a point, the above can also be accomplished
2112 priority => { '<', 2 },
2113 requestor => { '!=', undef },
2119 Conditions on boolean columns can be expressed in the same way, passing
2120 a reference to an empty string, however using liternal SQL in this way
2121 is deprecated - the preferred method is to use the boolean operators -
2122 see L</"Unary operators: bool"> :
2125 priority => { '<', 2 },
2131 $stmt = "WHERE priority < ? AND is_ready";
2135 =head2 Literal SQL with placeholders and bind values (subqueries)
2137 If the literal SQL to be inserted has placeholders and bind values,
2138 use a reference to an arrayref (yes this is a double reference --
2139 not so common, but perfectly legal Perl). For example, to find a date
2140 in Postgres you can use something like this:
2143 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2148 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2151 Note that you must pass the bind values in the same format as they are returned
2152 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2153 provide the bind values in the C<< [ column_meta => value ] >> format, where
2154 C<column_meta> is an opaque scalar value; most commonly the column name, but
2155 you can use any scalar value (including references and blessed references),
2156 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2157 to C<columns> the above example will look like:
2160 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2163 Literal SQL is especially useful for nesting parenthesized clauses in the
2164 main SQL query. Here is a first example :
2166 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2170 bar => \["IN ($sub_stmt)" => @sub_bind],
2175 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2176 WHERE c2 < ? AND c3 LIKE ?))";
2177 @bind = (1234, 100, "foo%");
2179 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2180 are expressed in the same way. Of course the C<$sub_stmt> and
2181 its associated bind values can be generated through a former call
2184 my ($sub_stmt, @sub_bind)
2185 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2186 c3 => {-like => "foo%"}});
2189 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2192 In the examples above, the subquery was used as an operator on a column;
2193 but the same principle also applies for a clause within the main C<%where>
2194 hash, like an EXISTS subquery :
2196 my ($sub_stmt, @sub_bind)
2197 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2200 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2205 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2206 WHERE c1 = ? AND c2 > t0.c0))";
2210 Observe that the condition on C<c2> in the subquery refers to
2211 column C<t0.c0> of the main query : this is I<not> a bind
2212 value, so we have to express it through a scalar ref.
2213 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2214 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2215 what we wanted here.
2217 Another use of the subquery technique is when some SQL clauses need
2218 parentheses, as it often occurs with some proprietary SQL extensions
2219 like for example fulltext expressions, geospatial expressions,
2220 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2223 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2226 Finally, here is an example where a subquery is used
2227 for expressing unary negation:
2229 my ($sub_stmt, @sub_bind)
2230 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2231 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2233 lname => {like => '%son%'},
2234 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2239 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2240 @bind = ('%son%', 10, 20)
2246 These pages could go on for a while, since the nesting of the data
2247 structures this module can handle are pretty much unlimited (the
2248 module implements the C<WHERE> expansion as a recursive function
2249 internally). Your best bet is to "play around" with the module a
2250 little to see how the data structures behave, and choose the best
2251 format for your data based on that.
2253 And of course, all the values above will probably be replaced with
2254 variables gotten from forms or the command line. After all, if you
2255 knew everything ahead of time, you wouldn't have to worry about
2256 dynamically-generating SQL and could just hardwire it into your
2262 =head1 ORDER BY CLAUSES
2264 Some functions take an order by clause. This can either be a scalar (just a
2265 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2266 or an array of either of the two previous forms. Examples:
2268 Given | Will Generate
2269 ----------------------------------------------------------
2271 \'colA DESC' | ORDER BY colA DESC
2273 'colA' | ORDER BY colA
2275 [qw/colA colB/] | ORDER BY colA, colB
2277 {-asc => 'colA'} | ORDER BY colA ASC
2279 {-desc => 'colB'} | ORDER BY colB DESC
2281 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2283 { -asc => [qw/colA colB] } | ORDER BY colA ASC, colB ASC
2286 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2287 { -desc => [qw/colB/], | colC ASC, colD ASC
2288 { -asc => [qw/colC colD/],|
2290 ===========================================================
2294 =head1 SPECIAL OPERATORS
2296 my $sqlmaker = SQL::Abstract->new(special_ops => [
2300 my ($self, $field, $op, $arg) = @_;
2306 handler => 'method_name',
2310 A "special operator" is a SQL syntactic clause that can be
2311 applied to a field, instead of a usual binary operator.
2314 WHERE field IN (?, ?, ?)
2315 WHERE field BETWEEN ? AND ?
2316 WHERE MATCH(field) AGAINST (?, ?)
2318 Special operators IN and BETWEEN are fairly standard and therefore
2319 are builtin within C<SQL::Abstract> (as the overridable methods
2320 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2321 like the MATCH .. AGAINST example above which is specific to MySQL,
2322 you can write your own operator handlers - supply a C<special_ops>
2323 argument to the C<new> method. That argument takes an arrayref of
2324 operator definitions; each operator definition is a hashref with two
2331 the regular expression to match the operator
2335 Either a coderef or a plain scalar method name. In both cases
2336 the expected return is C<< ($sql, @bind) >>.
2338 When supplied with a method name, it is simply called on the
2339 L<SQL::Abstract/> object as:
2341 $self->$method_name ($field, $op, $arg)
2345 $op is the part that matched the handler regex
2346 $field is the LHS of the operator
2349 When supplied with a coderef, it is called as:
2351 $coderef->($self, $field, $op, $arg)
2356 For example, here is an implementation
2357 of the MATCH .. AGAINST syntax for MySQL
2359 my $sqlmaker = SQL::Abstract->new(special_ops => [
2361 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2362 {regex => qr/^match$/i,
2364 my ($self, $field, $op, $arg) = @_;
2365 $arg = [$arg] if not ref $arg;
2366 my $label = $self->_quote($field);
2367 my ($placeholder) = $self->_convert('?');
2368 my $placeholders = join ", ", (($placeholder) x @$arg);
2369 my $sql = $self->_sqlcase('match') . " ($label) "
2370 . $self->_sqlcase('against') . " ($placeholders) ";
2371 my @bind = $self->_bindtype($field, @$arg);
2372 return ($sql, @bind);
2379 =head1 UNARY OPERATORS
2381 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2385 my ($self, $op, $arg) = @_;
2391 handler => 'method_name',
2395 A "unary operator" is a SQL syntactic clause that can be
2396 applied to a field - the operator goes before the field
2398 You can write your own operator handlers - supply a C<unary_ops>
2399 argument to the C<new> method. That argument takes an arrayref of
2400 operator definitions; each operator definition is a hashref with two
2407 the regular expression to match the operator
2411 Either a coderef or a plain scalar method name. In both cases
2412 the expected return is C<< $sql >>.
2414 When supplied with a method name, it is simply called on the
2415 L<SQL::Abstract/> object as:
2417 $self->$method_name ($op, $arg)
2421 $op is the part that matched the handler regex
2422 $arg is the RHS or argument of the operator
2424 When supplied with a coderef, it is called as:
2426 $coderef->($self, $op, $arg)
2434 Thanks to some benchmarking by Mark Stosberg, it turns out that
2435 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2436 I must admit this wasn't an intentional design issue, but it's a
2437 byproduct of the fact that you get to control your C<DBI> handles
2440 To maximize performance, use a code snippet like the following:
2442 # prepare a statement handle using the first row
2443 # and then reuse it for the rest of the rows
2445 for my $href (@array_of_hashrefs) {
2446 $stmt ||= $sql->insert('table', $href);
2447 $sth ||= $dbh->prepare($stmt);
2448 $sth->execute($sql->values($href));
2451 The reason this works is because the keys in your C<$href> are sorted
2452 internally by B<SQL::Abstract>. Thus, as long as your data retains
2453 the same structure, you only have to generate the SQL the first time
2454 around. On subsequent queries, simply use the C<values> function provided
2455 by this module to return your values in the correct order.
2460 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2461 really like this part (I do, at least). Building up a complex query
2462 can be as simple as the following:
2466 use CGI::FormBuilder;
2469 my $form = CGI::FormBuilder->new(...);
2470 my $sql = SQL::Abstract->new;
2472 if ($form->submitted) {
2473 my $field = $form->field;
2474 my $id = delete $field->{id};
2475 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2478 Of course, you would still have to connect using C<DBI> to run the
2479 query, but the point is that if you make your form look like your
2480 table, the actual query script can be extremely simplistic.
2482 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2483 a fast interface to returning and formatting data. I frequently
2484 use these three modules together to write complex database query
2485 apps in under 50 lines.
2490 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2491 Great care has been taken to preserve the I<published> behavior
2492 documented in previous versions in the 1.* family; however,
2493 some features that were previously undocumented, or behaved
2494 differently from the documentation, had to be changed in order
2495 to clarify the semantics. Hence, client code that was relying
2496 on some dark areas of C<SQL::Abstract> v1.*
2497 B<might behave differently> in v1.50.
2499 The main changes are :
2505 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2509 support for the { operator => \"..." } construct (to embed literal SQL)
2513 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2517 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2521 defensive programming : check arguments
2525 fixed bug with global logic, which was previously implemented
2526 through global variables yielding side-effects. Prior versions would
2527 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2528 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2529 Now this is interpreted
2530 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2535 fixed semantics of _bindtype on array args
2539 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2540 we just avoid shifting arrays within that tree.
2544 dropped the C<_modlogic> function
2550 =head1 ACKNOWLEDGEMENTS
2552 There are a number of individuals that have really helped out with
2553 this module. Unfortunately, most of them submitted bugs via CPAN
2554 so I have no idea who they are! But the people I do know are:
2556 Ash Berlin (order_by hash term support)
2557 Matt Trout (DBIx::Class support)
2558 Mark Stosberg (benchmarking)
2559 Chas Owens (initial "IN" operator support)
2560 Philip Collins (per-field SQL functions)
2561 Eric Kolve (hashref "AND" support)
2562 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2563 Dan Kubb (support for "quote_char" and "name_sep")
2564 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2565 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2566 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2567 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2573 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2577 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2579 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2581 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2582 While not an official support venue, C<DBIx::Class> makes heavy use of
2583 C<SQL::Abstract>, and as such list members there are very familiar with
2584 how to create queries.
2588 This module is free software; you may copy this under the terms of
2589 the GNU General Public License, or the Artistic License, copies of
2590 which should have accompanied your Perl kit.