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.87';
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 => sub { die "NOPE" }},
41 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
43 {regex => qr/^ ident $/ix, handler => sub { die "NOPE" }},
44 {regex => qr/^ value $/ix, handler => sub { die "NOPE" }},
47 #======================================================================
48 # DEBUGGING AND ERROR REPORTING
49 #======================================================================
52 return unless $_[0]->{debug}; shift; # a little faster
53 my $func = (caller(1))[3];
54 warn "[$func] ", @_, "\n";
58 my($func) = (caller(1))[3];
59 Carp::carp "[$func] Warning: ", @_;
63 my($func) = (caller(1))[3];
64 Carp::croak "[$func] Fatal: ", @_;
67 sub is_literal_value ($) {
68 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
69 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
73 sub is_undef_value ($) {
77 and exists $_[0]->{-value}
78 and not defined $_[0]->{-value}
82 # FIXME XSify - this can be done so much more efficiently
83 sub is_plain_value ($) {
85 ! length ref $_[0] ? \($_[0])
87 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
89 exists $_[0]->{-value}
90 ) ? \($_[0]->{-value})
92 # reuse @_ for even moar speedz
93 defined ( $_[1] = Scalar::Util::blessed $_[0] )
95 # deliberately not using Devel::OverloadInfo - the checks we are
96 # intersted in are much more limited than the fullblown thing, and
97 # this is a very hot piece of code
99 # simply using ->can('(""') can leave behind stub methods that
100 # break actually using the overload later (see L<perldiag/Stub
101 # found while resolving method "%s" overloading "%s" in package
102 # "%s"> and the source of overload::mycan())
104 # either has stringification which DBI SHOULD prefer out of the box
105 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
107 # has nummification or boolification, AND fallback is *not* disabled
109 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
112 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
114 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
118 # no fallback specified at all
119 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
121 # fallback explicitly undef
122 ! defined ${"$_[3]::()"}
135 #======================================================================
137 #======================================================================
141 my $class = ref($self) || $self;
142 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
144 # choose our case by keeping an option around
145 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
147 # default logic for interpreting arrayrefs
148 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
150 # how to return bind vars
151 $opt{bindtype} ||= 'normal';
153 # default comparison is "=", but can be overridden
156 # try to recognize which are the 'equality' and 'inequality' ops
157 # (temporary quickfix (in 2007), should go through a more seasoned API)
158 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
159 $opt{inequality_op} = qr/^( != | <> )$/ix;
161 $opt{like_op} = qr/^ (is_)?r?like $/xi;
162 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
165 $opt{sqltrue} ||= '1=1';
166 $opt{sqlfalse} ||= '0=1';
169 $opt{special_ops} ||= [];
171 # regexes are applied in order, thus push after user-defines
172 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
174 if ($class->isa('DBIx::Class::SQLMaker')) {
175 $opt{is_dbic_sqlmaker} = 1;
176 $opt{disable_old_special_ops} = 1;
180 $opt{unary_ops} ||= [];
182 # rudimentary sanity-check for user supplied bits treated as functions/operators
183 # If a purported function matches this regular expression, an exception is thrown.
184 # Literal SQL is *NOT* subject to this check, only functions (and column names
185 # when quoting is not in effect)
188 # need to guard against ()'s in column names too, but this will break tons of
189 # hacks... ideas anyone?
190 $opt{injection_guard} ||= qr/
196 $opt{expand_unary} = {};
199 -not => '_expand_not',
200 -bool => '_expand_bool',
201 -and => '_expand_op_andor',
202 -or => '_expand_op_andor',
203 -nest => '_expand_nest',
204 -bind => sub { shift; +{ @_ } },
206 -not_in => '_expand_in',
208 my ($self, $node, $args) = @_;
209 +{ $node => [ map $self->expand_expr($_), @$args ] };
211 -between => '_expand_between',
212 -not_between => '_expand_between',
214 my ($self, $node, $args) = @_;
215 my ($op, @opargs) = @$args;
216 +{ $node => [ $op, map $self->expand_expr($_), @opargs ] };
218 (map +($_ => '_expand_op_is'), ('-is', '-is_not')),
219 -ident => '_expand_ident',
220 -value => '_expand_value',
224 'between' => '_expand_between',
225 'not_between' => '_expand_between',
226 'in' => '_expand_in',
227 'not_in' => '_expand_in',
228 'nest' => '_expand_nest',
229 (map +($_ => '_expand_op_andor'), ('and', 'or')),
230 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
231 'ident' => '_expand_ident',
232 'value' => '_expand_value',
236 (map +("-$_", "_render_$_"), qw(op func bind ident literal row)),
241 (map +($_ => '_render_op_between'), 'between', 'not_between'),
242 (map +($_ => '_render_op_in'), 'in', 'not_in'),
243 (map +($_ => '_render_unop_postfix'),
244 'is_null', 'is_not_null', 'asc', 'desc',
246 (not => '_render_op_not'),
247 (map +($_ => '_render_op_andor'), qw(and or)),
248 ',' => '_render_op_multop',
251 return bless \%opt, $class;
254 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
255 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
257 sub _assert_pass_injection_guard {
258 if ($_[1] =~ $_[0]->{injection_guard}) {
259 my $class = ref $_[0];
260 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
261 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
262 . "{injection_guard} attribute to ${class}->new()"
267 #======================================================================
269 #======================================================================
273 my $table = $self->_table(shift);
274 my $data = shift || return;
277 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
278 my ($sql, @bind) = $self->$method($data);
279 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
281 if ($options->{returning}) {
282 my ($s, @b) = $self->_insert_returning($options);
287 return wantarray ? ($sql, @bind) : $sql;
290 # So that subclasses can override INSERT ... RETURNING separately from
291 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
292 sub _insert_returning { shift->_returning(@_) }
295 my ($self, $options) = @_;
297 my $f = $options->{returning};
299 my ($sql, @bind) = $self->render_aqt(
300 $self->_expand_maybe_list_expr($f, -ident)
303 ? $self->_sqlcase(' returning ') . $sql
304 : ($self->_sqlcase(' returning ').$sql, @bind);
307 sub _insert_HASHREF { # explicit list of fields and then values
308 my ($self, $data) = @_;
310 my @fields = sort keys %$data;
312 my ($sql, @bind) = $self->_insert_values($data);
315 $_ = $self->_quote($_) foreach @fields;
316 $sql = "( ".join(", ", @fields).") ".$sql;
318 return ($sql, @bind);
321 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
322 my ($self, $data) = @_;
324 # no names (arrayref) so can't generate bindtype
325 $self->{bindtype} ne 'columns'
326 or belch "can't do 'columns' bindtype when called with arrayref";
328 my (@values, @all_bind);
329 foreach my $value (@$data) {
330 my ($values, @bind) = $self->_insert_value(undef, $value);
331 push @values, $values;
332 push @all_bind, @bind;
334 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
335 return ($sql, @all_bind);
338 sub _insert_ARRAYREFREF { # literal SQL with bind
339 my ($self, $data) = @_;
341 my ($sql, @bind) = @${$data};
342 $self->_assert_bindval_matches_bindtype(@bind);
344 return ($sql, @bind);
348 sub _insert_SCALARREF { # literal SQL without bind
349 my ($self, $data) = @_;
355 my ($self, $data) = @_;
357 my (@values, @all_bind);
358 foreach my $column (sort keys %$data) {
359 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
360 push @values, $values;
361 push @all_bind, @bind;
363 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
364 return ($sql, @all_bind);
368 my ($self, $column, $v) = @_;
370 return $self->render_aqt(
371 $self->_expand_insert_value($column, $v)
375 sub _expand_insert_value {
376 my ($self, $column, $v) = @_;
378 if (ref($v) eq 'ARRAY') {
379 if ($self->{array_datatypes}) {
380 return +{ -bind => [ $column, $v ] };
382 my ($sql, @bind) = @$v;
383 $self->_assert_bindval_matches_bindtype(@bind);
384 return +{ -literal => $v };
386 if (ref($v) eq 'HASH') {
387 if (grep !/^-/, keys %$v) {
388 belch "HASH ref as bind value in insert is not supported";
389 return +{ -bind => [ $column, $v ] };
393 return +{ -bind => [ $column, undef ] };
395 local our $Cur_Col_Meta = $column;
396 return $self->expand_expr($v);
401 #======================================================================
403 #======================================================================
408 my $table = $self->_table(shift);
409 my $data = shift || return;
413 # first build the 'SET' part of the sql statement
414 puke "Unsupported data type specified to \$sql->update"
415 unless ref $data eq 'HASH';
417 my ($sql, @all_bind) = $self->_update_set_values($data);
418 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
422 my($where_sql, @where_bind) = $self->where($where);
424 push @all_bind, @where_bind;
427 if ($options->{returning}) {
428 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
429 $sql .= $returning_sql;
430 push @all_bind, @returning_bind;
433 return wantarray ? ($sql, @all_bind) : $sql;
436 sub _update_set_values {
437 my ($self, $data) = @_;
439 return $self->render_aqt(
440 $self->_expand_update_set_values($data),
444 sub _expand_update_set_values {
445 my ($self, $data) = @_;
446 $self->_expand_maybe_list_expr( [
449 $set = { -bind => $_ } unless defined $set;
450 +{ -op => [ '=', $self->_expand_ident(-ident => $k), $set ] };
456 ? ($self->{array_datatypes}
457 ? [ $k, +{ -bind => [ $k, $v ] } ]
458 : [ $k, +{ -literal => $v } ])
460 local our $Cur_Col_Meta = $k;
461 [ $k, $self->_expand_expr($v) ]
468 # So that subclasses can override UPDATE ... RETURNING separately from
470 sub _update_returning { shift->_returning(@_) }
474 #======================================================================
476 #======================================================================
481 my $table = $self->_table(shift);
482 my $fields = shift || '*';
486 my ($fields_sql, @bind) = $self->_select_fields($fields);
488 my ($where_sql, @where_bind) = $self->where($where, $order);
489 push @bind, @where_bind;
491 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
492 $self->_sqlcase('from'), $table)
495 return wantarray ? ($sql, @bind) : $sql;
499 my ($self, $fields) = @_;
500 return $fields unless ref($fields);
501 return $self->render_aqt(
502 $self->_expand_maybe_list_expr($fields, '-ident')
506 #======================================================================
508 #======================================================================
513 my $table = $self->_table(shift);
517 my($where_sql, @bind) = $self->where($where);
518 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
520 if ($options->{returning}) {
521 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
522 $sql .= $returning_sql;
523 push @bind, @returning_bind;
526 return wantarray ? ($sql, @bind) : $sql;
529 # So that subclasses can override DELETE ... RETURNING separately from
531 sub _delete_returning { shift->_returning(@_) }
535 #======================================================================
537 #======================================================================
541 # Finally, a separate routine just to handle WHERE clauses
543 my ($self, $where, $order) = @_;
545 local $self->{convert_where} = $self->{convert};
548 my ($sql, @bind) = defined($where)
549 ? $self->_recurse_where($where)
551 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
555 my ($order_sql, @order_bind) = $self->_order_by($order);
557 push @bind, @order_bind;
560 return wantarray ? ($sql, @bind) : $sql;
563 { our $Default_Scalar_To = -value }
566 my ($self, $expr, $default_scalar_to) = @_;
567 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
568 $self->_expand_expr($expr);
572 my ($self, $aqt) = @_;
573 my ($k, $v, @rest) = %$aqt;
575 if (my $meth = $self->{render}{$k}) {
576 return $self->$meth($v);
578 die "notreached: $k";
582 my ($self, $expr) = @_;
583 $self->render_aqt($self->expand_expr($expr));
587 my ($self, $raw) = @_;
588 s/^-(?=.)//, s/\s+/_/g for my $op = lc $raw;
593 my ($self, $expr) = @_;
594 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
595 return undef unless defined($expr);
596 if (ref($expr) eq 'HASH') {
597 return undef unless my $kc = keys %$expr;
599 return $self->_expand_op_andor(-and => $expr);
601 my ($key, $value) = %$expr;
602 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
603 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
604 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
606 if (my $exp = $self->{expand}{$key}) {
607 return $self->$exp($key, $value);
609 return $self->_expand_expr_hashpair($key, $value);
611 if (ref($expr) eq 'ARRAY') {
612 my $logic = '-'.lc($self->{logic});
613 return $self->_expand_op_andor($logic, $expr);
615 if (my $literal = is_literal_value($expr)) {
616 return +{ -literal => $literal };
618 if (!ref($expr) or Scalar::Util::blessed($expr)) {
619 return $self->_expand_expr_scalar($expr);
624 sub _expand_expr_hashpair {
625 my ($self, $k, $v) = @_;
626 unless (defined($k) and length($k)) {
627 if (defined($k) and my $literal = is_literal_value($v)) {
628 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
629 return { -literal => $literal };
631 puke "Supplying an empty left hand side argument is not supported";
634 return $self->_expand_expr_hashpair_op($k, $v);
636 return $self->_expand_expr_hashpair_ident($k, $v);
639 sub _expand_expr_hashpair_ident {
640 my ($self, $k, $v) = @_;
642 local our $Cur_Col_Meta = $k;
644 # hash with multiple or no elements is andor
646 if (ref($v) eq 'HASH' and keys %$v != 1) {
647 return $self->_expand_op_andor(-and => $v, $k);
650 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
652 if (is_undef_value($v)) {
653 return $self->_expand_expr_hashpair_cmp($k => undef);
656 # scalars and objects get expanded as whatever requested or values
658 if (!ref($v) or Scalar::Util::blessed($v)) {
659 return $self->_expand_expr_hashpair_scalar($k, $v);
662 # single key hashref is a hashtriple
664 if (ref($v) eq 'HASH') {
665 return $self->_expand_expr_hashtriple($k, %$v);
668 # arrayref needs re-engineering over the elements
670 if (ref($v) eq 'ARRAY') {
671 return $self->sqlfalse unless @$v;
672 $self->_debug("ARRAY($k) means distribute over elements");
674 $v->[0] =~ /^-(and|or)$/i
675 ? shift(@{$v = [ @$v ]})
676 : '-'.lc($self->{logic} || 'OR')
678 return $self->_expand_op_andor(
683 if (my $literal = is_literal_value($v)) {
685 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
688 my ($sql, @bind) = @$literal;
689 if ($self->{bindtype} eq 'columns') {
691 $self->_assert_bindval_matches_bindtype($_);
694 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
699 sub _expand_expr_scalar {
700 my ($self, $expr) = @_;
702 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
705 sub _expand_expr_hashpair_scalar {
706 my ($self, $k, $v) = @_;
708 return $self->_expand_expr_hashpair_cmp(
709 $k, $self->_expand_expr_scalar($v),
713 sub _expand_expr_hashpair_op {
714 my ($self, $k, $v) = @_;
716 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
718 my $op = $self->_normalize_op($k);
720 # Ops prefixed with -not_ get converted
722 if (my ($rest) = $op =~/^not_(.*)$/) {
725 $self->_expand_expr({ "-${rest}", $v })
731 my $op = join(' ', split '_', $op);
733 # the old special op system requires illegality for top-level use
736 (our $Expand_Depth) == 1
737 and $self->{disable_old_special_ops}
738 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
740 puke "Illegal use of top-level '-$op'"
743 # the old unary op system means we should touch nothing and let it work
745 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
746 return { -op => [ $op, $v ] };
750 # an explicit node type is currently assumed to be expanded (this is almost
751 # certainly wrong and there should be expansion anyway)
753 if ($self->{render}{$k}) {
757 # hashref RHS values get expanded and used as op/func args
762 and (keys %$v)[0] =~ /^-/
764 my ($func) = $k =~ /^-(.*)$/;
766 if (List::Util::first { $func =~ $_->{regex} } @{$self->{special_ops}}) {
767 return +{ -op => [ $func, $self->_expand_expr($v) ] };
770 return +{ -func => [ $func, $self->_expand_expr($v) ] };
773 # scalars and literals get simply expanded
775 if (!ref($v) or is_literal_value($v)) {
776 return +{ -op => [ $op, $self->_expand_expr($v) ] };
782 sub _expand_expr_hashpair_cmp {
783 my ($self, $k, $v) = @_;
784 $self->_expand_expr_hashtriple($k, $self->{cmp}, $v);
787 sub _expand_expr_hashtriple {
788 my ($self, $k, $vk, $vv) = @_;
790 my $ik = $self->_expand_ident(-ident => $k);
792 my $op = $self->_normalize_op($vk);
793 $self->_assert_pass_injection_guard($op);
795 if ($op =~ s/ _? \d+ $//x ) {
796 return $self->_expand_expr($k, { $vk, $vv });
798 if (my $x = $self->{expand_op}{$op}) {
799 local our $Cur_Col_Meta = $k;
800 return $self->$x($op, $vv, $k);
804 my $op = join(' ', split '_', $op);
806 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
807 return { -op => [ $op, $ik, $vv ] };
809 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
813 { -op => [ $op, $vv ] }
817 if (ref($vv) eq 'ARRAY') {
819 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
820 ? shift @raw : '-or';
821 my @values = map +{ $vk => $_ }, @raw;
823 $op =~ $self->{inequality_op}
824 or $op =~ $self->{not_like_op}
826 if (lc($logic) eq '-or' and @values > 1) {
827 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
828 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
829 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
834 # try to DWIM on equality operators
835 return ($self->_dwim_op_to_is($op,
836 "Supplying an empty arrayref to '%s' is deprecated",
837 "operator '%s' applied on an empty array (field '$k')"
838 ) ? $self->sqlfalse : $self->sqltrue);
840 return $self->_expand_op_andor($logic => \@values, $k);
842 if (is_undef_value($vv)) {
843 my $is = ($self->_dwim_op_to_is($op,
844 "Supplying an undefined argument to '%s' is deprecated",
845 "unexpected operator '%s' with undef operand",
846 ) ? 'is' : 'is not');
848 return $self->_expand_expr_hashpair($k => { $is, undef });
850 local our $Cur_Col_Meta = $k;
854 $self->_expand_expr($vv)
859 my ($self, $raw, $empty, $fail) = @_;
861 my $op = $self->_normalize_op($raw);
863 if ($op =~ /^not$/i) {
866 if ($op =~ $self->{equality_op}) {
869 if ($op =~ $self->{like_op}) {
870 belch(sprintf $empty, uc(join ' ', split '_', $op));
873 if ($op =~ $self->{inequality_op}) {
876 if ($op =~ $self->{not_like_op}) {
877 belch(sprintf $empty, uc(join ' ', split '_', $op));
880 puke(sprintf $fail, $op);
884 my ($self, $op, $body, $k) = @_;
885 return $self->_expand_expr_hashpair_cmp(
886 $k, { -ident => $body }
888 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
889 puke "$op requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
891 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
892 ref($body) ? @$body : $body;
893 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
894 unless ($self->{quote_char}) {
895 $self->_assert_pass_injection_guard($_) for @parts;
897 return +{ -ident => \@parts };
901 return $_[0]->_expand_expr_hashpair_cmp(
902 $_[3], { -value => $_[2] },
904 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
908 +{ -op => [ 'not', $_[0]->_expand_expr($_[2]) ] };
912 my ($self, undef, $v) = @_;
914 return $self->_expand_expr($v);
916 puke "-bool => undef not supported" unless defined($v);
917 return $self->_expand_ident(-ident => $v);
920 sub _expand_op_andor {
921 my ($self, $logic, $v, $k) = @_;
923 $v = [ map +{ $k, $_ },
925 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
929 my ($logop) = $logic =~ /^-?(.*)$/;
930 if (ref($v) eq 'HASH') {
931 return undef unless keys %$v;
934 map $self->_expand_expr({ $_ => $v->{$_} }),
938 if (ref($v) eq 'ARRAY') {
939 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
942 (ref($_) eq 'ARRAY' and @$_)
943 or (ref($_) eq 'HASH' and %$_)
949 while (my ($el) = splice @expr, 0, 1) {
950 puke "Supplying an empty left hand side argument is not supported in array-pairs"
951 unless defined($el) and length($el);
952 my $elref = ref($el);
954 local our $Expand_Depth = 0;
955 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
956 } elsif ($elref eq 'ARRAY') {
957 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
958 } elsif (my $l = is_literal_value($el)) {
959 push @res, { -literal => $l };
960 } elsif ($elref eq 'HASH') {
961 local our $Expand_Depth = 0;
962 push @res, grep defined, $self->_expand_expr($el) if %$el;
968 # return $res[0] if @res == 1;
969 return { -op => [ $logop, @res ] };
975 my ($self, $op, $vv, $k) = @_;
977 ($k, $vv) = @$vv unless defined $k;
978 puke "$op can only take undef as argument"
982 and exists($vv->{-value})
983 and !defined($vv->{-value})
985 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
988 sub _expand_between {
989 my ($self, $op, $vv, $k) = @_;
991 $k = shift @{$vv = [ @$vv ]} unless defined $k;
992 my @rhs = map $self->_expand_expr($_),
993 ref($vv) eq 'ARRAY' ? @$vv : $vv;
995 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
997 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
999 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1003 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1009 my ($self, $raw, $vv, $k) = @_;
1010 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1011 my $op = $self->_normalize_op($raw);
1012 if (my $literal = is_literal_value($vv)) {
1013 my ($sql, @bind) = @$literal;
1014 my $opened_sql = $self->_open_outer_paren($sql);
1016 $op, $self->expand_expr($k, -ident),
1017 [ { -literal => [ $opened_sql, @bind ] } ]
1021 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1022 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1023 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1024 . 'will emit the logically correct SQL instead of raising this exception)'
1026 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1028 my @rhs = map $self->expand_expr($_, -value),
1029 map { defined($_) ? $_: puke($undef_err) }
1030 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1031 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1035 $self->expand_expr($k, -ident),
1041 my ($self, $op, $v) = @_;
1042 # DBIx::Class requires a nest warning to be emitted once but the private
1043 # method it overrode to do so no longer exists
1044 if ($self->{is_dbic_sqlmaker}) {
1045 unless (our $Nest_Warned) {
1047 "-nest in search conditions is deprecated, you most probably wanted:\n"
1048 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1053 return $self->_expand_expr($v);
1056 sub _recurse_where {
1057 my ($self, $where, $logic) = @_;
1059 # Special case: top level simple string treated as literal
1061 my $where_exp = (ref($where)
1062 ? $self->_expand_expr($where, $logic)
1063 : { -literal => [ $where ] });
1065 # dispatch expanded expression
1067 my ($sql, @bind) = defined($where_exp) ? $self->render_aqt($where_exp) : (undef);
1068 # DBIx::Class used to call _recurse_where in scalar context
1069 # something else might too...
1071 return ($sql, @bind);
1074 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1080 my ($self, $ident) = @_;
1082 return $self->_convert($self->_quote($ident));
1086 my ($self, $values) = @_;
1087 my ($sql, @bind) = $self->_render_op([ ',', @$values ]);
1088 return "($sql)", @bind;
1092 my ($self, $rest) = @_;
1093 my ($func, @args) = @$rest;
1097 push @arg_sql, shift @x;
1099 } map [ $self->render_aqt($_) ], @args;
1100 return ($self->_sqlcase($func).'('.join(', ', @arg_sql).')', @bind);
1104 my ($self, $bind) = @_;
1105 return ($self->_convert('?'), $self->_bindtype(@$bind));
1108 sub _render_literal {
1109 my ($self, $literal) = @_;
1110 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1115 my ($self, $v) = @_;
1116 my ($op, @args) = @$v;
1117 if (my $r = $self->{render_op}{$op}) {
1118 return $self->$r($op, \@args);
1123 my $op = join(' ', split '_', $op);
1125 my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1126 if ($us and @args > 1) {
1127 puke "Special op '${op}' requires first value to be identifier"
1128 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1129 my $k = join(($self->{name_sep}||'.'), @$ident);
1130 local our $Expand_Depth = 1;
1131 return $self->${\($us->{handler})}($k, $op, $args[1]);
1133 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1134 return $self->${\($us->{handler})}($op, $args[0]);
1139 return $self->_render_unop_prefix($op, \@args);
1141 return $self->_render_op_multop($op, \@args);
1147 sub _render_op_between {
1148 my ($self, $op, $args) = @_;
1149 my ($left, $low, $high) = @$args;
1150 my ($rhsql, @rhbind) = do {
1152 puke "Single arg to between must be a literal"
1153 unless $low->{-literal};
1156 my ($l, $h) = map [ $self->render_aqt($_) ], $low, $high;
1157 (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]),
1158 @{$l}[1..$#$l], @{$h}[1..$#$h])
1161 my ($lhsql, @lhbind) = $self->render_aqt($left);
1165 $self->_sqlcase(join ' ', split '_', $op),
1173 my ($self, $op, $args) = @_;
1174 my ($lhs, $rhs) = @$args;
1177 my ($sql, @bind) = $self->render_aqt($_);
1178 push @in_bind, @bind;
1181 my ($lhsql, @lbind) = $self->render_aqt($lhs);
1183 $lhsql.' '.$self->_sqlcase(join ' ', split '_', $op).' ( '
1184 .join(', ', @in_sql)
1190 sub _render_op_andor {
1191 my ($self, $op, $args) = @_;
1192 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @$args;
1193 return '' unless @parts;
1194 return @{$parts[0]} if @parts == 1;
1195 my ($sql, @bind) = $self->_render_op_multop($op, $args);
1196 return '( '.$sql.' )', @bind;
1199 sub _render_op_multop {
1200 my ($self, $op, $args) = @_;
1201 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @$args;
1202 return '' unless @parts;
1203 return @{$parts[0]} if @parts == 1;
1204 my ($final_sql) = join(
1205 ($op eq ',' ? '' : ' ').$self->_sqlcase(join ' ', split '_', $op).' ',
1210 map @{$_}[1..$#$_], @parts
1213 sub _render_op_not {
1214 my ($self, $op, $v) = @_;
1215 my ($sql, @bind) = $self->_render_unop_prefix($op, $v);
1216 return "(${sql})", @bind;
1219 sub _render_unop_prefix {
1220 my ($self, $op, $v) = @_;
1221 my ($expr_sql, @bind) = $self->render_aqt($v->[0]);
1223 my $op_sql = $self->_sqlcase($op); # join ' ', split '_', $op);
1224 return ("${op_sql} ${expr_sql}", @bind);
1227 sub _render_unop_postfix {
1228 my ($self, $op, $v) = @_;
1229 my ($expr_sql, @bind) = $self->render_aqt($v->[0]);
1230 my $op_sql = $self->_sqlcase(join ' ', split '_', $op);
1231 return ($expr_sql.' '.$op_sql, @bind);
1234 # Some databases (SQLite) treat col IN (1, 2) different from
1235 # col IN ( (1, 2) ). Use this to strip all outer parens while
1236 # adding them back in the corresponding method
1237 sub _open_outer_paren {
1238 my ($self, $sql) = @_;
1240 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1242 # there are closing parens inside, need the heavy duty machinery
1243 # to reevaluate the extraction starting from $sql (full reevaluation)
1244 if ($inner =~ /\)/) {
1245 require Text::Balanced;
1247 my (undef, $remainder) = do {
1248 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1250 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1253 # the entire expression needs to be a balanced bracketed thing
1254 # (after an extract no remainder sans trailing space)
1255 last if defined $remainder and $remainder =~ /\S/;
1265 #======================================================================
1267 #======================================================================
1269 sub _expand_order_by {
1270 my ($self, $arg) = @_;
1272 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1274 my $expander = sub {
1275 my ($self, $dir, $expr) = @_;
1276 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1277 foreach my $arg (@to_expand) {
1281 and grep /^-(asc|desc)$/, keys %$arg
1283 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1287 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1289 map $self->expand_expr($_, -ident),
1290 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1291 return undef unless @exp;
1292 return undef if @exp == 1 and not defined($exp[0]);
1293 return +{ -op => [ ',', @exp ] };
1296 local @{$self->{expand}}{qw(-asc -desc)} = (($expander) x 2);
1298 return $self->$expander(undef, $arg);
1302 my ($self, $arg) = @_;
1304 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1306 my ($sql, @bind) = $self->render_aqt($expanded);
1308 return '' unless length($sql);
1310 my $final_sql = $self->_sqlcase(' order by ').$sql;
1312 return wantarray ? ($final_sql, @bind) : $final_sql;
1315 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1317 sub _order_by_chunks {
1318 my ($self, $arg) = @_;
1320 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1322 return $self->_chunkify_order_by($expanded);
1325 sub _chunkify_order_by {
1326 my ($self, $expanded) = @_;
1328 return grep length, $self->render_aqt($expanded)
1329 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1332 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1333 my ($comma, @list) = @{$_->{-op}};
1334 return map $self->_chunkify_order_by($_), @list;
1336 return [ $self->render_aqt($_) ];
1340 #======================================================================
1341 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1342 #======================================================================
1348 $self->_expand_maybe_list_expr($from, -ident)
1353 #======================================================================
1355 #======================================================================
1357 sub _expand_maybe_list_expr {
1358 my ($self, $expr, $default) = @_;
1359 return +{ -op => [ ',',
1360 map $self->expand_expr($_, $default),
1361 ref($expr) eq 'ARRAY' ? @$expr : $expr
1365 # highly optimized, as it's called way too often
1367 # my ($self, $label) = @_;
1369 return '' unless defined $_[1];
1370 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1371 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1373 unless ($_[0]->{quote_char}) {
1374 if (ref($_[1]) eq 'ARRAY') {
1375 return join($_[0]->{name_sep}||'.', @{$_[1]});
1377 $_[0]->_assert_pass_injection_guard($_[1]);
1382 my $qref = ref $_[0]->{quote_char};
1384 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1385 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1386 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1388 my $esc = $_[0]->{escape_char} || $r;
1390 # parts containing * are naturally unquoted
1392 $_[0]->{name_sep}||'',
1396 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1398 (ref($_[1]) eq 'ARRAY'
1402 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1410 # Conversion, if applicable
1412 #my ($self, $arg) = @_;
1413 if ($_[0]->{convert_where}) {
1414 return $_[0]->_sqlcase($_[0]->{convert_where}) .'(' . $_[1] . ')';
1421 #my ($self, $col, @vals) = @_;
1422 # called often - tighten code
1423 return $_[0]->{bindtype} eq 'columns'
1424 ? map {[$_[1], $_]} @_[2 .. $#_]
1429 # Dies if any element of @bind is not in [colname => value] format
1430 # if bindtype is 'columns'.
1431 sub _assert_bindval_matches_bindtype {
1432 # my ($self, @bind) = @_;
1434 if ($self->{bindtype} eq 'columns') {
1436 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1437 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1443 sub _join_sql_clauses {
1444 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1446 if (@$clauses_aref > 1) {
1447 my $join = " " . $self->_sqlcase($logic) . " ";
1448 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1449 return ($sql, @$bind_aref);
1451 elsif (@$clauses_aref) {
1452 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1455 return (); # if no SQL, ignore @$bind_aref
1460 # Fix SQL case, if so requested
1462 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1463 # don't touch the argument ... crooked logic, but let's not change it!
1464 return $_[0]->{case} ? $_[1] : uc($_[1]);
1468 #======================================================================
1469 # DISPATCHING FROM REFKIND
1470 #======================================================================
1473 my ($self, $data) = @_;
1475 return 'UNDEF' unless defined $data;
1477 # blessed objects are treated like scalars
1478 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1480 return 'SCALAR' unless $ref;
1483 while ($ref eq 'REF') {
1485 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1489 return ($ref||'SCALAR') . ('REF' x $n_steps);
1493 my ($self, $data) = @_;
1494 my @try = ($self->_refkind($data));
1495 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1496 push @try, 'FALLBACK';
1500 sub _METHOD_FOR_refkind {
1501 my ($self, $meth_prefix, $data) = @_;
1504 for (@{$self->_try_refkind($data)}) {
1505 $method = $self->can($meth_prefix."_".$_)
1509 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1513 sub _SWITCH_refkind {
1514 my ($self, $data, $dispatch_table) = @_;
1517 for (@{$self->_try_refkind($data)}) {
1518 $coderef = $dispatch_table->{$_}
1522 puke "no dispatch entry for ".$self->_refkind($data)
1531 #======================================================================
1532 # VALUES, GENERATE, AUTOLOAD
1533 #======================================================================
1535 # LDNOTE: original code from nwiger, didn't touch code in that section
1536 # I feel the AUTOLOAD stuff should not be the default, it should
1537 # only be activated on explicit demand by user.
1541 my $data = shift || return;
1542 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1543 unless ref $data eq 'HASH';
1546 foreach my $k (sort keys %$data) {
1547 my $v = $data->{$k};
1548 $self->_SWITCH_refkind($v, {
1550 if ($self->{array_datatypes}) { # array datatype
1551 push @all_bind, $self->_bindtype($k, $v);
1553 else { # literal SQL with bind
1554 my ($sql, @bind) = @$v;
1555 $self->_assert_bindval_matches_bindtype(@bind);
1556 push @all_bind, @bind;
1559 ARRAYREFREF => sub { # literal SQL with bind
1560 my ($sql, @bind) = @${$v};
1561 $self->_assert_bindval_matches_bindtype(@bind);
1562 push @all_bind, @bind;
1564 SCALARREF => sub { # literal SQL without bind
1566 SCALAR_or_UNDEF => sub {
1567 push @all_bind, $self->_bindtype($k, $v);
1578 my(@sql, @sqlq, @sqlv);
1582 if ($ref eq 'HASH') {
1583 for my $k (sort keys %$_) {
1586 my $label = $self->_quote($k);
1587 if ($r eq 'ARRAY') {
1588 # literal SQL with bind
1589 my ($sql, @bind) = @$v;
1590 $self->_assert_bindval_matches_bindtype(@bind);
1591 push @sqlq, "$label = $sql";
1593 } elsif ($r eq 'SCALAR') {
1594 # literal SQL without bind
1595 push @sqlq, "$label = $$v";
1597 push @sqlq, "$label = ?";
1598 push @sqlv, $self->_bindtype($k, $v);
1601 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1602 } elsif ($ref eq 'ARRAY') {
1603 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1606 if ($r eq 'ARRAY') { # literal SQL with bind
1607 my ($sql, @bind) = @$v;
1608 $self->_assert_bindval_matches_bindtype(@bind);
1611 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1612 # embedded literal SQL
1619 push @sql, '(' . join(', ', @sqlq) . ')';
1620 } elsif ($ref eq 'SCALAR') {
1624 # strings get case twiddled
1625 push @sql, $self->_sqlcase($_);
1629 my $sql = join ' ', @sql;
1631 # this is pretty tricky
1632 # if ask for an array, return ($stmt, @bind)
1633 # otherwise, s/?/shift @sqlv/ to put it inline
1635 return ($sql, @sqlv);
1637 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1638 ref $d ? $d->[1] : $d/e;
1647 # This allows us to check for a local, then _form, attr
1649 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1650 return $self->generate($name, @_);
1661 SQL::Abstract - Generate SQL from Perl data structures
1667 my $sql = SQL::Abstract->new;
1669 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1671 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1673 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1675 my($stmt, @bind) = $sql->delete($table, \%where);
1677 # Then, use these in your DBI statements
1678 my $sth = $dbh->prepare($stmt);
1679 $sth->execute(@bind);
1681 # Just generate the WHERE clause
1682 my($stmt, @bind) = $sql->where(\%where, $order);
1684 # Return values in the same order, for hashed queries
1685 # See PERFORMANCE section for more details
1686 my @bind = $sql->values(\%fieldvals);
1690 This module was inspired by the excellent L<DBIx::Abstract>.
1691 However, in using that module I found that what I really wanted
1692 to do was generate SQL, but still retain complete control over my
1693 statement handles and use the DBI interface. So, I set out to
1694 create an abstract SQL generation module.
1696 While based on the concepts used by L<DBIx::Abstract>, there are
1697 several important differences, especially when it comes to WHERE
1698 clauses. I have modified the concepts used to make the SQL easier
1699 to generate from Perl data structures and, IMO, more intuitive.
1700 The underlying idea is for this module to do what you mean, based
1701 on the data structures you provide it. The big advantage is that
1702 you don't have to modify your code every time your data changes,
1703 as this module figures it out.
1705 To begin with, an SQL INSERT is as easy as just specifying a hash
1706 of C<key=value> pairs:
1709 name => 'Jimbo Bobson',
1710 phone => '123-456-7890',
1711 address => '42 Sister Lane',
1712 city => 'St. Louis',
1713 state => 'Louisiana',
1716 The SQL can then be generated with this:
1718 my($stmt, @bind) = $sql->insert('people', \%data);
1720 Which would give you something like this:
1722 $stmt = "INSERT INTO people
1723 (address, city, name, phone, state)
1724 VALUES (?, ?, ?, ?, ?)";
1725 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1726 '123-456-7890', 'Louisiana');
1728 These are then used directly in your DBI code:
1730 my $sth = $dbh->prepare($stmt);
1731 $sth->execute(@bind);
1733 =head2 Inserting and Updating Arrays
1735 If your database has array types (like for example Postgres),
1736 activate the special option C<< array_datatypes => 1 >>
1737 when creating the C<SQL::Abstract> object.
1738 Then you may use an arrayref to insert and update database array types:
1740 my $sql = SQL::Abstract->new(array_datatypes => 1);
1742 planets => [qw/Mercury Venus Earth Mars/]
1745 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1749 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1751 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1754 =head2 Inserting and Updating SQL
1756 In order to apply SQL functions to elements of your C<%data> you may
1757 specify a reference to an arrayref for the given hash value. For example,
1758 if you need to execute the Oracle C<to_date> function on a value, you can
1759 say something like this:
1763 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1766 The first value in the array is the actual SQL. Any other values are
1767 optional and would be included in the bind values array. This gives
1770 my($stmt, @bind) = $sql->insert('people', \%data);
1772 $stmt = "INSERT INTO people (name, date_entered)
1773 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1774 @bind = ('Bill', '03/02/2003');
1776 An UPDATE is just as easy, all you change is the name of the function:
1778 my($stmt, @bind) = $sql->update('people', \%data);
1780 Notice that your C<%data> isn't touched; the module will generate
1781 the appropriately quirky SQL for you automatically. Usually you'll
1782 want to specify a WHERE clause for your UPDATE, though, which is
1783 where handling C<%where> hashes comes in handy...
1785 =head2 Complex where statements
1787 This module can generate pretty complicated WHERE statements
1788 easily. For example, simple C<key=value> pairs are taken to mean
1789 equality, and if you want to see if a field is within a set
1790 of values, you can use an arrayref. Let's say we wanted to
1791 SELECT some data based on this criteria:
1794 requestor => 'inna',
1795 worker => ['nwiger', 'rcwe', 'sfz'],
1796 status => { '!=', 'completed' }
1799 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1801 The above would give you something like this:
1803 $stmt = "SELECT * FROM tickets WHERE
1804 ( requestor = ? ) AND ( status != ? )
1805 AND ( worker = ? OR worker = ? OR worker = ? )";
1806 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1808 Which you could then use in DBI code like so:
1810 my $sth = $dbh->prepare($stmt);
1811 $sth->execute(@bind);
1817 The methods are simple. There's one for every major SQL operation,
1818 and a constructor you use first. The arguments are specified in a
1819 similar order for each method (table, then fields, then a where
1820 clause) to try and simplify things.
1822 =head2 new(option => 'value')
1824 The C<new()> function takes a list of options and values, and returns
1825 a new B<SQL::Abstract> object which can then be used to generate SQL
1826 through the methods below. The options accepted are:
1832 If set to 'lower', then SQL will be generated in all lowercase. By
1833 default SQL is generated in "textbook" case meaning something like:
1835 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1837 Any setting other than 'lower' is ignored.
1841 This determines what the default comparison operator is. By default
1842 it is C<=>, meaning that a hash like this:
1844 %where = (name => 'nwiger', email => 'nate@wiger.org');
1846 Will generate SQL like this:
1848 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1850 However, you may want loose comparisons by default, so if you set
1851 C<cmp> to C<like> you would get SQL such as:
1853 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1855 You can also override the comparison on an individual basis - see
1856 the huge section on L</"WHERE CLAUSES"> at the bottom.
1858 =item sqltrue, sqlfalse
1860 Expressions for inserting boolean values within SQL statements.
1861 By default these are C<1=1> and C<1=0>. They are used
1862 by the special operators C<-in> and C<-not_in> for generating
1863 correct SQL even when the argument is an empty array (see below).
1867 This determines the default logical operator for multiple WHERE
1868 statements in arrays or hashes. If absent, the default logic is "or"
1869 for arrays, and "and" for hashes. This means that a WHERE
1873 event_date => {'>=', '2/13/99'},
1874 event_date => {'<=', '4/24/03'},
1877 will generate SQL like this:
1879 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1881 This is probably not what you want given this query, though (look
1882 at the dates). To change the "OR" to an "AND", simply specify:
1884 my $sql = SQL::Abstract->new(logic => 'and');
1886 Which will change the above C<WHERE> to:
1888 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1890 The logic can also be changed locally by inserting
1891 a modifier in front of an arrayref:
1893 @where = (-and => [event_date => {'>=', '2/13/99'},
1894 event_date => {'<=', '4/24/03'} ]);
1896 See the L</"WHERE CLAUSES"> section for explanations.
1900 This will automatically convert comparisons using the specified SQL
1901 function for both column and value. This is mostly used with an argument
1902 of C<upper> or C<lower>, so that the SQL will have the effect of
1903 case-insensitive "searches". For example, this:
1905 $sql = SQL::Abstract->new(convert => 'upper');
1906 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1908 Will turn out the following SQL:
1910 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1912 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1913 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1914 not validate this option; it will just pass through what you specify verbatim).
1918 This is a kludge because many databases suck. For example, you can't
1919 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1920 Instead, you have to use C<bind_param()>:
1922 $sth->bind_param(1, 'reg data');
1923 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1925 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1926 which loses track of which field each slot refers to. Fear not.
1928 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1929 Currently, you can specify either C<normal> (default) or C<columns>. If you
1930 specify C<columns>, you will get an array that looks like this:
1932 my $sql = SQL::Abstract->new(bindtype => 'columns');
1933 my($stmt, @bind) = $sql->insert(...);
1936 [ 'column1', 'value1' ],
1937 [ 'column2', 'value2' ],
1938 [ 'column3', 'value3' ],
1941 You can then iterate through this manually, using DBI's C<bind_param()>.
1943 $sth->prepare($stmt);
1946 my($col, $data) = @$_;
1947 if ($col eq 'details' || $col eq 'comments') {
1948 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1949 } elsif ($col eq 'image') {
1950 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1952 $sth->bind_param($i, $data);
1956 $sth->execute; # execute without @bind now
1958 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1959 Basically, the advantage is still that you don't have to care which fields
1960 are or are not included. You could wrap that above C<for> loop in a simple
1961 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1962 get a layer of abstraction over manual SQL specification.
1964 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
1965 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1966 will expect the bind values in this format.
1970 This is the character that a table or column name will be quoted
1971 with. By default this is an empty string, but you could set it to
1972 the character C<`>, to generate SQL like this:
1974 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1976 Alternatively, you can supply an array ref of two items, the first being the left
1977 hand quote character, and the second the right hand quote character. For
1978 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1979 that generates SQL like this:
1981 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1983 Quoting is useful if you have tables or columns names that are reserved
1984 words in your database's SQL dialect.
1988 This is the character that will be used to escape L</quote_char>s appearing
1989 in an identifier before it has been quoted.
1991 The parameter default in case of a single L</quote_char> character is the quote
1994 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
1995 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
1996 of the B<opening (left)> L</quote_char> within the identifier are currently left
1997 untouched. The default for opening-closing-style quotes may change in future
1998 versions, thus you are B<strongly encouraged> to specify the escape character
2003 This is the character that separates a table and column name. It is
2004 necessary to specify this when the C<quote_char> option is selected,
2005 so that tables and column names can be individually quoted like this:
2007 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2009 =item injection_guard
2011 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2012 column name specified in a query structure. This is a safety mechanism to avoid
2013 injection attacks when mishandling user input e.g.:
2015 my %condition_as_column_value_pairs = get_values_from_user();
2016 $sqla->select( ... , \%condition_as_column_value_pairs );
2018 If the expression matches an exception is thrown. Note that literal SQL
2019 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2021 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2023 =item array_datatypes
2025 When this option is true, arrayrefs in INSERT or UPDATE are
2026 interpreted as array datatypes and are passed directly
2028 When this option is false, arrayrefs are interpreted
2029 as literal SQL, just like refs to arrayrefs
2030 (but this behavior is for backwards compatibility; when writing
2031 new queries, use the "reference to arrayref" syntax
2037 Takes a reference to a list of "special operators"
2038 to extend the syntax understood by L<SQL::Abstract>.
2039 See section L</"SPECIAL OPERATORS"> for details.
2043 Takes a reference to a list of "unary operators"
2044 to extend the syntax understood by L<SQL::Abstract>.
2045 See section L</"UNARY OPERATORS"> for details.
2051 =head2 insert($table, \@values || \%fieldvals, \%options)
2053 This is the simplest function. You simply give it a table name
2054 and either an arrayref of values or hashref of field/value pairs.
2055 It returns an SQL INSERT statement and a list of bind values.
2056 See the sections on L</"Inserting and Updating Arrays"> and
2057 L</"Inserting and Updating SQL"> for information on how to insert
2058 with those data types.
2060 The optional C<\%options> hash reference may contain additional
2061 options to generate the insert SQL. Currently supported options
2068 Takes either a scalar of raw SQL fields, or an array reference of
2069 field names, and adds on an SQL C<RETURNING> statement at the end.
2070 This allows you to return data generated by the insert statement
2071 (such as row IDs) without performing another C<SELECT> statement.
2072 Note, however, this is not part of the SQL standard and may not
2073 be supported by all database engines.
2077 =head2 update($table, \%fieldvals, \%where, \%options)
2079 This takes a table, hashref of field/value pairs, and an optional
2080 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2082 See the sections on L</"Inserting and Updating Arrays"> and
2083 L</"Inserting and Updating SQL"> for information on how to insert
2084 with those data types.
2086 The optional C<\%options> hash reference may contain additional
2087 options to generate the update SQL. Currently supported options
2094 See the C<returning> option to
2095 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2099 =head2 select($source, $fields, $where, $order)
2101 This returns a SQL SELECT statement and associated list of bind values, as
2102 specified by the arguments:
2108 Specification of the 'FROM' part of the statement.
2109 The argument can be either a plain scalar (interpreted as a table
2110 name, will be quoted), or an arrayref (interpreted as a list
2111 of table names, joined by commas, quoted), or a scalarref
2112 (literal SQL, not quoted).
2116 Specification of the list of fields to retrieve from
2118 The argument can be either an arrayref (interpreted as a list
2119 of field names, will be joined by commas and quoted), or a
2120 plain scalar (literal SQL, not quoted).
2121 Please observe that this API is not as flexible as that of
2122 the first argument C<$source>, for backwards compatibility reasons.
2126 Optional argument to specify the WHERE part of the query.
2127 The argument is most often a hashref, but can also be
2128 an arrayref or plain scalar --
2129 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2133 Optional argument to specify the ORDER BY part of the query.
2134 The argument can be a scalar, a hashref or an arrayref
2135 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2141 =head2 delete($table, \%where, \%options)
2143 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2144 It returns an SQL DELETE statement and list of bind values.
2146 The optional C<\%options> hash reference may contain additional
2147 options to generate the delete SQL. Currently supported options
2154 See the C<returning> option to
2155 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2159 =head2 where(\%where, $order)
2161 This is used to generate just the WHERE clause. For example,
2162 if you have an arbitrary data structure and know what the
2163 rest of your SQL is going to look like, but want an easy way
2164 to produce a WHERE clause, use this. It returns an SQL WHERE
2165 clause and list of bind values.
2168 =head2 values(\%data)
2170 This just returns the values from the hash C<%data>, in the same
2171 order that would be returned from any of the other above queries.
2172 Using this allows you to markedly speed up your queries if you
2173 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2175 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2177 Warning: This is an experimental method and subject to change.
2179 This returns arbitrarily generated SQL. It's a really basic shortcut.
2180 It will return two different things, depending on return context:
2182 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2183 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2185 These would return the following:
2187 # First calling form
2188 $stmt = "CREATE TABLE test (?, ?)";
2189 @bind = (field1, field2);
2191 # Second calling form
2192 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2194 Depending on what you're trying to do, it's up to you to choose the correct
2195 format. In this example, the second form is what you would want.
2199 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2203 ALTER SESSION SET nls_date_format = 'MM/YY'
2205 You get the idea. Strings get their case twiddled, but everything
2206 else remains verbatim.
2208 =head1 EXPORTABLE FUNCTIONS
2210 =head2 is_plain_value
2212 Determines if the supplied argument is a plain value as understood by this
2217 =item * The value is C<undef>
2219 =item * The value is a non-reference
2221 =item * The value is an object with stringification overloading
2223 =item * The value is of the form C<< { -value => $anything } >>
2227 On failure returns C<undef>, on success returns a B<scalar> reference
2228 to the original supplied argument.
2234 The stringification overloading detection is rather advanced: it takes
2235 into consideration not only the presence of a C<""> overload, but if that
2236 fails also checks for enabled
2237 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2238 on either C<0+> or C<bool>.
2240 Unfortunately testing in the field indicates that this
2241 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2242 but only when very large numbers of stringifying objects are involved.
2243 At the time of writing ( Sep 2014 ) there is no clear explanation of
2244 the direct cause, nor is there a manageably small test case that reliably
2245 reproduces the problem.
2247 If you encounter any of the following exceptions in B<random places within
2248 your application stack> - this module may be to blame:
2250 Operation "ne": no method found,
2251 left argument in overloaded package <something>,
2252 right argument in overloaded package <something>
2256 Stub found while resolving method "???" overloading """" in package <something>
2258 If you fall victim to the above - please attempt to reduce the problem
2259 to something that could be sent to the L<SQL::Abstract developers
2260 |DBIx::Class/GETTING HELP/SUPPORT>
2261 (either publicly or privately). As a workaround in the meantime you can
2262 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2263 value, which will most likely eliminate your problem (at the expense of
2264 not being able to properly detect exotic forms of stringification).
2266 This notice and environment variable will be removed in a future version,
2267 as soon as the underlying problem is found and a reliable workaround is
2272 =head2 is_literal_value
2274 Determines if the supplied argument is a literal value as understood by this
2279 =item * C<\$sql_string>
2281 =item * C<\[ $sql_string, @bind_values ]>
2285 On failure returns C<undef>, on success returns an B<array> reference
2286 containing the unpacked version of the supplied literal SQL and bind values.
2288 =head1 WHERE CLAUSES
2292 This module uses a variation on the idea from L<DBIx::Abstract>. It
2293 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2294 module is that things in arrays are OR'ed, and things in hashes
2297 The easiest way to explain is to show lots of examples. After
2298 each C<%where> hash shown, it is assumed you used:
2300 my($stmt, @bind) = $sql->where(\%where);
2302 However, note that the C<%where> hash can be used directly in any
2303 of the other functions as well, as described above.
2305 =head2 Key-value pairs
2307 So, let's get started. To begin, a simple hash:
2311 status => 'completed'
2314 Is converted to SQL C<key = val> statements:
2316 $stmt = "WHERE user = ? AND status = ?";
2317 @bind = ('nwiger', 'completed');
2319 One common thing I end up doing is having a list of values that
2320 a field can be in. To do this, simply specify a list inside of
2325 status => ['assigned', 'in-progress', 'pending'];
2328 This simple code will create the following:
2330 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2331 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2333 A field associated to an empty arrayref will be considered a
2334 logical false and will generate 0=1.
2336 =head2 Tests for NULL values
2338 If the value part is C<undef> then this is converted to SQL <IS NULL>
2347 $stmt = "WHERE user = ? AND status IS NULL";
2350 To test if a column IS NOT NULL:
2354 status => { '!=', undef },
2357 =head2 Specific comparison operators
2359 If you want to specify a different type of operator for your comparison,
2360 you can use a hashref for a given column:
2364 status => { '!=', 'completed' }
2367 Which would generate:
2369 $stmt = "WHERE user = ? AND status != ?";
2370 @bind = ('nwiger', 'completed');
2372 To test against multiple values, just enclose the values in an arrayref:
2374 status => { '=', ['assigned', 'in-progress', 'pending'] };
2376 Which would give you:
2378 "WHERE status = ? OR status = ? OR status = ?"
2381 The hashref can also contain multiple pairs, in which case it is expanded
2382 into an C<AND> of its elements:
2386 status => { '!=', 'completed', -not_like => 'pending%' }
2389 # Or more dynamically, like from a form
2390 $where{user} = 'nwiger';
2391 $where{status}{'!='} = 'completed';
2392 $where{status}{'-not_like'} = 'pending%';
2394 # Both generate this
2395 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2396 @bind = ('nwiger', 'completed', 'pending%');
2399 To get an OR instead, you can combine it with the arrayref idea:
2403 priority => [ { '=', 2 }, { '>', 5 } ]
2406 Which would generate:
2408 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2409 @bind = ('2', '5', 'nwiger');
2411 If you want to include literal SQL (with or without bind values), just use a
2412 scalar reference or reference to an arrayref as the value:
2415 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2416 date_expires => { '<' => \"now()" }
2419 Which would generate:
2421 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2422 @bind = ('11/26/2008');
2425 =head2 Logic and nesting operators
2427 In the example above,
2428 there is a subtle trap if you want to say something like
2429 this (notice the C<AND>):
2431 WHERE priority != ? AND priority != ?
2433 Because, in Perl you I<can't> do this:
2435 priority => { '!=' => 2, '!=' => 1 }
2437 As the second C<!=> key will obliterate the first. The solution
2438 is to use the special C<-modifier> form inside an arrayref:
2440 priority => [ -and => {'!=', 2},
2444 Normally, these would be joined by C<OR>, but the modifier tells it
2445 to use C<AND> instead. (Hint: You can use this in conjunction with the
2446 C<logic> option to C<new()> in order to change the way your queries
2447 work by default.) B<Important:> Note that the C<-modifier> goes
2448 B<INSIDE> the arrayref, as an extra first element. This will
2449 B<NOT> do what you think it might:
2451 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2453 Here is a quick list of equivalencies, since there is some overlap:
2456 status => {'!=', 'completed', 'not like', 'pending%' }
2457 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2460 status => {'=', ['assigned', 'in-progress']}
2461 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2462 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2466 =head2 Special operators: IN, BETWEEN, etc.
2468 You can also use the hashref format to compare a list of fields using the
2469 C<IN> comparison operator, by specifying the list as an arrayref:
2472 status => 'completed',
2473 reportid => { -in => [567, 2335, 2] }
2476 Which would generate:
2478 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2479 @bind = ('completed', '567', '2335', '2');
2481 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2484 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2485 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2486 'sqltrue' (by default: C<1=1>).
2488 In addition to the array you can supply a chunk of literal sql or
2489 literal sql with bind:
2492 customer => { -in => \[
2493 'SELECT cust_id FROM cust WHERE balance > ?',
2496 status => { -in => \'SELECT status_codes FROM states' },
2502 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2503 AND status IN ( SELECT status_codes FROM states )
2507 Finally, if the argument to C<-in> is not a reference, it will be
2508 treated as a single-element array.
2510 Another pair of operators is C<-between> and C<-not_between>,
2511 used with an arrayref of two values:
2515 completion_date => {
2516 -not_between => ['2002-10-01', '2003-02-06']
2522 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2524 Just like with C<-in> all plausible combinations of literal SQL
2528 start0 => { -between => [ 1, 2 ] },
2529 start1 => { -between => \["? AND ?", 1, 2] },
2530 start2 => { -between => \"lower(x) AND upper(y)" },
2531 start3 => { -between => [
2533 \["upper(?)", 'stuff' ],
2540 ( start0 BETWEEN ? AND ? )
2541 AND ( start1 BETWEEN ? AND ? )
2542 AND ( start2 BETWEEN lower(x) AND upper(y) )
2543 AND ( start3 BETWEEN lower(x) AND upper(?) )
2545 @bind = (1, 2, 1, 2, 'stuff');
2548 These are the two builtin "special operators"; but the
2549 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2551 =head2 Unary operators: bool
2553 If you wish to test against boolean columns or functions within your
2554 database you can use the C<-bool> and C<-not_bool> operators. For
2555 example to test the column C<is_user> being true and the column
2556 C<is_enabled> being false you would use:-
2560 -not_bool => 'is_enabled',
2565 WHERE is_user AND NOT is_enabled
2567 If a more complex combination is required, testing more conditions,
2568 then you should use the and/or operators:-
2573 -not_bool => { two=> { -rlike => 'bar' } },
2574 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2585 (NOT ( three = ? OR three > ? ))
2588 =head2 Nested conditions, -and/-or prefixes
2590 So far, we've seen how multiple conditions are joined with a top-level
2591 C<AND>. We can change this by putting the different conditions we want in
2592 hashes and then putting those hashes in an array. For example:
2597 status => { -like => ['pending%', 'dispatched'] },
2601 status => 'unassigned',
2605 This data structure would create the following:
2607 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2608 OR ( user = ? AND status = ? ) )";
2609 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2612 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2613 to change the logic inside:
2619 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2620 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2627 $stmt = "WHERE ( user = ?
2628 AND ( ( workhrs > ? AND geo = ? )
2629 OR ( workhrs < ? OR geo = ? ) ) )";
2630 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2632 =head3 Algebraic inconsistency, for historical reasons
2634 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2635 operator goes C<outside> of the nested structure; whereas when connecting
2636 several constraints on one column, the C<-and> operator goes
2637 C<inside> the arrayref. Here is an example combining both features:
2640 -and => [a => 1, b => 2],
2641 -or => [c => 3, d => 4],
2642 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2647 WHERE ( ( ( a = ? AND b = ? )
2648 OR ( c = ? OR d = ? )
2649 OR ( e LIKE ? AND e LIKE ? ) ) )
2651 This difference in syntax is unfortunate but must be preserved for
2652 historical reasons. So be careful: the two examples below would
2653 seem algebraically equivalent, but they are not
2656 { -like => 'foo%' },
2657 { -like => '%bar' },
2659 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2662 { col => { -like => 'foo%' } },
2663 { col => { -like => '%bar' } },
2665 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2668 =head2 Literal SQL and value type operators
2670 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2671 side" is a column name and the "right side" is a value (normally rendered as
2672 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2673 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2674 alter this behavior. There are several ways of doing so.
2678 This is a virtual operator that signals the string to its right side is an
2679 identifier (a column name) and not a value. For example to compare two
2680 columns you would write:
2683 priority => { '<', 2 },
2684 requestor => { -ident => 'submitter' },
2689 $stmt = "WHERE priority < ? AND requestor = submitter";
2692 If you are maintaining legacy code you may see a different construct as
2693 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2698 This is a virtual operator that signals that the construct to its right side
2699 is a value to be passed to DBI. This is for example necessary when you want
2700 to write a where clause against an array (for RDBMS that support such
2701 datatypes). For example:
2704 array => { -value => [1, 2, 3] }
2709 $stmt = 'WHERE array = ?';
2710 @bind = ([1, 2, 3]);
2712 Note that if you were to simply say:
2718 the result would probably not be what you wanted:
2720 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2725 Finally, sometimes only literal SQL will do. To include a random snippet
2726 of SQL verbatim, you specify it as a scalar reference. Consider this only
2727 as a last resort. Usually there is a better way. For example:
2730 priority => { '<', 2 },
2731 requestor => { -in => \'(SELECT name FROM hitmen)' },
2736 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2739 Note that in this example, you only get one bind parameter back, since
2740 the verbatim SQL is passed as part of the statement.
2744 Never use untrusted input as a literal SQL argument - this is a massive
2745 security risk (there is no way to check literal snippets for SQL
2746 injections and other nastyness). If you need to deal with untrusted input
2747 use literal SQL with placeholders as described next.
2749 =head3 Literal SQL with placeholders and bind values (subqueries)
2751 If the literal SQL to be inserted has placeholders and bind values,
2752 use a reference to an arrayref (yes this is a double reference --
2753 not so common, but perfectly legal Perl). For example, to find a date
2754 in Postgres you can use something like this:
2757 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2762 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2765 Note that you must pass the bind values in the same format as they are returned
2766 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2767 to C<columns>, you must provide the bind values in the
2768 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2769 scalar value; most commonly the column name, but you can use any scalar value
2770 (including references and blessed references), L<SQL::Abstract> will simply
2771 pass it through intact. So if C<bindtype> is set to C<columns> the above
2772 example will look like:
2775 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2778 Literal SQL is especially useful for nesting parenthesized clauses in the
2779 main SQL query. Here is a first example:
2781 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2785 bar => \["IN ($sub_stmt)" => @sub_bind],
2790 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2791 WHERE c2 < ? AND c3 LIKE ?))";
2792 @bind = (1234, 100, "foo%");
2794 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2795 are expressed in the same way. Of course the C<$sub_stmt> and
2796 its associated bind values can be generated through a former call
2799 my ($sub_stmt, @sub_bind)
2800 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2801 c3 => {-like => "foo%"}});
2804 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2807 In the examples above, the subquery was used as an operator on a column;
2808 but the same principle also applies for a clause within the main C<%where>
2809 hash, like an EXISTS subquery:
2811 my ($sub_stmt, @sub_bind)
2812 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2813 my %where = ( -and => [
2815 \["EXISTS ($sub_stmt)" => @sub_bind],
2820 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2821 WHERE c1 = ? AND c2 > t0.c0))";
2825 Observe that the condition on C<c2> in the subquery refers to
2826 column C<t0.c0> of the main query: this is I<not> a bind
2827 value, so we have to express it through a scalar ref.
2828 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2829 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2830 what we wanted here.
2832 Finally, here is an example where a subquery is used
2833 for expressing unary negation:
2835 my ($sub_stmt, @sub_bind)
2836 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2837 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2839 lname => {like => '%son%'},
2840 \["NOT ($sub_stmt)" => @sub_bind],
2845 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2846 @bind = ('%son%', 10, 20)
2848 =head3 Deprecated usage of Literal SQL
2850 Below are some examples of archaic use of literal SQL. It is shown only as
2851 reference for those who deal with legacy code. Each example has a much
2852 better, cleaner and safer alternative that users should opt for in new code.
2858 my %where = ( requestor => \'IS NOT NULL' )
2860 $stmt = "WHERE requestor IS NOT NULL"
2862 This used to be the way of generating NULL comparisons, before the handling
2863 of C<undef> got formalized. For new code please use the superior syntax as
2864 described in L</Tests for NULL values>.
2868 my %where = ( requestor => \'= submitter' )
2870 $stmt = "WHERE requestor = submitter"
2872 This used to be the only way to compare columns. Use the superior L</-ident>
2873 method for all new code. For example an identifier declared in such a way
2874 will be properly quoted if L</quote_char> is properly set, while the legacy
2875 form will remain as supplied.
2879 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2881 $stmt = "WHERE completed > ? AND is_ready"
2882 @bind = ('2012-12-21')
2884 Using an empty string literal used to be the only way to express a boolean.
2885 For all new code please use the much more readable
2886 L<-bool|/Unary operators: bool> operator.
2892 These pages could go on for a while, since the nesting of the data
2893 structures this module can handle are pretty much unlimited (the
2894 module implements the C<WHERE> expansion as a recursive function
2895 internally). Your best bet is to "play around" with the module a
2896 little to see how the data structures behave, and choose the best
2897 format for your data based on that.
2899 And of course, all the values above will probably be replaced with
2900 variables gotten from forms or the command line. After all, if you
2901 knew everything ahead of time, you wouldn't have to worry about
2902 dynamically-generating SQL and could just hardwire it into your
2905 =head1 ORDER BY CLAUSES
2907 Some functions take an order by clause. This can either be a scalar (just a
2908 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
2909 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
2912 Given | Will Generate
2913 ---------------------------------------------------------------
2915 'colA' | ORDER BY colA
2917 [qw/colA colB/] | ORDER BY colA, colB
2919 {-asc => 'colA'} | ORDER BY colA ASC
2921 {-desc => 'colB'} | ORDER BY colB DESC
2923 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2925 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2927 \'colA DESC' | ORDER BY colA DESC
2929 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
2930 | /* ...with $x bound to ? */
2933 { -asc => 'colA' }, | colA ASC,
2934 { -desc => [qw/colB/] }, | colB DESC,
2935 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
2936 \'colE DESC', | colE DESC,
2937 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
2938 ] | /* ...with $x bound to ? */
2939 ===============================================================
2943 =head1 SPECIAL OPERATORS
2945 my $sqlmaker = SQL::Abstract->new(special_ops => [
2949 my ($self, $field, $op, $arg) = @_;
2955 handler => 'method_name',
2959 A "special operator" is a SQL syntactic clause that can be
2960 applied to a field, instead of a usual binary operator.
2963 WHERE field IN (?, ?, ?)
2964 WHERE field BETWEEN ? AND ?
2965 WHERE MATCH(field) AGAINST (?, ?)
2967 Special operators IN and BETWEEN are fairly standard and therefore
2968 are builtin within C<SQL::Abstract> (as the overridable methods
2969 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2970 like the MATCH .. AGAINST example above which is specific to MySQL,
2971 you can write your own operator handlers - supply a C<special_ops>
2972 argument to the C<new> method. That argument takes an arrayref of
2973 operator definitions; each operator definition is a hashref with two
2980 the regular expression to match the operator
2984 Either a coderef or a plain scalar method name. In both cases
2985 the expected return is C<< ($sql, @bind) >>.
2987 When supplied with a method name, it is simply called on the
2988 L<SQL::Abstract> object as:
2990 $self->$method_name($field, $op, $arg)
2994 $field is the LHS of the operator
2995 $op is the part that matched the handler regex
2998 When supplied with a coderef, it is called as:
3000 $coderef->($self, $field, $op, $arg)
3005 For example, here is an implementation
3006 of the MATCH .. AGAINST syntax for MySQL
3008 my $sqlmaker = SQL::Abstract->new(special_ops => [
3010 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3011 {regex => qr/^match$/i,
3013 my ($self, $field, $op, $arg) = @_;
3014 $arg = [$arg] if not ref $arg;
3015 my $label = $self->_quote($field);
3016 my ($placeholder) = $self->_convert('?');
3017 my $placeholders = join ", ", (($placeholder) x @$arg);
3018 my $sql = $self->_sqlcase('match') . " ($label) "
3019 . $self->_sqlcase('against') . " ($placeholders) ";
3020 my @bind = $self->_bindtype($field, @$arg);
3021 return ($sql, @bind);
3028 =head1 UNARY OPERATORS
3030 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3034 my ($self, $op, $arg) = @_;
3040 handler => 'method_name',
3044 A "unary operator" is a SQL syntactic clause that can be
3045 applied to a field - the operator goes before the field
3047 You can write your own operator handlers - supply a C<unary_ops>
3048 argument to the C<new> method. That argument takes an arrayref of
3049 operator definitions; each operator definition is a hashref with two
3056 the regular expression to match the operator
3060 Either a coderef or a plain scalar method name. In both cases
3061 the expected return is C<< $sql >>.
3063 When supplied with a method name, it is simply called on the
3064 L<SQL::Abstract> object as:
3066 $self->$method_name($op, $arg)
3070 $op is the part that matched the handler regex
3071 $arg is the RHS or argument of the operator
3073 When supplied with a coderef, it is called as:
3075 $coderef->($self, $op, $arg)
3083 Thanks to some benchmarking by Mark Stosberg, it turns out that
3084 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3085 I must admit this wasn't an intentional design issue, but it's a
3086 byproduct of the fact that you get to control your C<DBI> handles
3089 To maximize performance, use a code snippet like the following:
3091 # prepare a statement handle using the first row
3092 # and then reuse it for the rest of the rows
3094 for my $href (@array_of_hashrefs) {
3095 $stmt ||= $sql->insert('table', $href);
3096 $sth ||= $dbh->prepare($stmt);
3097 $sth->execute($sql->values($href));
3100 The reason this works is because the keys in your C<$href> are sorted
3101 internally by B<SQL::Abstract>. Thus, as long as your data retains
3102 the same structure, you only have to generate the SQL the first time
3103 around. On subsequent queries, simply use the C<values> function provided
3104 by this module to return your values in the correct order.
3106 However this depends on the values having the same type - if, for
3107 example, the values of a where clause may either have values
3108 (resulting in sql of the form C<column = ?> with a single bind
3109 value), or alternatively the values might be C<undef> (resulting in
3110 sql of the form C<column IS NULL> with no bind value) then the
3111 caching technique suggested will not work.
3115 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3116 really like this part (I do, at least). Building up a complex query
3117 can be as simple as the following:
3124 use CGI::FormBuilder;
3127 my $form = CGI::FormBuilder->new(...);
3128 my $sql = SQL::Abstract->new;
3130 if ($form->submitted) {
3131 my $field = $form->field;
3132 my $id = delete $field->{id};
3133 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3136 Of course, you would still have to connect using C<DBI> to run the
3137 query, but the point is that if you make your form look like your
3138 table, the actual query script can be extremely simplistic.
3140 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3141 a fast interface to returning and formatting data. I frequently
3142 use these three modules together to write complex database query
3143 apps in under 50 lines.
3145 =head1 HOW TO CONTRIBUTE
3147 Contributions are always welcome, in all usable forms (we especially
3148 welcome documentation improvements). The delivery methods include git-
3149 or unified-diff formatted patches, GitHub pull requests, or plain bug
3150 reports either via RT or the Mailing list. Contributors are generally
3151 granted full access to the official repository after their first several
3152 patches pass successful review.
3154 This project is maintained in a git repository. The code and related tools are
3155 accessible at the following locations:
3159 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3161 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3163 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3165 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3171 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3172 Great care has been taken to preserve the I<published> behavior
3173 documented in previous versions in the 1.* family; however,
3174 some features that were previously undocumented, or behaved
3175 differently from the documentation, had to be changed in order
3176 to clarify the semantics. Hence, client code that was relying
3177 on some dark areas of C<SQL::Abstract> v1.*
3178 B<might behave differently> in v1.50.
3180 The main changes are:
3186 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3190 support for the { operator => \"..." } construct (to embed literal SQL)
3194 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3198 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3202 defensive programming: check arguments
3206 fixed bug with global logic, which was previously implemented
3207 through global variables yielding side-effects. Prior versions would
3208 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3209 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3210 Now this is interpreted
3211 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3216 fixed semantics of _bindtype on array args
3220 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3221 we just avoid shifting arrays within that tree.
3225 dropped the C<_modlogic> function
3229 =head1 ACKNOWLEDGEMENTS
3231 There are a number of individuals that have really helped out with
3232 this module. Unfortunately, most of them submitted bugs via CPAN
3233 so I have no idea who they are! But the people I do know are:
3235 Ash Berlin (order_by hash term support)
3236 Matt Trout (DBIx::Class support)
3237 Mark Stosberg (benchmarking)
3238 Chas Owens (initial "IN" operator support)
3239 Philip Collins (per-field SQL functions)
3240 Eric Kolve (hashref "AND" support)
3241 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3242 Dan Kubb (support for "quote_char" and "name_sep")
3243 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3244 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3245 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3246 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3247 Oliver Charles (support for "RETURNING" after "INSERT")
3253 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3257 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3259 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3261 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3262 While not an official support venue, C<DBIx::Class> makes heavy use of
3263 C<SQL::Abstract>, and as such list members there are very familiar with
3264 how to create queries.
3268 This module is free software; you may copy this under the same
3269 terms as perl itself (either the GNU General Public License or
3270 the Artistic License)