1 package SQL::Abstract; # see doc at end of file
10 our @EXPORT_OK = qw(is_plain_value is_literal_value);
20 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
26 #======================================================================
28 #======================================================================
30 our $VERSION = '1.86';
32 # This would confuse some packagers
33 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
37 # special operators (-in, -between). May be extended/overridden by user.
38 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
39 my @BUILTIN_SPECIAL_OPS = (
40 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
41 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
42 {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
43 {regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
44 {regex => qr/^ is (?: \s+ not )? $/ix, handler => '_where_field_IS'},
47 # unaryish operators - key maps to handler
48 my @BUILTIN_UNARY_OPS = (
49 # the digits are backcompat stuff
50 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
51 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
52 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
53 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
54 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
55 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
56 { regex => qr/^ op $/xi, handler => '_where_op_OP' },
57 { regex => qr/^ bind $/xi, handler => '_where_op_BIND' },
60 #======================================================================
61 # DEBUGGING AND ERROR REPORTING
62 #======================================================================
65 return unless $_[0]->{debug}; shift; # a little faster
66 my $func = (caller(1))[3];
67 warn "[$func] ", @_, "\n";
71 my($func) = (caller(1))[3];
72 Carp::carp "[$func] Warning: ", @_;
76 my($func) = (caller(1))[3];
77 Carp::croak "[$func] Fatal: ", @_;
80 sub is_literal_value ($) {
81 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
82 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
86 # FIXME XSify - this can be done so much more efficiently
87 sub is_plain_value ($) {
89 ! length ref $_[0] ? \($_[0])
91 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
93 exists $_[0]->{-value}
94 ) ? \($_[0]->{-value})
96 # reuse @_ for even moar speedz
97 defined ( $_[1] = Scalar::Util::blessed $_[0] )
99 # deliberately not using Devel::OverloadInfo - the checks we are
100 # intersted in are much more limited than the fullblown thing, and
101 # this is a very hot piece of code
103 # simply using ->can('(""') can leave behind stub methods that
104 # break actually using the overload later (see L<perldiag/Stub
105 # found while resolving method "%s" overloading "%s" in package
106 # "%s"> and the source of overload::mycan())
108 # either has stringification which DBI SHOULD prefer out of the box
109 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
111 # has nummification or boolification, AND fallback is *not* disabled
113 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
116 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
118 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
122 # no fallback specified at all
123 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
125 # fallback explicitly undef
126 ! defined ${"$_[3]::()"}
139 #======================================================================
141 #======================================================================
145 my $class = ref($self) || $self;
146 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
148 # choose our case by keeping an option around
149 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
151 # default logic for interpreting arrayrefs
152 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
154 # how to return bind vars
155 $opt{bindtype} ||= 'normal';
157 # default comparison is "=", but can be overridden
160 # try to recognize which are the 'equality' and 'inequality' ops
161 # (temporary quickfix (in 2007), should go through a more seasoned API)
162 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
163 $opt{inequality_op} = qr/^( != | <> )$/ix;
165 $opt{like_op} = qr/^ (is\s+)? r?like $/xi;
166 $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
169 $opt{sqltrue} ||= '1=1';
170 $opt{sqlfalse} ||= '0=1';
173 $opt{special_ops} ||= [];
174 # regexes are applied in order, thus push after user-defines
175 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
178 $opt{unary_ops} ||= [];
179 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
181 # rudimentary sanity-check for user supplied bits treated as functions/operators
182 # If a purported function matches this regular expression, an exception is thrown.
183 # Literal SQL is *NOT* subject to this check, only functions (and column names
184 # when quoting is not in effect)
187 # need to guard against ()'s in column names too, but this will break tons of
188 # hacks... ideas anyone?
189 $opt{injection_guard} ||= qr/
195 return bless \%opt, $class;
199 sub _assert_pass_injection_guard {
200 if ($_[1] =~ $_[0]->{injection_guard}) {
201 my $class = ref $_[0];
202 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
203 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
204 . "{injection_guard} attribute to ${class}->new()"
209 #======================================================================
211 #======================================================================
215 my $table = $self->_table(shift);
216 my $data = shift || return;
219 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
220 my ($sql, @bind) = $self->$method($data);
221 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
223 if ($options->{returning}) {
224 my ($s, @b) = $self->_insert_returning($options);
229 return wantarray ? ($sql, @bind) : $sql;
232 # So that subclasses can override INSERT ... RETURNING separately from
233 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
234 sub _insert_returning { shift->_returning(@_) }
237 my ($self, $options) = @_;
239 my $f = $options->{returning};
241 my $fieldlist = $self->_SWITCH_refkind($f, {
242 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
243 SCALAR => sub {$self->_quote($f)},
244 SCALARREF => sub {$$f},
246 return $self->_sqlcase(' returning ') . $fieldlist;
249 sub _insert_HASHREF { # explicit list of fields and then values
250 my ($self, $data) = @_;
252 my @fields = sort keys %$data;
254 my ($sql, @bind) = $self->_insert_values($data);
257 $_ = $self->_quote($_) foreach @fields;
258 $sql = "( ".join(", ", @fields).") ".$sql;
260 return ($sql, @bind);
263 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
264 my ($self, $data) = @_;
266 # no names (arrayref) so can't generate bindtype
267 $self->{bindtype} ne 'columns'
268 or belch "can't do 'columns' bindtype when called with arrayref";
270 my (@values, @all_bind);
271 foreach my $value (@$data) {
272 my ($values, @bind) = $self->_insert_value(undef, $value);
273 push @values, $values;
274 push @all_bind, @bind;
276 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
277 return ($sql, @all_bind);
280 sub _insert_ARRAYREFREF { # literal SQL with bind
281 my ($self, $data) = @_;
283 my ($sql, @bind) = @${$data};
284 $self->_assert_bindval_matches_bindtype(@bind);
286 return ($sql, @bind);
290 sub _insert_SCALARREF { # literal SQL without bind
291 my ($self, $data) = @_;
297 my ($self, $data) = @_;
299 my (@values, @all_bind);
300 foreach my $column (sort keys %$data) {
301 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
302 push @values, $values;
303 push @all_bind, @bind;
305 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
306 return ($sql, @all_bind);
310 my ($self, $column, $v) = @_;
312 my (@values, @all_bind);
313 $self->_SWITCH_refkind($v, {
316 if ($self->{array_datatypes}) { # if array datatype are activated
318 push @all_bind, $self->_bindtype($column, $v);
320 else { # else literal SQL with bind
321 my ($sql, @bind) = @$v;
322 $self->_assert_bindval_matches_bindtype(@bind);
324 push @all_bind, @bind;
328 ARRAYREFREF => sub { # literal SQL with bind
329 my ($sql, @bind) = @${$v};
330 $self->_assert_bindval_matches_bindtype(@bind);
332 push @all_bind, @bind;
335 # THINK: anything useful to do with a HASHREF ?
336 HASHREF => sub { # (nothing, but old SQLA passed it through)
337 #TODO in SQLA >= 2.0 it will die instead
338 belch "HASH ref as bind value in insert is not supported";
340 push @all_bind, $self->_bindtype($column, $v);
343 SCALARREF => sub { # literal SQL without bind
347 SCALAR_or_UNDEF => sub {
349 push @all_bind, $self->_bindtype($column, $v);
354 my $sql = join(", ", @values);
355 return ($sql, @all_bind);
360 #======================================================================
362 #======================================================================
367 my $table = $self->_table(shift);
368 my $data = shift || return;
372 # first build the 'SET' part of the sql statement
373 puke "Unsupported data type specified to \$sql->update"
374 unless ref $data eq 'HASH';
376 my ($sql, @all_bind) = $self->_update_set_values($data);
377 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
381 my($where_sql, @where_bind) = $self->where($where);
383 push @all_bind, @where_bind;
386 if ($options->{returning}) {
387 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
388 $sql .= $returning_sql;
389 push @all_bind, @returning_bind;
392 return wantarray ? ($sql, @all_bind) : $sql;
395 sub _update_set_values {
396 my ($self, $data) = @_;
398 my (@set, @all_bind);
399 for my $k (sort keys %$data) {
402 my $label = $self->_quote($k);
404 $self->_SWITCH_refkind($v, {
406 if ($self->{array_datatypes}) { # array datatype
407 push @set, "$label = ?";
408 push @all_bind, $self->_bindtype($k, $v);
410 else { # literal SQL with bind
411 my ($sql, @bind) = @$v;
412 $self->_assert_bindval_matches_bindtype(@bind);
413 push @set, "$label = $sql";
414 push @all_bind, @bind;
417 ARRAYREFREF => sub { # literal SQL with bind
418 my ($sql, @bind) = @${$v};
419 $self->_assert_bindval_matches_bindtype(@bind);
420 push @set, "$label = $sql";
421 push @all_bind, @bind;
423 SCALARREF => sub { # literal SQL without bind
424 push @set, "$label = $$v";
427 my ($op, $arg, @rest) = %$v;
429 puke 'Operator calls in update must be in the form { -op => $arg }'
430 if (@rest or not $op =~ /^\-(.+)/);
432 local $self->{_nested_func_lhs} = $k;
433 my ($sql, @bind) = $self->_where_unary_op($1, $arg);
435 push @set, "$label = $sql";
436 push @all_bind, @bind;
438 SCALAR_or_UNDEF => sub {
439 push @set, "$label = ?";
440 push @all_bind, $self->_bindtype($k, $v);
446 my $sql = join ', ', @set;
448 return ($sql, @all_bind);
451 # So that subclasses can override UPDATE ... RETURNING separately from
453 sub _update_returning { shift->_returning(@_) }
457 #======================================================================
459 #======================================================================
464 my $table = $self->_table(shift);
465 my $fields = shift || '*';
469 my ($fields_sql, @bind) = $self->_select_fields($fields);
471 my ($where_sql, @where_bind) = $self->where($where, $order);
472 push @bind, @where_bind;
474 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
475 $self->_sqlcase('from'), $table)
478 return wantarray ? ($sql, @bind) : $sql;
482 my ($self, $fields) = @_;
483 return ref $fields eq 'ARRAY' ? join ', ', map { $self->_quote($_) } @$fields
487 #======================================================================
489 #======================================================================
494 my $table = $self->_table(shift);
498 my($where_sql, @bind) = $self->where($where);
499 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
501 if ($options->{returning}) {
502 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
503 $sql .= $returning_sql;
504 push @bind, @returning_bind;
507 return wantarray ? ($sql, @bind) : $sql;
510 # So that subclasses can override DELETE ... RETURNING separately from
512 sub _delete_returning { shift->_returning(@_) }
516 #======================================================================
518 #======================================================================
522 # Finally, a separate routine just to handle WHERE clauses
524 my ($self, $where, $order) = @_;
527 my ($sql, @bind) = $self->_recurse_where($where);
528 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
532 my ($order_sql, @order_bind) = $self->_order_by($order);
534 push @bind, @order_bind;
537 return wantarray ? ($sql, @bind) : $sql;
541 my ($self, $expr, $logic) = @_;
542 if (ref($expr) eq 'HASH') {
543 if (keys %$expr > 1) {
545 return +{ "-${logic}" => [
546 map $self->_expand_expr_hashpair($_ => $expr->{$_}, $logic),
550 return $self->_expand_expr_hashpair(%$expr, $logic);
555 sub _expand_expr_hashpair {
556 my ($self, $k, $v, $logic) = @_;
557 unless (defined($k) and length($k)) {
558 if (defined($k) and is_literal_value($v)) {
559 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
562 puke "Supplying an empty left hand side argument is not supported";
566 return $self->_expand_expr($v);
570 return $self->_expand_expr($v);
572 puke "-bool => undef not supported" unless defined($v);
573 return { -ident => $v };
575 if (my ($rest) = $k =~/^-not[_ ](.*)$/) {
576 return $self->_expand_expr({ -not => { "-${rest}", $v } }, $logic);
579 unless (defined($v)) {
580 my $orig_op = my $op = $self->{cmp};
582 $op =~ /^not$/i ? 'is not' # legacy
583 : $op =~ $self->{equality_op} ? 'is'
584 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
585 : $op =~ $self->{inequality_op} ? 'is not'
586 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
587 : puke "unexpected operator '$orig_op' with undef operand";
588 return +{ -op => [ $is.' null', { -ident => $k } ] };
595 { -bind => [ $k, $v ] }
599 if (ref($v) eq 'ARRAY') {
600 return $self->{sqlfalse} unless @$v;
601 $self->_debug("ARRAY($k) means distribute over elements");
603 $v->[0] =~ /^-((?:and|or))$/i
604 ? ($v = [ @{$v}[1..$#$v] ], $1)
605 : ($self->{logic} || 'or')
607 return +{ "-${this_logic}" => [ map $self->_expand_expr({ $k => $_ }, $this_logic), @$v ] };
609 if (my $literal = is_literal_value($v)) {
611 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
614 my ($sql, @bind) = @$literal;
615 return \[ $self->_quote($k).' '.$sql, @bind ];
622 my ($self, $where, $logic) = @_;
624 my $where_exp = $self->_expand_expr($where, $logic);
626 # dispatch on appropriate method according to refkind of $where
627 my $method = $self->_METHOD_FOR_refkind("_where", $where_exp);
629 my ($sql, @bind) = $self->$method($where_exp, $logic);
631 # DBIx::Class used to call _recurse_where in scalar context
632 # something else might too...
634 return ($sql, @bind);
637 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
644 #======================================================================
645 # WHERE: top-level ARRAYREF
646 #======================================================================
649 sub _where_ARRAYREF {
650 my ($self, $where, $logic) = @_;
652 $logic = uc($logic || $self->{logic});
653 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
655 my @clauses = @$where;
657 my (@sql_clauses, @all_bind);
658 # need to use while() so can shift() for pairs
660 my $el = shift @clauses;
662 $el = undef if (defined $el and ! length $el);
664 # switch according to kind of $el and get corresponding ($sql, @bind)
665 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
667 # skip empty elements, otherwise get invalid trailing AND stuff
668 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
672 $self->_assert_bindval_matches_bindtype(@b);
676 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
678 SCALARREF => sub { ($$el); },
681 # top-level arrayref with scalars, recurse in pairs
682 $self->_recurse_where({$el => shift(@clauses)})
685 UNDEF => sub {puke "Supplying an empty left hand side argument is not supported in array-pairs" },
689 push @sql_clauses, $sql;
690 push @all_bind, @bind;
694 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
697 #======================================================================
698 # WHERE: top-level ARRAYREFREF
699 #======================================================================
701 sub _where_ARRAYREFREF {
702 my ($self, $where) = @_;
703 my ($sql, @bind) = @$$where;
704 $self->_assert_bindval_matches_bindtype(@bind);
705 return ($sql, @bind);
708 #======================================================================
709 # WHERE: top-level HASHREF
710 #======================================================================
713 my ($self, $where) = @_;
714 my (@sql_clauses, @all_bind);
716 for my $k (sort keys %$where) {
717 my $v = $where->{$k};
719 # ($k => $v) is either a special unary op or a regular hashpair
720 my ($sql, @bind) = do {
722 # put the operator in canonical form
724 $op = substr $op, 1; # remove initial dash
725 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
726 $op =~ s/\s+/ /g; # compress whitespace
728 # so that -not_foo works correctly
729 $op =~ s/^not_/NOT /i;
731 $self->_debug("Unary OP(-$op) within hashref, recursing...");
732 my ($s, @b) = $self->_where_unary_op($op, $v);
734 # top level vs nested
735 # we assume that handled unary ops will take care of their ()s
737 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
739 ( defined $self->{_nested_func_lhs} and $self->{_nested_func_lhs} eq $k )
745 if (is_literal_value ($v) ) {
746 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
749 puke "Supplying an empty left hand side argument is not supported in hash-pairs";
753 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
754 $self->$method($k, $v);
758 push @sql_clauses, $sql;
759 push @all_bind, @bind;
762 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
765 sub _where_unary_op {
766 my ($self, $op, $rhs) = @_;
768 # top level special ops are illegal in general
769 puke "Illegal use of top-level '-$op'"
770 if !(defined $self->{_nested_func_lhs})
771 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
772 and not List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}};
774 if (my $op_entry = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
775 my $handler = $op_entry->{handler};
777 if (not ref $handler) {
778 if ($op =~ s/ [_\s]? \d+ $//x ) {
779 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
780 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
782 return $self->$handler($op, $rhs);
784 elsif (ref $handler eq 'CODE') {
785 return $handler->($self, $op, $rhs);
788 puke "Illegal handler for operator $op - expecting a method name or a coderef";
792 $self->_debug("Generic unary OP: $op - recursing as function");
794 $self->_assert_pass_injection_guard($op);
796 my ($sql, @bind) = $self->_SWITCH_refkind($rhs, {
798 puke "Illegal use of top-level '-$op'"
799 unless defined $self->{_nested_func_lhs};
802 $self->_convert('?'),
803 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
807 $self->_recurse_where($rhs)
811 $sql = sprintf('%s %s',
812 $self->_sqlcase($op),
816 return ($sql, @bind);
819 sub _where_op_ANDOR {
820 my ($self, $op, $v) = @_;
822 $self->_SWITCH_refkind($v, {
824 return $self->_where_ARRAYREF($v, $op);
828 return ($op =~ /^or/i)
829 ? $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], $op)
830 : $self->_where_HASHREF($v);
834 puke "-$op => \\\$scalar makes little sense, use " .
836 ? '[ \$scalar, \%rest_of_conditions ] instead'
837 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
842 puke "-$op => \\[...] makes little sense, use " .
844 ? '[ \[...], \%rest_of_conditions ] instead'
845 : '-and => [ \[...], \%rest_of_conditions ] instead'
849 SCALAR => sub { # permissively interpreted as SQL
850 puke "-$op => \$value makes little sense, use -bool => \$value instead";
854 puke "-$op => undef not supported";
860 my ($self, $op, $v) = @_;
862 $self->_SWITCH_refkind($v, {
864 SCALAR => sub { # permissively interpreted as SQL
865 belch "literal SQL should be -nest => \\'scalar' "
866 . "instead of -nest => 'scalar' ";
871 puke "-$op => undef not supported";
875 $self->_recurse_where($v);
883 my ($self, $op, $v) = @_;
885 my ($s, @b) = $self->_SWITCH_refkind($v, {
886 SCALAR => sub { # interpreted as SQL column
887 $self->_convert($self->_quote($v));
891 puke "-$op => undef not supported";
895 $self->_recurse_where($v);
899 $s = "(NOT $s)" if $op =~ /^not/i;
904 sub _where_op_IDENT {
906 my ($op, $rhs) = splice @_, -2;
907 if (! defined $rhs or length ref $rhs) {
908 puke "-$op requires a single plain scalar argument (a quotable identifier)";
911 # in case we are called as a top level special op (no '=')
912 my $has_lhs = my $lhs = shift;
914 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
922 sub _where_op_VALUE {
924 my ($op, $rhs) = splice @_, -2;
926 # in case we are called as a top level special op (no '=')
930 if (! defined $rhs) {
932 ? $self->_where_hashpair_HASHREF($lhs, { -is => undef })
939 (defined $lhs ? $lhs : $self->{_nested_func_lhs}),
946 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
950 $self->_convert('?'),
957 my %unop_postfix = map +($_ => 1), 'is null', 'is not null';
960 my ($self, undef, $v) = @_;
961 my ($op, @args) = @$v;
962 $op =~ s/^-// if length($op) > 1;
963 local $self->{_nested_func_lhs};
965 my ($expr_sql, @bind) = $self->_recurse_where($args[0]);
966 my $final_op = join ' ', split '_', $op;
967 my $op_sql = $self->_sqlcase($final_op);
969 $unop_postfix{lc($final_op)}
970 ? "${expr_sql} ${op_sql}"
971 : "${op_sql} ${expr_sql}"
973 return ($final_sql, @bind);
974 } elsif (@args == 2) {
975 my ($l, $r) = map [ $self->_recurse_where($_) ], @args;
976 return ( $l->[0].' '.$self->_sqlcase(join ' ', split '_', $op).' '.$r->[0], @{$l}[1..$#$l], @{$r}[1..$#$r] );
982 my ($self, undef, $bind) = @_;
983 return ($self->_convert('?'), $self->_bindtype(@$bind));
986 sub _where_hashpair_ARRAYREF {
987 my ($self, $k, $v) = @_;
990 my @v = @$v; # need copy because of shift below
991 $self->_debug("ARRAY($k) means distribute over elements");
993 # put apart first element if it is an operator (-and, -or)
995 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
999 my @distributed = map { {$k => $_} } @v;
1002 $self->_debug("OP($op) reinjected into the distributed array");
1003 unshift @distributed, $op;
1006 my $logic = $op ? substr($op, 1) : '';
1008 return $self->_recurse_where(\@distributed, $logic);
1011 $self->_debug("empty ARRAY($k) means 0=1");
1012 return ($self->{sqlfalse});
1016 sub _where_hashpair_HASHREF {
1017 my ($self, $k, $v, $logic) = @_;
1020 local $self->{_nested_func_lhs} = defined $self->{_nested_func_lhs}
1021 ? $self->{_nested_func_lhs}
1025 my ($all_sql, @all_bind);
1027 for my $orig_op (sort keys %$v) {
1028 my $val = $v->{$orig_op};
1030 # put the operator in canonical form
1033 # FIXME - we need to phase out dash-less ops
1034 $op =~ s/^-//; # remove possible initial dash
1035 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
1036 $op =~ s/\s+/ /g; # compress whitespace
1038 $self->_assert_pass_injection_guard($op);
1041 $op =~ s/^is_not/IS NOT/i;
1043 # so that -not_foo works correctly
1044 $op =~ s/^not_/NOT /i;
1046 # another retarded special case: foo => { $op => { -value => undef } }
1047 if (ref $val eq 'HASH' and keys %$val == 1 and exists $val->{-value} and ! defined $val->{-value} ) {
1053 # CASE: col-value logic modifiers
1054 if ($orig_op =~ /^ \- (and|or) $/xi) {
1055 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
1057 # CASE: special operators like -in or -between
1058 elsif (my $special_op = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1059 my $handler = $special_op->{handler};
1061 puke "No handler supplied for special operator $orig_op";
1063 elsif (not ref $handler) {
1064 ($sql, @bind) = $self->$handler($k, $op, $val);
1066 elsif (ref $handler eq 'CODE') {
1067 ($sql, @bind) = $handler->($self, $k, $op, $val);
1070 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
1074 $self->_SWITCH_refkind($val, {
1076 ARRAYREF => sub { # CASE: col => {op => \@vals}
1077 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
1080 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
1081 my ($sub_sql, @sub_bind) = @$$val;
1082 $self->_assert_bindval_matches_bindtype(@sub_bind);
1083 $sql = join ' ', $self->_convert($self->_quote($k)),
1084 $self->_sqlcase($op),
1089 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
1091 $op =~ /^not$/i ? 'is not' # legacy
1092 : $op =~ $self->{equality_op} ? 'is'
1093 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
1094 : $op =~ $self->{inequality_op} ? 'is not'
1095 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
1096 : puke "unexpected operator '$orig_op' with undef operand";
1098 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
1101 FALLBACK => sub { # CASE: col => {op/func => $stuff}
1102 ($sql, @bind) = $self->_where_unary_op($op, $val);
1105 $self->_convert($self->_quote($k)),
1106 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
1112 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
1113 push @all_bind, @bind;
1115 return ($all_sql, @all_bind);
1118 sub _where_field_IS {
1119 my ($self, $k, $op, $v) = @_;
1121 my ($s) = $self->_SWITCH_refkind($v, {
1124 $self->_convert($self->_quote($k)),
1125 map { $self->_sqlcase($_)} ($op, 'null')
1128 puke "$op can only take undef as argument";
1135 sub _where_field_op_ARRAYREF {
1136 my ($self, $k, $op, $vals) = @_;
1138 my @vals = @$vals; #always work on a copy
1141 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
1143 join(', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
1146 # see if the first element is an -and/-or op
1148 if (defined $vals[0] && $vals[0] =~ /^ - (AND|OR) $/ix) {
1153 # a long standing API wart - an attempt to change this behavior during
1154 # the 1.50 series failed *spectacularly*. Warn instead and leave the
1159 (!$logic or $logic eq 'OR')
1161 ($op =~ $self->{inequality_op} or $op =~ $self->{not_like_op})
1164 belch "A multi-element arrayref as an argument to the inequality op '$o' "
1165 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1166 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1170 # distribute $op over each remaining member of @vals, append logic if exists
1171 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
1175 # try to DWIM on equality operators
1177 $op =~ $self->{equality_op} ? $self->{sqlfalse}
1178 : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqlfalse}
1179 : $op =~ $self->{inequality_op} ? $self->{sqltrue}
1180 : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqltrue}
1181 : puke "operator '$op' applied on an empty array (field '$k')";
1186 sub _where_hashpair_SCALARREF {
1187 my ($self, $k, $v) = @_;
1188 $self->_debug("SCALAR($k) means literal SQL: $$v");
1189 my $sql = $self->_quote($k) . " " . $$v;
1193 # literal SQL with bind
1194 sub _where_hashpair_ARRAYREFREF {
1195 my ($self, $k, $v) = @_;
1196 $self->_debug("REF($k) means literal SQL: @${$v}");
1197 my ($sql, @bind) = @$$v;
1198 $self->_assert_bindval_matches_bindtype(@bind);
1199 $sql = $self->_quote($k) . " " . $sql;
1200 return ($sql, @bind );
1203 # literal SQL without bind
1204 sub _where_hashpair_SCALAR {
1205 my ($self, $k, $v) = @_;
1206 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
1207 return ($self->_where_hashpair_HASHREF($k, { $self->{cmp} => $v }));
1211 sub _where_hashpair_UNDEF {
1212 my ($self, $k, $v) = @_;
1213 $self->_debug("UNDEF($k) means IS NULL");
1214 return $self->_where_hashpair_HASHREF($k, { -is => undef });
1217 #======================================================================
1218 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
1219 #======================================================================
1222 sub _where_SCALARREF {
1223 my ($self, $where) = @_;
1226 $self->_debug("SCALAR(*top) means literal SQL: $$where");
1232 my ($self, $where) = @_;
1235 $self->_debug("NOREF(*top) means literal SQL: $where");
1246 #======================================================================
1247 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
1248 #======================================================================
1251 sub _where_field_BETWEEN {
1252 my ($self, $k, $op, $vals) = @_;
1254 my ($label, $and, $placeholder);
1255 $label = $self->_convert($self->_quote($k));
1256 $and = ' ' . $self->_sqlcase('and') . ' ';
1257 $placeholder = $self->_convert('?');
1258 $op = $self->_sqlcase($op);
1260 my $invalid_args = "Operator '$op' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1262 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
1263 ARRAYREFREF => sub {
1264 my ($s, @b) = @$$vals;
1265 $self->_assert_bindval_matches_bindtype(@b);
1272 puke $invalid_args if @$vals != 2;
1274 my (@all_sql, @all_bind);
1275 foreach my $val (@$vals) {
1276 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1278 return ($placeholder, $self->_bindtype($k, $val) );
1283 ARRAYREFREF => sub {
1284 my ($sql, @bind) = @$$val;
1285 $self->_assert_bindval_matches_bindtype(@bind);
1286 return ($sql, @bind);
1289 my ($func, $arg, @rest) = %$val;
1290 puke "Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN"
1291 if (@rest or $func !~ /^ \- (.+)/x);
1292 $self->_where_unary_op($1 => $arg);
1298 push @all_sql, $sql;
1299 push @all_bind, @bind;
1303 (join $and, @all_sql),
1312 my $sql = "( $label $op $clause )";
1313 return ($sql, @bind)
1317 sub _where_field_IN {
1318 my ($self, $k, $op, $vals) = @_;
1320 # backwards compatibility: if scalar, force into an arrayref
1321 $vals = [$vals] if defined $vals && ! ref $vals;
1323 my ($label) = $self->_convert($self->_quote($k));
1324 my ($placeholder) = $self->_convert('?');
1325 $op = $self->_sqlcase($op);
1327 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1328 ARRAYREF => sub { # list of choices
1329 if (@$vals) { # nonempty list
1330 my (@all_sql, @all_bind);
1332 for my $val (@$vals) {
1333 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1335 return ($placeholder, $val);
1340 ARRAYREFREF => sub {
1341 my ($sql, @bind) = @$$val;
1342 $self->_assert_bindval_matches_bindtype(@bind);
1343 return ($sql, @bind);
1346 my ($func, $arg, @rest) = %$val;
1347 puke "Only simple { -func => arg } functions accepted as sub-arguments to IN"
1348 if (@rest or $func !~ /^ \- (.+)/x);
1349 $self->_where_unary_op($1 => $arg);
1353 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1354 . "-$op operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1355 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1356 . 'will emit the logically correct SQL instead of raising this exception)'
1360 push @all_sql, $sql;
1361 push @all_bind, @bind;
1365 sprintf('%s %s ( %s )',
1368 join(', ', @all_sql)
1370 $self->_bindtype($k, @all_bind),
1373 else { # empty list: some databases won't understand "IN ()", so DWIM
1374 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1379 SCALARREF => sub { # literal SQL
1380 my $sql = $self->_open_outer_paren($$vals);
1381 return ("$label $op ( $sql )");
1383 ARRAYREFREF => sub { # literal SQL with bind
1384 my ($sql, @bind) = @$$vals;
1385 $self->_assert_bindval_matches_bindtype(@bind);
1386 $sql = $self->_open_outer_paren($sql);
1387 return ("$label $op ( $sql )", @bind);
1391 puke "Argument passed to the '$op' operator can not be undefined";
1395 puke "special op $op requires an arrayref (or scalarref/arrayref-ref)";
1399 return ($sql, @bind);
1402 # Some databases (SQLite) treat col IN (1, 2) different from
1403 # col IN ( (1, 2) ). Use this to strip all outer parens while
1404 # adding them back in the corresponding method
1405 sub _open_outer_paren {
1406 my ($self, $sql) = @_;
1408 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1410 # there are closing parens inside, need the heavy duty machinery
1411 # to reevaluate the extraction starting from $sql (full reevaluation)
1412 if ($inner =~ /\)/) {
1413 require Text::Balanced;
1415 my (undef, $remainder) = do {
1416 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1418 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1421 # the entire expression needs to be a balanced bracketed thing
1422 # (after an extract no remainder sans trailing space)
1423 last if defined $remainder and $remainder =~ /\S/;
1433 #======================================================================
1435 #======================================================================
1438 my ($self, $arg) = @_;
1441 for my $c ($self->_order_by_chunks($arg) ) {
1442 $self->_SWITCH_refkind($c, {
1443 SCALAR => sub { push @sql, $c },
1444 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1450 $self->_sqlcase(' order by'),
1456 return wantarray ? ($sql, @bind) : $sql;
1459 sub _order_by_chunks {
1460 my ($self, $arg) = @_;
1462 return $self->_SWITCH_refkind($arg, {
1465 map { $self->_order_by_chunks($_ ) } @$arg;
1468 ARRAYREFREF => sub {
1469 my ($s, @b) = @$$arg;
1470 $self->_assert_bindval_matches_bindtype(@b);
1474 SCALAR => sub {$self->_quote($arg)},
1476 UNDEF => sub {return () },
1478 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1481 # get first pair in hash
1482 my ($key, $val, @rest) = %$arg;
1484 return () unless $key;
1486 if (@rest or not $key =~ /^-(desc|asc)/i) {
1487 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1493 for my $c ($self->_order_by_chunks($val)) {
1496 $self->_SWITCH_refkind($c, {
1501 ($sql, @bind) = @$c;
1505 $sql = $sql . ' ' . $self->_sqlcase($direction);
1507 push @ret, [ $sql, @bind];
1516 #======================================================================
1517 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1518 #======================================================================
1523 $self->_SWITCH_refkind($from, {
1524 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1525 SCALAR => sub {$self->_quote($from)},
1526 SCALARREF => sub {$$from},
1531 #======================================================================
1533 #======================================================================
1535 # highly optimized, as it's called way too often
1537 # my ($self, $label) = @_;
1539 return '' unless defined $_[1];
1540 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1542 $_[0]->{quote_char} or
1543 ($_[0]->_assert_pass_injection_guard($_[1]), return $_[1]);
1545 my $qref = ref $_[0]->{quote_char};
1547 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1548 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1549 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1551 my $esc = $_[0]->{escape_char} || $r;
1553 # parts containing * are naturally unquoted
1554 return join($_[0]->{name_sep}||'', map
1555 +( $_ eq '*' ? $_ : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r } ),
1556 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1561 # Conversion, if applicable
1563 #my ($self, $arg) = @_;
1564 if ($_[0]->{convert}) {
1565 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1572 #my ($self, $col, @vals) = @_;
1573 # called often - tighten code
1574 return $_[0]->{bindtype} eq 'columns'
1575 ? map {[$_[1], $_]} @_[2 .. $#_]
1580 # Dies if any element of @bind is not in [colname => value] format
1581 # if bindtype is 'columns'.
1582 sub _assert_bindval_matches_bindtype {
1583 # my ($self, @bind) = @_;
1585 if ($self->{bindtype} eq 'columns') {
1587 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1588 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1594 sub _join_sql_clauses {
1595 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1597 if (@$clauses_aref > 1) {
1598 my $join = " " . $self->_sqlcase($logic) . " ";
1599 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1600 return ($sql, @$bind_aref);
1602 elsif (@$clauses_aref) {
1603 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1606 return (); # if no SQL, ignore @$bind_aref
1611 # Fix SQL case, if so requested
1613 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1614 # don't touch the argument ... crooked logic, but let's not change it!
1615 return $_[0]->{case} ? $_[1] : uc($_[1]);
1619 #======================================================================
1620 # DISPATCHING FROM REFKIND
1621 #======================================================================
1624 my ($self, $data) = @_;
1626 return 'UNDEF' unless defined $data;
1628 # blessed objects are treated like scalars
1629 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1631 return 'SCALAR' unless $ref;
1634 while ($ref eq 'REF') {
1636 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1640 return ($ref||'SCALAR') . ('REF' x $n_steps);
1644 my ($self, $data) = @_;
1645 my @try = ($self->_refkind($data));
1646 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1647 push @try, 'FALLBACK';
1651 sub _METHOD_FOR_refkind {
1652 my ($self, $meth_prefix, $data) = @_;
1655 for (@{$self->_try_refkind($data)}) {
1656 $method = $self->can($meth_prefix."_".$_)
1660 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1664 sub _SWITCH_refkind {
1665 my ($self, $data, $dispatch_table) = @_;
1668 for (@{$self->_try_refkind($data)}) {
1669 $coderef = $dispatch_table->{$_}
1673 puke "no dispatch entry for ".$self->_refkind($data)
1682 #======================================================================
1683 # VALUES, GENERATE, AUTOLOAD
1684 #======================================================================
1686 # LDNOTE: original code from nwiger, didn't touch code in that section
1687 # I feel the AUTOLOAD stuff should not be the default, it should
1688 # only be activated on explicit demand by user.
1692 my $data = shift || return;
1693 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1694 unless ref $data eq 'HASH';
1697 foreach my $k (sort keys %$data) {
1698 my $v = $data->{$k};
1699 $self->_SWITCH_refkind($v, {
1701 if ($self->{array_datatypes}) { # array datatype
1702 push @all_bind, $self->_bindtype($k, $v);
1704 else { # literal SQL with bind
1705 my ($sql, @bind) = @$v;
1706 $self->_assert_bindval_matches_bindtype(@bind);
1707 push @all_bind, @bind;
1710 ARRAYREFREF => sub { # literal SQL with bind
1711 my ($sql, @bind) = @${$v};
1712 $self->_assert_bindval_matches_bindtype(@bind);
1713 push @all_bind, @bind;
1715 SCALARREF => sub { # literal SQL without bind
1717 SCALAR_or_UNDEF => sub {
1718 push @all_bind, $self->_bindtype($k, $v);
1729 my(@sql, @sqlq, @sqlv);
1733 if ($ref eq 'HASH') {
1734 for my $k (sort keys %$_) {
1737 my $label = $self->_quote($k);
1738 if ($r eq 'ARRAY') {
1739 # literal SQL with bind
1740 my ($sql, @bind) = @$v;
1741 $self->_assert_bindval_matches_bindtype(@bind);
1742 push @sqlq, "$label = $sql";
1744 } elsif ($r eq 'SCALAR') {
1745 # literal SQL without bind
1746 push @sqlq, "$label = $$v";
1748 push @sqlq, "$label = ?";
1749 push @sqlv, $self->_bindtype($k, $v);
1752 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1753 } elsif ($ref eq 'ARRAY') {
1754 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1757 if ($r eq 'ARRAY') { # literal SQL with bind
1758 my ($sql, @bind) = @$v;
1759 $self->_assert_bindval_matches_bindtype(@bind);
1762 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1763 # embedded literal SQL
1770 push @sql, '(' . join(', ', @sqlq) . ')';
1771 } elsif ($ref eq 'SCALAR') {
1775 # strings get case twiddled
1776 push @sql, $self->_sqlcase($_);
1780 my $sql = join ' ', @sql;
1782 # this is pretty tricky
1783 # if ask for an array, return ($stmt, @bind)
1784 # otherwise, s/?/shift @sqlv/ to put it inline
1786 return ($sql, @sqlv);
1788 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1789 ref $d ? $d->[1] : $d/e;
1798 # This allows us to check for a local, then _form, attr
1800 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1801 return $self->generate($name, @_);
1812 SQL::Abstract - Generate SQL from Perl data structures
1818 my $sql = SQL::Abstract->new;
1820 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1822 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1824 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1826 my($stmt, @bind) = $sql->delete($table, \%where);
1828 # Then, use these in your DBI statements
1829 my $sth = $dbh->prepare($stmt);
1830 $sth->execute(@bind);
1832 # Just generate the WHERE clause
1833 my($stmt, @bind) = $sql->where(\%where, $order);
1835 # Return values in the same order, for hashed queries
1836 # See PERFORMANCE section for more details
1837 my @bind = $sql->values(\%fieldvals);
1841 This module was inspired by the excellent L<DBIx::Abstract>.
1842 However, in using that module I found that what I really wanted
1843 to do was generate SQL, but still retain complete control over my
1844 statement handles and use the DBI interface. So, I set out to
1845 create an abstract SQL generation module.
1847 While based on the concepts used by L<DBIx::Abstract>, there are
1848 several important differences, especially when it comes to WHERE
1849 clauses. I have modified the concepts used to make the SQL easier
1850 to generate from Perl data structures and, IMO, more intuitive.
1851 The underlying idea is for this module to do what you mean, based
1852 on the data structures you provide it. The big advantage is that
1853 you don't have to modify your code every time your data changes,
1854 as this module figures it out.
1856 To begin with, an SQL INSERT is as easy as just specifying a hash
1857 of C<key=value> pairs:
1860 name => 'Jimbo Bobson',
1861 phone => '123-456-7890',
1862 address => '42 Sister Lane',
1863 city => 'St. Louis',
1864 state => 'Louisiana',
1867 The SQL can then be generated with this:
1869 my($stmt, @bind) = $sql->insert('people', \%data);
1871 Which would give you something like this:
1873 $stmt = "INSERT INTO people
1874 (address, city, name, phone, state)
1875 VALUES (?, ?, ?, ?, ?)";
1876 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1877 '123-456-7890', 'Louisiana');
1879 These are then used directly in your DBI code:
1881 my $sth = $dbh->prepare($stmt);
1882 $sth->execute(@bind);
1884 =head2 Inserting and Updating Arrays
1886 If your database has array types (like for example Postgres),
1887 activate the special option C<< array_datatypes => 1 >>
1888 when creating the C<SQL::Abstract> object.
1889 Then you may use an arrayref to insert and update database array types:
1891 my $sql = SQL::Abstract->new(array_datatypes => 1);
1893 planets => [qw/Mercury Venus Earth Mars/]
1896 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1900 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1902 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1905 =head2 Inserting and Updating SQL
1907 In order to apply SQL functions to elements of your C<%data> you may
1908 specify a reference to an arrayref for the given hash value. For example,
1909 if you need to execute the Oracle C<to_date> function on a value, you can
1910 say something like this:
1914 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1917 The first value in the array is the actual SQL. Any other values are
1918 optional and would be included in the bind values array. This gives
1921 my($stmt, @bind) = $sql->insert('people', \%data);
1923 $stmt = "INSERT INTO people (name, date_entered)
1924 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1925 @bind = ('Bill', '03/02/2003');
1927 An UPDATE is just as easy, all you change is the name of the function:
1929 my($stmt, @bind) = $sql->update('people', \%data);
1931 Notice that your C<%data> isn't touched; the module will generate
1932 the appropriately quirky SQL for you automatically. Usually you'll
1933 want to specify a WHERE clause for your UPDATE, though, which is
1934 where handling C<%where> hashes comes in handy...
1936 =head2 Complex where statements
1938 This module can generate pretty complicated WHERE statements
1939 easily. For example, simple C<key=value> pairs are taken to mean
1940 equality, and if you want to see if a field is within a set
1941 of values, you can use an arrayref. Let's say we wanted to
1942 SELECT some data based on this criteria:
1945 requestor => 'inna',
1946 worker => ['nwiger', 'rcwe', 'sfz'],
1947 status => { '!=', 'completed' }
1950 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1952 The above would give you something like this:
1954 $stmt = "SELECT * FROM tickets WHERE
1955 ( requestor = ? ) AND ( status != ? )
1956 AND ( worker = ? OR worker = ? OR worker = ? )";
1957 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1959 Which you could then use in DBI code like so:
1961 my $sth = $dbh->prepare($stmt);
1962 $sth->execute(@bind);
1968 The methods are simple. There's one for every major SQL operation,
1969 and a constructor you use first. The arguments are specified in a
1970 similar order for each method (table, then fields, then a where
1971 clause) to try and simplify things.
1973 =head2 new(option => 'value')
1975 The C<new()> function takes a list of options and values, and returns
1976 a new B<SQL::Abstract> object which can then be used to generate SQL
1977 through the methods below. The options accepted are:
1983 If set to 'lower', then SQL will be generated in all lowercase. By
1984 default SQL is generated in "textbook" case meaning something like:
1986 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1988 Any setting other than 'lower' is ignored.
1992 This determines what the default comparison operator is. By default
1993 it is C<=>, meaning that a hash like this:
1995 %where = (name => 'nwiger', email => 'nate@wiger.org');
1997 Will generate SQL like this:
1999 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2001 However, you may want loose comparisons by default, so if you set
2002 C<cmp> to C<like> you would get SQL such as:
2004 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2006 You can also override the comparison on an individual basis - see
2007 the huge section on L</"WHERE CLAUSES"> at the bottom.
2009 =item sqltrue, sqlfalse
2011 Expressions for inserting boolean values within SQL statements.
2012 By default these are C<1=1> and C<1=0>. They are used
2013 by the special operators C<-in> and C<-not_in> for generating
2014 correct SQL even when the argument is an empty array (see below).
2018 This determines the default logical operator for multiple WHERE
2019 statements in arrays or hashes. If absent, the default logic is "or"
2020 for arrays, and "and" for hashes. This means that a WHERE
2024 event_date => {'>=', '2/13/99'},
2025 event_date => {'<=', '4/24/03'},
2028 will generate SQL like this:
2030 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2032 This is probably not what you want given this query, though (look
2033 at the dates). To change the "OR" to an "AND", simply specify:
2035 my $sql = SQL::Abstract->new(logic => 'and');
2037 Which will change the above C<WHERE> to:
2039 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2041 The logic can also be changed locally by inserting
2042 a modifier in front of an arrayref:
2044 @where = (-and => [event_date => {'>=', '2/13/99'},
2045 event_date => {'<=', '4/24/03'} ]);
2047 See the L</"WHERE CLAUSES"> section for explanations.
2051 This will automatically convert comparisons using the specified SQL
2052 function for both column and value. This is mostly used with an argument
2053 of C<upper> or C<lower>, so that the SQL will have the effect of
2054 case-insensitive "searches". For example, this:
2056 $sql = SQL::Abstract->new(convert => 'upper');
2057 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2059 Will turn out the following SQL:
2061 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2063 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2064 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2065 not validate this option; it will just pass through what you specify verbatim).
2069 This is a kludge because many databases suck. For example, you can't
2070 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2071 Instead, you have to use C<bind_param()>:
2073 $sth->bind_param(1, 'reg data');
2074 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2076 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2077 which loses track of which field each slot refers to. Fear not.
2079 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2080 Currently, you can specify either C<normal> (default) or C<columns>. If you
2081 specify C<columns>, you will get an array that looks like this:
2083 my $sql = SQL::Abstract->new(bindtype => 'columns');
2084 my($stmt, @bind) = $sql->insert(...);
2087 [ 'column1', 'value1' ],
2088 [ 'column2', 'value2' ],
2089 [ 'column3', 'value3' ],
2092 You can then iterate through this manually, using DBI's C<bind_param()>.
2094 $sth->prepare($stmt);
2097 my($col, $data) = @$_;
2098 if ($col eq 'details' || $col eq 'comments') {
2099 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2100 } elsif ($col eq 'image') {
2101 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2103 $sth->bind_param($i, $data);
2107 $sth->execute; # execute without @bind now
2109 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2110 Basically, the advantage is still that you don't have to care which fields
2111 are or are not included. You could wrap that above C<for> loop in a simple
2112 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2113 get a layer of abstraction over manual SQL specification.
2115 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2116 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2117 will expect the bind values in this format.
2121 This is the character that a table or column name will be quoted
2122 with. By default this is an empty string, but you could set it to
2123 the character C<`>, to generate SQL like this:
2125 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2127 Alternatively, you can supply an array ref of two items, the first being the left
2128 hand quote character, and the second the right hand quote character. For
2129 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2130 that generates SQL like this:
2132 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2134 Quoting is useful if you have tables or columns names that are reserved
2135 words in your database's SQL dialect.
2139 This is the character that will be used to escape L</quote_char>s appearing
2140 in an identifier before it has been quoted.
2142 The parameter default in case of a single L</quote_char> character is the quote
2145 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2146 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2147 of the B<opening (left)> L</quote_char> within the identifier are currently left
2148 untouched. The default for opening-closing-style quotes may change in future
2149 versions, thus you are B<strongly encouraged> to specify the escape character
2154 This is the character that separates a table and column name. It is
2155 necessary to specify this when the C<quote_char> option is selected,
2156 so that tables and column names can be individually quoted like this:
2158 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2160 =item injection_guard
2162 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2163 column name specified in a query structure. This is a safety mechanism to avoid
2164 injection attacks when mishandling user input e.g.:
2166 my %condition_as_column_value_pairs = get_values_from_user();
2167 $sqla->select( ... , \%condition_as_column_value_pairs );
2169 If the expression matches an exception is thrown. Note that literal SQL
2170 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2172 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2174 =item array_datatypes
2176 When this option is true, arrayrefs in INSERT or UPDATE are
2177 interpreted as array datatypes and are passed directly
2179 When this option is false, arrayrefs are interpreted
2180 as literal SQL, just like refs to arrayrefs
2181 (but this behavior is for backwards compatibility; when writing
2182 new queries, use the "reference to arrayref" syntax
2188 Takes a reference to a list of "special operators"
2189 to extend the syntax understood by L<SQL::Abstract>.
2190 See section L</"SPECIAL OPERATORS"> for details.
2194 Takes a reference to a list of "unary operators"
2195 to extend the syntax understood by L<SQL::Abstract>.
2196 See section L</"UNARY OPERATORS"> for details.
2202 =head2 insert($table, \@values || \%fieldvals, \%options)
2204 This is the simplest function. You simply give it a table name
2205 and either an arrayref of values or hashref of field/value pairs.
2206 It returns an SQL INSERT statement and a list of bind values.
2207 See the sections on L</"Inserting and Updating Arrays"> and
2208 L</"Inserting and Updating SQL"> for information on how to insert
2209 with those data types.
2211 The optional C<\%options> hash reference may contain additional
2212 options to generate the insert SQL. Currently supported options
2219 Takes either a scalar of raw SQL fields, or an array reference of
2220 field names, and adds on an SQL C<RETURNING> statement at the end.
2221 This allows you to return data generated by the insert statement
2222 (such as row IDs) without performing another C<SELECT> statement.
2223 Note, however, this is not part of the SQL standard and may not
2224 be supported by all database engines.
2228 =head2 update($table, \%fieldvals, \%where, \%options)
2230 This takes a table, hashref of field/value pairs, and an optional
2231 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2233 See the sections on L</"Inserting and Updating Arrays"> and
2234 L</"Inserting and Updating SQL"> for information on how to insert
2235 with those data types.
2237 The optional C<\%options> hash reference may contain additional
2238 options to generate the update SQL. Currently supported options
2245 See the C<returning> option to
2246 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2250 =head2 select($source, $fields, $where, $order)
2252 This returns a SQL SELECT statement and associated list of bind values, as
2253 specified by the arguments:
2259 Specification of the 'FROM' part of the statement.
2260 The argument can be either a plain scalar (interpreted as a table
2261 name, will be quoted), or an arrayref (interpreted as a list
2262 of table names, joined by commas, quoted), or a scalarref
2263 (literal SQL, not quoted).
2267 Specification of the list of fields to retrieve from
2269 The argument can be either an arrayref (interpreted as a list
2270 of field names, will be joined by commas and quoted), or a
2271 plain scalar (literal SQL, not quoted).
2272 Please observe that this API is not as flexible as that of
2273 the first argument C<$source>, for backwards compatibility reasons.
2277 Optional argument to specify the WHERE part of the query.
2278 The argument is most often a hashref, but can also be
2279 an arrayref or plain scalar --
2280 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2284 Optional argument to specify the ORDER BY part of the query.
2285 The argument can be a scalar, a hashref or an arrayref
2286 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2292 =head2 delete($table, \%where, \%options)
2294 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2295 It returns an SQL DELETE statement and list of bind values.
2297 The optional C<\%options> hash reference may contain additional
2298 options to generate the delete SQL. Currently supported options
2305 See the C<returning> option to
2306 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2310 =head2 where(\%where, $order)
2312 This is used to generate just the WHERE clause. For example,
2313 if you have an arbitrary data structure and know what the
2314 rest of your SQL is going to look like, but want an easy way
2315 to produce a WHERE clause, use this. It returns an SQL WHERE
2316 clause and list of bind values.
2319 =head2 values(\%data)
2321 This just returns the values from the hash C<%data>, in the same
2322 order that would be returned from any of the other above queries.
2323 Using this allows you to markedly speed up your queries if you
2324 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2326 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2328 Warning: This is an experimental method and subject to change.
2330 This returns arbitrarily generated SQL. It's a really basic shortcut.
2331 It will return two different things, depending on return context:
2333 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2334 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2336 These would return the following:
2338 # First calling form
2339 $stmt = "CREATE TABLE test (?, ?)";
2340 @bind = (field1, field2);
2342 # Second calling form
2343 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2345 Depending on what you're trying to do, it's up to you to choose the correct
2346 format. In this example, the second form is what you would want.
2350 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2354 ALTER SESSION SET nls_date_format = 'MM/YY'
2356 You get the idea. Strings get their case twiddled, but everything
2357 else remains verbatim.
2359 =head1 EXPORTABLE FUNCTIONS
2361 =head2 is_plain_value
2363 Determines if the supplied argument is a plain value as understood by this
2368 =item * The value is C<undef>
2370 =item * The value is a non-reference
2372 =item * The value is an object with stringification overloading
2374 =item * The value is of the form C<< { -value => $anything } >>
2378 On failure returns C<undef>, on success returns a B<scalar> reference
2379 to the original supplied argument.
2385 The stringification overloading detection is rather advanced: it takes
2386 into consideration not only the presence of a C<""> overload, but if that
2387 fails also checks for enabled
2388 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2389 on either C<0+> or C<bool>.
2391 Unfortunately testing in the field indicates that this
2392 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2393 but only when very large numbers of stringifying objects are involved.
2394 At the time of writing ( Sep 2014 ) there is no clear explanation of
2395 the direct cause, nor is there a manageably small test case that reliably
2396 reproduces the problem.
2398 If you encounter any of the following exceptions in B<random places within
2399 your application stack> - this module may be to blame:
2401 Operation "ne": no method found,
2402 left argument in overloaded package <something>,
2403 right argument in overloaded package <something>
2407 Stub found while resolving method "???" overloading """" in package <something>
2409 If you fall victim to the above - please attempt to reduce the problem
2410 to something that could be sent to the L<SQL::Abstract developers
2411 |DBIx::Class/GETTING HELP/SUPPORT>
2412 (either publicly or privately). As a workaround in the meantime you can
2413 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2414 value, which will most likely eliminate your problem (at the expense of
2415 not being able to properly detect exotic forms of stringification).
2417 This notice and environment variable will be removed in a future version,
2418 as soon as the underlying problem is found and a reliable workaround is
2423 =head2 is_literal_value
2425 Determines if the supplied argument is a literal value as understood by this
2430 =item * C<\$sql_string>
2432 =item * C<\[ $sql_string, @bind_values ]>
2436 On failure returns C<undef>, on success returns an B<array> reference
2437 containing the unpacked version of the supplied literal SQL and bind values.
2439 =head1 WHERE CLAUSES
2443 This module uses a variation on the idea from L<DBIx::Abstract>. It
2444 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2445 module is that things in arrays are OR'ed, and things in hashes
2448 The easiest way to explain is to show lots of examples. After
2449 each C<%where> hash shown, it is assumed you used:
2451 my($stmt, @bind) = $sql->where(\%where);
2453 However, note that the C<%where> hash can be used directly in any
2454 of the other functions as well, as described above.
2456 =head2 Key-value pairs
2458 So, let's get started. To begin, a simple hash:
2462 status => 'completed'
2465 Is converted to SQL C<key = val> statements:
2467 $stmt = "WHERE user = ? AND status = ?";
2468 @bind = ('nwiger', 'completed');
2470 One common thing I end up doing is having a list of values that
2471 a field can be in. To do this, simply specify a list inside of
2476 status => ['assigned', 'in-progress', 'pending'];
2479 This simple code will create the following:
2481 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2482 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2484 A field associated to an empty arrayref will be considered a
2485 logical false and will generate 0=1.
2487 =head2 Tests for NULL values
2489 If the value part is C<undef> then this is converted to SQL <IS NULL>
2498 $stmt = "WHERE user = ? AND status IS NULL";
2501 To test if a column IS NOT NULL:
2505 status => { '!=', undef },
2508 =head2 Specific comparison operators
2510 If you want to specify a different type of operator for your comparison,
2511 you can use a hashref for a given column:
2515 status => { '!=', 'completed' }
2518 Which would generate:
2520 $stmt = "WHERE user = ? AND status != ?";
2521 @bind = ('nwiger', 'completed');
2523 To test against multiple values, just enclose the values in an arrayref:
2525 status => { '=', ['assigned', 'in-progress', 'pending'] };
2527 Which would give you:
2529 "WHERE status = ? OR status = ? OR status = ?"
2532 The hashref can also contain multiple pairs, in which case it is expanded
2533 into an C<AND> of its elements:
2537 status => { '!=', 'completed', -not_like => 'pending%' }
2540 # Or more dynamically, like from a form
2541 $where{user} = 'nwiger';
2542 $where{status}{'!='} = 'completed';
2543 $where{status}{'-not_like'} = 'pending%';
2545 # Both generate this
2546 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2547 @bind = ('nwiger', 'completed', 'pending%');
2550 To get an OR instead, you can combine it with the arrayref idea:
2554 priority => [ { '=', 2 }, { '>', 5 } ]
2557 Which would generate:
2559 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2560 @bind = ('2', '5', 'nwiger');
2562 If you want to include literal SQL (with or without bind values), just use a
2563 scalar reference or reference to an arrayref as the value:
2566 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2567 date_expires => { '<' => \"now()" }
2570 Which would generate:
2572 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2573 @bind = ('11/26/2008');
2576 =head2 Logic and nesting operators
2578 In the example above,
2579 there is a subtle trap if you want to say something like
2580 this (notice the C<AND>):
2582 WHERE priority != ? AND priority != ?
2584 Because, in Perl you I<can't> do this:
2586 priority => { '!=' => 2, '!=' => 1 }
2588 As the second C<!=> key will obliterate the first. The solution
2589 is to use the special C<-modifier> form inside an arrayref:
2591 priority => [ -and => {'!=', 2},
2595 Normally, these would be joined by C<OR>, but the modifier tells it
2596 to use C<AND> instead. (Hint: You can use this in conjunction with the
2597 C<logic> option to C<new()> in order to change the way your queries
2598 work by default.) B<Important:> Note that the C<-modifier> goes
2599 B<INSIDE> the arrayref, as an extra first element. This will
2600 B<NOT> do what you think it might:
2602 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2604 Here is a quick list of equivalencies, since there is some overlap:
2607 status => {'!=', 'completed', 'not like', 'pending%' }
2608 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2611 status => {'=', ['assigned', 'in-progress']}
2612 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2613 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2617 =head2 Special operators: IN, BETWEEN, etc.
2619 You can also use the hashref format to compare a list of fields using the
2620 C<IN> comparison operator, by specifying the list as an arrayref:
2623 status => 'completed',
2624 reportid => { -in => [567, 2335, 2] }
2627 Which would generate:
2629 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2630 @bind = ('completed', '567', '2335', '2');
2632 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2635 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2636 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2637 'sqltrue' (by default: C<1=1>).
2639 In addition to the array you can supply a chunk of literal sql or
2640 literal sql with bind:
2643 customer => { -in => \[
2644 'SELECT cust_id FROM cust WHERE balance > ?',
2647 status => { -in => \'SELECT status_codes FROM states' },
2653 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2654 AND status IN ( SELECT status_codes FROM states )
2658 Finally, if the argument to C<-in> is not a reference, it will be
2659 treated as a single-element array.
2661 Another pair of operators is C<-between> and C<-not_between>,
2662 used with an arrayref of two values:
2666 completion_date => {
2667 -not_between => ['2002-10-01', '2003-02-06']
2673 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2675 Just like with C<-in> all plausible combinations of literal SQL
2679 start0 => { -between => [ 1, 2 ] },
2680 start1 => { -between => \["? AND ?", 1, 2] },
2681 start2 => { -between => \"lower(x) AND upper(y)" },
2682 start3 => { -between => [
2684 \["upper(?)", 'stuff' ],
2691 ( start0 BETWEEN ? AND ? )
2692 AND ( start1 BETWEEN ? AND ? )
2693 AND ( start2 BETWEEN lower(x) AND upper(y) )
2694 AND ( start3 BETWEEN lower(x) AND upper(?) )
2696 @bind = (1, 2, 1, 2, 'stuff');
2699 These are the two builtin "special operators"; but the
2700 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2702 =head2 Unary operators: bool
2704 If you wish to test against boolean columns or functions within your
2705 database you can use the C<-bool> and C<-not_bool> operators. For
2706 example to test the column C<is_user> being true and the column
2707 C<is_enabled> being false you would use:-
2711 -not_bool => 'is_enabled',
2716 WHERE is_user AND NOT is_enabled
2718 If a more complex combination is required, testing more conditions,
2719 then you should use the and/or operators:-
2724 -not_bool => { two=> { -rlike => 'bar' } },
2725 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2736 (NOT ( three = ? OR three > ? ))
2739 =head2 Nested conditions, -and/-or prefixes
2741 So far, we've seen how multiple conditions are joined with a top-level
2742 C<AND>. We can change this by putting the different conditions we want in
2743 hashes and then putting those hashes in an array. For example:
2748 status => { -like => ['pending%', 'dispatched'] },
2752 status => 'unassigned',
2756 This data structure would create the following:
2758 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2759 OR ( user = ? AND status = ? ) )";
2760 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2763 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2764 to change the logic inside:
2770 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2771 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2778 $stmt = "WHERE ( user = ?
2779 AND ( ( workhrs > ? AND geo = ? )
2780 OR ( workhrs < ? OR geo = ? ) ) )";
2781 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2783 =head3 Algebraic inconsistency, for historical reasons
2785 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2786 operator goes C<outside> of the nested structure; whereas when connecting
2787 several constraints on one column, the C<-and> operator goes
2788 C<inside> the arrayref. Here is an example combining both features:
2791 -and => [a => 1, b => 2],
2792 -or => [c => 3, d => 4],
2793 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2798 WHERE ( ( ( a = ? AND b = ? )
2799 OR ( c = ? OR d = ? )
2800 OR ( e LIKE ? AND e LIKE ? ) ) )
2802 This difference in syntax is unfortunate but must be preserved for
2803 historical reasons. So be careful: the two examples below would
2804 seem algebraically equivalent, but they are not
2807 { -like => 'foo%' },
2808 { -like => '%bar' },
2810 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2813 { col => { -like => 'foo%' } },
2814 { col => { -like => '%bar' } },
2816 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2819 =head2 Literal SQL and value type operators
2821 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2822 side" is a column name and the "right side" is a value (normally rendered as
2823 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2824 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2825 alter this behavior. There are several ways of doing so.
2829 This is a virtual operator that signals the string to its right side is an
2830 identifier (a column name) and not a value. For example to compare two
2831 columns you would write:
2834 priority => { '<', 2 },
2835 requestor => { -ident => 'submitter' },
2840 $stmt = "WHERE priority < ? AND requestor = submitter";
2843 If you are maintaining legacy code you may see a different construct as
2844 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2849 This is a virtual operator that signals that the construct to its right side
2850 is a value to be passed to DBI. This is for example necessary when you want
2851 to write a where clause against an array (for RDBMS that support such
2852 datatypes). For example:
2855 array => { -value => [1, 2, 3] }
2860 $stmt = 'WHERE array = ?';
2861 @bind = ([1, 2, 3]);
2863 Note that if you were to simply say:
2869 the result would probably not be what you wanted:
2871 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2876 Finally, sometimes only literal SQL will do. To include a random snippet
2877 of SQL verbatim, you specify it as a scalar reference. Consider this only
2878 as a last resort. Usually there is a better way. For example:
2881 priority => { '<', 2 },
2882 requestor => { -in => \'(SELECT name FROM hitmen)' },
2887 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2890 Note that in this example, you only get one bind parameter back, since
2891 the verbatim SQL is passed as part of the statement.
2895 Never use untrusted input as a literal SQL argument - this is a massive
2896 security risk (there is no way to check literal snippets for SQL
2897 injections and other nastyness). If you need to deal with untrusted input
2898 use literal SQL with placeholders as described next.
2900 =head3 Literal SQL with placeholders and bind values (subqueries)
2902 If the literal SQL to be inserted has placeholders and bind values,
2903 use a reference to an arrayref (yes this is a double reference --
2904 not so common, but perfectly legal Perl). For example, to find a date
2905 in Postgres you can use something like this:
2908 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2913 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2916 Note that you must pass the bind values in the same format as they are returned
2917 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2918 to C<columns>, you must provide the bind values in the
2919 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2920 scalar value; most commonly the column name, but you can use any scalar value
2921 (including references and blessed references), L<SQL::Abstract> will simply
2922 pass it through intact. So if C<bindtype> is set to C<columns> the above
2923 example will look like:
2926 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2929 Literal SQL is especially useful for nesting parenthesized clauses in the
2930 main SQL query. Here is a first example:
2932 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2936 bar => \["IN ($sub_stmt)" => @sub_bind],
2941 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2942 WHERE c2 < ? AND c3 LIKE ?))";
2943 @bind = (1234, 100, "foo%");
2945 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2946 are expressed in the same way. Of course the C<$sub_stmt> and
2947 its associated bind values can be generated through a former call
2950 my ($sub_stmt, @sub_bind)
2951 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2952 c3 => {-like => "foo%"}});
2955 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2958 In the examples above, the subquery was used as an operator on a column;
2959 but the same principle also applies for a clause within the main C<%where>
2960 hash, like an EXISTS subquery:
2962 my ($sub_stmt, @sub_bind)
2963 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2964 my %where = ( -and => [
2966 \["EXISTS ($sub_stmt)" => @sub_bind],
2971 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2972 WHERE c1 = ? AND c2 > t0.c0))";
2976 Observe that the condition on C<c2> in the subquery refers to
2977 column C<t0.c0> of the main query: this is I<not> a bind
2978 value, so we have to express it through a scalar ref.
2979 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2980 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2981 what we wanted here.
2983 Finally, here is an example where a subquery is used
2984 for expressing unary negation:
2986 my ($sub_stmt, @sub_bind)
2987 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2988 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2990 lname => {like => '%son%'},
2991 \["NOT ($sub_stmt)" => @sub_bind],
2996 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2997 @bind = ('%son%', 10, 20)
2999 =head3 Deprecated usage of Literal SQL
3001 Below are some examples of archaic use of literal SQL. It is shown only as
3002 reference for those who deal with legacy code. Each example has a much
3003 better, cleaner and safer alternative that users should opt for in new code.
3009 my %where = ( requestor => \'IS NOT NULL' )
3011 $stmt = "WHERE requestor IS NOT NULL"
3013 This used to be the way of generating NULL comparisons, before the handling
3014 of C<undef> got formalized. For new code please use the superior syntax as
3015 described in L</Tests for NULL values>.
3019 my %where = ( requestor => \'= submitter' )
3021 $stmt = "WHERE requestor = submitter"
3023 This used to be the only way to compare columns. Use the superior L</-ident>
3024 method for all new code. For example an identifier declared in such a way
3025 will be properly quoted if L</quote_char> is properly set, while the legacy
3026 form will remain as supplied.
3030 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3032 $stmt = "WHERE completed > ? AND is_ready"
3033 @bind = ('2012-12-21')
3035 Using an empty string literal used to be the only way to express a boolean.
3036 For all new code please use the much more readable
3037 L<-bool|/Unary operators: bool> operator.
3043 These pages could go on for a while, since the nesting of the data
3044 structures this module can handle are pretty much unlimited (the
3045 module implements the C<WHERE> expansion as a recursive function
3046 internally). Your best bet is to "play around" with the module a
3047 little to see how the data structures behave, and choose the best
3048 format for your data based on that.
3050 And of course, all the values above will probably be replaced with
3051 variables gotten from forms or the command line. After all, if you
3052 knew everything ahead of time, you wouldn't have to worry about
3053 dynamically-generating SQL and could just hardwire it into your
3056 =head1 ORDER BY CLAUSES
3058 Some functions take an order by clause. This can either be a scalar (just a
3059 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3060 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3063 Given | Will Generate
3064 ---------------------------------------------------------------
3066 'colA' | ORDER BY colA
3068 [qw/colA colB/] | ORDER BY colA, colB
3070 {-asc => 'colA'} | ORDER BY colA ASC
3072 {-desc => 'colB'} | ORDER BY colB DESC
3074 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3076 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3078 \'colA DESC' | ORDER BY colA DESC
3080 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3081 | /* ...with $x bound to ? */
3084 { -asc => 'colA' }, | colA ASC,
3085 { -desc => [qw/colB/] }, | colB DESC,
3086 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3087 \'colE DESC', | colE DESC,
3088 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3089 ] | /* ...with $x bound to ? */
3090 ===============================================================
3094 =head1 SPECIAL OPERATORS
3096 my $sqlmaker = SQL::Abstract->new(special_ops => [
3100 my ($self, $field, $op, $arg) = @_;
3106 handler => 'method_name',
3110 A "special operator" is a SQL syntactic clause that can be
3111 applied to a field, instead of a usual binary operator.
3114 WHERE field IN (?, ?, ?)
3115 WHERE field BETWEEN ? AND ?
3116 WHERE MATCH(field) AGAINST (?, ?)
3118 Special operators IN and BETWEEN are fairly standard and therefore
3119 are builtin within C<SQL::Abstract> (as the overridable methods
3120 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3121 like the MATCH .. AGAINST example above which is specific to MySQL,
3122 you can write your own operator handlers - supply a C<special_ops>
3123 argument to the C<new> method. That argument takes an arrayref of
3124 operator definitions; each operator definition is a hashref with two
3131 the regular expression to match the operator
3135 Either a coderef or a plain scalar method name. In both cases
3136 the expected return is C<< ($sql, @bind) >>.
3138 When supplied with a method name, it is simply called on the
3139 L<SQL::Abstract> object as:
3141 $self->$method_name($field, $op, $arg)
3145 $field is the LHS of the operator
3146 $op is the part that matched the handler regex
3149 When supplied with a coderef, it is called as:
3151 $coderef->($self, $field, $op, $arg)
3156 For example, here is an implementation
3157 of the MATCH .. AGAINST syntax for MySQL
3159 my $sqlmaker = SQL::Abstract->new(special_ops => [
3161 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3162 {regex => qr/^match$/i,
3164 my ($self, $field, $op, $arg) = @_;
3165 $arg = [$arg] if not ref $arg;
3166 my $label = $self->_quote($field);
3167 my ($placeholder) = $self->_convert('?');
3168 my $placeholders = join ", ", (($placeholder) x @$arg);
3169 my $sql = $self->_sqlcase('match') . " ($label) "
3170 . $self->_sqlcase('against') . " ($placeholders) ";
3171 my @bind = $self->_bindtype($field, @$arg);
3172 return ($sql, @bind);
3179 =head1 UNARY OPERATORS
3181 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3185 my ($self, $op, $arg) = @_;
3191 handler => 'method_name',
3195 A "unary operator" is a SQL syntactic clause that can be
3196 applied to a field - the operator goes before the field
3198 You can write your own operator handlers - supply a C<unary_ops>
3199 argument to the C<new> method. That argument takes an arrayref of
3200 operator definitions; each operator definition is a hashref with two
3207 the regular expression to match the operator
3211 Either a coderef or a plain scalar method name. In both cases
3212 the expected return is C<< $sql >>.
3214 When supplied with a method name, it is simply called on the
3215 L<SQL::Abstract> object as:
3217 $self->$method_name($op, $arg)
3221 $op is the part that matched the handler regex
3222 $arg is the RHS or argument of the operator
3224 When supplied with a coderef, it is called as:
3226 $coderef->($self, $op, $arg)
3234 Thanks to some benchmarking by Mark Stosberg, it turns out that
3235 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3236 I must admit this wasn't an intentional design issue, but it's a
3237 byproduct of the fact that you get to control your C<DBI> handles
3240 To maximize performance, use a code snippet like the following:
3242 # prepare a statement handle using the first row
3243 # and then reuse it for the rest of the rows
3245 for my $href (@array_of_hashrefs) {
3246 $stmt ||= $sql->insert('table', $href);
3247 $sth ||= $dbh->prepare($stmt);
3248 $sth->execute($sql->values($href));
3251 The reason this works is because the keys in your C<$href> are sorted
3252 internally by B<SQL::Abstract>. Thus, as long as your data retains
3253 the same structure, you only have to generate the SQL the first time
3254 around. On subsequent queries, simply use the C<values> function provided
3255 by this module to return your values in the correct order.
3257 However this depends on the values having the same type - if, for
3258 example, the values of a where clause may either have values
3259 (resulting in sql of the form C<column = ?> with a single bind
3260 value), or alternatively the values might be C<undef> (resulting in
3261 sql of the form C<column IS NULL> with no bind value) then the
3262 caching technique suggested will not work.
3266 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3267 really like this part (I do, at least). Building up a complex query
3268 can be as simple as the following:
3275 use CGI::FormBuilder;
3278 my $form = CGI::FormBuilder->new(...);
3279 my $sql = SQL::Abstract->new;
3281 if ($form->submitted) {
3282 my $field = $form->field;
3283 my $id = delete $field->{id};
3284 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3287 Of course, you would still have to connect using C<DBI> to run the
3288 query, but the point is that if you make your form look like your
3289 table, the actual query script can be extremely simplistic.
3291 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3292 a fast interface to returning and formatting data. I frequently
3293 use these three modules together to write complex database query
3294 apps in under 50 lines.
3296 =head1 HOW TO CONTRIBUTE
3298 Contributions are always welcome, in all usable forms (we especially
3299 welcome documentation improvements). The delivery methods include git-
3300 or unified-diff formatted patches, GitHub pull requests, or plain bug
3301 reports either via RT or the Mailing list. Contributors are generally
3302 granted full access to the official repository after their first several
3303 patches pass successful review.
3305 This project is maintained in a git repository. The code and related tools are
3306 accessible at the following locations:
3310 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3312 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3314 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3316 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3322 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3323 Great care has been taken to preserve the I<published> behavior
3324 documented in previous versions in the 1.* family; however,
3325 some features that were previously undocumented, or behaved
3326 differently from the documentation, had to be changed in order
3327 to clarify the semantics. Hence, client code that was relying
3328 on some dark areas of C<SQL::Abstract> v1.*
3329 B<might behave differently> in v1.50.
3331 The main changes are:
3337 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3341 support for the { operator => \"..." } construct (to embed literal SQL)
3345 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3349 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3353 defensive programming: check arguments
3357 fixed bug with global logic, which was previously implemented
3358 through global variables yielding side-effects. Prior versions would
3359 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3360 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3361 Now this is interpreted
3362 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3367 fixed semantics of _bindtype on array args
3371 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3372 we just avoid shifting arrays within that tree.
3376 dropped the C<_modlogic> function
3380 =head1 ACKNOWLEDGEMENTS
3382 There are a number of individuals that have really helped out with
3383 this module. Unfortunately, most of them submitted bugs via CPAN
3384 so I have no idea who they are! But the people I do know are:
3386 Ash Berlin (order_by hash term support)
3387 Matt Trout (DBIx::Class support)
3388 Mark Stosberg (benchmarking)
3389 Chas Owens (initial "IN" operator support)
3390 Philip Collins (per-field SQL functions)
3391 Eric Kolve (hashref "AND" support)
3392 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3393 Dan Kubb (support for "quote_char" and "name_sep")
3394 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3395 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3396 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3397 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3398 Oliver Charles (support for "RETURNING" after "INSERT")
3404 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3408 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3410 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3412 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3413 While not an official support venue, C<DBIx::Class> makes heavy use of
3414 C<SQL::Abstract>, and as such list members there are very familiar with
3415 how to create queries.
3419 This module is free software; you may copy this under the same
3420 terms as perl itself (either the GNU General Public License or
3421 the Artistic License)