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.54';
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) = @_;
696 $self->_debug("ARRAY($vals) means multiple elements: [ @$vals ]");
698 # see if the first element is an -and/-or op
700 if ($vals->[0] =~ /^ - ( AND|OR ) $/ix) {
705 # distribute $op over each remaining member of @$vals, append logic if exists
706 return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
708 # LDNOTE : had planned to change the distribution logic when
709 # $op =~ $self->{inequality_op}, because of Morgan laws :
710 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
711 # WHERE field != 22 OR field != 33 : the user probably means
712 # WHERE field != 22 AND field != 33.
713 # To do this, replace the above to roughly :
714 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
715 # return $self->_recurse_where([map { {$k => {$op, $_}} } @$vals], $logic);
719 # try to DWIM on equality operators
720 # LDNOTE : not 100% sure this is the correct thing to do ...
721 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
722 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
725 puke "operator '$op' applied on an empty array (field '$k')";
730 sub _where_hashpair_SCALARREF {
731 my ($self, $k, $v) = @_;
732 $self->_debug("SCALAR($k) means literal SQL: $$v");
733 my $sql = $self->_quote($k) . " " . $$v;
737 # literal SQL with bind
738 sub _where_hashpair_ARRAYREFREF {
739 my ($self, $k, $v) = @_;
740 $self->_debug("REF($k) means literal SQL: @${$v}");
741 my ($sql, @bind) = @${$v};
742 $self->_assert_bindval_matches_bindtype(@bind);
743 $sql = $self->_quote($k) . " " . $sql;
744 return ($sql, @bind );
747 # literal SQL without bind
748 sub _where_hashpair_SCALAR {
749 my ($self, $k, $v) = @_;
750 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
751 my $sql = join ' ', $self->_convert($self->_quote($k)),
752 $self->_sqlcase($self->{cmp}),
753 $self->_convert('?');
754 my @bind = $self->_bindtype($k, $v);
755 return ( $sql, @bind);
759 sub _where_hashpair_UNDEF {
760 my ($self, $k, $v) = @_;
761 $self->_debug("UNDEF($k) means IS NULL");
762 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
766 #======================================================================
767 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
768 #======================================================================
771 sub _where_SCALARREF {
772 my ($self, $where) = @_;
775 $self->_debug("SCALAR(*top) means literal SQL: $$where");
781 my ($self, $where) = @_;
784 $self->_debug("NOREF(*top) means literal SQL: $where");
795 #======================================================================
796 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
797 #======================================================================
800 sub _where_field_BETWEEN {
801 my ($self, $k, $op, $vals) = @_;
803 (ref $vals eq 'ARRAY' && @$vals == 2) or
804 (ref $vals eq 'REF' && (@$$vals == 1 || @$$vals == 2 || @$$vals == 3))
805 or puke "special op 'between' requires an arrayref of two values (or a scalarref or arrayrefref for literal SQL)";
807 my ($clause, @bind, $label, $and, $placeholder);
808 $label = $self->_convert($self->_quote($k));
809 $and = ' ' . $self->_sqlcase('and') . ' ';
810 $placeholder = $self->_convert('?');
811 $op = $self->_sqlcase($op);
813 if (ref $vals eq 'REF') {
814 ($clause, @bind) = @$$vals;
817 my (@all_sql, @all_bind);
819 foreach my $val (@$vals) {
820 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
822 return ($placeholder, ($val));
825 return ($self->_convert($$val), ());
829 push @all_bind, @bind;
832 $clause = (join $and, @all_sql);
833 @bind = $self->_bindtype($k, @all_bind);
835 my $sql = "( $label $op $clause )";
840 sub _where_field_IN {
841 my ($self, $k, $op, $vals) = @_;
843 # backwards compatibility : if scalar, force into an arrayref
844 $vals = [$vals] if defined $vals && ! ref $vals;
846 my ($label) = $self->_convert($self->_quote($k));
847 my ($placeholder) = $self->_convert('?');
848 $op = $self->_sqlcase($op);
850 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
851 ARRAYREF => sub { # list of choices
852 if (@$vals) { # nonempty list
853 my $placeholders = join ", ", (($placeholder) x @$vals);
854 my $sql = "$label $op ( $placeholders )";
855 my @bind = $self->_bindtype($k, @$vals);
857 return ($sql, @bind);
859 else { # empty list : some databases won't understand "IN ()", so DWIM
860 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
865 ARRAYREFREF => sub { # literal SQL with bind
866 my ($sql, @bind) = @$$vals;
867 $self->_assert_bindval_matches_bindtype(@bind);
868 return ("$label $op ( $sql )", @bind);
872 puke "special op 'in' requires an arrayref (or arrayref-ref)";
876 return ($sql, @bind);
882 #======================================================================
884 #======================================================================
887 my ($self, $arg) = @_;
889 # construct list of ordering instructions
890 my @order = $self->_SWITCH_refkind($arg, {
893 map {$self->_SWITCH_refkind($_, {
894 SCALAR => sub {$self->_quote($_)},
896 SCALARREF => sub {$$_}, # literal SQL, no quoting
897 HASHREF => sub {$self->_order_by_hash($_)}
901 SCALAR => sub {$self->_quote($arg)},
903 SCALARREF => sub {$$arg}, # literal SQL, no quoting
904 HASHREF => sub {$self->_order_by_hash($arg)},
909 my $order = join ', ', @order;
910 return $order ? $self->_sqlcase(' order by')." $order" : '';
915 my ($self, $hash) = @_;
917 # get first pair in hash
918 my ($key, $val) = each %$hash;
920 # check if one pair was found and no other pair in hash
921 $key && !(each %$hash)
922 or puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
924 my ($order) = ($key =~ /^-(desc|asc)/i)
925 or puke "invalid key in _order_by hash : $key";
927 $val = ref $val eq 'ARRAY' ? $val : [$val];
928 return join ', ', map { $self->_quote($_) . ' ' . $self->_sqlcase($order) } @$val;
933 #======================================================================
934 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
935 #======================================================================
940 $self->_SWITCH_refkind($from, {
941 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
942 SCALAR => sub {$self->_quote($from)},
943 SCALARREF => sub {$$from},
944 ARRAYREFREF => sub {join ', ', @$from;},
949 #======================================================================
951 #======================================================================
957 $label or puke "can't quote an empty label";
959 # left and right quote characters
960 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
961 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
962 ARRAYREF => sub {@{$self->{quote_char}}},
966 or puke "quote_char must be an arrayref of 2 values";
968 # no quoting if no quoting chars
969 $ql or return $label;
971 # no quoting for literal SQL
972 return $$label if ref($label) eq 'SCALAR';
974 # separate table / column (if applicable)
975 my $sep = $self->{name_sep} || '';
976 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
978 # do the quoting, except for "*" or for `table`.*
979 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
981 # reassemble and return.
982 return join $sep, @quoted;
986 # Conversion, if applicable
988 my ($self, $arg) = @_;
990 # LDNOTE : modified the previous implementation below because
991 # it was not consistent : the first "return" is always an array,
992 # the second "return" is context-dependent. Anyway, _convert
993 # seems always used with just a single argument, so make it a
995 # return @_ unless $self->{convert};
996 # my $conv = $self->_sqlcase($self->{convert});
997 # my @ret = map { $conv.'('.$_.')' } @_;
998 # return wantarray ? @ret : $ret[0];
999 if ($self->{convert}) {
1000 my $conv = $self->_sqlcase($self->{convert});
1001 $arg = $conv.'('.$arg.')';
1009 my($col, @vals) = @_;
1011 #LDNOTE : changed original implementation below because it did not make
1012 # sense when bindtype eq 'columns' and @vals > 1.
1013 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1015 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
1018 # Dies if any element of @bind is not in [colname => value] format
1019 # if bindtype is 'columns'.
1020 sub _assert_bindval_matches_bindtype {
1021 my ($self, @bind) = @_;
1023 if ($self->{bindtype} eq 'columns') {
1024 foreach my $val (@bind) {
1025 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1026 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1032 sub _join_sql_clauses {
1033 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1035 if (@$clauses_aref > 1) {
1036 my $join = " " . $self->_sqlcase($logic) . " ";
1037 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1038 return ($sql, @$bind_aref);
1040 elsif (@$clauses_aref) {
1041 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1044 return (); # if no SQL, ignore @$bind_aref
1049 # Fix SQL case, if so requested
1053 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1054 # don't touch the argument ... crooked logic, but let's not change it!
1055 return $self->{case} ? $_[0] : uc($_[0]);
1059 #======================================================================
1060 # DISPATCHING FROM REFKIND
1061 #======================================================================
1064 my ($self, $data) = @_;
1070 # blessed objects are treated like scalars
1071 $ref = (blessed $data) ? '' : ref $data;
1072 $n_steps += 1 if $ref;
1073 last if $ref ne 'REF';
1077 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
1079 return $base . ('REF' x $n_steps);
1085 my ($self, $data) = @_;
1086 my @try = ($self->_refkind($data));
1087 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1088 push @try, 'FALLBACK';
1092 sub _METHOD_FOR_refkind {
1093 my ($self, $meth_prefix, $data) = @_;
1094 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
1095 $self->_try_refkind($data)
1096 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1101 sub _SWITCH_refkind {
1102 my ($self, $data, $dispatch_table) = @_;
1104 my $coderef = first {$_} map {$dispatch_table->{$_}}
1105 $self->_try_refkind($data)
1106 or puke "no dispatch entry for ".$self->_refkind($data);
1113 #======================================================================
1114 # VALUES, GENERATE, AUTOLOAD
1115 #======================================================================
1117 # LDNOTE: original code from nwiger, didn't touch code in that section
1118 # I feel the AUTOLOAD stuff should not be the default, it should
1119 # only be activated on explicit demand by user.
1123 my $data = shift || return;
1124 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1125 unless ref $data eq 'HASH';
1128 foreach my $k ( sort keys %$data ) {
1129 my $v = $data->{$k};
1130 $self->_SWITCH_refkind($v, {
1132 if ($self->{array_datatypes}) { # array datatype
1133 push @all_bind, $self->_bindtype($k, $v);
1135 else { # literal SQL with bind
1136 my ($sql, @bind) = @$v;
1137 $self->_assert_bindval_matches_bindtype(@bind);
1138 push @all_bind, @bind;
1141 ARRAYREFREF => sub { # literal SQL with bind
1142 my ($sql, @bind) = @${$v};
1143 $self->_assert_bindval_matches_bindtype(@bind);
1144 push @all_bind, @bind;
1146 SCALARREF => sub { # literal SQL without bind
1148 SCALAR_or_UNDEF => sub {
1149 push @all_bind, $self->_bindtype($k, $v);
1160 my(@sql, @sqlq, @sqlv);
1164 if ($ref eq 'HASH') {
1165 for my $k (sort keys %$_) {
1168 my $label = $self->_quote($k);
1169 if ($r eq 'ARRAY') {
1170 # literal SQL with bind
1171 my ($sql, @bind) = @$v;
1172 $self->_assert_bindval_matches_bindtype(@bind);
1173 push @sqlq, "$label = $sql";
1175 } elsif ($r eq 'SCALAR') {
1176 # literal SQL without bind
1177 push @sqlq, "$label = $$v";
1179 push @sqlq, "$label = ?";
1180 push @sqlv, $self->_bindtype($k, $v);
1183 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1184 } elsif ($ref eq 'ARRAY') {
1185 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1188 if ($r eq 'ARRAY') { # literal SQL with bind
1189 my ($sql, @bind) = @$v;
1190 $self->_assert_bindval_matches_bindtype(@bind);
1193 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1194 # embedded literal SQL
1201 push @sql, '(' . join(', ', @sqlq) . ')';
1202 } elsif ($ref eq 'SCALAR') {
1206 # strings get case twiddled
1207 push @sql, $self->_sqlcase($_);
1211 my $sql = join ' ', @sql;
1213 # this is pretty tricky
1214 # if ask for an array, return ($stmt, @bind)
1215 # otherwise, s/?/shift @sqlv/ to put it inline
1217 return ($sql, @sqlv);
1219 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1220 ref $d ? $d->[1] : $d/e;
1229 # This allows us to check for a local, then _form, attr
1231 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1232 return $self->generate($name, @_);
1243 SQL::Abstract - Generate SQL from Perl data structures
1249 my $sql = SQL::Abstract->new;
1251 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1253 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1255 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1257 my($stmt, @bind) = $sql->delete($table, \%where);
1259 # Then, use these in your DBI statements
1260 my $sth = $dbh->prepare($stmt);
1261 $sth->execute(@bind);
1263 # Just generate the WHERE clause
1264 my($stmt, @bind) = $sql->where(\%where, \@order);
1266 # Return values in the same order, for hashed queries
1267 # See PERFORMANCE section for more details
1268 my @bind = $sql->values(\%fieldvals);
1272 This module was inspired by the excellent L<DBIx::Abstract>.
1273 However, in using that module I found that what I really wanted
1274 to do was generate SQL, but still retain complete control over my
1275 statement handles and use the DBI interface. So, I set out to
1276 create an abstract SQL generation module.
1278 While based on the concepts used by L<DBIx::Abstract>, there are
1279 several important differences, especially when it comes to WHERE
1280 clauses. I have modified the concepts used to make the SQL easier
1281 to generate from Perl data structures and, IMO, more intuitive.
1282 The underlying idea is for this module to do what you mean, based
1283 on the data structures you provide it. The big advantage is that
1284 you don't have to modify your code every time your data changes,
1285 as this module figures it out.
1287 To begin with, an SQL INSERT is as easy as just specifying a hash
1288 of C<key=value> pairs:
1291 name => 'Jimbo Bobson',
1292 phone => '123-456-7890',
1293 address => '42 Sister Lane',
1294 city => 'St. Louis',
1295 state => 'Louisiana',
1298 The SQL can then be generated with this:
1300 my($stmt, @bind) = $sql->insert('people', \%data);
1302 Which would give you something like this:
1304 $stmt = "INSERT INTO people
1305 (address, city, name, phone, state)
1306 VALUES (?, ?, ?, ?, ?)";
1307 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1308 '123-456-7890', 'Louisiana');
1310 These are then used directly in your DBI code:
1312 my $sth = $dbh->prepare($stmt);
1313 $sth->execute(@bind);
1315 =head2 Inserting and Updating Arrays
1317 If your database has array types (like for example Postgres),
1318 activate the special option C<< array_datatypes => 1 >>
1319 when creating the C<SQL::Abstract> object.
1320 Then you may use an arrayref to insert and update database array types:
1322 my $sql = SQL::Abstract->new(array_datatypes => 1);
1324 planets => [qw/Mercury Venus Earth Mars/]
1327 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1331 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1333 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1336 =head2 Inserting and Updating SQL
1338 In order to apply SQL functions to elements of your C<%data> you may
1339 specify a reference to an arrayref for the given hash value. For example,
1340 if you need to execute the Oracle C<to_date> function on a value, you can
1341 say something like this:
1345 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1348 The first value in the array is the actual SQL. Any other values are
1349 optional and would be included in the bind values array. This gives
1352 my($stmt, @bind) = $sql->insert('people', \%data);
1354 $stmt = "INSERT INTO people (name, date_entered)
1355 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1356 @bind = ('Bill', '03/02/2003');
1358 An UPDATE is just as easy, all you change is the name of the function:
1360 my($stmt, @bind) = $sql->update('people', \%data);
1362 Notice that your C<%data> isn't touched; the module will generate
1363 the appropriately quirky SQL for you automatically. Usually you'll
1364 want to specify a WHERE clause for your UPDATE, though, which is
1365 where handling C<%where> hashes comes in handy...
1367 =head2 Complex where statements
1369 This module can generate pretty complicated WHERE statements
1370 easily. For example, simple C<key=value> pairs are taken to mean
1371 equality, and if you want to see if a field is within a set
1372 of values, you can use an arrayref. Let's say we wanted to
1373 SELECT some data based on this criteria:
1376 requestor => 'inna',
1377 worker => ['nwiger', 'rcwe', 'sfz'],
1378 status => { '!=', 'completed' }
1381 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1383 The above would give you something like this:
1385 $stmt = "SELECT * FROM tickets WHERE
1386 ( requestor = ? ) AND ( status != ? )
1387 AND ( worker = ? OR worker = ? OR worker = ? )";
1388 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1390 Which you could then use in DBI code like so:
1392 my $sth = $dbh->prepare($stmt);
1393 $sth->execute(@bind);
1399 The functions are simple. There's one for each major SQL operation,
1400 and a constructor you use first. The arguments are specified in a
1401 similar order to each function (table, then fields, then a where
1402 clause) to try and simplify things.
1407 =head2 new(option => 'value')
1409 The C<new()> function takes a list of options and values, and returns
1410 a new B<SQL::Abstract> object which can then be used to generate SQL
1411 through the methods below. The options accepted are:
1417 If set to 'lower', then SQL will be generated in all lowercase. By
1418 default SQL is generated in "textbook" case meaning something like:
1420 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1422 Any setting other than 'lower' is ignored.
1426 This determines what the default comparison operator is. By default
1427 it is C<=>, meaning that a hash like this:
1429 %where = (name => 'nwiger', email => 'nate@wiger.org');
1431 Will generate SQL like this:
1433 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1435 However, you may want loose comparisons by default, so if you set
1436 C<cmp> to C<like> you would get SQL such as:
1438 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1440 You can also override the comparsion on an individual basis - see
1441 the huge section on L</"WHERE CLAUSES"> at the bottom.
1443 =item sqltrue, sqlfalse
1445 Expressions for inserting boolean values within SQL statements.
1446 By default these are C<1=1> and C<1=0>. They are used
1447 by the special operators C<-in> and C<-not_in> for generating
1448 correct SQL even when the argument is an empty array (see below).
1452 This determines the default logical operator for multiple WHERE
1453 statements in arrays or hashes. If absent, the default logic is "or"
1454 for arrays, and "and" for hashes. This means that a WHERE
1458 event_date => {'>=', '2/13/99'},
1459 event_date => {'<=', '4/24/03'},
1462 will generate SQL like this:
1464 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1466 This is probably not what you want given this query, though (look
1467 at the dates). To change the "OR" to an "AND", simply specify:
1469 my $sql = SQL::Abstract->new(logic => 'and');
1471 Which will change the above C<WHERE> to:
1473 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1475 The logic can also be changed locally by inserting
1476 a modifier in front of an arrayref :
1478 @where = (-and => [event_date => {'>=', '2/13/99'},
1479 event_date => {'<=', '4/24/03'} ]);
1481 See the L</"WHERE CLAUSES"> section for explanations.
1485 This will automatically convert comparisons using the specified SQL
1486 function for both column and value. This is mostly used with an argument
1487 of C<upper> or C<lower>, so that the SQL will have the effect of
1488 case-insensitive "searches". For example, this:
1490 $sql = SQL::Abstract->new(convert => 'upper');
1491 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1493 Will turn out the following SQL:
1495 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1497 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1498 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1499 not validate this option; it will just pass through what you specify verbatim).
1503 This is a kludge because many databases suck. For example, you can't
1504 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1505 Instead, you have to use C<bind_param()>:
1507 $sth->bind_param(1, 'reg data');
1508 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1510 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1511 which loses track of which field each slot refers to. Fear not.
1513 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1514 Currently, you can specify either C<normal> (default) or C<columns>. If you
1515 specify C<columns>, you will get an array that looks like this:
1517 my $sql = SQL::Abstract->new(bindtype => 'columns');
1518 my($stmt, @bind) = $sql->insert(...);
1521 [ 'column1', 'value1' ],
1522 [ 'column2', 'value2' ],
1523 [ 'column3', 'value3' ],
1526 You can then iterate through this manually, using DBI's C<bind_param()>.
1528 $sth->prepare($stmt);
1531 my($col, $data) = @$_;
1532 if ($col eq 'details' || $col eq 'comments') {
1533 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1534 } elsif ($col eq 'image') {
1535 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1537 $sth->bind_param($i, $data);
1541 $sth->execute; # execute without @bind now
1543 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1544 Basically, the advantage is still that you don't have to care which fields
1545 are or are not included. You could wrap that above C<for> loop in a simple
1546 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1547 get a layer of abstraction over manual SQL specification.
1549 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1550 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1551 will expect the bind values in this format.
1555 This is the character that a table or column name will be quoted
1556 with. By default this is an empty string, but you could set it to
1557 the character C<`>, to generate SQL like this:
1559 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1561 Alternatively, you can supply an array ref of two items, the first being the left
1562 hand quote character, and the second the right hand quote character. For
1563 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1564 that generates SQL like this:
1566 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1568 Quoting is useful if you have tables or columns names that are reserved
1569 words in your database's SQL dialect.
1573 This is the character that separates a table and column name. It is
1574 necessary to specify this when the C<quote_char> option is selected,
1575 so that tables and column names can be individually quoted like this:
1577 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1579 =item array_datatypes
1581 When this option is true, arrayrefs in INSERT or UPDATE are
1582 interpreted as array datatypes and are passed directly
1584 When this option is false, arrayrefs are interpreted
1585 as literal SQL, just like refs to arrayrefs
1586 (but this behavior is for backwards compatibility; when writing
1587 new queries, use the "reference to arrayref" syntax
1593 Takes a reference to a list of "special operators"
1594 to extend the syntax understood by L<SQL::Abstract>.
1595 See section L</"SPECIAL OPERATORS"> for details.
1599 Takes a reference to a list of "unary operators"
1600 to extend the syntax understood by L<SQL::Abstract>.
1601 See section L</"UNARY OPERATORS"> for details.
1607 =head2 insert($table, \@values || \%fieldvals)
1609 This is the simplest function. You simply give it a table name
1610 and either an arrayref of values or hashref of field/value pairs.
1611 It returns an SQL INSERT statement and a list of bind values.
1612 See the sections on L</"Inserting and Updating Arrays"> and
1613 L</"Inserting and Updating SQL"> for information on how to insert
1614 with those data types.
1616 =head2 update($table, \%fieldvals, \%where)
1618 This takes a table, hashref of field/value pairs, and an optional
1619 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1621 See the sections on L</"Inserting and Updating Arrays"> and
1622 L</"Inserting and Updating SQL"> for information on how to insert
1623 with those data types.
1625 =head2 select($source, $fields, $where, $order)
1627 This returns a SQL SELECT statement and associated list of bind values, as
1628 specified by the arguments :
1634 Specification of the 'FROM' part of the statement.
1635 The argument can be either a plain scalar (interpreted as a table
1636 name, will be quoted), or an arrayref (interpreted as a list
1637 of table names, joined by commas, quoted), or a scalarref
1638 (literal table name, not quoted), or a ref to an arrayref
1639 (list of literal table names, joined by commas, not quoted).
1643 Specification of the list of fields to retrieve from
1645 The argument can be either an arrayref (interpreted as a list
1646 of field names, will be joined by commas and quoted), or a
1647 plain scalar (literal SQL, not quoted).
1648 Please observe that this API is not as flexible as for
1649 the first argument C<$table>, for backwards compatibility reasons.
1653 Optional argument to specify the WHERE part of the query.
1654 The argument is most often a hashref, but can also be
1655 an arrayref or plain scalar --
1656 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1660 Optional argument to specify the ORDER BY part of the query.
1661 The argument can be a scalar, a hashref or an arrayref
1662 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1668 =head2 delete($table, \%where)
1670 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1671 It returns an SQL DELETE statement and list of bind values.
1673 =head2 where(\%where, \@order)
1675 This is used to generate just the WHERE clause. For example,
1676 if you have an arbitrary data structure and know what the
1677 rest of your SQL is going to look like, but want an easy way
1678 to produce a WHERE clause, use this. It returns an SQL WHERE
1679 clause and list of bind values.
1682 =head2 values(\%data)
1684 This just returns the values from the hash C<%data>, in the same
1685 order that would be returned from any of the other above queries.
1686 Using this allows you to markedly speed up your queries if you
1687 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1689 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1691 Warning: This is an experimental method and subject to change.
1693 This returns arbitrarily generated SQL. It's a really basic shortcut.
1694 It will return two different things, depending on return context:
1696 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1697 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1699 These would return the following:
1701 # First calling form
1702 $stmt = "CREATE TABLE test (?, ?)";
1703 @bind = (field1, field2);
1705 # Second calling form
1706 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1708 Depending on what you're trying to do, it's up to you to choose the correct
1709 format. In this example, the second form is what you would want.
1713 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1717 ALTER SESSION SET nls_date_format = 'MM/YY'
1719 You get the idea. Strings get their case twiddled, but everything
1720 else remains verbatim.
1725 =head1 WHERE CLAUSES
1729 This module uses a variation on the idea from L<DBIx::Abstract>. It
1730 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1731 module is that things in arrays are OR'ed, and things in hashes
1734 The easiest way to explain is to show lots of examples. After
1735 each C<%where> hash shown, it is assumed you used:
1737 my($stmt, @bind) = $sql->where(\%where);
1739 However, note that the C<%where> hash can be used directly in any
1740 of the other functions as well, as described above.
1742 =head2 Key-value pairs
1744 So, let's get started. To begin, a simple hash:
1748 status => 'completed'
1751 Is converted to SQL C<key = val> statements:
1753 $stmt = "WHERE user = ? AND status = ?";
1754 @bind = ('nwiger', 'completed');
1756 One common thing I end up doing is having a list of values that
1757 a field can be in. To do this, simply specify a list inside of
1762 status => ['assigned', 'in-progress', 'pending'];
1765 This simple code will create the following:
1767 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1768 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1770 A field associated to an empty arrayref will be considered a
1771 logical false and will generate 0=1.
1773 =head2 Specific comparison operators
1775 If you want to specify a different type of operator for your comparison,
1776 you can use a hashref for a given column:
1780 status => { '!=', 'completed' }
1783 Which would generate:
1785 $stmt = "WHERE user = ? AND status != ?";
1786 @bind = ('nwiger', 'completed');
1788 To test against multiple values, just enclose the values in an arrayref:
1790 status => { '=', ['assigned', 'in-progress', 'pending'] };
1792 Which would give you:
1794 "WHERE status = ? OR status = ? OR status = ?"
1797 The hashref can also contain multiple pairs, in which case it is expanded
1798 into an C<AND> of its elements:
1802 status => { '!=', 'completed', -not_like => 'pending%' }
1805 # Or more dynamically, like from a form
1806 $where{user} = 'nwiger';
1807 $where{status}{'!='} = 'completed';
1808 $where{status}{'-not_like'} = 'pending%';
1810 # Both generate this
1811 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1812 @bind = ('nwiger', 'completed', 'pending%');
1815 To get an OR instead, you can combine it with the arrayref idea:
1819 priority => [ {'=', 2}, {'!=', 1} ]
1822 Which would generate:
1824 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1825 @bind = ('nwiger', '2', '1');
1827 If you want to include literal SQL (with or without bind values), just use a
1828 scalar reference or array reference as the value:
1831 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1832 date_expires => { '<' => \"now()" }
1835 Which would generate:
1837 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1838 @bind = ('11/26/2008');
1841 =head2 Logic and nesting operators
1843 In the example above,
1844 there is a subtle trap if you want to say something like
1845 this (notice the C<AND>):
1847 WHERE priority != ? AND priority != ?
1849 Because, in Perl you I<can't> do this:
1851 priority => { '!=', 2, '!=', 1 }
1853 As the second C<!=> key will obliterate the first. The solution
1854 is to use the special C<-modifier> form inside an arrayref:
1856 priority => [ -and => {'!=', 2},
1860 Normally, these would be joined by C<OR>, but the modifier tells it
1861 to use C<AND> instead. (Hint: You can use this in conjunction with the
1862 C<logic> option to C<new()> in order to change the way your queries
1863 work by default.) B<Important:> Note that the C<-modifier> goes
1864 B<INSIDE> the arrayref, as an extra first element. This will
1865 B<NOT> do what you think it might:
1867 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1869 Here is a quick list of equivalencies, since there is some overlap:
1872 status => {'!=', 'completed', 'not like', 'pending%' }
1873 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1876 status => {'=', ['assigned', 'in-progress']}
1877 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1878 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1882 =head2 Special operators : IN, BETWEEN, etc.
1884 You can also use the hashref format to compare a list of fields using the
1885 C<IN> comparison operator, by specifying the list as an arrayref:
1888 status => 'completed',
1889 reportid => { -in => [567, 2335, 2] }
1892 Which would generate:
1894 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1895 @bind = ('completed', '567', '2335', '2');
1897 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1900 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1901 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1902 'sqltrue' (by default : C<1=1>).
1906 Another pair of operators is C<-between> and C<-not_between>,
1907 used with an arrayref of two values:
1911 completion_date => {
1912 -not_between => ['2002-10-01', '2003-02-06']
1918 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1920 These are the two builtin "special operators"; but the
1921 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1923 =head2 Unary operators: bool
1925 If you wish to test against boolean columns or functions within your
1926 database you can use the C<-bool> and C<-not_bool> operators. For
1927 example to test the column C<is_user> being true and the column
1928 <is_enabled> being false you would use:-
1932 -not_bool => 'is_enabled',
1937 WHERE is_user AND NOT is_enabledmv
1941 =head2 Nested conditions, -and/-or prefixes
1943 So far, we've seen how multiple conditions are joined with a top-level
1944 C<AND>. We can change this by putting the different conditions we want in
1945 hashes and then putting those hashes in an array. For example:
1950 status => { -like => ['pending%', 'dispatched'] },
1954 status => 'unassigned',
1958 This data structure would create the following:
1960 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1961 OR ( user = ? AND status = ? ) )";
1962 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1965 There is also a special C<-nest>
1966 operator which adds an additional set of parens, to create a subquery.
1967 For example, to get something like this:
1969 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1970 @bind = ('nwiger', '20', 'ASIA');
1976 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1980 Finally, clauses in hashrefs or arrayrefs can be
1981 prefixed with an C<-and> or C<-or> to change the logic
1988 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
1989 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
1996 WHERE ( user = ? AND
1997 ( ( workhrs > ? AND geo = ? )
1998 OR ( workhrs < ? AND geo = ? ) ) )
2001 =head2 Algebraic inconsistency, for historical reasons
2003 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2004 operator goes C<outside> of the nested structure; whereas when connecting
2005 several constraints on one column, the C<-and> operator goes
2006 C<inside> the arrayref. Here is an example combining both features :
2009 -and => [a => 1, b => 2],
2010 -or => [c => 3, d => 4],
2011 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2016 WHERE ( ( ( a = ? AND b = ? )
2017 OR ( c = ? OR d = ? )
2018 OR ( e LIKE ? AND e LIKE ? ) ) )
2020 This difference in syntax is unfortunate but must be preserved for
2021 historical reasons. So be careful : the two examples below would
2022 seem algebraically equivalent, but they are not
2024 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2025 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2027 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2028 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2033 Finally, sometimes only literal SQL will do. If you want to include
2034 literal SQL verbatim, you can specify it as a scalar reference, namely:
2036 my $inn = 'is Not Null';
2038 priority => { '<', 2 },
2044 $stmt = "WHERE priority < ? AND requestor is Not Null";
2047 Note that in this example, you only get one bind parameter back, since
2048 the verbatim SQL is passed as part of the statement.
2050 Of course, just to prove a point, the above can also be accomplished
2054 priority => { '<', 2 },
2055 requestor => { '!=', undef },
2061 Conditions on boolean columns can be expressed in the
2062 same way, passing a reference to an empty string :
2065 priority => { '<', 2 },
2071 $stmt = "WHERE priority < ? AND is_ready";
2075 =head2 Literal SQL with placeholders and bind values (subqueries)
2077 If the literal SQL to be inserted has placeholders and bind values,
2078 use a reference to an arrayref (yes this is a double reference --
2079 not so common, but perfectly legal Perl). For example, to find a date
2080 in Postgres you can use something like this:
2083 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2088 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2091 Note that you must pass the bind values in the same format as they are returned
2092 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2093 provide the bind values in the C<< [ column_meta => value ] >> format, where
2094 C<column_meta> is an opaque scalar value; most commonly the column name, but
2095 you can use any scalar value (including references and blessed references),
2096 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2097 to C<columns> the above example will look like:
2100 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2103 Literal SQL is especially useful for nesting parenthesized clauses in the
2104 main SQL query. Here is a first example :
2106 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2110 bar => \["IN ($sub_stmt)" => @sub_bind],
2115 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2116 WHERE c2 < ? AND c3 LIKE ?))";
2117 @bind = (1234, 100, "foo%");
2119 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2120 are expressed in the same way. Of course the C<$sub_stmt> and
2121 its associated bind values can be generated through a former call
2124 my ($sub_stmt, @sub_bind)
2125 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2126 c3 => {-like => "foo%"}});
2129 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2132 In the examples above, the subquery was used as an operator on a column;
2133 but the same principle also applies for a clause within the main C<%where>
2134 hash, like an EXISTS subquery :
2136 my ($sub_stmt, @sub_bind)
2137 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2140 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2145 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2146 WHERE c1 = ? AND c2 > t0.c0))";
2150 Observe that the condition on C<c2> in the subquery refers to
2151 column C<t0.c0> of the main query : this is I<not> a bind
2152 value, so we have to express it through a scalar ref.
2153 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2154 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2155 what we wanted here.
2157 Another use of the subquery technique is when some SQL clauses need
2158 parentheses, as it often occurs with some proprietary SQL extensions
2159 like for example fulltext expressions, geospatial expressions,
2160 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2163 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2166 Finally, here is an example where a subquery is used
2167 for expressing unary negation:
2169 my ($sub_stmt, @sub_bind)
2170 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2171 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2173 lname => {like => '%son%'},
2174 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2179 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2180 @bind = ('%son%', 10, 20)
2186 These pages could go on for a while, since the nesting of the data
2187 structures this module can handle are pretty much unlimited (the
2188 module implements the C<WHERE> expansion as a recursive function
2189 internally). Your best bet is to "play around" with the module a
2190 little to see how the data structures behave, and choose the best
2191 format for your data based on that.
2193 And of course, all the values above will probably be replaced with
2194 variables gotten from forms or the command line. After all, if you
2195 knew everything ahead of time, you wouldn't have to worry about
2196 dynamically-generating SQL and could just hardwire it into your
2202 =head1 ORDER BY CLAUSES
2204 Some functions take an order by clause. This can either be a scalar (just a
2205 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2206 or an array of either of the two previous forms. Examples:
2208 Given | Will Generate
2209 ----------------------------------------------------------
2211 \'colA DESC' | ORDER BY colA DESC
2213 'colA' | ORDER BY colA
2215 [qw/colA colB/] | ORDER BY colA, colB
2217 {-asc => 'colA'} | ORDER BY colA ASC
2219 {-desc => 'colB'} | ORDER BY colB DESC
2221 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2223 { -asc => [qw/colA colB] } | ORDER BY colA ASC, colB ASC
2226 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2227 { -desc => [qw/colB/], | colC ASC, colD ASC
2228 { -asc => [qw/colC colD/],|
2230 ===========================================================
2234 =head1 SPECIAL OPERATORS
2236 my $sqlmaker = SQL::Abstract->new(special_ops => [
2240 my ($self, $field, $op, $arg) = @_;
2246 handler => 'method_name',
2250 A "special operator" is a SQL syntactic clause that can be
2251 applied to a field, instead of a usual binary operator.
2254 WHERE field IN (?, ?, ?)
2255 WHERE field BETWEEN ? AND ?
2256 WHERE MATCH(field) AGAINST (?, ?)
2258 Special operators IN and BETWEEN are fairly standard and therefore
2259 are builtin within C<SQL::Abstract> (as the overridable methods
2260 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2261 like the MATCH .. AGAINST example above which is specific to MySQL,
2262 you can write your own operator handlers - supply a C<special_ops>
2263 argument to the C<new> method. That argument takes an arrayref of
2264 operator definitions; each operator definition is a hashref with two
2271 the regular expression to match the operator
2275 Either a coderef or a plain scalar method name. In both cases
2276 the expected return is C<< ($sql, @bind) >>.
2278 When supplied with a method name, it is simply called on the
2279 L<SQL::Abstract/> object as:
2281 $self->$method_name ($field, $op, $arg)
2285 $op is the part that matched the handler regex
2286 $field is the LHS of the operator
2289 When supplied with a coderef, it is called as:
2291 $coderef->($self, $field, $op, $arg)
2296 For example, here is an implementation
2297 of the MATCH .. AGAINST syntax for MySQL
2299 my $sqlmaker = SQL::Abstract->new(special_ops => [
2301 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2302 {regex => qr/^match$/i,
2304 my ($self, $field, $op, $arg) = @_;
2305 $arg = [$arg] if not ref $arg;
2306 my $label = $self->_quote($field);
2307 my ($placeholder) = $self->_convert('?');
2308 my $placeholders = join ", ", (($placeholder) x @$arg);
2309 my $sql = $self->_sqlcase('match') . " ($label) "
2310 . $self->_sqlcase('against') . " ($placeholders) ";
2311 my @bind = $self->_bindtype($field, @$arg);
2312 return ($sql, @bind);
2319 =head1 UNARY OPERATORS
2321 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2325 my ($self, $op, $arg) = @_;
2331 handler => 'method_name',
2335 A "unary operator" is a SQL syntactic clause that can be
2336 applied to a field - the operator goes before the field
2338 You can write your own operator handlers - supply a C<unary_ops>
2339 argument to the C<new> method. That argument takes an arrayref of
2340 operator definitions; each operator definition is a hashref with two
2347 the regular expression to match the operator
2351 Either a coderef or a plain scalar method name. In both cases
2352 the expected return is C<< $sql >>.
2354 When supplied with a method name, it is simply called on the
2355 L<SQL::Abstract/> object as:
2357 $self->$method_name ($op, $arg)
2361 $op is the part that matched the handler regex
2362 $arg is the RHS or argument of the operator
2364 When supplied with a coderef, it is called as:
2366 $coderef->($self, $op, $arg)
2374 Thanks to some benchmarking by Mark Stosberg, it turns out that
2375 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2376 I must admit this wasn't an intentional design issue, but it's a
2377 byproduct of the fact that you get to control your C<DBI> handles
2380 To maximize performance, use a code snippet like the following:
2382 # prepare a statement handle using the first row
2383 # and then reuse it for the rest of the rows
2385 for my $href (@array_of_hashrefs) {
2386 $stmt ||= $sql->insert('table', $href);
2387 $sth ||= $dbh->prepare($stmt);
2388 $sth->execute($sql->values($href));
2391 The reason this works is because the keys in your C<$href> are sorted
2392 internally by B<SQL::Abstract>. Thus, as long as your data retains
2393 the same structure, you only have to generate the SQL the first time
2394 around. On subsequent queries, simply use the C<values> function provided
2395 by this module to return your values in the correct order.
2400 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2401 really like this part (I do, at least). Building up a complex query
2402 can be as simple as the following:
2406 use CGI::FormBuilder;
2409 my $form = CGI::FormBuilder->new(...);
2410 my $sql = SQL::Abstract->new;
2412 if ($form->submitted) {
2413 my $field = $form->field;
2414 my $id = delete $field->{id};
2415 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2418 Of course, you would still have to connect using C<DBI> to run the
2419 query, but the point is that if you make your form look like your
2420 table, the actual query script can be extremely simplistic.
2422 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2423 a fast interface to returning and formatting data. I frequently
2424 use these three modules together to write complex database query
2425 apps in under 50 lines.
2430 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2431 Great care has been taken to preserve the I<published> behavior
2432 documented in previous versions in the 1.* family; however,
2433 some features that were previously undocumented, or behaved
2434 differently from the documentation, had to be changed in order
2435 to clarify the semantics. Hence, client code that was relying
2436 on some dark areas of C<SQL::Abstract> v1.*
2437 B<might behave differently> in v1.50.
2439 The main changes are :
2445 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2449 support for the { operator => \"..." } construct (to embed literal SQL)
2453 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2457 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2461 defensive programming : check arguments
2465 fixed bug with global logic, which was previously implemented
2466 through global variables yielding side-effects. Prior versions would
2467 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2468 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2469 Now this is interpreted
2470 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2475 fixed semantics of _bindtype on array args
2479 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2480 we just avoid shifting arrays within that tree.
2484 dropped the C<_modlogic> function
2490 =head1 ACKNOWLEDGEMENTS
2492 There are a number of individuals that have really helped out with
2493 this module. Unfortunately, most of them submitted bugs via CPAN
2494 so I have no idea who they are! But the people I do know are:
2496 Ash Berlin (order_by hash term support)
2497 Matt Trout (DBIx::Class support)
2498 Mark Stosberg (benchmarking)
2499 Chas Owens (initial "IN" operator support)
2500 Philip Collins (per-field SQL functions)
2501 Eric Kolve (hashref "AND" support)
2502 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2503 Dan Kubb (support for "quote_char" and "name_sep")
2504 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2505 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2506 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2507 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2513 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2517 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2519 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2521 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2522 While not an official support venue, C<DBIx::Class> makes heavy use of
2523 C<SQL::Abstract>, and as such list members there are very familiar with
2524 how to create queries.
2528 This module is free software; you may copy this under the terms of
2529 the GNU General Public License, or the Artistic License, copies of
2530 which should have accompanied your Perl kit.