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/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
45 #======================================================================
46 # DEBUGGING AND ERROR REPORTING
47 #======================================================================
50 return unless $_[0]->{debug}; shift; # a little faster
51 my $func = (caller(1))[3];
52 warn "[$func] ", @_, "\n";
56 my($func) = (caller(1))[3];
57 Carp::carp "[$func] Warning: ", @_;
61 my($func) = (caller(1))[3];
62 Carp::croak "[$func] Fatal: ", @_;
65 sub is_literal_value ($) {
66 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
67 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
71 # FIXME XSify - this can be done so much more efficiently
72 sub is_plain_value ($) {
74 ! length ref $_[0] ? \($_[0])
76 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
78 exists $_[0]->{-value}
79 ) ? \($_[0]->{-value})
81 # reuse @_ for even moar speedz
82 defined ( $_[1] = Scalar::Util::blessed $_[0] )
84 # deliberately not using Devel::OverloadInfo - the checks we are
85 # intersted in are much more limited than the fullblown thing, and
86 # this is a very hot piece of code
88 # simply using ->can('(""') can leave behind stub methods that
89 # break actually using the overload later (see L<perldiag/Stub
90 # found while resolving method "%s" overloading "%s" in package
91 # "%s"> and the source of overload::mycan())
93 # either has stringification which DBI SHOULD prefer out of the box
94 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
96 # has nummification or boolification, AND fallback is *not* disabled
98 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
101 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
103 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
107 # no fallback specified at all
108 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
110 # fallback explicitly undef
111 ! defined ${"$_[3]::()"}
124 #======================================================================
126 #======================================================================
130 my $class = ref($self) || $self;
131 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
133 # choose our case by keeping an option around
134 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
136 # default logic for interpreting arrayrefs
137 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
139 # how to return bind vars
140 $opt{bindtype} ||= 'normal';
142 # default comparison is "=", but can be overridden
145 # try to recognize which are the 'equality' and 'inequality' ops
146 # (temporary quickfix (in 2007), should go through a more seasoned API)
147 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
148 $opt{inequality_op} = qr/^( != | <> )$/ix;
150 $opt{like_op} = qr/^ (is\s+)? r?like $/xi;
151 $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
154 $opt{sqltrue} ||= '1=1';
155 $opt{sqlfalse} ||= '0=1';
158 $opt{special_ops} ||= [];
160 # regexes are applied in order, thus push after user-defines
161 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
163 if ($class->isa('DBIx::Class::SQLMaker')) {
164 push @{$opt{special_ops}}, our $DBIC_Compat_Op ||= {
165 regex => qr/^(?:ident|value)$/i, handler => sub { die "NOPE" }
167 $opt{is_dbic_sqlmaker} = 1;
171 $opt{unary_ops} ||= [];
173 # rudimentary sanity-check for user supplied bits treated as functions/operators
174 # If a purported function matches this regular expression, an exception is thrown.
175 # Literal SQL is *NOT* subject to this check, only functions (and column names
176 # when quoting is not in effect)
179 # need to guard against ()'s in column names too, but this will break tons of
180 # hacks... ideas anyone?
181 $opt{injection_guard} ||= qr/
188 (map +("-$_", "_render_$_"), qw(op func bind ident literal list)),
192 $opt{expand_unary} = {};
195 -ident => '_expand_ident',
196 -value => sub { +{ -bind => [ our $Cur_Col_Meta, $_[2] ] } },
199 return bless \%opt, $class;
202 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
203 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
205 sub _assert_pass_injection_guard {
206 if ($_[1] =~ $_[0]->{injection_guard}) {
207 my $class = ref $_[0];
208 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
209 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
210 . "{injection_guard} attribute to ${class}->new()"
215 #======================================================================
217 #======================================================================
221 my $table = $self->_table(shift);
222 my $data = shift || return;
225 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
226 my ($sql, @bind) = $self->$method($data);
227 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
229 if ($options->{returning}) {
230 my ($s, @b) = $self->_insert_returning($options);
235 return wantarray ? ($sql, @bind) : $sql;
238 # So that subclasses can override INSERT ... RETURNING separately from
239 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
240 sub _insert_returning { shift->_returning(@_) }
243 my ($self, $options) = @_;
245 my $f = $options->{returning};
247 my ($sql, @bind) = $self->render_aqt(
248 $self->_expand_maybe_list_expr($f, undef, -ident)
251 ? $self->_sqlcase(' returning ') . $sql
252 : ($self->_sqlcase(' returning ').$sql, @bind);
255 sub _insert_HASHREF { # explicit list of fields and then values
256 my ($self, $data) = @_;
258 my @fields = sort keys %$data;
260 my ($sql, @bind) = $self->_insert_values($data);
263 $_ = $self->_quote($_) foreach @fields;
264 $sql = "( ".join(", ", @fields).") ".$sql;
266 return ($sql, @bind);
269 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
270 my ($self, $data) = @_;
272 # no names (arrayref) so can't generate bindtype
273 $self->{bindtype} ne 'columns'
274 or belch "can't do 'columns' bindtype when called with arrayref";
276 my (@values, @all_bind);
277 foreach my $value (@$data) {
278 my ($values, @bind) = $self->_insert_value(undef, $value);
279 push @values, $values;
280 push @all_bind, @bind;
282 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
283 return ($sql, @all_bind);
286 sub _insert_ARRAYREFREF { # literal SQL with bind
287 my ($self, $data) = @_;
289 my ($sql, @bind) = @${$data};
290 $self->_assert_bindval_matches_bindtype(@bind);
292 return ($sql, @bind);
296 sub _insert_SCALARREF { # literal SQL without bind
297 my ($self, $data) = @_;
303 my ($self, $data) = @_;
305 my (@values, @all_bind);
306 foreach my $column (sort keys %$data) {
307 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
308 push @values, $values;
309 push @all_bind, @bind;
311 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
312 return ($sql, @all_bind);
316 my ($self, $column, $v) = @_;
318 return $self->render_aqt(
319 $self->_expand_insert_value($column, $v)
323 sub _expand_insert_value {
324 my ($self, $column, $v) = @_;
326 if (ref($v) eq 'ARRAY') {
327 if ($self->{array_datatypes}) {
328 return +{ -bind => [ $column, $v ] };
330 my ($sql, @bind) = @$v;
331 $self->_assert_bindval_matches_bindtype(@bind);
332 return +{ -literal => $v };
334 if (ref($v) eq 'HASH') {
335 if (grep !/^-/, keys %$v) {
336 belch "HASH ref as bind value in insert is not supported";
337 return +{ -bind => [ $column, $v ] };
341 return +{ -bind => [ $column, undef ] };
343 local our $Cur_Col_Meta = $column;
344 return $self->expand_expr($v);
349 #======================================================================
351 #======================================================================
356 my $table = $self->_table(shift);
357 my $data = shift || return;
361 # first build the 'SET' part of the sql statement
362 puke "Unsupported data type specified to \$sql->update"
363 unless ref $data eq 'HASH';
365 my ($sql, @all_bind) = $self->_update_set_values($data);
366 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
370 my($where_sql, @where_bind) = $self->where($where);
372 push @all_bind, @where_bind;
375 if ($options->{returning}) {
376 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
377 $sql .= $returning_sql;
378 push @all_bind, @returning_bind;
381 return wantarray ? ($sql, @all_bind) : $sql;
384 sub _update_set_values {
385 my ($self, $data) = @_;
387 return $self->render_aqt(
388 $self->_expand_update_set_values($data),
392 sub _expand_update_set_values {
393 my ($self, $data) = @_;
394 $self->_expand_maybe_list_expr( [
397 $set = { -bind => $_ } unless defined $set;
398 +{ -op => [ '=', $self->_expand_ident(-ident => $k), $set ] };
404 ? ($self->{array_datatypes}
405 ? [ $k, +{ -bind => [ $k, $v ] } ]
406 : [ $k, +{ -literal => $v } ])
408 local our $Cur_Col_Meta = $k;
409 [ $k, $self->_expand_expr($v) ]
416 # So that subclasses can override UPDATE ... RETURNING separately from
418 sub _update_returning { shift->_returning(@_) }
422 #======================================================================
424 #======================================================================
429 my $table = $self->_table(shift);
430 my $fields = shift || '*';
434 my ($fields_sql, @bind) = $self->_select_fields($fields);
436 my ($where_sql, @where_bind) = $self->where($where, $order);
437 push @bind, @where_bind;
439 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
440 $self->_sqlcase('from'), $table)
443 return wantarray ? ($sql, @bind) : $sql;
447 my ($self, $fields) = @_;
448 return $fields unless ref($fields);
449 return $self->render_aqt(
450 $self->_expand_maybe_list_expr($fields, undef, '-ident')
454 #======================================================================
456 #======================================================================
461 my $table = $self->_table(shift);
465 my($where_sql, @bind) = $self->where($where);
466 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
468 if ($options->{returning}) {
469 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
470 $sql .= $returning_sql;
471 push @bind, @returning_bind;
474 return wantarray ? ($sql, @bind) : $sql;
477 # So that subclasses can override DELETE ... RETURNING separately from
479 sub _delete_returning { shift->_returning(@_) }
483 #======================================================================
485 #======================================================================
489 # Finally, a separate routine just to handle WHERE clauses
491 my ($self, $where, $order) = @_;
493 local $self->{convert_where} = $self->{convert};
496 my ($sql, @bind) = defined($where)
497 ? $self->_recurse_where($where)
499 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
503 my ($order_sql, @order_bind) = $self->_order_by($order);
505 push @bind, @order_bind;
508 return wantarray ? ($sql, @bind) : $sql;
512 my ($self, $expr, $default_scalar_to) = @_;
513 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
514 $self->_expand_expr($expr);
518 my ($self, $aqt) = @_;
519 my ($k, $v, @rest) = %$aqt;
521 if (my $meth = $self->{render}{$k}) {
522 return $self->$meth($v);
524 die "notreached: $k";
528 my ($self, $expr) = @_;
529 $self->render_aqt($self->expand_expr($expr));
533 my ($self, $expr, $logic) = @_;
534 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
535 return undef unless defined($expr);
536 if (ref($expr) eq 'HASH') {
537 return undef unless my $kc = keys %$expr;
542 map $self->_expand_expr({ $_ => $expr->{$_} }, $logic),
546 my ($key, $value) = %$expr;
547 if (my $exp = $self->{expand}{$key}) {
548 return $self->$exp($key, $value);
550 return $self->_expand_expr_hashpair($key, $value, $logic);
552 if (ref($expr) eq 'ARRAY') {
553 my $logic = lc($logic || $self->{logic});
554 $logic eq 'and' or $logic eq 'or' or puke "unknown logic: $logic";
557 (ref($_) eq 'ARRAY' and @$_)
558 or (ref($_) eq 'HASH' and %$_)
564 while (my ($el) = splice @expr, 0, 1) {
565 puke "Supplying an empty left hand side argument is not supported in array-pairs"
566 unless defined($el) and length($el);
567 my $elref = ref($el);
569 local $Expand_Depth = 0;
570 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
571 } elsif ($elref eq 'ARRAY') {
572 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
573 } elsif (my $l = is_literal_value($el)) {
574 push @res, { -literal => $l };
575 } elsif ($elref eq 'HASH') {
576 local $Expand_Depth = 0;
577 push @res, grep defined, $self->_expand_expr($el) if %$el;
583 # return $res[0] if @res == 1;
584 return { -op => [ $logic, @res ] };
586 if (my $literal = is_literal_value($expr)) {
587 return +{ -literal => $literal };
589 if (!ref($expr) or Scalar::Util::blessed($expr)) {
590 if (my $d = our $Default_Scalar_To) {
591 return $self->_expand_expr({ $d => $expr });
593 if (my $m = our $Cur_Col_Meta) {
594 return +{ -bind => [ $m, $expr ] };
596 return +{ -bind => [ undef, $expr ] };
601 sub _expand_expr_hashpair {
602 my ($self, $k, $v, $logic) = @_;
603 unless (defined($k) and length($k)) {
604 if (defined($k) and my $literal = is_literal_value($v)) {
605 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
606 return { -literal => $literal };
608 puke "Supplying an empty left hand side argument is not supported";
611 $self->_assert_pass_injection_guard($k =~ /^-(.*)$/s);
612 if ($k =~ s/ [_\s]? \d+ $//x ) {
613 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
614 . "You probably wanted ...-and => [ $k => COND1, $k => COND2 ... ]";
617 # DBIx::Class requires a nest warning to be emitted once but the private
618 # method it overrode to do so no longer exists
619 if ($self->{is_dbic_sqlmaker}) {
620 unless (our $Nest_Warned) {
622 "-nest in search conditions is deprecated, you most probably wanted:\n"
623 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
628 return $self->_expand_expr($v);
632 return $self->_expand_expr($v);
634 puke "-bool => undef not supported" unless defined($v);
635 return $self->_expand_ident(-ident => $v);
638 return { -op => [ 'not', $self->_expand_expr($v) ] };
640 if (my ($rest) = $k =~/^-not[_ ](.*)$/) {
643 $self->_expand_expr({ "-${rest}", $v }, $logic)
646 if (my ($logic) = $k =~ /^-(and|or)$/i) {
647 if (ref($v) eq 'HASH') {
648 return $self->_expand_expr($v, $logic);
650 if (ref($v) eq 'ARRAY') {
651 return $self->_expand_expr($v, $logic);
656 $op =~ s/^-// if length($op) > 1;
658 # top level special ops are illegal in general
659 # note that, arguably, if it makes no sense at top level, it also
660 # makes no sense on the other side of an = sign or similar but DBIC
661 # gets disappointingly upset if I disallow it
663 (our $Expand_Depth) == 1
664 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
666 puke "Illegal use of top-level '-$op'"
668 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
669 return { -op => [ $op, $v ] };
672 if (my $custom = $self->{expand_unary}{$k}) {
673 return $self->$custom($v);
675 if ($self->{render}{$k}) {
681 and (keys %$v)[0] =~ /^-/
683 my ($func) = $k =~ /^-(.*)$/;
684 if (List::Util::first { $func =~ $_->{regex} } @{$self->{special_ops}}) {
685 return +{ -op => [ $func, $self->_expand_expr($v) ] };
687 return +{ -func => [ $func, $self->_expand_expr($v) ] };
689 if (!ref($v) or is_literal_value($v)) {
690 return +{ -op => [ $k =~ /^-(.*)$/, $self->_expand_expr($v) ] };
697 and exists $v->{-value}
698 and not defined $v->{-value}
701 return $self->_expand_expr({ $k => { $self->{cmp} => undef } });
703 if (!ref($v) or Scalar::Util::blessed($v)) {
704 my $d = our $Default_Scalar_To;
708 $self->_expand_ident(-ident => $k),
710 ? $self->_expand_expr($d => $v)
711 : { -bind => [ $k, $v ] }
716 if (ref($v) eq 'HASH') {
720 map $self->_expand_expr({ $k => { $_ => $v->{$_} } }),
724 return undef unless keys %$v;
726 my $op = join ' ', split '_', (map lc, $vk =~ /^-?(.*)$/)[0];
727 $self->_assert_pass_injection_guard($op);
728 if ($op =~ s/ [_\s]? \d+ $//x ) {
729 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
730 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
732 if ($op =~ /^(?:not )?between$/) {
733 local our $Cur_Col_Meta = $k;
734 my @rhs = map $self->_expand_expr($_),
735 ref($vv) eq 'ARRAY' ? @$vv : $vv;
737 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
739 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
741 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
745 $self->_expand_ident(-ident => $k),
749 if ($op =~ /^(?:not )?in$/) {
750 if (my $literal = is_literal_value($vv)) {
751 my ($sql, @bind) = @$literal;
752 my $opened_sql = $self->_open_outer_paren($sql);
754 $op, $self->_expand_ident(-ident => $k),
755 [ { -literal => [ $opened_sql, @bind ] } ]
759 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
760 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
761 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
762 . 'will emit the logically correct SQL instead of raising this exception)'
764 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
766 my @rhs = map $self->_expand_expr($_),
767 map { ref($_) ? $_ : { -bind => [ $k, $_ ] } }
768 map { defined($_) ? $_: puke($undef_err) }
769 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
770 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
774 $self->_expand_ident(-ident => $k),
778 if ($op eq 'ident') {
779 if (! defined $vv or (ref($vv) and ref($vv) eq 'ARRAY')) {
780 puke "-$op requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
784 $self->_expand_ident(-ident => $k),
785 $self->_expand_ident(-ident => $vv),
788 if ($op eq 'value') {
789 return $self->_expand_expr({ $k, undef }) unless defined($vv);
792 $self->_expand_ident(-ident => $k),
793 { -bind => [ $k, $vv ] }
796 if ($op =~ /^is(?: not)?$/) {
797 puke "$op can only take undef as argument"
801 and exists($vv->{-value})
802 and !defined($vv->{-value})
804 return +{ -op => [ $op.' null', $self->_expand_ident(-ident => $k) ] };
806 if ($op =~ /^(and|or)$/) {
807 if (ref($vv) eq 'HASH') {
810 map $self->_expand_expr({ $k, { $_ => $vv->{$_} } }),
815 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
816 return { -op => [ $op, $self->_expand_ident(-ident => $k), $vv ] };
818 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
821 $self->_expand_ident(-ident => $k),
822 { -op => [ $op, $vv ] }
825 if (ref($vv) eq 'ARRAY') {
826 my ($logic, @values) = (
827 (defined($vv->[0]) and $vv->[0] =~ /^-(and|or)$/i)
832 $op =~ $self->{inequality_op}
833 or $op =~ $self->{not_like_op}
835 if (lc($logic) eq '-or' and @values > 1) {
836 belch "A multi-element arrayref as an argument to the inequality op '${\uc($op)}' "
837 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
838 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
843 # try to DWIM on equality operators
845 $op =~ $self->{equality_op} ? $self->sqlfalse
846 : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqlfalse
847 : $op =~ $self->{inequality_op} ? $self->sqltrue
848 : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqltrue
849 : puke "operator '$op' applied on an empty array (field '$k')";
853 map $self->_expand_expr({ $k => { $vk => $_ } }),
861 and exists $vv->{-value}
862 and not defined $vv->{-value}
866 $op =~ /^not$/i ? 'is not' # legacy
867 : $op =~ $self->{equality_op} ? 'is'
868 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
869 : $op =~ $self->{inequality_op} ? 'is not'
870 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
871 : puke "unexpected operator '$op' with undef operand";
872 return +{ -op => [ $is.' null', $self->_expand_ident(-ident => $k) ] };
874 local our $Cur_Col_Meta = $k;
877 $self->_expand_ident(-ident => $k),
878 $self->_expand_expr($vv)
881 if (ref($v) eq 'ARRAY') {
882 return $self->sqlfalse unless @$v;
883 $self->_debug("ARRAY($k) means distribute over elements");
885 $v->[0] =~ /^-((?:and|or))$/i
886 ? ($v = [ @{$v}[1..$#$v] ], $1)
887 : ($self->{logic} || 'or')
891 map $self->_expand_expr({ $k => $_ }, $this_logic), @$v
894 if (my $literal = is_literal_value($v)) {
896 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
899 my ($sql, @bind) = @$literal;
900 if ($self->{bindtype} eq 'columns') {
902 $self->_assert_bindval_matches_bindtype($_);
905 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
911 my ($self, undef, $body) = @_;
912 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
913 ref($body) ? @$body : $body;
914 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
915 unless ($self->{quote_char}) {
916 $self->_assert_pass_injection_guard($_) for @parts;
918 return +{ -ident => \@parts };
922 my ($self, $where, $logic) = @_;
924 # Special case: top level simple string treated as literal
926 my $where_exp = (ref($where)
927 ? $self->_expand_expr($where, $logic)
928 : { -literal => [ $where ] });
930 # dispatch expanded expression
932 my ($sql, @bind) = defined($where_exp) ? $self->render_aqt($where_exp) : (undef);
933 # DBIx::Class used to call _recurse_where in scalar context
934 # something else might too...
936 return ($sql, @bind);
939 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
945 my ($self, $ident) = @_;
947 return $self->_convert($self->_quote($ident));
950 my %unop_postfix = map +($_ => 1),
951 'is null', 'is not null',
959 my ($self, $args) = @_;
960 my ($left, $low, $high) = @$args;
961 my ($rhsql, @rhbind) = do {
963 puke "Single arg to between must be a literal"
964 unless $low->{-literal};
967 my ($l, $h) = map [ $self->render_aqt($_) ], $low, $high;
968 (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]),
969 @{$l}[1..$#$l], @{$h}[1..$#$h])
972 my ($lhsql, @lhbind) = $self->render_aqt($left);
974 join(' ', '(', $lhsql, $self->_sqlcase($op), $rhsql, ')'),
978 }), 'between', 'not between'),
982 my ($self, $args) = @_;
983 my ($lhs, $rhs) = @$args;
986 my ($sql, @bind) = $self->render_aqt($_);
987 push @in_bind, @bind;
990 my ($lhsql, @lbind) = $self->render_aqt($lhs);
992 $lhsql.' '.$self->_sqlcase($op).' ( '
1002 my ($self, $v) = @_;
1003 my ($op, @args) = @$v;
1004 $op =~ s/^-// if length($op) > 1;
1006 if (my $h = $special{$op}) {
1007 return $self->$h(\@args);
1009 my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1010 if ($us and @args > 1) {
1011 puke "Special op '${op}' requires first value to be identifier"
1012 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1013 my $k = join(($self->{name_sep}||'.'), @$ident);
1014 local our $Expand_Depth = 1;
1015 return $self->${\($us->{handler})}($k, $op, $args[1]);
1017 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1018 return $self->${\($us->{handler})}($op, $args[0]);
1020 my $final_op = $op =~ /^(?:is|not)_/ ? join(' ', split '_', $op) : $op;
1021 if (@args == 1 and $op !~ /^(and|or)$/) {
1022 my ($expr_sql, @bind) = $self->render_aqt($args[0]);
1023 my $op_sql = $self->_sqlcase($final_op);
1025 $unop_postfix{lc($final_op)}
1026 ? "${expr_sql} ${op_sql}"
1027 : "${op_sql} ${expr_sql}"
1029 return (($op eq 'not' || $us ? '('.$final_sql.')' : $final_sql), @bind);
1031 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @args;
1032 return '' unless @parts;
1033 my $is_andor = !!($op =~ /^(and|or)$/);
1034 return @{$parts[0]} if $is_andor and @parts == 1;
1035 my ($final_sql) = map +($is_andor ? "( ${_} )" : $_), join(
1036 ' '.$self->_sqlcase($final_op).' ',
1041 map @{$_}[1..$#$_], @parts
1048 my ($self, $list) = @_;
1049 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @$list;
1050 return join(', ', map $_->[0], @parts), map @{$_}[1..$#$_], @parts;
1054 my ($self, $rest) = @_;
1055 my ($func, @args) = @$rest;
1059 push @arg_sql, shift @x;
1061 } map [ $self->render_aqt($_) ], @args;
1062 return ($self->_sqlcase($func).'('.join(', ', @arg_sql).')', @bind);
1066 my ($self, $bind) = @_;
1067 return ($self->_convert('?'), $self->_bindtype(@$bind));
1070 sub _render_literal {
1071 my ($self, $literal) = @_;
1072 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1076 # Some databases (SQLite) treat col IN (1, 2) different from
1077 # col IN ( (1, 2) ). Use this to strip all outer parens while
1078 # adding them back in the corresponding method
1079 sub _open_outer_paren {
1080 my ($self, $sql) = @_;
1082 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1084 # there are closing parens inside, need the heavy duty machinery
1085 # to reevaluate the extraction starting from $sql (full reevaluation)
1086 if ($inner =~ /\)/) {
1087 require Text::Balanced;
1089 my (undef, $remainder) = do {
1090 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1092 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1095 # the entire expression needs to be a balanced bracketed thing
1096 # (after an extract no remainder sans trailing space)
1097 last if defined $remainder and $remainder =~ /\S/;
1107 #======================================================================
1109 #======================================================================
1111 sub _expand_order_by {
1112 my ($self, $arg) = @_;
1114 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1116 my $expander = sub {
1117 my ($self, $dir, $expr) = @_;
1118 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1119 foreach my $arg (@to_expand) {
1123 and grep /^-(asc|desc)$/, keys %$arg
1125 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1128 my @exp = map +(defined($dir) ? { -op => [ $dir => $_ ] } : $_),
1129 map $self->expand_expr($_, -ident),
1130 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1131 return (@exp > 1 ? { -list => \@exp } : $exp[0]);
1134 local @{$self->{expand_unary}}{qw(-asc -desc)} = (
1135 sub { shift->$expander(asc => @_) },
1136 sub { shift->$expander(desc => @_) },
1139 return $self->$expander(undef, $arg);
1143 my ($self, $arg) = @_;
1145 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1147 my ($sql, @bind) = $self->render_aqt($expanded);
1149 return '' unless length($sql);
1151 my $final_sql = $self->_sqlcase(' order by ').$sql;
1153 return wantarray ? ($final_sql, @bind) : $final_sql;
1156 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1158 sub _order_by_chunks {
1159 my ($self, $arg) = @_;
1161 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1163 return $self->_chunkify_order_by($expanded);
1166 sub _chunkify_order_by {
1167 my ($self, $expanded) = @_;
1169 return grep length, $self->render_aqt($expanded)
1170 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1173 if (ref() eq 'HASH' and my $l = $_->{-list}) {
1174 return map $self->_chunkify_order_by($_), @$l;
1176 return [ $self->render_aqt($_) ];
1180 #======================================================================
1181 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1182 #======================================================================
1188 $self->_expand_maybe_list_expr($from, undef, -ident)
1193 #======================================================================
1195 #======================================================================
1197 sub _expand_maybe_list_expr {
1198 my ($self, $expr, $logic, $default) = @_;
1200 if (ref($expr) eq 'ARRAY') {
1202 map $self->expand_expr($_, $default), @$expr
1209 return $self->expand_expr($e, $default);
1212 # highly optimized, as it's called way too often
1214 # my ($self, $label) = @_;
1216 return '' unless defined $_[1];
1217 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1218 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1220 unless ($_[0]->{quote_char}) {
1221 if (ref($_[1]) eq 'ARRAY') {
1222 return join($_[0]->{name_sep}||'.', @{$_[1]});
1224 $_[0]->_assert_pass_injection_guard($_[1]);
1229 my $qref = ref $_[0]->{quote_char};
1231 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1232 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1233 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1235 my $esc = $_[0]->{escape_char} || $r;
1237 # parts containing * are naturally unquoted
1239 $_[0]->{name_sep}||'',
1243 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1245 (ref($_[1]) eq 'ARRAY'
1249 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1257 # Conversion, if applicable
1259 #my ($self, $arg) = @_;
1260 if ($_[0]->{convert_where}) {
1261 return $_[0]->_sqlcase($_[0]->{convert_where}) .'(' . $_[1] . ')';
1268 #my ($self, $col, @vals) = @_;
1269 # called often - tighten code
1270 return $_[0]->{bindtype} eq 'columns'
1271 ? map {[$_[1], $_]} @_[2 .. $#_]
1276 # Dies if any element of @bind is not in [colname => value] format
1277 # if bindtype is 'columns'.
1278 sub _assert_bindval_matches_bindtype {
1279 # my ($self, @bind) = @_;
1281 if ($self->{bindtype} eq 'columns') {
1283 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1284 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1290 sub _join_sql_clauses {
1291 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1293 if (@$clauses_aref > 1) {
1294 my $join = " " . $self->_sqlcase($logic) . " ";
1295 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1296 return ($sql, @$bind_aref);
1298 elsif (@$clauses_aref) {
1299 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1302 return (); # if no SQL, ignore @$bind_aref
1307 # Fix SQL case, if so requested
1309 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1310 # don't touch the argument ... crooked logic, but let's not change it!
1311 return $_[0]->{case} ? $_[1] : uc($_[1]);
1315 #======================================================================
1316 # DISPATCHING FROM REFKIND
1317 #======================================================================
1320 my ($self, $data) = @_;
1322 return 'UNDEF' unless defined $data;
1324 # blessed objects are treated like scalars
1325 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1327 return 'SCALAR' unless $ref;
1330 while ($ref eq 'REF') {
1332 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1336 return ($ref||'SCALAR') . ('REF' x $n_steps);
1340 my ($self, $data) = @_;
1341 my @try = ($self->_refkind($data));
1342 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1343 push @try, 'FALLBACK';
1347 sub _METHOD_FOR_refkind {
1348 my ($self, $meth_prefix, $data) = @_;
1351 for (@{$self->_try_refkind($data)}) {
1352 $method = $self->can($meth_prefix."_".$_)
1356 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1360 sub _SWITCH_refkind {
1361 my ($self, $data, $dispatch_table) = @_;
1364 for (@{$self->_try_refkind($data)}) {
1365 $coderef = $dispatch_table->{$_}
1369 puke "no dispatch entry for ".$self->_refkind($data)
1378 #======================================================================
1379 # VALUES, GENERATE, AUTOLOAD
1380 #======================================================================
1382 # LDNOTE: original code from nwiger, didn't touch code in that section
1383 # I feel the AUTOLOAD stuff should not be the default, it should
1384 # only be activated on explicit demand by user.
1388 my $data = shift || return;
1389 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1390 unless ref $data eq 'HASH';
1393 foreach my $k (sort keys %$data) {
1394 my $v = $data->{$k};
1395 $self->_SWITCH_refkind($v, {
1397 if ($self->{array_datatypes}) { # array datatype
1398 push @all_bind, $self->_bindtype($k, $v);
1400 else { # literal SQL with bind
1401 my ($sql, @bind) = @$v;
1402 $self->_assert_bindval_matches_bindtype(@bind);
1403 push @all_bind, @bind;
1406 ARRAYREFREF => sub { # literal SQL with bind
1407 my ($sql, @bind) = @${$v};
1408 $self->_assert_bindval_matches_bindtype(@bind);
1409 push @all_bind, @bind;
1411 SCALARREF => sub { # literal SQL without bind
1413 SCALAR_or_UNDEF => sub {
1414 push @all_bind, $self->_bindtype($k, $v);
1425 my(@sql, @sqlq, @sqlv);
1429 if ($ref eq 'HASH') {
1430 for my $k (sort keys %$_) {
1433 my $label = $self->_quote($k);
1434 if ($r eq 'ARRAY') {
1435 # literal SQL with bind
1436 my ($sql, @bind) = @$v;
1437 $self->_assert_bindval_matches_bindtype(@bind);
1438 push @sqlq, "$label = $sql";
1440 } elsif ($r eq 'SCALAR') {
1441 # literal SQL without bind
1442 push @sqlq, "$label = $$v";
1444 push @sqlq, "$label = ?";
1445 push @sqlv, $self->_bindtype($k, $v);
1448 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1449 } elsif ($ref eq 'ARRAY') {
1450 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1453 if ($r eq 'ARRAY') { # literal SQL with bind
1454 my ($sql, @bind) = @$v;
1455 $self->_assert_bindval_matches_bindtype(@bind);
1458 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1459 # embedded literal SQL
1466 push @sql, '(' . join(', ', @sqlq) . ')';
1467 } elsif ($ref eq 'SCALAR') {
1471 # strings get case twiddled
1472 push @sql, $self->_sqlcase($_);
1476 my $sql = join ' ', @sql;
1478 # this is pretty tricky
1479 # if ask for an array, return ($stmt, @bind)
1480 # otherwise, s/?/shift @sqlv/ to put it inline
1482 return ($sql, @sqlv);
1484 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1485 ref $d ? $d->[1] : $d/e;
1494 # This allows us to check for a local, then _form, attr
1496 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1497 return $self->generate($name, @_);
1508 SQL::Abstract - Generate SQL from Perl data structures
1514 my $sql = SQL::Abstract->new;
1516 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1518 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1520 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1522 my($stmt, @bind) = $sql->delete($table, \%where);
1524 # Then, use these in your DBI statements
1525 my $sth = $dbh->prepare($stmt);
1526 $sth->execute(@bind);
1528 # Just generate the WHERE clause
1529 my($stmt, @bind) = $sql->where(\%where, $order);
1531 # Return values in the same order, for hashed queries
1532 # See PERFORMANCE section for more details
1533 my @bind = $sql->values(\%fieldvals);
1537 This module was inspired by the excellent L<DBIx::Abstract>.
1538 However, in using that module I found that what I really wanted
1539 to do was generate SQL, but still retain complete control over my
1540 statement handles and use the DBI interface. So, I set out to
1541 create an abstract SQL generation module.
1543 While based on the concepts used by L<DBIx::Abstract>, there are
1544 several important differences, especially when it comes to WHERE
1545 clauses. I have modified the concepts used to make the SQL easier
1546 to generate from Perl data structures and, IMO, more intuitive.
1547 The underlying idea is for this module to do what you mean, based
1548 on the data structures you provide it. The big advantage is that
1549 you don't have to modify your code every time your data changes,
1550 as this module figures it out.
1552 To begin with, an SQL INSERT is as easy as just specifying a hash
1553 of C<key=value> pairs:
1556 name => 'Jimbo Bobson',
1557 phone => '123-456-7890',
1558 address => '42 Sister Lane',
1559 city => 'St. Louis',
1560 state => 'Louisiana',
1563 The SQL can then be generated with this:
1565 my($stmt, @bind) = $sql->insert('people', \%data);
1567 Which would give you something like this:
1569 $stmt = "INSERT INTO people
1570 (address, city, name, phone, state)
1571 VALUES (?, ?, ?, ?, ?)";
1572 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1573 '123-456-7890', 'Louisiana');
1575 These are then used directly in your DBI code:
1577 my $sth = $dbh->prepare($stmt);
1578 $sth->execute(@bind);
1580 =head2 Inserting and Updating Arrays
1582 If your database has array types (like for example Postgres),
1583 activate the special option C<< array_datatypes => 1 >>
1584 when creating the C<SQL::Abstract> object.
1585 Then you may use an arrayref to insert and update database array types:
1587 my $sql = SQL::Abstract->new(array_datatypes => 1);
1589 planets => [qw/Mercury Venus Earth Mars/]
1592 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1596 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1598 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1601 =head2 Inserting and Updating SQL
1603 In order to apply SQL functions to elements of your C<%data> you may
1604 specify a reference to an arrayref for the given hash value. For example,
1605 if you need to execute the Oracle C<to_date> function on a value, you can
1606 say something like this:
1610 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1613 The first value in the array is the actual SQL. Any other values are
1614 optional and would be included in the bind values array. This gives
1617 my($stmt, @bind) = $sql->insert('people', \%data);
1619 $stmt = "INSERT INTO people (name, date_entered)
1620 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1621 @bind = ('Bill', '03/02/2003');
1623 An UPDATE is just as easy, all you change is the name of the function:
1625 my($stmt, @bind) = $sql->update('people', \%data);
1627 Notice that your C<%data> isn't touched; the module will generate
1628 the appropriately quirky SQL for you automatically. Usually you'll
1629 want to specify a WHERE clause for your UPDATE, though, which is
1630 where handling C<%where> hashes comes in handy...
1632 =head2 Complex where statements
1634 This module can generate pretty complicated WHERE statements
1635 easily. For example, simple C<key=value> pairs are taken to mean
1636 equality, and if you want to see if a field is within a set
1637 of values, you can use an arrayref. Let's say we wanted to
1638 SELECT some data based on this criteria:
1641 requestor => 'inna',
1642 worker => ['nwiger', 'rcwe', 'sfz'],
1643 status => { '!=', 'completed' }
1646 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1648 The above would give you something like this:
1650 $stmt = "SELECT * FROM tickets WHERE
1651 ( requestor = ? ) AND ( status != ? )
1652 AND ( worker = ? OR worker = ? OR worker = ? )";
1653 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1655 Which you could then use in DBI code like so:
1657 my $sth = $dbh->prepare($stmt);
1658 $sth->execute(@bind);
1664 The methods are simple. There's one for every major SQL operation,
1665 and a constructor you use first. The arguments are specified in a
1666 similar order for each method (table, then fields, then a where
1667 clause) to try and simplify things.
1669 =head2 new(option => 'value')
1671 The C<new()> function takes a list of options and values, and returns
1672 a new B<SQL::Abstract> object which can then be used to generate SQL
1673 through the methods below. The options accepted are:
1679 If set to 'lower', then SQL will be generated in all lowercase. By
1680 default SQL is generated in "textbook" case meaning something like:
1682 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1684 Any setting other than 'lower' is ignored.
1688 This determines what the default comparison operator is. By default
1689 it is C<=>, meaning that a hash like this:
1691 %where = (name => 'nwiger', email => 'nate@wiger.org');
1693 Will generate SQL like this:
1695 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1697 However, you may want loose comparisons by default, so if you set
1698 C<cmp> to C<like> you would get SQL such as:
1700 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1702 You can also override the comparison on an individual basis - see
1703 the huge section on L</"WHERE CLAUSES"> at the bottom.
1705 =item sqltrue, sqlfalse
1707 Expressions for inserting boolean values within SQL statements.
1708 By default these are C<1=1> and C<1=0>. They are used
1709 by the special operators C<-in> and C<-not_in> for generating
1710 correct SQL even when the argument is an empty array (see below).
1714 This determines the default logical operator for multiple WHERE
1715 statements in arrays or hashes. If absent, the default logic is "or"
1716 for arrays, and "and" for hashes. This means that a WHERE
1720 event_date => {'>=', '2/13/99'},
1721 event_date => {'<=', '4/24/03'},
1724 will generate SQL like this:
1726 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1728 This is probably not what you want given this query, though (look
1729 at the dates). To change the "OR" to an "AND", simply specify:
1731 my $sql = SQL::Abstract->new(logic => 'and');
1733 Which will change the above C<WHERE> to:
1735 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1737 The logic can also be changed locally by inserting
1738 a modifier in front of an arrayref:
1740 @where = (-and => [event_date => {'>=', '2/13/99'},
1741 event_date => {'<=', '4/24/03'} ]);
1743 See the L</"WHERE CLAUSES"> section for explanations.
1747 This will automatically convert comparisons using the specified SQL
1748 function for both column and value. This is mostly used with an argument
1749 of C<upper> or C<lower>, so that the SQL will have the effect of
1750 case-insensitive "searches". For example, this:
1752 $sql = SQL::Abstract->new(convert => 'upper');
1753 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1755 Will turn out the following SQL:
1757 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1759 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1760 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1761 not validate this option; it will just pass through what you specify verbatim).
1765 This is a kludge because many databases suck. For example, you can't
1766 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1767 Instead, you have to use C<bind_param()>:
1769 $sth->bind_param(1, 'reg data');
1770 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1772 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1773 which loses track of which field each slot refers to. Fear not.
1775 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1776 Currently, you can specify either C<normal> (default) or C<columns>. If you
1777 specify C<columns>, you will get an array that looks like this:
1779 my $sql = SQL::Abstract->new(bindtype => 'columns');
1780 my($stmt, @bind) = $sql->insert(...);
1783 [ 'column1', 'value1' ],
1784 [ 'column2', 'value2' ],
1785 [ 'column3', 'value3' ],
1788 You can then iterate through this manually, using DBI's C<bind_param()>.
1790 $sth->prepare($stmt);
1793 my($col, $data) = @$_;
1794 if ($col eq 'details' || $col eq 'comments') {
1795 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1796 } elsif ($col eq 'image') {
1797 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1799 $sth->bind_param($i, $data);
1803 $sth->execute; # execute without @bind now
1805 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1806 Basically, the advantage is still that you don't have to care which fields
1807 are or are not included. You could wrap that above C<for> loop in a simple
1808 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1809 get a layer of abstraction over manual SQL specification.
1811 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
1812 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1813 will expect the bind values in this format.
1817 This is the character that a table or column name will be quoted
1818 with. By default this is an empty string, but you could set it to
1819 the character C<`>, to generate SQL like this:
1821 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1823 Alternatively, you can supply an array ref of two items, the first being the left
1824 hand quote character, and the second the right hand quote character. For
1825 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1826 that generates SQL like this:
1828 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1830 Quoting is useful if you have tables or columns names that are reserved
1831 words in your database's SQL dialect.
1835 This is the character that will be used to escape L</quote_char>s appearing
1836 in an identifier before it has been quoted.
1838 The parameter default in case of a single L</quote_char> character is the quote
1841 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
1842 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
1843 of the B<opening (left)> L</quote_char> within the identifier are currently left
1844 untouched. The default for opening-closing-style quotes may change in future
1845 versions, thus you are B<strongly encouraged> to specify the escape character
1850 This is the character that separates a table and column name. It is
1851 necessary to specify this when the C<quote_char> option is selected,
1852 so that tables and column names can be individually quoted like this:
1854 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1856 =item injection_guard
1858 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1859 column name specified in a query structure. This is a safety mechanism to avoid
1860 injection attacks when mishandling user input e.g.:
1862 my %condition_as_column_value_pairs = get_values_from_user();
1863 $sqla->select( ... , \%condition_as_column_value_pairs );
1865 If the expression matches an exception is thrown. Note that literal SQL
1866 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1868 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1870 =item array_datatypes
1872 When this option is true, arrayrefs in INSERT or UPDATE are
1873 interpreted as array datatypes and are passed directly
1875 When this option is false, arrayrefs are interpreted
1876 as literal SQL, just like refs to arrayrefs
1877 (but this behavior is for backwards compatibility; when writing
1878 new queries, use the "reference to arrayref" syntax
1884 Takes a reference to a list of "special operators"
1885 to extend the syntax understood by L<SQL::Abstract>.
1886 See section L</"SPECIAL OPERATORS"> for details.
1890 Takes a reference to a list of "unary operators"
1891 to extend the syntax understood by L<SQL::Abstract>.
1892 See section L</"UNARY OPERATORS"> for details.
1898 =head2 insert($table, \@values || \%fieldvals, \%options)
1900 This is the simplest function. You simply give it a table name
1901 and either an arrayref of values or hashref of field/value pairs.
1902 It returns an SQL INSERT statement and a list of bind values.
1903 See the sections on L</"Inserting and Updating Arrays"> and
1904 L</"Inserting and Updating SQL"> for information on how to insert
1905 with those data types.
1907 The optional C<\%options> hash reference may contain additional
1908 options to generate the insert SQL. Currently supported options
1915 Takes either a scalar of raw SQL fields, or an array reference of
1916 field names, and adds on an SQL C<RETURNING> statement at the end.
1917 This allows you to return data generated by the insert statement
1918 (such as row IDs) without performing another C<SELECT> statement.
1919 Note, however, this is not part of the SQL standard and may not
1920 be supported by all database engines.
1924 =head2 update($table, \%fieldvals, \%where, \%options)
1926 This takes a table, hashref of field/value pairs, and an optional
1927 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1929 See the sections on L</"Inserting and Updating Arrays"> and
1930 L</"Inserting and Updating SQL"> for information on how to insert
1931 with those data types.
1933 The optional C<\%options> hash reference may contain additional
1934 options to generate the update SQL. Currently supported options
1941 See the C<returning> option to
1942 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
1946 =head2 select($source, $fields, $where, $order)
1948 This returns a SQL SELECT statement and associated list of bind values, as
1949 specified by the arguments:
1955 Specification of the 'FROM' part of the statement.
1956 The argument can be either a plain scalar (interpreted as a table
1957 name, will be quoted), or an arrayref (interpreted as a list
1958 of table names, joined by commas, quoted), or a scalarref
1959 (literal SQL, not quoted).
1963 Specification of the list of fields to retrieve from
1965 The argument can be either an arrayref (interpreted as a list
1966 of field names, will be joined by commas and quoted), or a
1967 plain scalar (literal SQL, not quoted).
1968 Please observe that this API is not as flexible as that of
1969 the first argument C<$source>, for backwards compatibility reasons.
1973 Optional argument to specify the WHERE part of the query.
1974 The argument is most often a hashref, but can also be
1975 an arrayref or plain scalar --
1976 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1980 Optional argument to specify the ORDER BY part of the query.
1981 The argument can be a scalar, a hashref or an arrayref
1982 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1988 =head2 delete($table, \%where, \%options)
1990 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1991 It returns an SQL DELETE statement and list of bind values.
1993 The optional C<\%options> hash reference may contain additional
1994 options to generate the delete SQL. Currently supported options
2001 See the C<returning> option to
2002 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2006 =head2 where(\%where, $order)
2008 This is used to generate just the WHERE clause. For example,
2009 if you have an arbitrary data structure and know what the
2010 rest of your SQL is going to look like, but want an easy way
2011 to produce a WHERE clause, use this. It returns an SQL WHERE
2012 clause and list of bind values.
2015 =head2 values(\%data)
2017 This just returns the values from the hash C<%data>, in the same
2018 order that would be returned from any of the other above queries.
2019 Using this allows you to markedly speed up your queries if you
2020 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2022 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2024 Warning: This is an experimental method and subject to change.
2026 This returns arbitrarily generated SQL. It's a really basic shortcut.
2027 It will return two different things, depending on return context:
2029 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2030 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2032 These would return the following:
2034 # First calling form
2035 $stmt = "CREATE TABLE test (?, ?)";
2036 @bind = (field1, field2);
2038 # Second calling form
2039 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2041 Depending on what you're trying to do, it's up to you to choose the correct
2042 format. In this example, the second form is what you would want.
2046 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2050 ALTER SESSION SET nls_date_format = 'MM/YY'
2052 You get the idea. Strings get their case twiddled, but everything
2053 else remains verbatim.
2055 =head1 EXPORTABLE FUNCTIONS
2057 =head2 is_plain_value
2059 Determines if the supplied argument is a plain value as understood by this
2064 =item * The value is C<undef>
2066 =item * The value is a non-reference
2068 =item * The value is an object with stringification overloading
2070 =item * The value is of the form C<< { -value => $anything } >>
2074 On failure returns C<undef>, on success returns a B<scalar> reference
2075 to the original supplied argument.
2081 The stringification overloading detection is rather advanced: it takes
2082 into consideration not only the presence of a C<""> overload, but if that
2083 fails also checks for enabled
2084 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2085 on either C<0+> or C<bool>.
2087 Unfortunately testing in the field indicates that this
2088 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2089 but only when very large numbers of stringifying objects are involved.
2090 At the time of writing ( Sep 2014 ) there is no clear explanation of
2091 the direct cause, nor is there a manageably small test case that reliably
2092 reproduces the problem.
2094 If you encounter any of the following exceptions in B<random places within
2095 your application stack> - this module may be to blame:
2097 Operation "ne": no method found,
2098 left argument in overloaded package <something>,
2099 right argument in overloaded package <something>
2103 Stub found while resolving method "???" overloading """" in package <something>
2105 If you fall victim to the above - please attempt to reduce the problem
2106 to something that could be sent to the L<SQL::Abstract developers
2107 |DBIx::Class/GETTING HELP/SUPPORT>
2108 (either publicly or privately). As a workaround in the meantime you can
2109 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2110 value, which will most likely eliminate your problem (at the expense of
2111 not being able to properly detect exotic forms of stringification).
2113 This notice and environment variable will be removed in a future version,
2114 as soon as the underlying problem is found and a reliable workaround is
2119 =head2 is_literal_value
2121 Determines if the supplied argument is a literal value as understood by this
2126 =item * C<\$sql_string>
2128 =item * C<\[ $sql_string, @bind_values ]>
2132 On failure returns C<undef>, on success returns an B<array> reference
2133 containing the unpacked version of the supplied literal SQL and bind values.
2135 =head1 WHERE CLAUSES
2139 This module uses a variation on the idea from L<DBIx::Abstract>. It
2140 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2141 module is that things in arrays are OR'ed, and things in hashes
2144 The easiest way to explain is to show lots of examples. After
2145 each C<%where> hash shown, it is assumed you used:
2147 my($stmt, @bind) = $sql->where(\%where);
2149 However, note that the C<%where> hash can be used directly in any
2150 of the other functions as well, as described above.
2152 =head2 Key-value pairs
2154 So, let's get started. To begin, a simple hash:
2158 status => 'completed'
2161 Is converted to SQL C<key = val> statements:
2163 $stmt = "WHERE user = ? AND status = ?";
2164 @bind = ('nwiger', 'completed');
2166 One common thing I end up doing is having a list of values that
2167 a field can be in. To do this, simply specify a list inside of
2172 status => ['assigned', 'in-progress', 'pending'];
2175 This simple code will create the following:
2177 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2178 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2180 A field associated to an empty arrayref will be considered a
2181 logical false and will generate 0=1.
2183 =head2 Tests for NULL values
2185 If the value part is C<undef> then this is converted to SQL <IS NULL>
2194 $stmt = "WHERE user = ? AND status IS NULL";
2197 To test if a column IS NOT NULL:
2201 status => { '!=', undef },
2204 =head2 Specific comparison operators
2206 If you want to specify a different type of operator for your comparison,
2207 you can use a hashref for a given column:
2211 status => { '!=', 'completed' }
2214 Which would generate:
2216 $stmt = "WHERE user = ? AND status != ?";
2217 @bind = ('nwiger', 'completed');
2219 To test against multiple values, just enclose the values in an arrayref:
2221 status => { '=', ['assigned', 'in-progress', 'pending'] };
2223 Which would give you:
2225 "WHERE status = ? OR status = ? OR status = ?"
2228 The hashref can also contain multiple pairs, in which case it is expanded
2229 into an C<AND> of its elements:
2233 status => { '!=', 'completed', -not_like => 'pending%' }
2236 # Or more dynamically, like from a form
2237 $where{user} = 'nwiger';
2238 $where{status}{'!='} = 'completed';
2239 $where{status}{'-not_like'} = 'pending%';
2241 # Both generate this
2242 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2243 @bind = ('nwiger', 'completed', 'pending%');
2246 To get an OR instead, you can combine it with the arrayref idea:
2250 priority => [ { '=', 2 }, { '>', 5 } ]
2253 Which would generate:
2255 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2256 @bind = ('2', '5', 'nwiger');
2258 If you want to include literal SQL (with or without bind values), just use a
2259 scalar reference or reference to an arrayref as the value:
2262 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2263 date_expires => { '<' => \"now()" }
2266 Which would generate:
2268 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2269 @bind = ('11/26/2008');
2272 =head2 Logic and nesting operators
2274 In the example above,
2275 there is a subtle trap if you want to say something like
2276 this (notice the C<AND>):
2278 WHERE priority != ? AND priority != ?
2280 Because, in Perl you I<can't> do this:
2282 priority => { '!=' => 2, '!=' => 1 }
2284 As the second C<!=> key will obliterate the first. The solution
2285 is to use the special C<-modifier> form inside an arrayref:
2287 priority => [ -and => {'!=', 2},
2291 Normally, these would be joined by C<OR>, but the modifier tells it
2292 to use C<AND> instead. (Hint: You can use this in conjunction with the
2293 C<logic> option to C<new()> in order to change the way your queries
2294 work by default.) B<Important:> Note that the C<-modifier> goes
2295 B<INSIDE> the arrayref, as an extra first element. This will
2296 B<NOT> do what you think it might:
2298 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2300 Here is a quick list of equivalencies, since there is some overlap:
2303 status => {'!=', 'completed', 'not like', 'pending%' }
2304 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2307 status => {'=', ['assigned', 'in-progress']}
2308 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2309 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2313 =head2 Special operators: IN, BETWEEN, etc.
2315 You can also use the hashref format to compare a list of fields using the
2316 C<IN> comparison operator, by specifying the list as an arrayref:
2319 status => 'completed',
2320 reportid => { -in => [567, 2335, 2] }
2323 Which would generate:
2325 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2326 @bind = ('completed', '567', '2335', '2');
2328 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2331 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2332 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2333 'sqltrue' (by default: C<1=1>).
2335 In addition to the array you can supply a chunk of literal sql or
2336 literal sql with bind:
2339 customer => { -in => \[
2340 'SELECT cust_id FROM cust WHERE balance > ?',
2343 status => { -in => \'SELECT status_codes FROM states' },
2349 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2350 AND status IN ( SELECT status_codes FROM states )
2354 Finally, if the argument to C<-in> is not a reference, it will be
2355 treated as a single-element array.
2357 Another pair of operators is C<-between> and C<-not_between>,
2358 used with an arrayref of two values:
2362 completion_date => {
2363 -not_between => ['2002-10-01', '2003-02-06']
2369 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2371 Just like with C<-in> all plausible combinations of literal SQL
2375 start0 => { -between => [ 1, 2 ] },
2376 start1 => { -between => \["? AND ?", 1, 2] },
2377 start2 => { -between => \"lower(x) AND upper(y)" },
2378 start3 => { -between => [
2380 \["upper(?)", 'stuff' ],
2387 ( start0 BETWEEN ? AND ? )
2388 AND ( start1 BETWEEN ? AND ? )
2389 AND ( start2 BETWEEN lower(x) AND upper(y) )
2390 AND ( start3 BETWEEN lower(x) AND upper(?) )
2392 @bind = (1, 2, 1, 2, 'stuff');
2395 These are the two builtin "special operators"; but the
2396 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2398 =head2 Unary operators: bool
2400 If you wish to test against boolean columns or functions within your
2401 database you can use the C<-bool> and C<-not_bool> operators. For
2402 example to test the column C<is_user> being true and the column
2403 C<is_enabled> being false you would use:-
2407 -not_bool => 'is_enabled',
2412 WHERE is_user AND NOT is_enabled
2414 If a more complex combination is required, testing more conditions,
2415 then you should use the and/or operators:-
2420 -not_bool => { two=> { -rlike => 'bar' } },
2421 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2432 (NOT ( three = ? OR three > ? ))
2435 =head2 Nested conditions, -and/-or prefixes
2437 So far, we've seen how multiple conditions are joined with a top-level
2438 C<AND>. We can change this by putting the different conditions we want in
2439 hashes and then putting those hashes in an array. For example:
2444 status => { -like => ['pending%', 'dispatched'] },
2448 status => 'unassigned',
2452 This data structure would create the following:
2454 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2455 OR ( user = ? AND status = ? ) )";
2456 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2459 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2460 to change the logic inside:
2466 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2467 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2474 $stmt = "WHERE ( user = ?
2475 AND ( ( workhrs > ? AND geo = ? )
2476 OR ( workhrs < ? OR geo = ? ) ) )";
2477 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2479 =head3 Algebraic inconsistency, for historical reasons
2481 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2482 operator goes C<outside> of the nested structure; whereas when connecting
2483 several constraints on one column, the C<-and> operator goes
2484 C<inside> the arrayref. Here is an example combining both features:
2487 -and => [a => 1, b => 2],
2488 -or => [c => 3, d => 4],
2489 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2494 WHERE ( ( ( a = ? AND b = ? )
2495 OR ( c = ? OR d = ? )
2496 OR ( e LIKE ? AND e LIKE ? ) ) )
2498 This difference in syntax is unfortunate but must be preserved for
2499 historical reasons. So be careful: the two examples below would
2500 seem algebraically equivalent, but they are not
2503 { -like => 'foo%' },
2504 { -like => '%bar' },
2506 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2509 { col => { -like => 'foo%' } },
2510 { col => { -like => '%bar' } },
2512 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2515 =head2 Literal SQL and value type operators
2517 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2518 side" is a column name and the "right side" is a value (normally rendered as
2519 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2520 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2521 alter this behavior. There are several ways of doing so.
2525 This is a virtual operator that signals the string to its right side is an
2526 identifier (a column name) and not a value. For example to compare two
2527 columns you would write:
2530 priority => { '<', 2 },
2531 requestor => { -ident => 'submitter' },
2536 $stmt = "WHERE priority < ? AND requestor = submitter";
2539 If you are maintaining legacy code you may see a different construct as
2540 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2545 This is a virtual operator that signals that the construct to its right side
2546 is a value to be passed to DBI. This is for example necessary when you want
2547 to write a where clause against an array (for RDBMS that support such
2548 datatypes). For example:
2551 array => { -value => [1, 2, 3] }
2556 $stmt = 'WHERE array = ?';
2557 @bind = ([1, 2, 3]);
2559 Note that if you were to simply say:
2565 the result would probably not be what you wanted:
2567 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2572 Finally, sometimes only literal SQL will do. To include a random snippet
2573 of SQL verbatim, you specify it as a scalar reference. Consider this only
2574 as a last resort. Usually there is a better way. For example:
2577 priority => { '<', 2 },
2578 requestor => { -in => \'(SELECT name FROM hitmen)' },
2583 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2586 Note that in this example, you only get one bind parameter back, since
2587 the verbatim SQL is passed as part of the statement.
2591 Never use untrusted input as a literal SQL argument - this is a massive
2592 security risk (there is no way to check literal snippets for SQL
2593 injections and other nastyness). If you need to deal with untrusted input
2594 use literal SQL with placeholders as described next.
2596 =head3 Literal SQL with placeholders and bind values (subqueries)
2598 If the literal SQL to be inserted has placeholders and bind values,
2599 use a reference to an arrayref (yes this is a double reference --
2600 not so common, but perfectly legal Perl). For example, to find a date
2601 in Postgres you can use something like this:
2604 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2609 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2612 Note that you must pass the bind values in the same format as they are returned
2613 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2614 to C<columns>, you must provide the bind values in the
2615 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2616 scalar value; most commonly the column name, but you can use any scalar value
2617 (including references and blessed references), L<SQL::Abstract> will simply
2618 pass it through intact. So if C<bindtype> is set to C<columns> the above
2619 example will look like:
2622 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2625 Literal SQL is especially useful for nesting parenthesized clauses in the
2626 main SQL query. Here is a first example:
2628 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2632 bar => \["IN ($sub_stmt)" => @sub_bind],
2637 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2638 WHERE c2 < ? AND c3 LIKE ?))";
2639 @bind = (1234, 100, "foo%");
2641 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2642 are expressed in the same way. Of course the C<$sub_stmt> and
2643 its associated bind values can be generated through a former call
2646 my ($sub_stmt, @sub_bind)
2647 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2648 c3 => {-like => "foo%"}});
2651 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2654 In the examples above, the subquery was used as an operator on a column;
2655 but the same principle also applies for a clause within the main C<%where>
2656 hash, like an EXISTS subquery:
2658 my ($sub_stmt, @sub_bind)
2659 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2660 my %where = ( -and => [
2662 \["EXISTS ($sub_stmt)" => @sub_bind],
2667 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2668 WHERE c1 = ? AND c2 > t0.c0))";
2672 Observe that the condition on C<c2> in the subquery refers to
2673 column C<t0.c0> of the main query: this is I<not> a bind
2674 value, so we have to express it through a scalar ref.
2675 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2676 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2677 what we wanted here.
2679 Finally, here is an example where a subquery is used
2680 for expressing unary negation:
2682 my ($sub_stmt, @sub_bind)
2683 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2684 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2686 lname => {like => '%son%'},
2687 \["NOT ($sub_stmt)" => @sub_bind],
2692 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2693 @bind = ('%son%', 10, 20)
2695 =head3 Deprecated usage of Literal SQL
2697 Below are some examples of archaic use of literal SQL. It is shown only as
2698 reference for those who deal with legacy code. Each example has a much
2699 better, cleaner and safer alternative that users should opt for in new code.
2705 my %where = ( requestor => \'IS NOT NULL' )
2707 $stmt = "WHERE requestor IS NOT NULL"
2709 This used to be the way of generating NULL comparisons, before the handling
2710 of C<undef> got formalized. For new code please use the superior syntax as
2711 described in L</Tests for NULL values>.
2715 my %where = ( requestor => \'= submitter' )
2717 $stmt = "WHERE requestor = submitter"
2719 This used to be the only way to compare columns. Use the superior L</-ident>
2720 method for all new code. For example an identifier declared in such a way
2721 will be properly quoted if L</quote_char> is properly set, while the legacy
2722 form will remain as supplied.
2726 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2728 $stmt = "WHERE completed > ? AND is_ready"
2729 @bind = ('2012-12-21')
2731 Using an empty string literal used to be the only way to express a boolean.
2732 For all new code please use the much more readable
2733 L<-bool|/Unary operators: bool> operator.
2739 These pages could go on for a while, since the nesting of the data
2740 structures this module can handle are pretty much unlimited (the
2741 module implements the C<WHERE> expansion as a recursive function
2742 internally). Your best bet is to "play around" with the module a
2743 little to see how the data structures behave, and choose the best
2744 format for your data based on that.
2746 And of course, all the values above will probably be replaced with
2747 variables gotten from forms or the command line. After all, if you
2748 knew everything ahead of time, you wouldn't have to worry about
2749 dynamically-generating SQL and could just hardwire it into your
2752 =head1 ORDER BY CLAUSES
2754 Some functions take an order by clause. This can either be a scalar (just a
2755 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
2756 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
2759 Given | Will Generate
2760 ---------------------------------------------------------------
2762 'colA' | ORDER BY colA
2764 [qw/colA colB/] | ORDER BY colA, colB
2766 {-asc => 'colA'} | ORDER BY colA ASC
2768 {-desc => 'colB'} | ORDER BY colB DESC
2770 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2772 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2774 \'colA DESC' | ORDER BY colA DESC
2776 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
2777 | /* ...with $x bound to ? */
2780 { -asc => 'colA' }, | colA ASC,
2781 { -desc => [qw/colB/] }, | colB DESC,
2782 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
2783 \'colE DESC', | colE DESC,
2784 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
2785 ] | /* ...with $x bound to ? */
2786 ===============================================================
2790 =head1 SPECIAL OPERATORS
2792 my $sqlmaker = SQL::Abstract->new(special_ops => [
2796 my ($self, $field, $op, $arg) = @_;
2802 handler => 'method_name',
2806 A "special operator" is a SQL syntactic clause that can be
2807 applied to a field, instead of a usual binary operator.
2810 WHERE field IN (?, ?, ?)
2811 WHERE field BETWEEN ? AND ?
2812 WHERE MATCH(field) AGAINST (?, ?)
2814 Special operators IN and BETWEEN are fairly standard and therefore
2815 are builtin within C<SQL::Abstract> (as the overridable methods
2816 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2817 like the MATCH .. AGAINST example above which is specific to MySQL,
2818 you can write your own operator handlers - supply a C<special_ops>
2819 argument to the C<new> method. That argument takes an arrayref of
2820 operator definitions; each operator definition is a hashref with two
2827 the regular expression to match the operator
2831 Either a coderef or a plain scalar method name. In both cases
2832 the expected return is C<< ($sql, @bind) >>.
2834 When supplied with a method name, it is simply called on the
2835 L<SQL::Abstract> object as:
2837 $self->$method_name($field, $op, $arg)
2841 $field is the LHS of the operator
2842 $op is the part that matched the handler regex
2845 When supplied with a coderef, it is called as:
2847 $coderef->($self, $field, $op, $arg)
2852 For example, here is an implementation
2853 of the MATCH .. AGAINST syntax for MySQL
2855 my $sqlmaker = SQL::Abstract->new(special_ops => [
2857 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2858 {regex => qr/^match$/i,
2860 my ($self, $field, $op, $arg) = @_;
2861 $arg = [$arg] if not ref $arg;
2862 my $label = $self->_quote($field);
2863 my ($placeholder) = $self->_convert('?');
2864 my $placeholders = join ", ", (($placeholder) x @$arg);
2865 my $sql = $self->_sqlcase('match') . " ($label) "
2866 . $self->_sqlcase('against') . " ($placeholders) ";
2867 my @bind = $self->_bindtype($field, @$arg);
2868 return ($sql, @bind);
2875 =head1 UNARY OPERATORS
2877 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2881 my ($self, $op, $arg) = @_;
2887 handler => 'method_name',
2891 A "unary operator" is a SQL syntactic clause that can be
2892 applied to a field - the operator goes before the field
2894 You can write your own operator handlers - supply a C<unary_ops>
2895 argument to the C<new> method. That argument takes an arrayref of
2896 operator definitions; each operator definition is a hashref with two
2903 the regular expression to match the operator
2907 Either a coderef or a plain scalar method name. In both cases
2908 the expected return is C<< $sql >>.
2910 When supplied with a method name, it is simply called on the
2911 L<SQL::Abstract> object as:
2913 $self->$method_name($op, $arg)
2917 $op is the part that matched the handler regex
2918 $arg is the RHS or argument of the operator
2920 When supplied with a coderef, it is called as:
2922 $coderef->($self, $op, $arg)
2930 Thanks to some benchmarking by Mark Stosberg, it turns out that
2931 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2932 I must admit this wasn't an intentional design issue, but it's a
2933 byproduct of the fact that you get to control your C<DBI> handles
2936 To maximize performance, use a code snippet like the following:
2938 # prepare a statement handle using the first row
2939 # and then reuse it for the rest of the rows
2941 for my $href (@array_of_hashrefs) {
2942 $stmt ||= $sql->insert('table', $href);
2943 $sth ||= $dbh->prepare($stmt);
2944 $sth->execute($sql->values($href));
2947 The reason this works is because the keys in your C<$href> are sorted
2948 internally by B<SQL::Abstract>. Thus, as long as your data retains
2949 the same structure, you only have to generate the SQL the first time
2950 around. On subsequent queries, simply use the C<values> function provided
2951 by this module to return your values in the correct order.
2953 However this depends on the values having the same type - if, for
2954 example, the values of a where clause may either have values
2955 (resulting in sql of the form C<column = ?> with a single bind
2956 value), or alternatively the values might be C<undef> (resulting in
2957 sql of the form C<column IS NULL> with no bind value) then the
2958 caching technique suggested will not work.
2962 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2963 really like this part (I do, at least). Building up a complex query
2964 can be as simple as the following:
2971 use CGI::FormBuilder;
2974 my $form = CGI::FormBuilder->new(...);
2975 my $sql = SQL::Abstract->new;
2977 if ($form->submitted) {
2978 my $field = $form->field;
2979 my $id = delete $field->{id};
2980 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2983 Of course, you would still have to connect using C<DBI> to run the
2984 query, but the point is that if you make your form look like your
2985 table, the actual query script can be extremely simplistic.
2987 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2988 a fast interface to returning and formatting data. I frequently
2989 use these three modules together to write complex database query
2990 apps in under 50 lines.
2992 =head1 HOW TO CONTRIBUTE
2994 Contributions are always welcome, in all usable forms (we especially
2995 welcome documentation improvements). The delivery methods include git-
2996 or unified-diff formatted patches, GitHub pull requests, or plain bug
2997 reports either via RT or the Mailing list. Contributors are generally
2998 granted full access to the official repository after their first several
2999 patches pass successful review.
3001 This project is maintained in a git repository. The code and related tools are
3002 accessible at the following locations:
3006 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3008 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3010 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3012 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3018 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3019 Great care has been taken to preserve the I<published> behavior
3020 documented in previous versions in the 1.* family; however,
3021 some features that were previously undocumented, or behaved
3022 differently from the documentation, had to be changed in order
3023 to clarify the semantics. Hence, client code that was relying
3024 on some dark areas of C<SQL::Abstract> v1.*
3025 B<might behave differently> in v1.50.
3027 The main changes are:
3033 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3037 support for the { operator => \"..." } construct (to embed literal SQL)
3041 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3045 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3049 defensive programming: check arguments
3053 fixed bug with global logic, which was previously implemented
3054 through global variables yielding side-effects. Prior versions would
3055 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3056 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3057 Now this is interpreted
3058 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3063 fixed semantics of _bindtype on array args
3067 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3068 we just avoid shifting arrays within that tree.
3072 dropped the C<_modlogic> function
3076 =head1 ACKNOWLEDGEMENTS
3078 There are a number of individuals that have really helped out with
3079 this module. Unfortunately, most of them submitted bugs via CPAN
3080 so I have no idea who they are! But the people I do know are:
3082 Ash Berlin (order_by hash term support)
3083 Matt Trout (DBIx::Class support)
3084 Mark Stosberg (benchmarking)
3085 Chas Owens (initial "IN" operator support)
3086 Philip Collins (per-field SQL functions)
3087 Eric Kolve (hashref "AND" support)
3088 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3089 Dan Kubb (support for "quote_char" and "name_sep")
3090 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3091 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3092 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3093 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3094 Oliver Charles (support for "RETURNING" after "INSERT")
3100 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3104 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3106 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3108 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3109 While not an official support venue, C<DBIx::Class> makes heavy use of
3110 C<SQL::Abstract>, and as such list members there are very familiar with
3111 how to create queries.
3115 This module is free software; you may copy this under the same
3116 terms as perl itself (either the GNU General Public License or
3117 the Artistic License)