1 package SQL::Abstract; # see doc at end of file
5 use Module::Runtime ();
10 use Exporter 'import';
11 our @EXPORT_OK = qw(is_plain_value is_literal_value);
21 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
27 #======================================================================
29 #======================================================================
31 our $VERSION = '1.87';
33 # This would confuse some packagers
34 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
38 # special operators (-in, -between). May be extended/overridden by user.
39 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
40 my @BUILTIN_SPECIAL_OPS = (
41 {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
43 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
44 {regex => qr/^ ident $/ix, handler => sub { die "NOPE" }},
45 {regex => qr/^ value $/ix, handler => sub { die "NOPE" }},
48 #======================================================================
49 # DEBUGGING AND ERROR REPORTING
50 #======================================================================
53 return unless $_[0]->{debug}; shift; # a little faster
54 my $func = (caller(1))[3];
55 warn "[$func] ", @_, "\n";
59 my($func) = (caller(1))[3];
60 Carp::carp "[$func] Warning: ", @_;
64 my($func) = (caller(1))[3];
65 Carp::croak "[$func] Fatal: ", @_;
68 sub is_literal_value ($) {
69 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
70 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
74 sub is_undef_value ($) {
78 and exists $_[0]->{-value}
79 and not defined $_[0]->{-value}
83 # FIXME XSify - this can be done so much more efficiently
84 sub is_plain_value ($) {
86 ! length ref $_[0] ? \($_[0])
88 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
90 exists $_[0]->{-value}
91 ) ? \($_[0]->{-value})
93 # reuse @_ for even moar speedz
94 defined ( $_[1] = Scalar::Util::blessed $_[0] )
96 # deliberately not using Devel::OverloadInfo - the checks we are
97 # intersted in are much more limited than the fullblown thing, and
98 # this is a very hot piece of code
100 # simply using ->can('(""') can leave behind stub methods that
101 # break actually using the overload later (see L<perldiag/Stub
102 # found while resolving method "%s" overloading "%s" in package
103 # "%s"> and the source of overload::mycan())
105 # either has stringification which DBI SHOULD prefer out of the box
106 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
108 # has nummification or boolification, AND fallback is *not* disabled
110 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
113 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
115 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
119 # no fallback specified at all
120 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
122 # fallback explicitly undef
123 ! defined ${"$_[3]::()"}
136 #======================================================================
138 #======================================================================
142 not => '_expand_not',
143 bool => '_expand_bool',
144 and => '_expand_op_andor',
145 or => '_expand_op_andor',
146 nest => '_expand_nest',
147 bind => '_expand_bind',
149 not_in => '_expand_in',
150 row => '_expand_row',
151 between => '_expand_between',
152 not_between => '_expand_between',
154 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
155 ident => '_expand_ident',
156 value => '_expand_value',
157 func => '_expand_func',
158 values => '_expand_values',
161 'between' => '_expand_between',
162 'not_between' => '_expand_between',
163 'in' => '_expand_in',
164 'not_in' => '_expand_in',
165 'nest' => '_expand_nest',
166 (map +($_ => '_expand_op_andor'), ('and', 'or')),
167 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
168 'ident' => '_expand_ident',
169 'value' => '_expand_value',
172 (map +($_, "_render_$_"), qw(op func bind ident literal row values)),
175 (map +($_ => '_render_op_between'), 'between', 'not_between'),
176 (map +($_ => '_render_op_in'), 'in', 'not_in'),
177 (map +($_ => '_render_unop_postfix'),
178 'is_null', 'is_not_null', 'asc', 'desc',
180 (not => '_render_unop_paren'),
181 (map +($_ => '_render_op_andor'), qw(and or)),
182 ',' => '_render_op_multop',
185 delete => [ qw(target where returning) ],
186 update => [ qw(target set where returning) ],
187 insert => [ qw(target fields from returning) ],
190 'delete.from' => '_expand_delete_clause_target',
191 'update.update' => '_expand_update_clause_target',
192 'insert.into' => '_expand_insert_clause_target',
193 'insert.values' => '_expand_insert_clause_from',
196 'delete.target' => '_render_delete_clause_target',
197 'update.target' => '_render_update_clause_target',
198 'insert.target' => '_render_insert_clause_target',
199 'insert.fields' => '_render_insert_clause_fields',
200 'insert.from' => '_render_insert_clause_from',
204 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
205 $Defaults{expand}{$stmt} = '_expand_statement';
206 $Defaults{render}{$stmt} = '_render_statement';
207 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
208 $Defaults{expand_clause}{"${stmt}.${clause}"}
209 = "_expand_${stmt}_clause_${clause}";
215 my $class = ref($self) || $self;
216 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
218 # choose our case by keeping an option around
219 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
221 # default logic for interpreting arrayrefs
222 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
224 # how to return bind vars
225 $opt{bindtype} ||= 'normal';
227 # default comparison is "=", but can be overridden
230 # try to recognize which are the 'equality' and 'inequality' ops
231 # (temporary quickfix (in 2007), should go through a more seasoned API)
232 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
233 $opt{inequality_op} = qr/^( != | <> )$/ix;
235 $opt{like_op} = qr/^ (is_)?r?like $/xi;
236 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
239 $opt{sqltrue} ||= '1=1';
240 $opt{sqlfalse} ||= '0=1';
243 $opt{special_ops} ||= [];
245 if ($class->isa('DBIx::Class::SQLMaker')) {
246 $opt{warn_once_on_nest} = 1;
247 $opt{disable_old_special_ops} = 1;
251 $opt{unary_ops} ||= [];
253 # rudimentary sanity-check for user supplied bits treated as functions/operators
254 # If a purported function matches this regular expression, an exception is thrown.
255 # Literal SQL is *NOT* subject to this check, only functions (and column names
256 # when quoting is not in effect)
259 # need to guard against ()'s in column names too, but this will break tons of
260 # hacks... ideas anyone?
261 $opt{injection_guard} ||= qr/
267 $opt{expand_unary} = {};
269 foreach my $name (sort keys %Defaults) {
270 $opt{$name} = { %{$Defaults{$name}} };
273 if ($opt{lazy_join_sql_parts}) {
274 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
275 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
278 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
280 return bless \%opt, $class;
283 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
284 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
286 sub _assert_pass_injection_guard {
287 if ($_[1] =~ $_[0]->{injection_guard}) {
288 my $class = ref $_[0];
289 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
290 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
291 . "{injection_guard} attribute to ${class}->new()"
296 #======================================================================
298 #======================================================================
301 my ($self, $table, $data, $options) = @_;
304 if (ref($table) eq 'HASH') {
307 my %clauses = (target => $table, values => $data, %{$options||{}});
311 my @rendered = $self->render_statement({ -insert => $stmt });
312 return wantarray ? @rendered : $rendered[0];
315 sub _expand_insert_clause_target {
316 +(target => $_[0]->_expand_maybe_list_expr($_[2], -ident));
319 sub _expand_insert_clause_fields {
321 $_[0]->_expand_maybe_list_expr($_[2], -ident)
322 ] } if ref($_[2]) eq 'ARRAY';
323 return $_[2]; # should maybe still expand somewhat?
326 sub _expand_insert_clause_from {
327 my ($self, undef, $data) = @_;
328 if (ref($data) eq 'HASH' and (keys(%$data))[0] =~ /^-/) {
329 return $self->expand_expr($data);
331 return $data if ref($data) eq 'HASH' and $data->{-row};
332 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
334 from => { -values => [ $v_aqt ] },
335 ($f_aqt ? (fields => $f_aqt) : ()),
339 sub _expand_insert_clause_returning {
340 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
343 sub _expand_insert_values {
344 my ($self, $data) = @_;
345 if (is_literal_value($data)) {
346 (undef, $self->expand_expr($data));
348 my ($fields, $values) = (
349 ref($data) eq 'HASH' ?
350 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
354 # no names (arrayref) means can't generate bindtype
355 !($fields) && $self->{bindtype} eq 'columns'
356 && belch "can't do 'columns' bindtype when called with arrayref";
360 ? $self->expand_expr({ -row => $fields }, -ident)
365 local our $Cur_Col_Meta = $fields->[$_];
366 $self->_expand_insert_value($values->[$_])
373 sub _render_insert_clause_fields {
374 return $_[0]->render_aqt($_[2]);
377 sub _render_insert_clause_target {
378 my ($self, undef, $from) = @_;
379 $self->join_query_parts(' ', $self->format_keyword('insert into'), $from);
382 sub _render_insert_clause_from {
383 return $_[0]->render_aqt($_[2], 1);
386 # So that subclasses can override INSERT ... RETURNING separately from
387 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
388 sub _insert_returning { shift->_returning(@_) }
390 sub _redispatch_returning {
391 my ($self, $type, undef, $returning) = @_;
392 [ $self->${\"_${type}_returning"}({ returning => $returning }) ];
396 my ($self, $options) = @_;
398 my $f = $options->{returning};
400 my ($sql, @bind) = @{ $self->render_aqt(
401 $self->_expand_maybe_list_expr($f, -ident)
403 return ($self->_sqlcase(' returning ').$sql, @bind);
406 sub _expand_insert_value {
409 my $k = our $Cur_Col_Meta;
411 if (ref($v) eq 'ARRAY') {
412 if ($self->{array_datatypes}) {
413 return +{ -bind => [ $k, $v ] };
415 my ($sql, @bind) = @$v;
416 $self->_assert_bindval_matches_bindtype(@bind);
417 return +{ -literal => $v };
419 if (ref($v) eq 'HASH') {
420 if (grep !/^-/, keys %$v) {
421 belch "HASH ref as bind value in insert is not supported";
422 return +{ -bind => [ $k, $v ] };
426 return +{ -bind => [ $k, undef ] };
428 return $self->expand_expr($v);
433 #======================================================================
435 #======================================================================
438 my ($self, $table, $set, $where, $options) = @_;
441 if (ref($table) eq 'HASH') {
445 @clauses{qw(target set where)} = ($table, $set, $where);
446 puke "Unsupported data type specified to \$sql->update"
447 unless ref($clauses{set}) eq 'HASH';
448 @clauses{keys %$options} = values %$options;
452 my @rendered = $self->render_statement({ -update => $stmt });
453 return wantarray ? @rendered : $rendered[0];
456 sub _render_update_clause_target {
457 my ($self, undef, $target) = @_;
458 $self->join_query_parts(' ', $self->format_keyword('update'), $target);
461 sub _update_set_values {
462 my ($self, $data) = @_;
464 return @{ $self->render_aqt(
465 $self->_expand_update_set_values(undef, $data),
469 sub _expand_update_set_values {
470 my ($self, undef, $data) = @_;
471 $self->_expand_maybe_list_expr( [
474 $set = { -bind => $_ } unless defined $set;
475 +{ -op => [ '=', { -ident => $k }, $set ] };
481 ? ($self->{array_datatypes}
482 ? [ $k, +{ -bind => [ $k, $v ] } ]
483 : [ $k, +{ -literal => $v } ])
485 local our $Cur_Col_Meta = $k;
486 [ $k, $self->_expand_expr($v) ]
493 sub _expand_update_clause_target {
494 my ($self, undef, $target) = @_;
495 +(target => $self->_expand_maybe_list_expr($target, -ident));
498 sub _expand_update_clause_set {
499 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
500 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
503 sub _expand_update_clause_where {
504 +(where => $_[0]->expand_expr($_[2]));
507 sub _expand_update_clause_returning {
508 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
511 # So that subclasses can override UPDATE ... RETURNING separately from
513 sub _update_returning { shift->_returning(@_) }
517 #======================================================================
519 #======================================================================
524 my $table = $self->_table(shift);
525 my $fields = shift || '*';
529 my ($fields_sql, @bind) = $self->_select_fields($fields);
531 my ($where_sql, @where_bind) = $self->where($where, $order);
532 push @bind, @where_bind;
534 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
535 $self->_sqlcase('from'), $table)
538 return wantarray ? ($sql, @bind) : $sql;
542 my ($self, $fields) = @_;
543 return $fields unless ref($fields);
544 return @{ $self->render_aqt(
545 $self->_expand_maybe_list_expr($fields, '-ident')
549 #======================================================================
551 #======================================================================
554 my ($self, $table, $where, $options) = @_;
557 if (ref($table) eq 'HASH') {
560 my %clauses = (target => $table, where => $where, %{$options||{}});
564 my @rendered = $self->render_statement({ -delete => $stmt });
565 return wantarray ? @rendered : $rendered[0];
568 # So that subclasses can override DELETE ... RETURNING separately from
570 sub _delete_returning { shift->_returning(@_) }
572 sub _expand_delete_clause_target {
573 +(target => $_[0]->_expand_maybe_list_expr($_[2], -ident));
576 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
578 sub _expand_delete_clause_returning {
579 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
582 sub _render_delete_clause_target {
583 my ($self, undef, $from) = @_;
584 $self->join_query_parts(' ', $self->format_keyword('delete from'), $from);
587 #======================================================================
589 #======================================================================
593 # Finally, a separate routine just to handle WHERE clauses
595 my ($self, $where, $order) = @_;
597 local $self->{convert_where} = $self->{convert};
600 my ($sql, @bind) = defined($where)
601 ? $self->_recurse_where($where)
603 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
607 my ($order_sql, @order_bind) = $self->_order_by($order);
609 push @bind, @order_bind;
612 return wantarray ? ($sql, @bind) : $sql;
615 { our $Default_Scalar_To = -value }
618 my ($self, $expr, $default_scalar_to) = @_;
619 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
620 $self->_expand_expr($expr);
624 my ($self, $aqt, $top_level) = @_;
625 my ($k, $v, @rest) = %$aqt;
627 die "Not a node type: $k" unless $k =~ s/^-//;
628 if (my $meth = $self->{render}{$k}) {
629 local our $Render_Top_Level = $top_level;
630 return $self->$meth($k, $v);
632 die "notreached: $k";
636 my ($self, $expr, $default_scalar_to) = @_;
637 return @{ $self->render_aqt(
638 $self->expand_expr($expr, $default_scalar_to)
642 sub render_statement {
643 my ($self, $expr, $default_scalar_to) = @_;
645 $self->expand_expr($expr, $default_scalar_to), 1
649 sub _expand_statement {
650 my ($self, $type, $args) = @_;
651 my $ec = $self->{expand_clause};
654 $args->{$type} = delete $args->{_}
656 return +{ "-${type}" => +{
658 my $val = $args->{$_};
659 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
660 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
666 ($_ => $self->expand_expr($val))
672 sub _render_statement {
673 my ($self, $type, $args) = @_;
675 foreach my $clause (@{$self->{clauses_of}{$type}}) {
676 next unless my $clause_expr = $args->{$clause};
678 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
679 $self->$rdr($clause, $clause_expr);
681 my $r = $self->render_aqt($clause_expr, 1);
682 next unless defined $r->[0] and length $r->[0];
683 $self->join_query_parts(' ',
684 $self->format_keyword($clause),
691 my $q = $self->join_query_parts(' ', @parts);
692 return $self->join_query_parts('',
693 (our $Render_Top_Level ? $q : ('(', $q, ')'))
698 my ($self, $raw) = @_;
700 return $op if grep $_->{$op}, @{$self}{qw(is_op expand_op render_op)};
701 s/^-(?=.)//, s/\s+/_/g for $op;
706 my ($self, $expr) = @_;
707 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
708 return undef unless defined($expr);
709 if (ref($expr) eq 'HASH') {
710 return undef unless my $kc = keys %$expr;
712 return $self->_expand_op_andor(and => $expr);
714 my ($key, $value) = %$expr;
715 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
716 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
717 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
719 return $self->_expand_hashpair($key, $value);
721 if (ref($expr) eq 'ARRAY') {
722 return $self->_expand_op_andor(lc($self->{logic}), $expr);
724 if (my $literal = is_literal_value($expr)) {
725 return +{ -literal => $literal };
727 if (!ref($expr) or Scalar::Util::blessed($expr)) {
728 return $self->_expand_scalar($expr);
733 sub _expand_hashpair {
734 my ($self, $k, $v) = @_;
735 unless (defined($k) and length($k)) {
736 if (defined($k) and my $literal = is_literal_value($v)) {
737 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
738 return { -literal => $literal };
740 puke "Supplying an empty left hand side argument is not supported";
743 return $self->_expand_hashpair_op($k, $v);
744 } elsif ($k =~ /^[^\w]/i) {
745 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
746 return $self->_expand_op(
747 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
750 return $self->_expand_hashpair_ident($k, $v);
753 sub _expand_hashpair_ident {
754 my ($self, $k, $v) = @_;
756 local our $Cur_Col_Meta = $k;
758 # hash with multiple or no elements is andor
760 if (ref($v) eq 'HASH' and keys %$v != 1) {
761 return $self->_expand_op_andor(and => $v, $k);
764 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
766 if (is_undef_value($v)) {
767 return $self->_expand_hashpair_cmp($k => undef);
770 # scalars and objects get expanded as whatever requested or values
772 if (!ref($v) or Scalar::Util::blessed($v)) {
773 return $self->_expand_hashpair_scalar($k, $v);
776 # single key hashref is a hashtriple
778 if (ref($v) eq 'HASH') {
779 return $self->_expand_hashtriple($k, %$v);
782 # arrayref needs re-engineering over the elements
784 if (ref($v) eq 'ARRAY') {
785 return $self->sqlfalse unless @$v;
786 $self->_debug("ARRAY($k) means distribute over elements");
788 $v->[0] =~ /^-(and|or)$/i
789 ? (shift(@{$v = [ @$v ]}), $1)
790 : lc($self->{logic} || 'OR')
792 return $self->_expand_op_andor(
797 if (my $literal = is_literal_value($v)) {
799 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
802 my ($sql, @bind) = @$literal;
803 if ($self->{bindtype} eq 'columns') {
805 $self->_assert_bindval_matches_bindtype($_);
808 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
814 my ($self, $expr) = @_;
816 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
819 sub _expand_hashpair_scalar {
820 my ($self, $k, $v) = @_;
822 return $self->_expand_hashpair_cmp(
823 $k, $self->_expand_scalar($v),
827 sub _expand_hashpair_op {
828 my ($self, $k, $v) = @_;
830 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
832 my $op = $self->_normalize_op($k);
836 my $op = join(' ', split '_', $op);
838 # the old special op system requires illegality for top-level use
841 (our $Expand_Depth) == 1
843 List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
845 $self->{disable_old_special_ops}
846 and List::Util::first { $op =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
850 puke "Illegal use of top-level '-$op'"
854 if (my $exp = $self->{expand}{$op}) {
855 return $self->$exp($op, $v);
858 # Ops prefixed with -not_ get converted
860 if (my ($rest) = $op =~/^not_(.*)$/) {
863 $self->_expand_expr({ "-${rest}", $v })
869 # the old unary op system means we should touch nothing and let it work
871 my $op = join(' ', split '_', $op);
873 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
874 return { -op => [ $op, $v ] };
878 # an explicit node type is currently assumed to be expanded (this is almost
879 # certainly wrong and there should be expansion anyway)
881 if ($self->{render}{$op}) {
885 my $type = $self->{unknown_unop_always_func} ? -func : -op;
892 and (keys %$v)[0] =~ /^-/
895 (List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}})
904 ($type eq -func and ref($v) eq 'ARRAY')
905 ? map $self->_expand_expr($_), @$v
906 : $self->_expand_expr($v)
910 sub _expand_hashpair_cmp {
911 my ($self, $k, $v) = @_;
912 $self->_expand_hashtriple($k, $self->{cmp}, $v);
915 sub _expand_hashtriple {
916 my ($self, $k, $vk, $vv) = @_;
918 my $ik = $self->_expand_expr({ -ident => $k });
920 my $op = $self->_normalize_op($vk);
921 $self->_assert_pass_injection_guard($op);
923 if ($op =~ s/ _? \d+ $//x ) {
924 return $self->_expand_expr($k, { $vk, $vv });
926 if (my $x = $self->{expand_op}{$op}) {
927 local our $Cur_Col_Meta = $k;
928 return $self->$x($op, $vv, $k);
932 my $op = join(' ', split '_', $op);
934 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
935 return { -op => [ $op, $ik, $vv ] };
937 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
941 { -op => [ $op, $vv ] }
945 if (ref($vv) eq 'ARRAY') {
947 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
948 ? (shift(@raw), lc $1) : 'or';
949 my @values = map +{ $vk => $_ }, @raw;
951 $op =~ $self->{inequality_op}
952 or $op =~ $self->{not_like_op}
954 if (lc($logic) eq 'or' and @values > 1) {
955 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
956 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
957 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
962 # try to DWIM on equality operators
963 return ($self->_dwim_op_to_is($op,
964 "Supplying an empty arrayref to '%s' is deprecated",
965 "operator '%s' applied on an empty array (field '$k')"
966 ) ? $self->sqlfalse : $self->sqltrue);
968 return $self->_expand_op_andor($logic => \@values, $k);
970 if (is_undef_value($vv)) {
971 my $is = ($self->_dwim_op_to_is($op,
972 "Supplying an undefined argument to '%s' is deprecated",
973 "unexpected operator '%s' with undef operand",
974 ) ? 'is' : 'is not');
976 return $self->_expand_hashpair($k => { $is, undef });
978 local our $Cur_Col_Meta = $k;
982 $self->_expand_expr($vv)
987 my ($self, $raw, $empty, $fail) = @_;
989 my $op = $self->_normalize_op($raw);
991 if ($op =~ /^not$/i) {
994 if ($op =~ $self->{equality_op}) {
997 if ($op =~ $self->{like_op}) {
998 belch(sprintf $empty, uc(join ' ', split '_', $op));
1001 if ($op =~ $self->{inequality_op}) {
1004 if ($op =~ $self->{not_like_op}) {
1005 belch(sprintf $empty, uc(join ' ', split '_', $op));
1008 puke(sprintf $fail, $op);
1012 my ($self, undef, $args) = @_;
1013 my ($func, @args) = @$args;
1014 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
1018 my ($self, undef, $body, $k) = @_;
1019 return $self->_expand_hashpair_cmp(
1020 $k, { -ident => $body }
1022 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
1023 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
1025 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
1026 ref($body) ? @$body : $body;
1027 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
1028 unless ($self->{quote_char}) {
1029 $self->_assert_pass_injection_guard($_) for @parts;
1031 return +{ -ident => \@parts };
1035 return $_[0]->_expand_hashpair_cmp(
1036 $_[3], { -value => $_[2] },
1037 ) if defined($_[3]);
1038 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
1042 +{ -op => [ 'not', $_[0]->_expand_expr($_[2]) ] };
1046 my ($self, undef, $args) = @_;
1047 +{ -row => [ map $self->expand_expr($_), @$args ] };
1051 my ($self, undef, $args) = @_;
1052 my ($op, @opargs) = @$args;
1053 if (my $exp = $self->{expand_op}{$op}) {
1054 return $self->$exp($op, \@opargs);
1056 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1060 my ($self, undef, $v) = @_;
1062 return $self->_expand_expr($v);
1064 puke "-bool => undef not supported" unless defined($v);
1065 return $self->_expand_expr({ -ident => $v });
1068 sub _expand_op_andor {
1069 my ($self, $logop, $v, $k) = @_;
1071 $v = [ map +{ $k, $_ },
1073 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1077 if (ref($v) eq 'HASH') {
1078 return undef unless keys %$v;
1081 map $self->_expand_expr({ $_ => $v->{$_} }),
1085 if (ref($v) eq 'ARRAY') {
1086 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1089 (ref($_) eq 'ARRAY' and @$_)
1090 or (ref($_) eq 'HASH' and %$_)
1096 while (my ($el) = splice @expr, 0, 1) {
1097 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1098 unless defined($el) and length($el);
1099 my $elref = ref($el);
1101 local our $Expand_Depth = 0;
1102 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1103 } elsif ($elref eq 'ARRAY') {
1104 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1105 } elsif (my $l = is_literal_value($el)) {
1106 push @res, { -literal => $l };
1107 } elsif ($elref eq 'HASH') {
1108 local our $Expand_Depth = 0;
1109 push @res, grep defined, $self->_expand_expr($el) if %$el;
1115 # return $res[0] if @res == 1;
1116 return { -op => [ $logop, @res ] };
1122 my ($self, $op, $vv, $k) = @_;
1123 ($k, $vv) = @$vv unless defined $k;
1124 puke "$op can only take undef as argument"
1128 and exists($vv->{-value})
1129 and !defined($vv->{-value})
1131 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1134 sub _expand_between {
1135 my ($self, $op, $vv, $k) = @_;
1136 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1137 my @rhs = map $self->_expand_expr($_),
1138 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1140 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1142 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1144 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1148 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1154 my ($self, $op, $vv, $k) = @_;
1155 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1156 if (my $literal = is_literal_value($vv)) {
1157 my ($sql, @bind) = @$literal;
1158 my $opened_sql = $self->_open_outer_paren($sql);
1160 $op, $self->expand_expr($k, -ident),
1161 { -literal => [ $opened_sql, @bind ] }
1165 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1166 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1167 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1168 . 'will emit the logically correct SQL instead of raising this exception)'
1170 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1172 my @rhs = map $self->expand_expr($_, -value),
1173 map { defined($_) ? $_: puke($undef_err) }
1174 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1175 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1179 $self->expand_expr($k, -ident),
1185 my ($self, undef, $v) = @_;
1186 # DBIx::Class requires a nest warning to be emitted once but the private
1187 # method it overrode to do so no longer exists
1188 if ($self->{warn_once_on_nest}) {
1189 unless (our $Nest_Warned) {
1191 "-nest in search conditions is deprecated, you most probably wanted:\n"
1192 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1197 return $self->_expand_expr($v);
1201 my ($self, undef, $bind) = @_;
1202 return { -bind => $bind };
1205 sub _expand_values {
1206 my ($self, undef, $values) = @_;
1207 return { -values => [
1210 ? $self->expand_expr($_)
1211 : +{ -row => [ map $self->expand_expr($_), @$_ ] }
1212 ), ref($values) eq 'ARRAY' ? @$values : $values
1216 sub _recurse_where {
1217 my ($self, $where, $logic) = @_;
1219 # Special case: top level simple string treated as literal
1221 my $where_exp = (ref($where)
1222 ? $self->_expand_expr($where, $logic)
1223 : { -literal => [ $where ] });
1225 # dispatch expanded expression
1227 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1228 # DBIx::Class used to call _recurse_where in scalar context
1229 # something else might too...
1231 return ($sql, @bind);
1234 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1240 my ($self, undef, $ident) = @_;
1242 return [ $self->_convert($self->_quote($ident)) ];
1246 my ($self, undef, $values) = @_;
1247 return $self->join_query_parts('',
1249 $self->_render_op(undef, [ ',', @$values ]),
1255 my ($self, undef, $rest) = @_;
1256 my ($func, @args) = @$rest;
1257 return $self->join_query_parts('',
1258 $self->_sqlcase($func),
1259 $self->join_query_parts('',
1261 $self->join_query_parts(', ', @args),
1268 my ($self, undef, $bind) = @_;
1269 return [ $self->_convert('?'), $self->_bindtype(@$bind) ];
1272 sub _render_literal {
1273 my ($self, undef, $literal) = @_;
1274 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1279 my ($self, undef, $v) = @_;
1280 my ($op, @args) = @$v;
1281 if (my $r = $self->{render_op}{$op}) {
1282 return $self->$r($op, \@args);
1287 my $op = join(' ', split '_', $op);
1289 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1290 if ($ss and @args > 1) {
1291 puke "Special op '${op}' requires first value to be identifier"
1292 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1293 my $k = join(($self->{name_sep}||'.'), @$ident);
1294 local our $Expand_Depth = 1;
1295 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1297 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1298 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1301 return $self->_render_unop_paren($op, \@args);
1305 return $self->_render_unop_prefix($op, \@args);
1307 return $self->_render_op_multop($op, \@args);
1313 sub _render_op_between {
1314 my ($self, $op, $args) = @_;
1315 my ($left, $low, $high) = @$args;
1318 puke "Single arg to between must be a literal"
1319 unless $low->{-literal};
1322 +($low, $self->format_keyword('and'), $high);
1325 return $self->join_query_parts(' ',
1326 '(', $left, $self->format_keyword($op), @rh, ')',
1331 my ($self, $op, $args) = @_;
1332 my ($lhs, @rhs) = @$args;
1334 return $self->join_query_parts(' ',
1336 $self->format_keyword($op),
1337 $self->join_query_parts(' ',
1339 $self->join_query_parts(', ', @rhs),
1345 sub _render_op_andor {
1346 my ($self, $op, $args) = @_;
1347 return undef unless @$args;
1348 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1349 my $inner = $self->_render_op_multop($op, $args);
1350 return undef unless defined($inner->[0]) and length($inner->[0]);
1351 return $self->join_query_parts(' ',
1356 sub _render_op_multop {
1357 my ($self, $op, $args) = @_;
1359 return undef unless @parts;
1360 return $self->render_aqt($parts[0]) if @parts == 1;
1361 my $join = ($op eq ','
1363 : ' '.$self->format_keyword($op).' '
1365 return $self->join_query_parts($join, @parts);
1368 sub _render_values {
1369 my ($self, undef, $values) = @_;
1370 my $inner = $self->join_query_parts(' ',
1371 $self->format_keyword('values'),
1372 $self->join_query_parts(', ',
1373 ref($values) eq 'ARRAY' ? @$values : $values
1376 return $self->join_query_parts('',
1377 (our $Render_Top_Level ? $inner : ('(', $inner, ')'))
1381 sub join_query_parts {
1382 my ($self, $join, @parts) = @_;
1385 ? $self->render_aqt($_)
1386 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1389 $self->{join_sql_parts}->($join, grep defined, map $_->[0], @final),
1390 (map @{$_}[1..$#$_], @final),
1394 sub _render_unop_paren {
1395 my ($self, $op, $v) = @_;
1396 return $self->join_query_parts('',
1397 '(', $self->_render_unop_prefix($op, $v), ')'
1401 sub _render_unop_prefix {
1402 my ($self, $op, $v) = @_;
1403 return $self->join_query_parts(' ',
1404 $self->_sqlcase($op), $v->[0]
1408 sub _render_unop_postfix {
1409 my ($self, $op, $v) = @_;
1410 return $self->join_query_parts(' ',
1411 $v->[0], $self->format_keyword($op),
1415 # Some databases (SQLite) treat col IN (1, 2) different from
1416 # col IN ( (1, 2) ). Use this to strip all outer parens while
1417 # adding them back in the corresponding method
1418 sub _open_outer_paren {
1419 my ($self, $sql) = @_;
1421 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1423 # there are closing parens inside, need the heavy duty machinery
1424 # to reevaluate the extraction starting from $sql (full reevaluation)
1425 if ($inner =~ /\)/) {
1426 require Text::Balanced;
1428 my (undef, $remainder) = do {
1429 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1431 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1434 # the entire expression needs to be a balanced bracketed thing
1435 # (after an extract no remainder sans trailing space)
1436 last if defined $remainder and $remainder =~ /\S/;
1446 #======================================================================
1448 #======================================================================
1450 sub _expand_order_by {
1451 my ($self, $arg) = @_;
1453 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1455 return $self->_expand_maybe_list_expr($arg)
1456 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1458 my $expander = sub {
1459 my ($self, $dir, $expr) = @_;
1460 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1461 foreach my $arg (@to_expand) {
1465 and grep /^-(asc|desc)$/, keys %$arg
1467 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1471 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1473 map $self->expand_expr($_, -ident),
1474 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1475 return undef unless @exp;
1476 return undef if @exp == 1 and not defined($exp[0]);
1477 return +{ -op => [ ',', @exp ] };
1480 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1482 return $self->$expander(undef, $arg);
1486 my ($self, $arg) = @_;
1488 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1490 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1492 return '' unless length($sql);
1494 my $final_sql = $self->_sqlcase(' order by ').$sql;
1496 return ($final_sql, @bind);
1499 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1501 sub _order_by_chunks {
1502 my ($self, $arg) = @_;
1504 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1506 my @res = $self->_chunkify_order_by($expanded);
1507 (ref() ? $_->[0] : $_) .= '' for @res;
1511 sub _chunkify_order_by {
1512 my ($self, $expanded) = @_;
1514 return grep length, @{ $self->render_aqt($expanded) }
1515 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1518 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1519 my ($comma, @list) = @{$_->{-op}};
1520 return map $self->_chunkify_order_by($_), @list;
1522 return $self->render_aqt($_);
1526 #======================================================================
1527 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1528 #======================================================================
1534 $self->_expand_maybe_list_expr($from, -ident)
1539 #======================================================================
1541 #======================================================================
1543 sub _expand_maybe_list_expr {
1544 my ($self, $expr, $default) = @_;
1546 ',', map $self->expand_expr($_, $default),
1547 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1548 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1549 return +{ -op => [ ',',
1550 map $self->expand_expr($_, $default),
1551 ref($expr) eq 'ARRAY' ? @$expr : $expr
1555 # highly optimized, as it's called way too often
1557 # my ($self, $label) = @_;
1559 return '' unless defined $_[1];
1560 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1561 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1563 unless ($_[0]->{quote_char}) {
1564 if (ref($_[1]) eq 'ARRAY') {
1565 return join($_[0]->{name_sep}||'.', @{$_[1]});
1567 $_[0]->_assert_pass_injection_guard($_[1]);
1572 my $qref = ref $_[0]->{quote_char};
1574 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1575 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1576 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1578 my $esc = $_[0]->{escape_char} || $r;
1580 # parts containing * are naturally unquoted
1582 $_[0]->{name_sep}||'',
1586 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1588 (ref($_[1]) eq 'ARRAY'
1592 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1600 # Conversion, if applicable
1602 #my ($self, $arg) = @_;
1603 if (my $conv = $_[0]->{convert_where}) {
1604 return @{ $_[0]->join_query_parts('',
1605 $_[0]->format_keyword($conv),
1614 #my ($self, $col, @vals) = @_;
1615 # called often - tighten code
1616 return $_[0]->{bindtype} eq 'columns'
1617 ? map {[$_[1], $_]} @_[2 .. $#_]
1622 # Dies if any element of @bind is not in [colname => value] format
1623 # if bindtype is 'columns'.
1624 sub _assert_bindval_matches_bindtype {
1625 # my ($self, @bind) = @_;
1627 if ($self->{bindtype} eq 'columns') {
1629 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1630 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1636 sub _join_sql_clauses {
1637 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1639 if (@$clauses_aref > 1) {
1640 my $join = " " . $self->_sqlcase($logic) . " ";
1641 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1642 return ($sql, @$bind_aref);
1644 elsif (@$clauses_aref) {
1645 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1648 return (); # if no SQL, ignore @$bind_aref
1653 # Fix SQL case, if so requested
1655 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1656 # don't touch the argument ... crooked logic, but let's not change it!
1657 return $_[0]->{case} ? $_[1] : uc($_[1]);
1660 sub format_keyword { $_[0]->_sqlcase(join ' ', split '_', $_[1]) }
1662 #======================================================================
1663 # DISPATCHING FROM REFKIND
1664 #======================================================================
1667 my ($self, $data) = @_;
1669 return 'UNDEF' unless defined $data;
1671 # blessed objects are treated like scalars
1672 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1674 return 'SCALAR' unless $ref;
1677 while ($ref eq 'REF') {
1679 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1683 return ($ref||'SCALAR') . ('REF' x $n_steps);
1687 my ($self, $data) = @_;
1688 my @try = ($self->_refkind($data));
1689 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1690 push @try, 'FALLBACK';
1694 sub _METHOD_FOR_refkind {
1695 my ($self, $meth_prefix, $data) = @_;
1698 for (@{$self->_try_refkind($data)}) {
1699 $method = $self->can($meth_prefix."_".$_)
1703 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1707 sub _SWITCH_refkind {
1708 my ($self, $data, $dispatch_table) = @_;
1711 for (@{$self->_try_refkind($data)}) {
1712 $coderef = $dispatch_table->{$_}
1716 puke "no dispatch entry for ".$self->_refkind($data)
1725 #======================================================================
1726 # VALUES, GENERATE, AUTOLOAD
1727 #======================================================================
1729 # LDNOTE: original code from nwiger, didn't touch code in that section
1730 # I feel the AUTOLOAD stuff should not be the default, it should
1731 # only be activated on explicit demand by user.
1735 my $data = shift || return;
1736 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1737 unless ref $data eq 'HASH';
1740 foreach my $k (sort keys %$data) {
1741 my $v = $data->{$k};
1742 $self->_SWITCH_refkind($v, {
1744 if ($self->{array_datatypes}) { # array datatype
1745 push @all_bind, $self->_bindtype($k, $v);
1747 else { # literal SQL with bind
1748 my ($sql, @bind) = @$v;
1749 $self->_assert_bindval_matches_bindtype(@bind);
1750 push @all_bind, @bind;
1753 ARRAYREFREF => sub { # literal SQL with bind
1754 my ($sql, @bind) = @${$v};
1755 $self->_assert_bindval_matches_bindtype(@bind);
1756 push @all_bind, @bind;
1758 SCALARREF => sub { # literal SQL without bind
1760 SCALAR_or_UNDEF => sub {
1761 push @all_bind, $self->_bindtype($k, $v);
1772 my(@sql, @sqlq, @sqlv);
1776 if ($ref eq 'HASH') {
1777 for my $k (sort keys %$_) {
1780 my $label = $self->_quote($k);
1781 if ($r eq 'ARRAY') {
1782 # literal SQL with bind
1783 my ($sql, @bind) = @$v;
1784 $self->_assert_bindval_matches_bindtype(@bind);
1785 push @sqlq, "$label = $sql";
1787 } elsif ($r eq 'SCALAR') {
1788 # literal SQL without bind
1789 push @sqlq, "$label = $$v";
1791 push @sqlq, "$label = ?";
1792 push @sqlv, $self->_bindtype($k, $v);
1795 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1796 } elsif ($ref eq 'ARRAY') {
1797 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1800 if ($r eq 'ARRAY') { # literal SQL with bind
1801 my ($sql, @bind) = @$v;
1802 $self->_assert_bindval_matches_bindtype(@bind);
1805 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1806 # embedded literal SQL
1813 push @sql, '(' . join(', ', @sqlq) . ')';
1814 } elsif ($ref eq 'SCALAR') {
1818 # strings get case twiddled
1819 push @sql, $self->_sqlcase($_);
1823 my $sql = join ' ', @sql;
1825 # this is pretty tricky
1826 # if ask for an array, return ($stmt, @bind)
1827 # otherwise, s/?/shift @sqlv/ to put it inline
1829 return ($sql, @sqlv);
1831 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1832 ref $d ? $d->[1] : $d/e;
1841 # This allows us to check for a local, then _form, attr
1843 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1844 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
1845 return $self->generate($name, @_);
1856 SQL::Abstract - Generate SQL from Perl data structures
1862 my $sql = SQL::Abstract->new;
1864 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1866 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1868 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1870 my($stmt, @bind) = $sql->delete($table, \%where);
1872 # Then, use these in your DBI statements
1873 my $sth = $dbh->prepare($stmt);
1874 $sth->execute(@bind);
1876 # Just generate the WHERE clause
1877 my($stmt, @bind) = $sql->where(\%where, $order);
1879 # Return values in the same order, for hashed queries
1880 # See PERFORMANCE section for more details
1881 my @bind = $sql->values(\%fieldvals);
1885 This module was inspired by the excellent L<DBIx::Abstract>.
1886 However, in using that module I found that what I really wanted
1887 to do was generate SQL, but still retain complete control over my
1888 statement handles and use the DBI interface. So, I set out to
1889 create an abstract SQL generation module.
1891 While based on the concepts used by L<DBIx::Abstract>, there are
1892 several important differences, especially when it comes to WHERE
1893 clauses. I have modified the concepts used to make the SQL easier
1894 to generate from Perl data structures and, IMO, more intuitive.
1895 The underlying idea is for this module to do what you mean, based
1896 on the data structures you provide it. The big advantage is that
1897 you don't have to modify your code every time your data changes,
1898 as this module figures it out.
1900 To begin with, an SQL INSERT is as easy as just specifying a hash
1901 of C<key=value> pairs:
1904 name => 'Jimbo Bobson',
1905 phone => '123-456-7890',
1906 address => '42 Sister Lane',
1907 city => 'St. Louis',
1908 state => 'Louisiana',
1911 The SQL can then be generated with this:
1913 my($stmt, @bind) = $sql->insert('people', \%data);
1915 Which would give you something like this:
1917 $stmt = "INSERT INTO people
1918 (address, city, name, phone, state)
1919 VALUES (?, ?, ?, ?, ?)";
1920 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1921 '123-456-7890', 'Louisiana');
1923 These are then used directly in your DBI code:
1925 my $sth = $dbh->prepare($stmt);
1926 $sth->execute(@bind);
1928 =head2 Inserting and Updating Arrays
1930 If your database has array types (like for example Postgres),
1931 activate the special option C<< array_datatypes => 1 >>
1932 when creating the C<SQL::Abstract> object.
1933 Then you may use an arrayref to insert and update database array types:
1935 my $sql = SQL::Abstract->new(array_datatypes => 1);
1937 planets => [qw/Mercury Venus Earth Mars/]
1940 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1944 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1946 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1949 =head2 Inserting and Updating SQL
1951 In order to apply SQL functions to elements of your C<%data> you may
1952 specify a reference to an arrayref for the given hash value. For example,
1953 if you need to execute the Oracle C<to_date> function on a value, you can
1954 say something like this:
1958 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1961 The first value in the array is the actual SQL. Any other values are
1962 optional and would be included in the bind values array. This gives
1965 my($stmt, @bind) = $sql->insert('people', \%data);
1967 $stmt = "INSERT INTO people (name, date_entered)
1968 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1969 @bind = ('Bill', '03/02/2003');
1971 An UPDATE is just as easy, all you change is the name of the function:
1973 my($stmt, @bind) = $sql->update('people', \%data);
1975 Notice that your C<%data> isn't touched; the module will generate
1976 the appropriately quirky SQL for you automatically. Usually you'll
1977 want to specify a WHERE clause for your UPDATE, though, which is
1978 where handling C<%where> hashes comes in handy...
1980 =head2 Complex where statements
1982 This module can generate pretty complicated WHERE statements
1983 easily. For example, simple C<key=value> pairs are taken to mean
1984 equality, and if you want to see if a field is within a set
1985 of values, you can use an arrayref. Let's say we wanted to
1986 SELECT some data based on this criteria:
1989 requestor => 'inna',
1990 worker => ['nwiger', 'rcwe', 'sfz'],
1991 status => { '!=', 'completed' }
1994 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1996 The above would give you something like this:
1998 $stmt = "SELECT * FROM tickets WHERE
1999 ( requestor = ? ) AND ( status != ? )
2000 AND ( worker = ? OR worker = ? OR worker = ? )";
2001 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2003 Which you could then use in DBI code like so:
2005 my $sth = $dbh->prepare($stmt);
2006 $sth->execute(@bind);
2012 The methods are simple. There's one for every major SQL operation,
2013 and a constructor you use first. The arguments are specified in a
2014 similar order for each method (table, then fields, then a where
2015 clause) to try and simplify things.
2017 =head2 new(option => 'value')
2019 The C<new()> function takes a list of options and values, and returns
2020 a new B<SQL::Abstract> object which can then be used to generate SQL
2021 through the methods below. The options accepted are:
2027 If set to 'lower', then SQL will be generated in all lowercase. By
2028 default SQL is generated in "textbook" case meaning something like:
2030 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2032 Any setting other than 'lower' is ignored.
2036 This determines what the default comparison operator is. By default
2037 it is C<=>, meaning that a hash like this:
2039 %where = (name => 'nwiger', email => 'nate@wiger.org');
2041 Will generate SQL like this:
2043 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2045 However, you may want loose comparisons by default, so if you set
2046 C<cmp> to C<like> you would get SQL such as:
2048 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2050 You can also override the comparison on an individual basis - see
2051 the huge section on L</"WHERE CLAUSES"> at the bottom.
2053 =item sqltrue, sqlfalse
2055 Expressions for inserting boolean values within SQL statements.
2056 By default these are C<1=1> and C<1=0>. They are used
2057 by the special operators C<-in> and C<-not_in> for generating
2058 correct SQL even when the argument is an empty array (see below).
2062 This determines the default logical operator for multiple WHERE
2063 statements in arrays or hashes. If absent, the default logic is "or"
2064 for arrays, and "and" for hashes. This means that a WHERE
2068 event_date => {'>=', '2/13/99'},
2069 event_date => {'<=', '4/24/03'},
2072 will generate SQL like this:
2074 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2076 This is probably not what you want given this query, though (look
2077 at the dates). To change the "OR" to an "AND", simply specify:
2079 my $sql = SQL::Abstract->new(logic => 'and');
2081 Which will change the above C<WHERE> to:
2083 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2085 The logic can also be changed locally by inserting
2086 a modifier in front of an arrayref:
2088 @where = (-and => [event_date => {'>=', '2/13/99'},
2089 event_date => {'<=', '4/24/03'} ]);
2091 See the L</"WHERE CLAUSES"> section for explanations.
2095 This will automatically convert comparisons using the specified SQL
2096 function for both column and value. This is mostly used with an argument
2097 of C<upper> or C<lower>, so that the SQL will have the effect of
2098 case-insensitive "searches". For example, this:
2100 $sql = SQL::Abstract->new(convert => 'upper');
2101 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2103 Will turn out the following SQL:
2105 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2107 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2108 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2109 not validate this option; it will just pass through what you specify verbatim).
2113 This is a kludge because many databases suck. For example, you can't
2114 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2115 Instead, you have to use C<bind_param()>:
2117 $sth->bind_param(1, 'reg data');
2118 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2120 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2121 which loses track of which field each slot refers to. Fear not.
2123 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2124 Currently, you can specify either C<normal> (default) or C<columns>. If you
2125 specify C<columns>, you will get an array that looks like this:
2127 my $sql = SQL::Abstract->new(bindtype => 'columns');
2128 my($stmt, @bind) = $sql->insert(...);
2131 [ 'column1', 'value1' ],
2132 [ 'column2', 'value2' ],
2133 [ 'column3', 'value3' ],
2136 You can then iterate through this manually, using DBI's C<bind_param()>.
2138 $sth->prepare($stmt);
2141 my($col, $data) = @$_;
2142 if ($col eq 'details' || $col eq 'comments') {
2143 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2144 } elsif ($col eq 'image') {
2145 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2147 $sth->bind_param($i, $data);
2151 $sth->execute; # execute without @bind now
2153 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2154 Basically, the advantage is still that you don't have to care which fields
2155 are or are not included. You could wrap that above C<for> loop in a simple
2156 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2157 get a layer of abstraction over manual SQL specification.
2159 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2160 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2161 will expect the bind values in this format.
2165 This is the character that a table or column name will be quoted
2166 with. By default this is an empty string, but you could set it to
2167 the character C<`>, to generate SQL like this:
2169 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2171 Alternatively, you can supply an array ref of two items, the first being the left
2172 hand quote character, and the second the right hand quote character. For
2173 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2174 that generates SQL like this:
2176 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2178 Quoting is useful if you have tables or columns names that are reserved
2179 words in your database's SQL dialect.
2183 This is the character that will be used to escape L</quote_char>s appearing
2184 in an identifier before it has been quoted.
2186 The parameter default in case of a single L</quote_char> character is the quote
2189 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2190 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2191 of the B<opening (left)> L</quote_char> within the identifier are currently left
2192 untouched. The default for opening-closing-style quotes may change in future
2193 versions, thus you are B<strongly encouraged> to specify the escape character
2198 This is the character that separates a table and column name. It is
2199 necessary to specify this when the C<quote_char> option is selected,
2200 so that tables and column names can be individually quoted like this:
2202 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2204 =item injection_guard
2206 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2207 column name specified in a query structure. This is a safety mechanism to avoid
2208 injection attacks when mishandling user input e.g.:
2210 my %condition_as_column_value_pairs = get_values_from_user();
2211 $sqla->select( ... , \%condition_as_column_value_pairs );
2213 If the expression matches an exception is thrown. Note that literal SQL
2214 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2216 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2218 =item array_datatypes
2220 When this option is true, arrayrefs in INSERT or UPDATE are
2221 interpreted as array datatypes and are passed directly
2223 When this option is false, arrayrefs are interpreted
2224 as literal SQL, just like refs to arrayrefs
2225 (but this behavior is for backwards compatibility; when writing
2226 new queries, use the "reference to arrayref" syntax
2232 Takes a reference to a list of "special operators"
2233 to extend the syntax understood by L<SQL::Abstract>.
2234 See section L</"SPECIAL OPERATORS"> for details.
2238 Takes a reference to a list of "unary operators"
2239 to extend the syntax understood by L<SQL::Abstract>.
2240 See section L</"UNARY OPERATORS"> for details.
2246 =head2 insert($table, \@values || \%fieldvals, \%options)
2248 This is the simplest function. You simply give it a table name
2249 and either an arrayref of values or hashref of field/value pairs.
2250 It returns an SQL INSERT statement and a list of bind values.
2251 See the sections on L</"Inserting and Updating Arrays"> and
2252 L</"Inserting and Updating SQL"> for information on how to insert
2253 with those data types.
2255 The optional C<\%options> hash reference may contain additional
2256 options to generate the insert SQL. Currently supported options
2263 Takes either a scalar of raw SQL fields, or an array reference of
2264 field names, and adds on an SQL C<RETURNING> statement at the end.
2265 This allows you to return data generated by the insert statement
2266 (such as row IDs) without performing another C<SELECT> statement.
2267 Note, however, this is not part of the SQL standard and may not
2268 be supported by all database engines.
2272 =head2 update($table, \%fieldvals, \%where, \%options)
2274 This takes a table, hashref of field/value pairs, and an optional
2275 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2277 See the sections on L</"Inserting and Updating Arrays"> and
2278 L</"Inserting and Updating SQL"> for information on how to insert
2279 with those data types.
2281 The optional C<\%options> hash reference may contain additional
2282 options to generate the update SQL. Currently supported options
2289 See the C<returning> option to
2290 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2294 =head2 select($source, $fields, $where, $order)
2296 This returns a SQL SELECT statement and associated list of bind values, as
2297 specified by the arguments:
2303 Specification of the 'FROM' part of the statement.
2304 The argument can be either a plain scalar (interpreted as a table
2305 name, will be quoted), or an arrayref (interpreted as a list
2306 of table names, joined by commas, quoted), or a scalarref
2307 (literal SQL, not quoted).
2311 Specification of the list of fields to retrieve from
2313 The argument can be either an arrayref (interpreted as a list
2314 of field names, will be joined by commas and quoted), or a
2315 plain scalar (literal SQL, not quoted).
2316 Please observe that this API is not as flexible as that of
2317 the first argument C<$source>, for backwards compatibility reasons.
2321 Optional argument to specify the WHERE part of the query.
2322 The argument is most often a hashref, but can also be
2323 an arrayref or plain scalar --
2324 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2328 Optional argument to specify the ORDER BY part of the query.
2329 The argument can be a scalar, a hashref or an arrayref
2330 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2336 =head2 delete($table, \%where, \%options)
2338 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2339 It returns an SQL DELETE statement and list of bind values.
2341 The optional C<\%options> hash reference may contain additional
2342 options to generate the delete SQL. Currently supported options
2349 See the C<returning> option to
2350 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2354 =head2 where(\%where, $order)
2356 This is used to generate just the WHERE clause. For example,
2357 if you have an arbitrary data structure and know what the
2358 rest of your SQL is going to look like, but want an easy way
2359 to produce a WHERE clause, use this. It returns an SQL WHERE
2360 clause and list of bind values.
2363 =head2 values(\%data)
2365 This just returns the values from the hash C<%data>, in the same
2366 order that would be returned from any of the other above queries.
2367 Using this allows you to markedly speed up your queries if you
2368 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2370 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2372 Warning: This is an experimental method and subject to change.
2374 This returns arbitrarily generated SQL. It's a really basic shortcut.
2375 It will return two different things, depending on return context:
2377 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2378 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2380 These would return the following:
2382 # First calling form
2383 $stmt = "CREATE TABLE test (?, ?)";
2384 @bind = (field1, field2);
2386 # Second calling form
2387 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2389 Depending on what you're trying to do, it's up to you to choose the correct
2390 format. In this example, the second form is what you would want.
2394 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2398 ALTER SESSION SET nls_date_format = 'MM/YY'
2400 You get the idea. Strings get their case twiddled, but everything
2401 else remains verbatim.
2403 =head1 EXPORTABLE FUNCTIONS
2405 =head2 is_plain_value
2407 Determines if the supplied argument is a plain value as understood by this
2412 =item * The value is C<undef>
2414 =item * The value is a non-reference
2416 =item * The value is an object with stringification overloading
2418 =item * The value is of the form C<< { -value => $anything } >>
2422 On failure returns C<undef>, on success returns a B<scalar> reference
2423 to the original supplied argument.
2429 The stringification overloading detection is rather advanced: it takes
2430 into consideration not only the presence of a C<""> overload, but if that
2431 fails also checks for enabled
2432 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2433 on either C<0+> or C<bool>.
2435 Unfortunately testing in the field indicates that this
2436 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2437 but only when very large numbers of stringifying objects are involved.
2438 At the time of writing ( Sep 2014 ) there is no clear explanation of
2439 the direct cause, nor is there a manageably small test case that reliably
2440 reproduces the problem.
2442 If you encounter any of the following exceptions in B<random places within
2443 your application stack> - this module may be to blame:
2445 Operation "ne": no method found,
2446 left argument in overloaded package <something>,
2447 right argument in overloaded package <something>
2451 Stub found while resolving method "???" overloading """" in package <something>
2453 If you fall victim to the above - please attempt to reduce the problem
2454 to something that could be sent to the L<SQL::Abstract developers
2455 |DBIx::Class/GETTING HELP/SUPPORT>
2456 (either publicly or privately). As a workaround in the meantime you can
2457 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2458 value, which will most likely eliminate your problem (at the expense of
2459 not being able to properly detect exotic forms of stringification).
2461 This notice and environment variable will be removed in a future version,
2462 as soon as the underlying problem is found and a reliable workaround is
2467 =head2 is_literal_value
2469 Determines if the supplied argument is a literal value as understood by this
2474 =item * C<\$sql_string>
2476 =item * C<\[ $sql_string, @bind_values ]>
2480 On failure returns C<undef>, on success returns an B<array> reference
2481 containing the unpacked version of the supplied literal SQL and bind values.
2483 =head1 WHERE CLAUSES
2487 This module uses a variation on the idea from L<DBIx::Abstract>. It
2488 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2489 module is that things in arrays are OR'ed, and things in hashes
2492 The easiest way to explain is to show lots of examples. After
2493 each C<%where> hash shown, it is assumed you used:
2495 my($stmt, @bind) = $sql->where(\%where);
2497 However, note that the C<%where> hash can be used directly in any
2498 of the other functions as well, as described above.
2500 =head2 Key-value pairs
2502 So, let's get started. To begin, a simple hash:
2506 status => 'completed'
2509 Is converted to SQL C<key = val> statements:
2511 $stmt = "WHERE user = ? AND status = ?";
2512 @bind = ('nwiger', 'completed');
2514 One common thing I end up doing is having a list of values that
2515 a field can be in. To do this, simply specify a list inside of
2520 status => ['assigned', 'in-progress', 'pending'];
2523 This simple code will create the following:
2525 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2526 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2528 A field associated to an empty arrayref will be considered a
2529 logical false and will generate 0=1.
2531 =head2 Tests for NULL values
2533 If the value part is C<undef> then this is converted to SQL <IS NULL>
2542 $stmt = "WHERE user = ? AND status IS NULL";
2545 To test if a column IS NOT NULL:
2549 status => { '!=', undef },
2552 =head2 Specific comparison operators
2554 If you want to specify a different type of operator for your comparison,
2555 you can use a hashref for a given column:
2559 status => { '!=', 'completed' }
2562 Which would generate:
2564 $stmt = "WHERE user = ? AND status != ?";
2565 @bind = ('nwiger', 'completed');
2567 To test against multiple values, just enclose the values in an arrayref:
2569 status => { '=', ['assigned', 'in-progress', 'pending'] };
2571 Which would give you:
2573 "WHERE status = ? OR status = ? OR status = ?"
2576 The hashref can also contain multiple pairs, in which case it is expanded
2577 into an C<AND> of its elements:
2581 status => { '!=', 'completed', -not_like => 'pending%' }
2584 # Or more dynamically, like from a form
2585 $where{user} = 'nwiger';
2586 $where{status}{'!='} = 'completed';
2587 $where{status}{'-not_like'} = 'pending%';
2589 # Both generate this
2590 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2591 @bind = ('nwiger', 'completed', 'pending%');
2594 To get an OR instead, you can combine it with the arrayref idea:
2598 priority => [ { '=', 2 }, { '>', 5 } ]
2601 Which would generate:
2603 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2604 @bind = ('2', '5', 'nwiger');
2606 If you want to include literal SQL (with or without bind values), just use a
2607 scalar reference or reference to an arrayref as the value:
2610 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2611 date_expires => { '<' => \"now()" }
2614 Which would generate:
2616 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2617 @bind = ('11/26/2008');
2620 =head2 Logic and nesting operators
2622 In the example above,
2623 there is a subtle trap if you want to say something like
2624 this (notice the C<AND>):
2626 WHERE priority != ? AND priority != ?
2628 Because, in Perl you I<can't> do this:
2630 priority => { '!=' => 2, '!=' => 1 }
2632 As the second C<!=> key will obliterate the first. The solution
2633 is to use the special C<-modifier> form inside an arrayref:
2635 priority => [ -and => {'!=', 2},
2639 Normally, these would be joined by C<OR>, but the modifier tells it
2640 to use C<AND> instead. (Hint: You can use this in conjunction with the
2641 C<logic> option to C<new()> in order to change the way your queries
2642 work by default.) B<Important:> Note that the C<-modifier> goes
2643 B<INSIDE> the arrayref, as an extra first element. This will
2644 B<NOT> do what you think it might:
2646 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2648 Here is a quick list of equivalencies, since there is some overlap:
2651 status => {'!=', 'completed', 'not like', 'pending%' }
2652 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2655 status => {'=', ['assigned', 'in-progress']}
2656 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2657 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2661 =head2 Special operators: IN, BETWEEN, etc.
2663 You can also use the hashref format to compare a list of fields using the
2664 C<IN> comparison operator, by specifying the list as an arrayref:
2667 status => 'completed',
2668 reportid => { -in => [567, 2335, 2] }
2671 Which would generate:
2673 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2674 @bind = ('completed', '567', '2335', '2');
2676 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2679 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2680 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2681 'sqltrue' (by default: C<1=1>).
2683 In addition to the array you can supply a chunk of literal sql or
2684 literal sql with bind:
2687 customer => { -in => \[
2688 'SELECT cust_id FROM cust WHERE balance > ?',
2691 status => { -in => \'SELECT status_codes FROM states' },
2697 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2698 AND status IN ( SELECT status_codes FROM states )
2702 Finally, if the argument to C<-in> is not a reference, it will be
2703 treated as a single-element array.
2705 Another pair of operators is C<-between> and C<-not_between>,
2706 used with an arrayref of two values:
2710 completion_date => {
2711 -not_between => ['2002-10-01', '2003-02-06']
2717 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2719 Just like with C<-in> all plausible combinations of literal SQL
2723 start0 => { -between => [ 1, 2 ] },
2724 start1 => { -between => \["? AND ?", 1, 2] },
2725 start2 => { -between => \"lower(x) AND upper(y)" },
2726 start3 => { -between => [
2728 \["upper(?)", 'stuff' ],
2735 ( start0 BETWEEN ? AND ? )
2736 AND ( start1 BETWEEN ? AND ? )
2737 AND ( start2 BETWEEN lower(x) AND upper(y) )
2738 AND ( start3 BETWEEN lower(x) AND upper(?) )
2740 @bind = (1, 2, 1, 2, 'stuff');
2743 These are the two builtin "special operators"; but the
2744 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2746 =head2 Unary operators: bool
2748 If you wish to test against boolean columns or functions within your
2749 database you can use the C<-bool> and C<-not_bool> operators. For
2750 example to test the column C<is_user> being true and the column
2751 C<is_enabled> being false you would use:-
2755 -not_bool => 'is_enabled',
2760 WHERE is_user AND NOT is_enabled
2762 If a more complex combination is required, testing more conditions,
2763 then you should use the and/or operators:-
2768 -not_bool => { two=> { -rlike => 'bar' } },
2769 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2780 (NOT ( three = ? OR three > ? ))
2783 =head2 Nested conditions, -and/-or prefixes
2785 So far, we've seen how multiple conditions are joined with a top-level
2786 C<AND>. We can change this by putting the different conditions we want in
2787 hashes and then putting those hashes in an array. For example:
2792 status => { -like => ['pending%', 'dispatched'] },
2796 status => 'unassigned',
2800 This data structure would create the following:
2802 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2803 OR ( user = ? AND status = ? ) )";
2804 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2807 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2808 to change the logic inside:
2814 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2815 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2822 $stmt = "WHERE ( user = ?
2823 AND ( ( workhrs > ? AND geo = ? )
2824 OR ( workhrs < ? OR geo = ? ) ) )";
2825 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2827 =head3 Algebraic inconsistency, for historical reasons
2829 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2830 operator goes C<outside> of the nested structure; whereas when connecting
2831 several constraints on one column, the C<-and> operator goes
2832 C<inside> the arrayref. Here is an example combining both features:
2835 -and => [a => 1, b => 2],
2836 -or => [c => 3, d => 4],
2837 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2842 WHERE ( ( ( a = ? AND b = ? )
2843 OR ( c = ? OR d = ? )
2844 OR ( e LIKE ? AND e LIKE ? ) ) )
2846 This difference in syntax is unfortunate but must be preserved for
2847 historical reasons. So be careful: the two examples below would
2848 seem algebraically equivalent, but they are not
2851 { -like => 'foo%' },
2852 { -like => '%bar' },
2854 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2857 { col => { -like => 'foo%' } },
2858 { col => { -like => '%bar' } },
2860 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2863 =head2 Literal SQL and value type operators
2865 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2866 side" is a column name and the "right side" is a value (normally rendered as
2867 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2868 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2869 alter this behavior. There are several ways of doing so.
2873 This is a virtual operator that signals the string to its right side is an
2874 identifier (a column name) and not a value. For example to compare two
2875 columns you would write:
2878 priority => { '<', 2 },
2879 requestor => { -ident => 'submitter' },
2884 $stmt = "WHERE priority < ? AND requestor = submitter";
2887 If you are maintaining legacy code you may see a different construct as
2888 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2893 This is a virtual operator that signals that the construct to its right side
2894 is a value to be passed to DBI. This is for example necessary when you want
2895 to write a where clause against an array (for RDBMS that support such
2896 datatypes). For example:
2899 array => { -value => [1, 2, 3] }
2904 $stmt = 'WHERE array = ?';
2905 @bind = ([1, 2, 3]);
2907 Note that if you were to simply say:
2913 the result would probably not be what you wanted:
2915 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2920 Finally, sometimes only literal SQL will do. To include a random snippet
2921 of SQL verbatim, you specify it as a scalar reference. Consider this only
2922 as a last resort. Usually there is a better way. For example:
2925 priority => { '<', 2 },
2926 requestor => { -in => \'(SELECT name FROM hitmen)' },
2931 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2934 Note that in this example, you only get one bind parameter back, since
2935 the verbatim SQL is passed as part of the statement.
2939 Never use untrusted input as a literal SQL argument - this is a massive
2940 security risk (there is no way to check literal snippets for SQL
2941 injections and other nastyness). If you need to deal with untrusted input
2942 use literal SQL with placeholders as described next.
2944 =head3 Literal SQL with placeholders and bind values (subqueries)
2946 If the literal SQL to be inserted has placeholders and bind values,
2947 use a reference to an arrayref (yes this is a double reference --
2948 not so common, but perfectly legal Perl). For example, to find a date
2949 in Postgres you can use something like this:
2952 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2957 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2960 Note that you must pass the bind values in the same format as they are returned
2961 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2962 to C<columns>, you must provide the bind values in the
2963 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2964 scalar value; most commonly the column name, but you can use any scalar value
2965 (including references and blessed references), L<SQL::Abstract> will simply
2966 pass it through intact. So if C<bindtype> is set to C<columns> the above
2967 example will look like:
2970 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2973 Literal SQL is especially useful for nesting parenthesized clauses in the
2974 main SQL query. Here is a first example:
2976 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2980 bar => \["IN ($sub_stmt)" => @sub_bind],
2985 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2986 WHERE c2 < ? AND c3 LIKE ?))";
2987 @bind = (1234, 100, "foo%");
2989 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2990 are expressed in the same way. Of course the C<$sub_stmt> and
2991 its associated bind values can be generated through a former call
2994 my ($sub_stmt, @sub_bind)
2995 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2996 c3 => {-like => "foo%"}});
2999 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3002 In the examples above, the subquery was used as an operator on a column;
3003 but the same principle also applies for a clause within the main C<%where>
3004 hash, like an EXISTS subquery:
3006 my ($sub_stmt, @sub_bind)
3007 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3008 my %where = ( -and => [
3010 \["EXISTS ($sub_stmt)" => @sub_bind],
3015 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3016 WHERE c1 = ? AND c2 > t0.c0))";
3020 Observe that the condition on C<c2> in the subquery refers to
3021 column C<t0.c0> of the main query: this is I<not> a bind
3022 value, so we have to express it through a scalar ref.
3023 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3024 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3025 what we wanted here.
3027 Finally, here is an example where a subquery is used
3028 for expressing unary negation:
3030 my ($sub_stmt, @sub_bind)
3031 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3032 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3034 lname => {like => '%son%'},
3035 \["NOT ($sub_stmt)" => @sub_bind],
3040 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3041 @bind = ('%son%', 10, 20)
3043 =head3 Deprecated usage of Literal SQL
3045 Below are some examples of archaic use of literal SQL. It is shown only as
3046 reference for those who deal with legacy code. Each example has a much
3047 better, cleaner and safer alternative that users should opt for in new code.
3053 my %where = ( requestor => \'IS NOT NULL' )
3055 $stmt = "WHERE requestor IS NOT NULL"
3057 This used to be the way of generating NULL comparisons, before the handling
3058 of C<undef> got formalized. For new code please use the superior syntax as
3059 described in L</Tests for NULL values>.
3063 my %where = ( requestor => \'= submitter' )
3065 $stmt = "WHERE requestor = submitter"
3067 This used to be the only way to compare columns. Use the superior L</-ident>
3068 method for all new code. For example an identifier declared in such a way
3069 will be properly quoted if L</quote_char> is properly set, while the legacy
3070 form will remain as supplied.
3074 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3076 $stmt = "WHERE completed > ? AND is_ready"
3077 @bind = ('2012-12-21')
3079 Using an empty string literal used to be the only way to express a boolean.
3080 For all new code please use the much more readable
3081 L<-bool|/Unary operators: bool> operator.
3087 These pages could go on for a while, since the nesting of the data
3088 structures this module can handle are pretty much unlimited (the
3089 module implements the C<WHERE> expansion as a recursive function
3090 internally). Your best bet is to "play around" with the module a
3091 little to see how the data structures behave, and choose the best
3092 format for your data based on that.
3094 And of course, all the values above will probably be replaced with
3095 variables gotten from forms or the command line. After all, if you
3096 knew everything ahead of time, you wouldn't have to worry about
3097 dynamically-generating SQL and could just hardwire it into your
3100 =head1 ORDER BY CLAUSES
3102 Some functions take an order by clause. This can either be a scalar (just a
3103 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3104 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3107 Given | Will Generate
3108 ---------------------------------------------------------------
3110 'colA' | ORDER BY colA
3112 [qw/colA colB/] | ORDER BY colA, colB
3114 {-asc => 'colA'} | ORDER BY colA ASC
3116 {-desc => 'colB'} | ORDER BY colB DESC
3118 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3120 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3122 \'colA DESC' | ORDER BY colA DESC
3124 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3125 | /* ...with $x bound to ? */
3128 { -asc => 'colA' }, | colA ASC,
3129 { -desc => [qw/colB/] }, | colB DESC,
3130 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3131 \'colE DESC', | colE DESC,
3132 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3133 ] | /* ...with $x bound to ? */
3134 ===============================================================
3138 =head1 SPECIAL OPERATORS
3140 my $sqlmaker = SQL::Abstract->new(special_ops => [
3144 my ($self, $field, $op, $arg) = @_;
3150 handler => 'method_name',
3154 A "special operator" is a SQL syntactic clause that can be
3155 applied to a field, instead of a usual binary operator.
3158 WHERE field IN (?, ?, ?)
3159 WHERE field BETWEEN ? AND ?
3160 WHERE MATCH(field) AGAINST (?, ?)
3162 Special operators IN and BETWEEN are fairly standard and therefore
3163 are builtin within C<SQL::Abstract> (as the overridable methods
3164 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3165 like the MATCH .. AGAINST example above which is specific to MySQL,
3166 you can write your own operator handlers - supply a C<special_ops>
3167 argument to the C<new> method. That argument takes an arrayref of
3168 operator definitions; each operator definition is a hashref with two
3175 the regular expression to match the operator
3179 Either a coderef or a plain scalar method name. In both cases
3180 the expected return is C<< ($sql, @bind) >>.
3182 When supplied with a method name, it is simply called on the
3183 L<SQL::Abstract> object as:
3185 $self->$method_name($field, $op, $arg)
3189 $field is the LHS of the operator
3190 $op is the part that matched the handler regex
3193 When supplied with a coderef, it is called as:
3195 $coderef->($self, $field, $op, $arg)
3200 For example, here is an implementation
3201 of the MATCH .. AGAINST syntax for MySQL
3203 my $sqlmaker = SQL::Abstract->new(special_ops => [
3205 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3206 {regex => qr/^match$/i,
3208 my ($self, $field, $op, $arg) = @_;
3209 $arg = [$arg] if not ref $arg;
3210 my $label = $self->_quote($field);
3211 my ($placeholder) = $self->_convert('?');
3212 my $placeholders = join ", ", (($placeholder) x @$arg);
3213 my $sql = $self->_sqlcase('match') . " ($label) "
3214 . $self->_sqlcase('against') . " ($placeholders) ";
3215 my @bind = $self->_bindtype($field, @$arg);
3216 return ($sql, @bind);
3223 =head1 UNARY OPERATORS
3225 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3229 my ($self, $op, $arg) = @_;
3235 handler => 'method_name',
3239 A "unary operator" is a SQL syntactic clause that can be
3240 applied to a field - the operator goes before the field
3242 You can write your own operator handlers - supply a C<unary_ops>
3243 argument to the C<new> method. That argument takes an arrayref of
3244 operator definitions; each operator definition is a hashref with two
3251 the regular expression to match the operator
3255 Either a coderef or a plain scalar method name. In both cases
3256 the expected return is C<< $sql >>.
3258 When supplied with a method name, it is simply called on the
3259 L<SQL::Abstract> object as:
3261 $self->$method_name($op, $arg)
3265 $op is the part that matched the handler regex
3266 $arg is the RHS or argument of the operator
3268 When supplied with a coderef, it is called as:
3270 $coderef->($self, $op, $arg)
3278 Thanks to some benchmarking by Mark Stosberg, it turns out that
3279 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3280 I must admit this wasn't an intentional design issue, but it's a
3281 byproduct of the fact that you get to control your C<DBI> handles
3284 To maximize performance, use a code snippet like the following:
3286 # prepare a statement handle using the first row
3287 # and then reuse it for the rest of the rows
3289 for my $href (@array_of_hashrefs) {
3290 $stmt ||= $sql->insert('table', $href);
3291 $sth ||= $dbh->prepare($stmt);
3292 $sth->execute($sql->values($href));
3295 The reason this works is because the keys in your C<$href> are sorted
3296 internally by B<SQL::Abstract>. Thus, as long as your data retains
3297 the same structure, you only have to generate the SQL the first time
3298 around. On subsequent queries, simply use the C<values> function provided
3299 by this module to return your values in the correct order.
3301 However this depends on the values having the same type - if, for
3302 example, the values of a where clause may either have values
3303 (resulting in sql of the form C<column = ?> with a single bind
3304 value), or alternatively the values might be C<undef> (resulting in
3305 sql of the form C<column IS NULL> with no bind value) then the
3306 caching technique suggested will not work.
3310 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3311 really like this part (I do, at least). Building up a complex query
3312 can be as simple as the following:
3319 use CGI::FormBuilder;
3322 my $form = CGI::FormBuilder->new(...);
3323 my $sql = SQL::Abstract->new;
3325 if ($form->submitted) {
3326 my $field = $form->field;
3327 my $id = delete $field->{id};
3328 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3331 Of course, you would still have to connect using C<DBI> to run the
3332 query, but the point is that if you make your form look like your
3333 table, the actual query script can be extremely simplistic.
3335 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3336 a fast interface to returning and formatting data. I frequently
3337 use these three modules together to write complex database query
3338 apps in under 50 lines.
3340 =head1 HOW TO CONTRIBUTE
3342 Contributions are always welcome, in all usable forms (we especially
3343 welcome documentation improvements). The delivery methods include git-
3344 or unified-diff formatted patches, GitHub pull requests, or plain bug
3345 reports either via RT or the Mailing list. Contributors are generally
3346 granted full access to the official repository after their first several
3347 patches pass successful review.
3349 This project is maintained in a git repository. The code and related tools are
3350 accessible at the following locations:
3354 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3356 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3358 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3360 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3366 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3367 Great care has been taken to preserve the I<published> behavior
3368 documented in previous versions in the 1.* family; however,
3369 some features that were previously undocumented, or behaved
3370 differently from the documentation, had to be changed in order
3371 to clarify the semantics. Hence, client code that was relying
3372 on some dark areas of C<SQL::Abstract> v1.*
3373 B<might behave differently> in v1.50.
3375 The main changes are:
3381 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3385 support for the { operator => \"..." } construct (to embed literal SQL)
3389 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3393 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3397 defensive programming: check arguments
3401 fixed bug with global logic, which was previously implemented
3402 through global variables yielding side-effects. Prior versions would
3403 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3404 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3405 Now this is interpreted
3406 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3411 fixed semantics of _bindtype on array args
3415 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3416 we just avoid shifting arrays within that tree.
3420 dropped the C<_modlogic> function
3424 =head1 ACKNOWLEDGEMENTS
3426 There are a number of individuals that have really helped out with
3427 this module. Unfortunately, most of them submitted bugs via CPAN
3428 so I have no idea who they are! But the people I do know are:
3430 Ash Berlin (order_by hash term support)
3431 Matt Trout (DBIx::Class support)
3432 Mark Stosberg (benchmarking)
3433 Chas Owens (initial "IN" operator support)
3434 Philip Collins (per-field SQL functions)
3435 Eric Kolve (hashref "AND" support)
3436 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3437 Dan Kubb (support for "quote_char" and "name_sep")
3438 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3439 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3440 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3441 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3442 Oliver Charles (support for "RETURNING" after "INSERT")
3448 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3452 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3454 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3456 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3457 While not an official support venue, C<DBIx::Class> makes heavy use of
3458 C<SQL::Abstract>, and as such list members there are very familiar with
3459 how to create queries.
3463 This module is free software; you may copy this under the same
3464 terms as perl itself (either the GNU General Public License or
3465 the Artistic License)