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',
160 'between' => '_expand_between',
161 'not_between' => '_expand_between',
162 'in' => '_expand_in',
163 'not_in' => '_expand_in',
164 'nest' => '_expand_nest',
165 (map +($_ => '_expand_op_andor'), ('and', 'or')),
166 (map +($_ => '_expand_op_is'), ('is', 'is_not')),
167 'ident' => '_expand_ident',
168 'value' => '_expand_value',
171 (map +($_, "_render_$_"), qw(op func bind ident literal row)),
174 (map +($_ => '_render_op_between'), 'between', 'not_between'),
175 (map +($_ => '_render_op_in'), 'in', 'not_in'),
176 (map +($_ => '_render_unop_postfix'),
177 'is_null', 'is_not_null', 'asc', 'desc',
179 (not => '_render_unop_paren'),
180 (map +($_ => '_render_op_andor'), qw(and or)),
181 ',' => '_render_op_multop',
184 delete => [ qw(target where returning) ],
185 update => [ qw(target set where returning) ],
188 'delete.from' => '_expand_delete_clause_target',
189 'update.update' => '_expand_update_clause_target',
192 'delete.target' => '_render_delete_clause_target',
193 'update.target' => '_render_update_clause_target',
197 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
198 $Defaults{expand}{$stmt} = '_expand_statement';
199 $Defaults{render}{$stmt} = '_render_statement';
200 foreach my $clause (@{$Defaults{clauses_of}{$stmt}}) {
201 $Defaults{expand_clause}{"${stmt}.${clause}"}
202 = "_expand_${stmt}_clause_${clause}";
208 my $class = ref($self) || $self;
209 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
211 # choose our case by keeping an option around
212 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
214 # default logic for interpreting arrayrefs
215 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
217 # how to return bind vars
218 $opt{bindtype} ||= 'normal';
220 # default comparison is "=", but can be overridden
223 # try to recognize which are the 'equality' and 'inequality' ops
224 # (temporary quickfix (in 2007), should go through a more seasoned API)
225 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
226 $opt{inequality_op} = qr/^( != | <> )$/ix;
228 $opt{like_op} = qr/^ (is_)?r?like $/xi;
229 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
232 $opt{sqltrue} ||= '1=1';
233 $opt{sqlfalse} ||= '0=1';
236 $opt{special_ops} ||= [];
238 if ($class->isa('DBIx::Class::SQLMaker')) {
239 $opt{warn_once_on_nest} = 1;
240 $opt{disable_old_special_ops} = 1;
244 $opt{unary_ops} ||= [];
246 # rudimentary sanity-check for user supplied bits treated as functions/operators
247 # If a purported function matches this regular expression, an exception is thrown.
248 # Literal SQL is *NOT* subject to this check, only functions (and column names
249 # when quoting is not in effect)
252 # need to guard against ()'s in column names too, but this will break tons of
253 # hacks... ideas anyone?
254 $opt{injection_guard} ||= qr/
260 $opt{expand_unary} = {};
262 foreach my $name (sort keys %Defaults) {
263 $opt{$name} = { %{$Defaults{$name}} };
266 if ($opt{lazy_join_sql_parts}) {
267 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
268 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
271 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
273 return bless \%opt, $class;
276 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
277 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
279 sub _assert_pass_injection_guard {
280 if ($_[1] =~ $_[0]->{injection_guard}) {
281 my $class = ref $_[0];
282 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
283 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
284 . "{injection_guard} attribute to ${class}->new()"
289 #======================================================================
291 #======================================================================
295 my $table = $self->_table(shift);
296 my $data = shift || return;
301 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
303 my @parts = ([ $self->_sqlcase('insert into').' '.$table ]);
304 push @parts, $self->render_aqt($f_aqt) if $f_aqt;
305 push @parts, [ $self->_sqlcase('values') ], $self->render_aqt($v_aqt);
307 if ($options->{returning}) {
308 push @parts, [ $self->_insert_returning($options) ];
311 my ($sql, @bind) = @{ $self->join_query_parts(' ', @parts) };
312 return wantarray ? ($sql, @bind) : $sql;
315 sub _expand_insert_values {
316 my ($self, $data) = @_;
317 if (is_literal_value($data)) {
318 (undef, $self->expand_expr($data));
320 my ($fields, $values) = (
321 ref($data) eq 'HASH' ?
322 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
326 # no names (arrayref) means can't generate bindtype
327 !($fields) && $self->{bindtype} eq 'columns'
328 && belch "can't do 'columns' bindtype when called with arrayref";
332 ? $self->expand_expr({ -row => $fields }, -ident)
337 local our $Cur_Col_Meta = $fields->[$_];
338 $self->_expand_insert_value($values->[$_])
345 # So that subclasses can override INSERT ... RETURNING separately from
346 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
347 sub _insert_returning { shift->_returning(@_) }
350 my ($self, $options) = @_;
352 my $f = $options->{returning};
354 my ($sql, @bind) = @{ $self->render_aqt(
355 $self->_expand_maybe_list_expr($f, -ident)
357 return ($self->_sqlcase(' returning ').$sql, @bind);
360 sub _expand_insert_value {
363 my $k = our $Cur_Col_Meta;
365 if (ref($v) eq 'ARRAY') {
366 if ($self->{array_datatypes}) {
367 return +{ -bind => [ $k, $v ] };
369 my ($sql, @bind) = @$v;
370 $self->_assert_bindval_matches_bindtype(@bind);
371 return +{ -literal => $v };
373 if (ref($v) eq 'HASH') {
374 if (grep !/^-/, keys %$v) {
375 belch "HASH ref as bind value in insert is not supported";
376 return +{ -bind => [ $k, $v ] };
380 return +{ -bind => [ $k, undef ] };
382 return $self->expand_expr($v);
387 #======================================================================
389 #======================================================================
392 my ($self, $table, $set, $where, $options) = @_;
395 if (ref($table) eq 'HASH') {
399 @clauses{qw(target set where)} = ($table, $set, $where);
400 puke "Unsupported data type specified to \$sql->update"
401 unless ref($clauses{set}) eq 'HASH';
402 @clauses{keys %$options} = values %$options;
406 my @rendered = $self->render_statement({ -update => $stmt });
407 return wantarray ? @rendered : $rendered[0];
410 sub _render_update_clause_target {
411 my ($self, undef, $target) = @_;
412 $self->join_query_parts(' ', $self->format_keyword('update'), $target);
415 sub _update_set_values {
416 my ($self, $data) = @_;
418 return @{ $self->render_aqt(
419 $self->_expand_update_set_values(undef, $data),
423 sub _expand_update_set_values {
424 my ($self, undef, $data) = @_;
425 $self->_expand_maybe_list_expr( [
428 $set = { -bind => $_ } unless defined $set;
429 +{ -op => [ '=', { -ident => $k }, $set ] };
435 ? ($self->{array_datatypes}
436 ? [ $k, +{ -bind => [ $k, $v ] } ]
437 : [ $k, +{ -literal => $v } ])
439 local our $Cur_Col_Meta = $k;
440 [ $k, $self->_expand_expr($v) ]
447 sub _expand_update_clause_target {
448 my ($self, undef, $target) = @_;
449 +(target => $self->_expand_maybe_list_expr($target, -ident));
452 sub _expand_update_clause_set {
453 return $_[2] if ref($_[2]) eq 'HASH' and ($_[2]->{-op}||[''])->[0] eq ',';
454 +(set => $_[0]->_expand_update_set_values($_[1], $_[2]));
457 sub _expand_update_clause_where {
458 +(where => $_[0]->expand_expr($_[2]));
461 sub _expand_update_clause_returning {
462 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
465 # So that subclasses can override UPDATE ... RETURNING separately from
467 sub _update_returning { shift->_returning(@_) }
471 #======================================================================
473 #======================================================================
478 my $table = $self->_table(shift);
479 my $fields = shift || '*';
483 my ($fields_sql, @bind) = $self->_select_fields($fields);
485 my ($where_sql, @where_bind) = $self->where($where, $order);
486 push @bind, @where_bind;
488 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
489 $self->_sqlcase('from'), $table)
492 return wantarray ? ($sql, @bind) : $sql;
496 my ($self, $fields) = @_;
497 return $fields unless ref($fields);
498 return @{ $self->render_aqt(
499 $self->_expand_maybe_list_expr($fields, '-ident')
503 #======================================================================
505 #======================================================================
508 my ($self, $table, $where, $options) = @_;
511 if (ref($table) eq 'HASH') {
514 my %clauses = (target => $table, where => $where, %{$options||{}});
518 my @rendered = $self->render_statement({ -delete => $stmt });
519 return wantarray ? @rendered : $rendered[0];
522 # So that subclasses can override DELETE ... RETURNING separately from
524 sub _delete_returning { shift->_returning(@_) }
526 sub _expand_delete_clause_target {
527 +(target => $_[0]->_expand_maybe_list_expr($_[2], -ident));
530 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
532 sub _expand_delete_clause_returning {
533 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
536 sub _render_delete_clause_target {
537 my ($self, undef, $from) = @_;
538 $self->join_query_parts(' ', $self->format_keyword('delete from'), $from);
541 #======================================================================
543 #======================================================================
547 # Finally, a separate routine just to handle WHERE clauses
549 my ($self, $where, $order) = @_;
551 local $self->{convert_where} = $self->{convert};
554 my ($sql, @bind) = defined($where)
555 ? $self->_recurse_where($where)
557 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
561 my ($order_sql, @order_bind) = $self->_order_by($order);
563 push @bind, @order_bind;
566 return wantarray ? ($sql, @bind) : $sql;
569 { our $Default_Scalar_To = -value }
572 my ($self, $expr, $default_scalar_to) = @_;
573 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
574 $self->_expand_expr($expr);
578 my ($self, $aqt, $top_level) = @_;
579 my ($k, $v, @rest) = %$aqt;
581 die "Not a node type: $k" unless $k =~ s/^-//;
582 if (my $meth = $self->{render}{$k}) {
583 local our $Render_Top_Level = $top_level;
584 return $self->$meth($k, $v);
586 die "notreached: $k";
590 my ($self, $expr, $default_scalar_to) = @_;
591 return @{ $self->render_aqt(
592 $self->expand_expr($expr, $default_scalar_to)
596 sub render_statement {
597 my ($self, $expr, $default_scalar_to) = @_;
599 $self->expand_expr($expr, $default_scalar_to), 1
603 sub _expand_statement {
604 my ($self, $type, $args) = @_;
605 my $ec = $self->{expand_clause};
608 $args->{$type} = delete $args->{_}
610 return +{ "-${type}" => +{
612 my $val = $args->{$_};
613 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
614 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
620 ($_ => $self->expand_expr($val))
626 sub _render_statement {
627 my ($self, $type, $args) = @_;
629 foreach my $clause (@{$self->{clauses_of}{$type}}) {
630 next unless my $clause_expr = $args->{$clause};
632 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
633 $self->$rdr($clause, $clause_expr);
635 my $r = $self->render_aqt($clause_expr, 1);
636 next unless defined $r->[0] and length $r->[0];
637 $self->join_query_parts(' ',
638 $self->format_keyword($clause),
645 my $q = $self->join_query_parts(' ', @parts);
646 return $self->join_query_parts('',
647 (our $Render_Top_Level ? $q : ('(', $q, ')'))
652 my ($self, $raw) = @_;
654 return $op if grep $_->{$op}, @{$self}{qw(is_op expand_op render_op)};
655 s/^-(?=.)//, s/\s+/_/g for $op;
660 my ($self, $expr) = @_;
661 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
662 return undef unless defined($expr);
663 if (ref($expr) eq 'HASH') {
664 return undef unless my $kc = keys %$expr;
666 return $self->_expand_op_andor(and => $expr);
668 my ($key, $value) = %$expr;
669 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
670 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
671 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
673 return $self->_expand_hashpair($key, $value);
675 if (ref($expr) eq 'ARRAY') {
676 return $self->_expand_op_andor(lc($self->{logic}), $expr);
678 if (my $literal = is_literal_value($expr)) {
679 return +{ -literal => $literal };
681 if (!ref($expr) or Scalar::Util::blessed($expr)) {
682 return $self->_expand_scalar($expr);
687 sub _expand_hashpair {
688 my ($self, $k, $v) = @_;
689 unless (defined($k) and length($k)) {
690 if (defined($k) and my $literal = is_literal_value($v)) {
691 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
692 return { -literal => $literal };
694 puke "Supplying an empty left hand side argument is not supported";
697 return $self->_expand_hashpair_op($k, $v);
698 } elsif ($k =~ /^[^\w]/i) {
699 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
700 return $self->_expand_op(
701 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
704 return $self->_expand_hashpair_ident($k, $v);
707 sub _expand_hashpair_ident {
708 my ($self, $k, $v) = @_;
710 local our $Cur_Col_Meta = $k;
712 # hash with multiple or no elements is andor
714 if (ref($v) eq 'HASH' and keys %$v != 1) {
715 return $self->_expand_op_andor(and => $v, $k);
718 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
720 if (is_undef_value($v)) {
721 return $self->_expand_hashpair_cmp($k => undef);
724 # scalars and objects get expanded as whatever requested or values
726 if (!ref($v) or Scalar::Util::blessed($v)) {
727 return $self->_expand_hashpair_scalar($k, $v);
730 # single key hashref is a hashtriple
732 if (ref($v) eq 'HASH') {
733 return $self->_expand_hashtriple($k, %$v);
736 # arrayref needs re-engineering over the elements
738 if (ref($v) eq 'ARRAY') {
739 return $self->sqlfalse unless @$v;
740 $self->_debug("ARRAY($k) means distribute over elements");
742 $v->[0] =~ /^-(and|or)$/i
743 ? (shift(@{$v = [ @$v ]}), $1)
744 : lc($self->{logic} || 'OR')
746 return $self->_expand_op_andor(
751 if (my $literal = is_literal_value($v)) {
753 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
756 my ($sql, @bind) = @$literal;
757 if ($self->{bindtype} eq 'columns') {
759 $self->_assert_bindval_matches_bindtype($_);
762 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
768 my ($self, $expr) = @_;
770 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
773 sub _expand_hashpair_scalar {
774 my ($self, $k, $v) = @_;
776 return $self->_expand_hashpair_cmp(
777 $k, $self->_expand_scalar($v),
781 sub _expand_hashpair_op {
782 my ($self, $k, $v) = @_;
784 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
786 my $op = $self->_normalize_op($k);
790 my $op = join(' ', split '_', $op);
792 # the old special op system requires illegality for top-level use
795 (our $Expand_Depth) == 1
797 List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
799 $self->{disable_old_special_ops}
800 and List::Util::first { $op =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
804 puke "Illegal use of top-level '-$op'"
808 if (my $exp = $self->{expand}{$op}) {
809 return $self->$exp($op, $v);
812 # Ops prefixed with -not_ get converted
814 if (my ($rest) = $op =~/^not_(.*)$/) {
817 $self->_expand_expr({ "-${rest}", $v })
823 # the old unary op system means we should touch nothing and let it work
825 my $op = join(' ', split '_', $op);
827 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
828 return { -op => [ $op, $v ] };
832 # an explicit node type is currently assumed to be expanded (this is almost
833 # certainly wrong and there should be expansion anyway)
835 if ($self->{render}{$op}) {
839 my $type = $self->{unknown_unop_always_func} ? -func : -op;
846 and (keys %$v)[0] =~ /^-/
849 (List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}})
858 ($type eq -func and ref($v) eq 'ARRAY')
859 ? map $self->_expand_expr($_), @$v
860 : $self->_expand_expr($v)
864 sub _expand_hashpair_cmp {
865 my ($self, $k, $v) = @_;
866 $self->_expand_hashtriple($k, $self->{cmp}, $v);
869 sub _expand_hashtriple {
870 my ($self, $k, $vk, $vv) = @_;
872 my $ik = $self->_expand_expr({ -ident => $k });
874 my $op = $self->_normalize_op($vk);
875 $self->_assert_pass_injection_guard($op);
877 if ($op =~ s/ _? \d+ $//x ) {
878 return $self->_expand_expr($k, { $vk, $vv });
880 if (my $x = $self->{expand_op}{$op}) {
881 local our $Cur_Col_Meta = $k;
882 return $self->$x($op, $vv, $k);
886 my $op = join(' ', split '_', $op);
888 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
889 return { -op => [ $op, $ik, $vv ] };
891 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
895 { -op => [ $op, $vv ] }
899 if (ref($vv) eq 'ARRAY') {
901 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
902 ? (shift(@raw), lc $1) : 'or';
903 my @values = map +{ $vk => $_ }, @raw;
905 $op =~ $self->{inequality_op}
906 or $op =~ $self->{not_like_op}
908 if (lc($logic) eq 'or' and @values > 1) {
909 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
910 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
911 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
916 # try to DWIM on equality operators
917 return ($self->_dwim_op_to_is($op,
918 "Supplying an empty arrayref to '%s' is deprecated",
919 "operator '%s' applied on an empty array (field '$k')"
920 ) ? $self->sqlfalse : $self->sqltrue);
922 return $self->_expand_op_andor($logic => \@values, $k);
924 if (is_undef_value($vv)) {
925 my $is = ($self->_dwim_op_to_is($op,
926 "Supplying an undefined argument to '%s' is deprecated",
927 "unexpected operator '%s' with undef operand",
928 ) ? 'is' : 'is not');
930 return $self->_expand_hashpair($k => { $is, undef });
932 local our $Cur_Col_Meta = $k;
936 $self->_expand_expr($vv)
941 my ($self, $raw, $empty, $fail) = @_;
943 my $op = $self->_normalize_op($raw);
945 if ($op =~ /^not$/i) {
948 if ($op =~ $self->{equality_op}) {
951 if ($op =~ $self->{like_op}) {
952 belch(sprintf $empty, uc(join ' ', split '_', $op));
955 if ($op =~ $self->{inequality_op}) {
958 if ($op =~ $self->{not_like_op}) {
959 belch(sprintf $empty, uc(join ' ', split '_', $op));
962 puke(sprintf $fail, $op);
966 my ($self, undef, $args) = @_;
967 my ($func, @args) = @$args;
968 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
972 my ($self, undef, $body, $k) = @_;
973 return $self->_expand_hashpair_cmp(
974 $k, { -ident => $body }
976 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
977 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
979 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
980 ref($body) ? @$body : $body;
981 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
982 unless ($self->{quote_char}) {
983 $self->_assert_pass_injection_guard($_) for @parts;
985 return +{ -ident => \@parts };
989 return $_[0]->_expand_hashpair_cmp(
990 $_[3], { -value => $_[2] },
992 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
996 +{ -op => [ 'not', $_[0]->_expand_expr($_[2]) ] };
1000 my ($self, undef, $args) = @_;
1001 +{ -row => [ map $self->expand_expr($_), @$args ] };
1005 my ($self, undef, $args) = @_;
1006 my ($op, @opargs) = @$args;
1007 if (my $exp = $self->{expand_op}{$op}) {
1008 return $self->$exp($op, \@opargs);
1010 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
1014 my ($self, undef, $v) = @_;
1016 return $self->_expand_expr($v);
1018 puke "-bool => undef not supported" unless defined($v);
1019 return $self->_expand_expr({ -ident => $v });
1022 sub _expand_op_andor {
1023 my ($self, $logop, $v, $k) = @_;
1025 $v = [ map +{ $k, $_ },
1027 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1031 if (ref($v) eq 'HASH') {
1032 return undef unless keys %$v;
1035 map $self->_expand_expr({ $_ => $v->{$_} }),
1039 if (ref($v) eq 'ARRAY') {
1040 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1043 (ref($_) eq 'ARRAY' and @$_)
1044 or (ref($_) eq 'HASH' and %$_)
1050 while (my ($el) = splice @expr, 0, 1) {
1051 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1052 unless defined($el) and length($el);
1053 my $elref = ref($el);
1055 local our $Expand_Depth = 0;
1056 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1057 } elsif ($elref eq 'ARRAY') {
1058 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1059 } elsif (my $l = is_literal_value($el)) {
1060 push @res, { -literal => $l };
1061 } elsif ($elref eq 'HASH') {
1062 local our $Expand_Depth = 0;
1063 push @res, grep defined, $self->_expand_expr($el) if %$el;
1069 # return $res[0] if @res == 1;
1070 return { -op => [ $logop, @res ] };
1076 my ($self, $op, $vv, $k) = @_;
1077 ($k, $vv) = @$vv unless defined $k;
1078 puke "$op can only take undef as argument"
1082 and exists($vv->{-value})
1083 and !defined($vv->{-value})
1085 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1088 sub _expand_between {
1089 my ($self, $op, $vv, $k) = @_;
1090 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1091 my @rhs = map $self->_expand_expr($_),
1092 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1094 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1096 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1098 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1102 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1108 my ($self, $op, $vv, $k) = @_;
1109 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1110 if (my $literal = is_literal_value($vv)) {
1111 my ($sql, @bind) = @$literal;
1112 my $opened_sql = $self->_open_outer_paren($sql);
1114 $op, $self->expand_expr($k, -ident),
1115 { -literal => [ $opened_sql, @bind ] }
1119 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1120 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1121 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1122 . 'will emit the logically correct SQL instead of raising this exception)'
1124 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1126 my @rhs = map $self->expand_expr($_, -value),
1127 map { defined($_) ? $_: puke($undef_err) }
1128 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1129 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1133 $self->expand_expr($k, -ident),
1139 my ($self, undef, $v) = @_;
1140 # DBIx::Class requires a nest warning to be emitted once but the private
1141 # method it overrode to do so no longer exists
1142 if ($self->{warn_once_on_nest}) {
1143 unless (our $Nest_Warned) {
1145 "-nest in search conditions is deprecated, you most probably wanted:\n"
1146 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1151 return $self->_expand_expr($v);
1155 my ($self, undef, $bind) = @_;
1156 return { -bind => $bind };
1159 sub _recurse_where {
1160 my ($self, $where, $logic) = @_;
1162 # Special case: top level simple string treated as literal
1164 my $where_exp = (ref($where)
1165 ? $self->_expand_expr($where, $logic)
1166 : { -literal => [ $where ] });
1168 # dispatch expanded expression
1170 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1171 # DBIx::Class used to call _recurse_where in scalar context
1172 # something else might too...
1174 return ($sql, @bind);
1177 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1183 my ($self, undef, $ident) = @_;
1185 return [ $self->_convert($self->_quote($ident)) ];
1189 my ($self, undef, $values) = @_;
1190 return $self->join_query_parts('',
1192 $self->_render_op(undef, [ ',', @$values ]),
1198 my ($self, undef, $rest) = @_;
1199 my ($func, @args) = @$rest;
1200 return $self->join_query_parts('',
1201 $self->_sqlcase($func),
1202 $self->join_query_parts('',
1204 $self->join_query_parts(', ', @args),
1211 my ($self, undef, $bind) = @_;
1212 return [ $self->_convert('?'), $self->_bindtype(@$bind) ];
1215 sub _render_literal {
1216 my ($self, undef, $literal) = @_;
1217 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1222 my ($self, undef, $v) = @_;
1223 my ($op, @args) = @$v;
1224 if (my $r = $self->{render_op}{$op}) {
1225 return $self->$r($op, \@args);
1230 my $op = join(' ', split '_', $op);
1232 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1233 if ($ss and @args > 1) {
1234 puke "Special op '${op}' requires first value to be identifier"
1235 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1236 my $k = join(($self->{name_sep}||'.'), @$ident);
1237 local our $Expand_Depth = 1;
1238 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1240 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1241 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1244 return $self->_render_unop_paren($op, \@args);
1248 return $self->_render_unop_prefix($op, \@args);
1250 return $self->_render_op_multop($op, \@args);
1256 sub _render_op_between {
1257 my ($self, $op, $args) = @_;
1258 my ($left, $low, $high) = @$args;
1261 puke "Single arg to between must be a literal"
1262 unless $low->{-literal};
1265 +($low, $self->format_keyword('and'), $high);
1268 return $self->join_query_parts(' ',
1269 '(', $left, $self->format_keyword($op), @rh, ')',
1274 my ($self, $op, $args) = @_;
1275 my ($lhs, @rhs) = @$args;
1277 return $self->join_query_parts(' ',
1279 $self->format_keyword($op),
1280 $self->join_query_parts(' ',
1282 $self->join_query_parts(', ', @rhs),
1288 sub _render_op_andor {
1289 my ($self, $op, $args) = @_;
1290 return undef unless @$args;
1291 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1292 my $inner = $self->_render_op_multop($op, $args);
1293 return undef unless defined($inner->[0]) and length($inner->[0]);
1294 return $self->join_query_parts(' ',
1299 sub _render_op_multop {
1300 my ($self, $op, $args) = @_;
1302 return undef unless @parts;
1303 return $self->render_aqt($parts[0]) if @parts == 1;
1304 my $join = ($op eq ','
1306 : ' '.$self->format_keyword($op).' '
1308 return $self->join_query_parts($join, @parts);
1311 sub join_query_parts {
1312 my ($self, $join, @parts) = @_;
1315 ? $self->render_aqt($_)
1316 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1319 $self->{join_sql_parts}->($join, grep defined, map $_->[0], @final),
1320 (map @{$_}[1..$#$_], @final),
1324 sub _render_unop_paren {
1325 my ($self, $op, $v) = @_;
1326 return $self->join_query_parts('',
1327 '(', $self->_render_unop_prefix($op, $v), ')'
1331 sub _render_unop_prefix {
1332 my ($self, $op, $v) = @_;
1333 return $self->join_query_parts(' ',
1334 $self->_sqlcase($op), $v->[0]
1338 sub _render_unop_postfix {
1339 my ($self, $op, $v) = @_;
1340 return $self->join_query_parts(' ',
1341 $v->[0], $self->format_keyword($op),
1345 # Some databases (SQLite) treat col IN (1, 2) different from
1346 # col IN ( (1, 2) ). Use this to strip all outer parens while
1347 # adding them back in the corresponding method
1348 sub _open_outer_paren {
1349 my ($self, $sql) = @_;
1351 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1353 # there are closing parens inside, need the heavy duty machinery
1354 # to reevaluate the extraction starting from $sql (full reevaluation)
1355 if ($inner =~ /\)/) {
1356 require Text::Balanced;
1358 my (undef, $remainder) = do {
1359 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1361 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1364 # the entire expression needs to be a balanced bracketed thing
1365 # (after an extract no remainder sans trailing space)
1366 last if defined $remainder and $remainder =~ /\S/;
1376 #======================================================================
1378 #======================================================================
1380 sub _expand_order_by {
1381 my ($self, $arg) = @_;
1383 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1385 return $self->_expand_maybe_list_expr($arg)
1386 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1388 my $expander = sub {
1389 my ($self, $dir, $expr) = @_;
1390 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1391 foreach my $arg (@to_expand) {
1395 and grep /^-(asc|desc)$/, keys %$arg
1397 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1401 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1403 map $self->expand_expr($_, -ident),
1404 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1405 return undef unless @exp;
1406 return undef if @exp == 1 and not defined($exp[0]);
1407 return +{ -op => [ ',', @exp ] };
1410 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1412 return $self->$expander(undef, $arg);
1416 my ($self, $arg) = @_;
1418 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1420 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1422 return '' unless length($sql);
1424 my $final_sql = $self->_sqlcase(' order by ').$sql;
1426 return ($final_sql, @bind);
1429 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1431 sub _order_by_chunks {
1432 my ($self, $arg) = @_;
1434 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1436 my @res = $self->_chunkify_order_by($expanded);
1437 (ref() ? $_->[0] : $_) .= '' for @res;
1441 sub _chunkify_order_by {
1442 my ($self, $expanded) = @_;
1444 return grep length, @{ $self->render_aqt($expanded) }
1445 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1448 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1449 my ($comma, @list) = @{$_->{-op}};
1450 return map $self->_chunkify_order_by($_), @list;
1452 return $self->render_aqt($_);
1456 #======================================================================
1457 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1458 #======================================================================
1464 $self->_expand_maybe_list_expr($from, -ident)
1469 #======================================================================
1471 #======================================================================
1473 sub _expand_maybe_list_expr {
1474 my ($self, $expr, $default) = @_;
1476 ',', map $self->expand_expr($_, $default),
1477 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1478 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1479 return +{ -op => [ ',',
1480 map $self->expand_expr($_, $default),
1481 ref($expr) eq 'ARRAY' ? @$expr : $expr
1485 # highly optimized, as it's called way too often
1487 # my ($self, $label) = @_;
1489 return '' unless defined $_[1];
1490 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1491 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1493 unless ($_[0]->{quote_char}) {
1494 if (ref($_[1]) eq 'ARRAY') {
1495 return join($_[0]->{name_sep}||'.', @{$_[1]});
1497 $_[0]->_assert_pass_injection_guard($_[1]);
1502 my $qref = ref $_[0]->{quote_char};
1504 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1505 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1506 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1508 my $esc = $_[0]->{escape_char} || $r;
1510 # parts containing * are naturally unquoted
1512 $_[0]->{name_sep}||'',
1516 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1518 (ref($_[1]) eq 'ARRAY'
1522 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1530 # Conversion, if applicable
1532 #my ($self, $arg) = @_;
1533 if (my $conv = $_[0]->{convert_where}) {
1534 return @{ $_[0]->join_query_parts('',
1535 $_[0]->format_keyword($conv),
1544 #my ($self, $col, @vals) = @_;
1545 # called often - tighten code
1546 return $_[0]->{bindtype} eq 'columns'
1547 ? map {[$_[1], $_]} @_[2 .. $#_]
1552 # Dies if any element of @bind is not in [colname => value] format
1553 # if bindtype is 'columns'.
1554 sub _assert_bindval_matches_bindtype {
1555 # my ($self, @bind) = @_;
1557 if ($self->{bindtype} eq 'columns') {
1559 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1560 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1566 sub _join_sql_clauses {
1567 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1569 if (@$clauses_aref > 1) {
1570 my $join = " " . $self->_sqlcase($logic) . " ";
1571 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1572 return ($sql, @$bind_aref);
1574 elsif (@$clauses_aref) {
1575 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1578 return (); # if no SQL, ignore @$bind_aref
1583 # Fix SQL case, if so requested
1585 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1586 # don't touch the argument ... crooked logic, but let's not change it!
1587 return $_[0]->{case} ? $_[1] : uc($_[1]);
1590 sub format_keyword { $_[0]->_sqlcase(join ' ', split '_', $_[1]) }
1592 #======================================================================
1593 # DISPATCHING FROM REFKIND
1594 #======================================================================
1597 my ($self, $data) = @_;
1599 return 'UNDEF' unless defined $data;
1601 # blessed objects are treated like scalars
1602 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1604 return 'SCALAR' unless $ref;
1607 while ($ref eq 'REF') {
1609 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1613 return ($ref||'SCALAR') . ('REF' x $n_steps);
1617 my ($self, $data) = @_;
1618 my @try = ($self->_refkind($data));
1619 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1620 push @try, 'FALLBACK';
1624 sub _METHOD_FOR_refkind {
1625 my ($self, $meth_prefix, $data) = @_;
1628 for (@{$self->_try_refkind($data)}) {
1629 $method = $self->can($meth_prefix."_".$_)
1633 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1637 sub _SWITCH_refkind {
1638 my ($self, $data, $dispatch_table) = @_;
1641 for (@{$self->_try_refkind($data)}) {
1642 $coderef = $dispatch_table->{$_}
1646 puke "no dispatch entry for ".$self->_refkind($data)
1655 #======================================================================
1656 # VALUES, GENERATE, AUTOLOAD
1657 #======================================================================
1659 # LDNOTE: original code from nwiger, didn't touch code in that section
1660 # I feel the AUTOLOAD stuff should not be the default, it should
1661 # only be activated on explicit demand by user.
1665 my $data = shift || return;
1666 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1667 unless ref $data eq 'HASH';
1670 foreach my $k (sort keys %$data) {
1671 my $v = $data->{$k};
1672 $self->_SWITCH_refkind($v, {
1674 if ($self->{array_datatypes}) { # array datatype
1675 push @all_bind, $self->_bindtype($k, $v);
1677 else { # literal SQL with bind
1678 my ($sql, @bind) = @$v;
1679 $self->_assert_bindval_matches_bindtype(@bind);
1680 push @all_bind, @bind;
1683 ARRAYREFREF => sub { # literal SQL with bind
1684 my ($sql, @bind) = @${$v};
1685 $self->_assert_bindval_matches_bindtype(@bind);
1686 push @all_bind, @bind;
1688 SCALARREF => sub { # literal SQL without bind
1690 SCALAR_or_UNDEF => sub {
1691 push @all_bind, $self->_bindtype($k, $v);
1702 my(@sql, @sqlq, @sqlv);
1706 if ($ref eq 'HASH') {
1707 for my $k (sort keys %$_) {
1710 my $label = $self->_quote($k);
1711 if ($r eq 'ARRAY') {
1712 # literal SQL with bind
1713 my ($sql, @bind) = @$v;
1714 $self->_assert_bindval_matches_bindtype(@bind);
1715 push @sqlq, "$label = $sql";
1717 } elsif ($r eq 'SCALAR') {
1718 # literal SQL without bind
1719 push @sqlq, "$label = $$v";
1721 push @sqlq, "$label = ?";
1722 push @sqlv, $self->_bindtype($k, $v);
1725 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1726 } elsif ($ref eq 'ARRAY') {
1727 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1730 if ($r eq 'ARRAY') { # literal SQL with bind
1731 my ($sql, @bind) = @$v;
1732 $self->_assert_bindval_matches_bindtype(@bind);
1735 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1736 # embedded literal SQL
1743 push @sql, '(' . join(', ', @sqlq) . ')';
1744 } elsif ($ref eq 'SCALAR') {
1748 # strings get case twiddled
1749 push @sql, $self->_sqlcase($_);
1753 my $sql = join ' ', @sql;
1755 # this is pretty tricky
1756 # if ask for an array, return ($stmt, @bind)
1757 # otherwise, s/?/shift @sqlv/ to put it inline
1759 return ($sql, @sqlv);
1761 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1762 ref $d ? $d->[1] : $d/e;
1771 # This allows us to check for a local, then _form, attr
1773 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1774 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
1775 return $self->generate($name, @_);
1786 SQL::Abstract - Generate SQL from Perl data structures
1792 my $sql = SQL::Abstract->new;
1794 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1796 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1798 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1800 my($stmt, @bind) = $sql->delete($table, \%where);
1802 # Then, use these in your DBI statements
1803 my $sth = $dbh->prepare($stmt);
1804 $sth->execute(@bind);
1806 # Just generate the WHERE clause
1807 my($stmt, @bind) = $sql->where(\%where, $order);
1809 # Return values in the same order, for hashed queries
1810 # See PERFORMANCE section for more details
1811 my @bind = $sql->values(\%fieldvals);
1815 This module was inspired by the excellent L<DBIx::Abstract>.
1816 However, in using that module I found that what I really wanted
1817 to do was generate SQL, but still retain complete control over my
1818 statement handles and use the DBI interface. So, I set out to
1819 create an abstract SQL generation module.
1821 While based on the concepts used by L<DBIx::Abstract>, there are
1822 several important differences, especially when it comes to WHERE
1823 clauses. I have modified the concepts used to make the SQL easier
1824 to generate from Perl data structures and, IMO, more intuitive.
1825 The underlying idea is for this module to do what you mean, based
1826 on the data structures you provide it. The big advantage is that
1827 you don't have to modify your code every time your data changes,
1828 as this module figures it out.
1830 To begin with, an SQL INSERT is as easy as just specifying a hash
1831 of C<key=value> pairs:
1834 name => 'Jimbo Bobson',
1835 phone => '123-456-7890',
1836 address => '42 Sister Lane',
1837 city => 'St. Louis',
1838 state => 'Louisiana',
1841 The SQL can then be generated with this:
1843 my($stmt, @bind) = $sql->insert('people', \%data);
1845 Which would give you something like this:
1847 $stmt = "INSERT INTO people
1848 (address, city, name, phone, state)
1849 VALUES (?, ?, ?, ?, ?)";
1850 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1851 '123-456-7890', 'Louisiana');
1853 These are then used directly in your DBI code:
1855 my $sth = $dbh->prepare($stmt);
1856 $sth->execute(@bind);
1858 =head2 Inserting and Updating Arrays
1860 If your database has array types (like for example Postgres),
1861 activate the special option C<< array_datatypes => 1 >>
1862 when creating the C<SQL::Abstract> object.
1863 Then you may use an arrayref to insert and update database array types:
1865 my $sql = SQL::Abstract->new(array_datatypes => 1);
1867 planets => [qw/Mercury Venus Earth Mars/]
1870 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1874 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1876 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1879 =head2 Inserting and Updating SQL
1881 In order to apply SQL functions to elements of your C<%data> you may
1882 specify a reference to an arrayref for the given hash value. For example,
1883 if you need to execute the Oracle C<to_date> function on a value, you can
1884 say something like this:
1888 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1891 The first value in the array is the actual SQL. Any other values are
1892 optional and would be included in the bind values array. This gives
1895 my($stmt, @bind) = $sql->insert('people', \%data);
1897 $stmt = "INSERT INTO people (name, date_entered)
1898 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1899 @bind = ('Bill', '03/02/2003');
1901 An UPDATE is just as easy, all you change is the name of the function:
1903 my($stmt, @bind) = $sql->update('people', \%data);
1905 Notice that your C<%data> isn't touched; the module will generate
1906 the appropriately quirky SQL for you automatically. Usually you'll
1907 want to specify a WHERE clause for your UPDATE, though, which is
1908 where handling C<%where> hashes comes in handy...
1910 =head2 Complex where statements
1912 This module can generate pretty complicated WHERE statements
1913 easily. For example, simple C<key=value> pairs are taken to mean
1914 equality, and if you want to see if a field is within a set
1915 of values, you can use an arrayref. Let's say we wanted to
1916 SELECT some data based on this criteria:
1919 requestor => 'inna',
1920 worker => ['nwiger', 'rcwe', 'sfz'],
1921 status => { '!=', 'completed' }
1924 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1926 The above would give you something like this:
1928 $stmt = "SELECT * FROM tickets WHERE
1929 ( requestor = ? ) AND ( status != ? )
1930 AND ( worker = ? OR worker = ? OR worker = ? )";
1931 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1933 Which you could then use in DBI code like so:
1935 my $sth = $dbh->prepare($stmt);
1936 $sth->execute(@bind);
1942 The methods are simple. There's one for every major SQL operation,
1943 and a constructor you use first. The arguments are specified in a
1944 similar order for each method (table, then fields, then a where
1945 clause) to try and simplify things.
1947 =head2 new(option => 'value')
1949 The C<new()> function takes a list of options and values, and returns
1950 a new B<SQL::Abstract> object which can then be used to generate SQL
1951 through the methods below. The options accepted are:
1957 If set to 'lower', then SQL will be generated in all lowercase. By
1958 default SQL is generated in "textbook" case meaning something like:
1960 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1962 Any setting other than 'lower' is ignored.
1966 This determines what the default comparison operator is. By default
1967 it is C<=>, meaning that a hash like this:
1969 %where = (name => 'nwiger', email => 'nate@wiger.org');
1971 Will generate SQL like this:
1973 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1975 However, you may want loose comparisons by default, so if you set
1976 C<cmp> to C<like> you would get SQL such as:
1978 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1980 You can also override the comparison on an individual basis - see
1981 the huge section on L</"WHERE CLAUSES"> at the bottom.
1983 =item sqltrue, sqlfalse
1985 Expressions for inserting boolean values within SQL statements.
1986 By default these are C<1=1> and C<1=0>. They are used
1987 by the special operators C<-in> and C<-not_in> for generating
1988 correct SQL even when the argument is an empty array (see below).
1992 This determines the default logical operator for multiple WHERE
1993 statements in arrays or hashes. If absent, the default logic is "or"
1994 for arrays, and "and" for hashes. This means that a WHERE
1998 event_date => {'>=', '2/13/99'},
1999 event_date => {'<=', '4/24/03'},
2002 will generate SQL like this:
2004 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2006 This is probably not what you want given this query, though (look
2007 at the dates). To change the "OR" to an "AND", simply specify:
2009 my $sql = SQL::Abstract->new(logic => 'and');
2011 Which will change the above C<WHERE> to:
2013 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2015 The logic can also be changed locally by inserting
2016 a modifier in front of an arrayref:
2018 @where = (-and => [event_date => {'>=', '2/13/99'},
2019 event_date => {'<=', '4/24/03'} ]);
2021 See the L</"WHERE CLAUSES"> section for explanations.
2025 This will automatically convert comparisons using the specified SQL
2026 function for both column and value. This is mostly used with an argument
2027 of C<upper> or C<lower>, so that the SQL will have the effect of
2028 case-insensitive "searches". For example, this:
2030 $sql = SQL::Abstract->new(convert => 'upper');
2031 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2033 Will turn out the following SQL:
2035 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2037 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2038 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2039 not validate this option; it will just pass through what you specify verbatim).
2043 This is a kludge because many databases suck. For example, you can't
2044 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2045 Instead, you have to use C<bind_param()>:
2047 $sth->bind_param(1, 'reg data');
2048 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2050 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2051 which loses track of which field each slot refers to. Fear not.
2053 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2054 Currently, you can specify either C<normal> (default) or C<columns>. If you
2055 specify C<columns>, you will get an array that looks like this:
2057 my $sql = SQL::Abstract->new(bindtype => 'columns');
2058 my($stmt, @bind) = $sql->insert(...);
2061 [ 'column1', 'value1' ],
2062 [ 'column2', 'value2' ],
2063 [ 'column3', 'value3' ],
2066 You can then iterate through this manually, using DBI's C<bind_param()>.
2068 $sth->prepare($stmt);
2071 my($col, $data) = @$_;
2072 if ($col eq 'details' || $col eq 'comments') {
2073 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2074 } elsif ($col eq 'image') {
2075 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2077 $sth->bind_param($i, $data);
2081 $sth->execute; # execute without @bind now
2083 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2084 Basically, the advantage is still that you don't have to care which fields
2085 are or are not included. You could wrap that above C<for> loop in a simple
2086 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2087 get a layer of abstraction over manual SQL specification.
2089 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2090 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2091 will expect the bind values in this format.
2095 This is the character that a table or column name will be quoted
2096 with. By default this is an empty string, but you could set it to
2097 the character C<`>, to generate SQL like this:
2099 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2101 Alternatively, you can supply an array ref of two items, the first being the left
2102 hand quote character, and the second the right hand quote character. For
2103 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2104 that generates SQL like this:
2106 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2108 Quoting is useful if you have tables or columns names that are reserved
2109 words in your database's SQL dialect.
2113 This is the character that will be used to escape L</quote_char>s appearing
2114 in an identifier before it has been quoted.
2116 The parameter default in case of a single L</quote_char> character is the quote
2119 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2120 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2121 of the B<opening (left)> L</quote_char> within the identifier are currently left
2122 untouched. The default for opening-closing-style quotes may change in future
2123 versions, thus you are B<strongly encouraged> to specify the escape character
2128 This is the character that separates a table and column name. It is
2129 necessary to specify this when the C<quote_char> option is selected,
2130 so that tables and column names can be individually quoted like this:
2132 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2134 =item injection_guard
2136 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2137 column name specified in a query structure. This is a safety mechanism to avoid
2138 injection attacks when mishandling user input e.g.:
2140 my %condition_as_column_value_pairs = get_values_from_user();
2141 $sqla->select( ... , \%condition_as_column_value_pairs );
2143 If the expression matches an exception is thrown. Note that literal SQL
2144 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2146 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2148 =item array_datatypes
2150 When this option is true, arrayrefs in INSERT or UPDATE are
2151 interpreted as array datatypes and are passed directly
2153 When this option is false, arrayrefs are interpreted
2154 as literal SQL, just like refs to arrayrefs
2155 (but this behavior is for backwards compatibility; when writing
2156 new queries, use the "reference to arrayref" syntax
2162 Takes a reference to a list of "special operators"
2163 to extend the syntax understood by L<SQL::Abstract>.
2164 See section L</"SPECIAL OPERATORS"> for details.
2168 Takes a reference to a list of "unary operators"
2169 to extend the syntax understood by L<SQL::Abstract>.
2170 See section L</"UNARY OPERATORS"> for details.
2176 =head2 insert($table, \@values || \%fieldvals, \%options)
2178 This is the simplest function. You simply give it a table name
2179 and either an arrayref of values or hashref of field/value pairs.
2180 It returns an SQL INSERT statement and a list of bind values.
2181 See the sections on L</"Inserting and Updating Arrays"> and
2182 L</"Inserting and Updating SQL"> for information on how to insert
2183 with those data types.
2185 The optional C<\%options> hash reference may contain additional
2186 options to generate the insert SQL. Currently supported options
2193 Takes either a scalar of raw SQL fields, or an array reference of
2194 field names, and adds on an SQL C<RETURNING> statement at the end.
2195 This allows you to return data generated by the insert statement
2196 (such as row IDs) without performing another C<SELECT> statement.
2197 Note, however, this is not part of the SQL standard and may not
2198 be supported by all database engines.
2202 =head2 update($table, \%fieldvals, \%where, \%options)
2204 This takes a table, hashref of field/value pairs, and an optional
2205 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2207 See the sections on L</"Inserting and Updating Arrays"> and
2208 L</"Inserting and Updating SQL"> for information on how to insert
2209 with those data types.
2211 The optional C<\%options> hash reference may contain additional
2212 options to generate the update SQL. Currently supported options
2219 See the C<returning> option to
2220 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2224 =head2 select($source, $fields, $where, $order)
2226 This returns a SQL SELECT statement and associated list of bind values, as
2227 specified by the arguments:
2233 Specification of the 'FROM' part of the statement.
2234 The argument can be either a plain scalar (interpreted as a table
2235 name, will be quoted), or an arrayref (interpreted as a list
2236 of table names, joined by commas, quoted), or a scalarref
2237 (literal SQL, not quoted).
2241 Specification of the list of fields to retrieve from
2243 The argument can be either an arrayref (interpreted as a list
2244 of field names, will be joined by commas and quoted), or a
2245 plain scalar (literal SQL, not quoted).
2246 Please observe that this API is not as flexible as that of
2247 the first argument C<$source>, for backwards compatibility reasons.
2251 Optional argument to specify the WHERE part of the query.
2252 The argument is most often a hashref, but can also be
2253 an arrayref or plain scalar --
2254 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2258 Optional argument to specify the ORDER BY part of the query.
2259 The argument can be a scalar, a hashref or an arrayref
2260 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2266 =head2 delete($table, \%where, \%options)
2268 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2269 It returns an SQL DELETE statement and list of bind values.
2271 The optional C<\%options> hash reference may contain additional
2272 options to generate the delete SQL. Currently supported options
2279 See the C<returning> option to
2280 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2284 =head2 where(\%where, $order)
2286 This is used to generate just the WHERE clause. For example,
2287 if you have an arbitrary data structure and know what the
2288 rest of your SQL is going to look like, but want an easy way
2289 to produce a WHERE clause, use this. It returns an SQL WHERE
2290 clause and list of bind values.
2293 =head2 values(\%data)
2295 This just returns the values from the hash C<%data>, in the same
2296 order that would be returned from any of the other above queries.
2297 Using this allows you to markedly speed up your queries if you
2298 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2300 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2302 Warning: This is an experimental method and subject to change.
2304 This returns arbitrarily generated SQL. It's a really basic shortcut.
2305 It will return two different things, depending on return context:
2307 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2308 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2310 These would return the following:
2312 # First calling form
2313 $stmt = "CREATE TABLE test (?, ?)";
2314 @bind = (field1, field2);
2316 # Second calling form
2317 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2319 Depending on what you're trying to do, it's up to you to choose the correct
2320 format. In this example, the second form is what you would want.
2324 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2328 ALTER SESSION SET nls_date_format = 'MM/YY'
2330 You get the idea. Strings get their case twiddled, but everything
2331 else remains verbatim.
2333 =head1 EXPORTABLE FUNCTIONS
2335 =head2 is_plain_value
2337 Determines if the supplied argument is a plain value as understood by this
2342 =item * The value is C<undef>
2344 =item * The value is a non-reference
2346 =item * The value is an object with stringification overloading
2348 =item * The value is of the form C<< { -value => $anything } >>
2352 On failure returns C<undef>, on success returns a B<scalar> reference
2353 to the original supplied argument.
2359 The stringification overloading detection is rather advanced: it takes
2360 into consideration not only the presence of a C<""> overload, but if that
2361 fails also checks for enabled
2362 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2363 on either C<0+> or C<bool>.
2365 Unfortunately testing in the field indicates that this
2366 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2367 but only when very large numbers of stringifying objects are involved.
2368 At the time of writing ( Sep 2014 ) there is no clear explanation of
2369 the direct cause, nor is there a manageably small test case that reliably
2370 reproduces the problem.
2372 If you encounter any of the following exceptions in B<random places within
2373 your application stack> - this module may be to blame:
2375 Operation "ne": no method found,
2376 left argument in overloaded package <something>,
2377 right argument in overloaded package <something>
2381 Stub found while resolving method "???" overloading """" in package <something>
2383 If you fall victim to the above - please attempt to reduce the problem
2384 to something that could be sent to the L<SQL::Abstract developers
2385 |DBIx::Class/GETTING HELP/SUPPORT>
2386 (either publicly or privately). As a workaround in the meantime you can
2387 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2388 value, which will most likely eliminate your problem (at the expense of
2389 not being able to properly detect exotic forms of stringification).
2391 This notice and environment variable will be removed in a future version,
2392 as soon as the underlying problem is found and a reliable workaround is
2397 =head2 is_literal_value
2399 Determines if the supplied argument is a literal value as understood by this
2404 =item * C<\$sql_string>
2406 =item * C<\[ $sql_string, @bind_values ]>
2410 On failure returns C<undef>, on success returns an B<array> reference
2411 containing the unpacked version of the supplied literal SQL and bind values.
2413 =head1 WHERE CLAUSES
2417 This module uses a variation on the idea from L<DBIx::Abstract>. It
2418 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2419 module is that things in arrays are OR'ed, and things in hashes
2422 The easiest way to explain is to show lots of examples. After
2423 each C<%where> hash shown, it is assumed you used:
2425 my($stmt, @bind) = $sql->where(\%where);
2427 However, note that the C<%where> hash can be used directly in any
2428 of the other functions as well, as described above.
2430 =head2 Key-value pairs
2432 So, let's get started. To begin, a simple hash:
2436 status => 'completed'
2439 Is converted to SQL C<key = val> statements:
2441 $stmt = "WHERE user = ? AND status = ?";
2442 @bind = ('nwiger', 'completed');
2444 One common thing I end up doing is having a list of values that
2445 a field can be in. To do this, simply specify a list inside of
2450 status => ['assigned', 'in-progress', 'pending'];
2453 This simple code will create the following:
2455 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2456 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2458 A field associated to an empty arrayref will be considered a
2459 logical false and will generate 0=1.
2461 =head2 Tests for NULL values
2463 If the value part is C<undef> then this is converted to SQL <IS NULL>
2472 $stmt = "WHERE user = ? AND status IS NULL";
2475 To test if a column IS NOT NULL:
2479 status => { '!=', undef },
2482 =head2 Specific comparison operators
2484 If you want to specify a different type of operator for your comparison,
2485 you can use a hashref for a given column:
2489 status => { '!=', 'completed' }
2492 Which would generate:
2494 $stmt = "WHERE user = ? AND status != ?";
2495 @bind = ('nwiger', 'completed');
2497 To test against multiple values, just enclose the values in an arrayref:
2499 status => { '=', ['assigned', 'in-progress', 'pending'] };
2501 Which would give you:
2503 "WHERE status = ? OR status = ? OR status = ?"
2506 The hashref can also contain multiple pairs, in which case it is expanded
2507 into an C<AND> of its elements:
2511 status => { '!=', 'completed', -not_like => 'pending%' }
2514 # Or more dynamically, like from a form
2515 $where{user} = 'nwiger';
2516 $where{status}{'!='} = 'completed';
2517 $where{status}{'-not_like'} = 'pending%';
2519 # Both generate this
2520 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2521 @bind = ('nwiger', 'completed', 'pending%');
2524 To get an OR instead, you can combine it with the arrayref idea:
2528 priority => [ { '=', 2 }, { '>', 5 } ]
2531 Which would generate:
2533 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2534 @bind = ('2', '5', 'nwiger');
2536 If you want to include literal SQL (with or without bind values), just use a
2537 scalar reference or reference to an arrayref as the value:
2540 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2541 date_expires => { '<' => \"now()" }
2544 Which would generate:
2546 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2547 @bind = ('11/26/2008');
2550 =head2 Logic and nesting operators
2552 In the example above,
2553 there is a subtle trap if you want to say something like
2554 this (notice the C<AND>):
2556 WHERE priority != ? AND priority != ?
2558 Because, in Perl you I<can't> do this:
2560 priority => { '!=' => 2, '!=' => 1 }
2562 As the second C<!=> key will obliterate the first. The solution
2563 is to use the special C<-modifier> form inside an arrayref:
2565 priority => [ -and => {'!=', 2},
2569 Normally, these would be joined by C<OR>, but the modifier tells it
2570 to use C<AND> instead. (Hint: You can use this in conjunction with the
2571 C<logic> option to C<new()> in order to change the way your queries
2572 work by default.) B<Important:> Note that the C<-modifier> goes
2573 B<INSIDE> the arrayref, as an extra first element. This will
2574 B<NOT> do what you think it might:
2576 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2578 Here is a quick list of equivalencies, since there is some overlap:
2581 status => {'!=', 'completed', 'not like', 'pending%' }
2582 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2585 status => {'=', ['assigned', 'in-progress']}
2586 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2587 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2591 =head2 Special operators: IN, BETWEEN, etc.
2593 You can also use the hashref format to compare a list of fields using the
2594 C<IN> comparison operator, by specifying the list as an arrayref:
2597 status => 'completed',
2598 reportid => { -in => [567, 2335, 2] }
2601 Which would generate:
2603 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2604 @bind = ('completed', '567', '2335', '2');
2606 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2609 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2610 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2611 'sqltrue' (by default: C<1=1>).
2613 In addition to the array you can supply a chunk of literal sql or
2614 literal sql with bind:
2617 customer => { -in => \[
2618 'SELECT cust_id FROM cust WHERE balance > ?',
2621 status => { -in => \'SELECT status_codes FROM states' },
2627 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2628 AND status IN ( SELECT status_codes FROM states )
2632 Finally, if the argument to C<-in> is not a reference, it will be
2633 treated as a single-element array.
2635 Another pair of operators is C<-between> and C<-not_between>,
2636 used with an arrayref of two values:
2640 completion_date => {
2641 -not_between => ['2002-10-01', '2003-02-06']
2647 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2649 Just like with C<-in> all plausible combinations of literal SQL
2653 start0 => { -between => [ 1, 2 ] },
2654 start1 => { -between => \["? AND ?", 1, 2] },
2655 start2 => { -between => \"lower(x) AND upper(y)" },
2656 start3 => { -between => [
2658 \["upper(?)", 'stuff' ],
2665 ( start0 BETWEEN ? AND ? )
2666 AND ( start1 BETWEEN ? AND ? )
2667 AND ( start2 BETWEEN lower(x) AND upper(y) )
2668 AND ( start3 BETWEEN lower(x) AND upper(?) )
2670 @bind = (1, 2, 1, 2, 'stuff');
2673 These are the two builtin "special operators"; but the
2674 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2676 =head2 Unary operators: bool
2678 If you wish to test against boolean columns or functions within your
2679 database you can use the C<-bool> and C<-not_bool> operators. For
2680 example to test the column C<is_user> being true and the column
2681 C<is_enabled> being false you would use:-
2685 -not_bool => 'is_enabled',
2690 WHERE is_user AND NOT is_enabled
2692 If a more complex combination is required, testing more conditions,
2693 then you should use the and/or operators:-
2698 -not_bool => { two=> { -rlike => 'bar' } },
2699 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2710 (NOT ( three = ? OR three > ? ))
2713 =head2 Nested conditions, -and/-or prefixes
2715 So far, we've seen how multiple conditions are joined with a top-level
2716 C<AND>. We can change this by putting the different conditions we want in
2717 hashes and then putting those hashes in an array. For example:
2722 status => { -like => ['pending%', 'dispatched'] },
2726 status => 'unassigned',
2730 This data structure would create the following:
2732 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2733 OR ( user = ? AND status = ? ) )";
2734 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2737 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2738 to change the logic inside:
2744 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2745 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2752 $stmt = "WHERE ( user = ?
2753 AND ( ( workhrs > ? AND geo = ? )
2754 OR ( workhrs < ? OR geo = ? ) ) )";
2755 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2757 =head3 Algebraic inconsistency, for historical reasons
2759 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2760 operator goes C<outside> of the nested structure; whereas when connecting
2761 several constraints on one column, the C<-and> operator goes
2762 C<inside> the arrayref. Here is an example combining both features:
2765 -and => [a => 1, b => 2],
2766 -or => [c => 3, d => 4],
2767 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2772 WHERE ( ( ( a = ? AND b = ? )
2773 OR ( c = ? OR d = ? )
2774 OR ( e LIKE ? AND e LIKE ? ) ) )
2776 This difference in syntax is unfortunate but must be preserved for
2777 historical reasons. So be careful: the two examples below would
2778 seem algebraically equivalent, but they are not
2781 { -like => 'foo%' },
2782 { -like => '%bar' },
2784 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2787 { col => { -like => 'foo%' } },
2788 { col => { -like => '%bar' } },
2790 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2793 =head2 Literal SQL and value type operators
2795 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2796 side" is a column name and the "right side" is a value (normally rendered as
2797 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2798 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2799 alter this behavior. There are several ways of doing so.
2803 This is a virtual operator that signals the string to its right side is an
2804 identifier (a column name) and not a value. For example to compare two
2805 columns you would write:
2808 priority => { '<', 2 },
2809 requestor => { -ident => 'submitter' },
2814 $stmt = "WHERE priority < ? AND requestor = submitter";
2817 If you are maintaining legacy code you may see a different construct as
2818 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2823 This is a virtual operator that signals that the construct to its right side
2824 is a value to be passed to DBI. This is for example necessary when you want
2825 to write a where clause against an array (for RDBMS that support such
2826 datatypes). For example:
2829 array => { -value => [1, 2, 3] }
2834 $stmt = 'WHERE array = ?';
2835 @bind = ([1, 2, 3]);
2837 Note that if you were to simply say:
2843 the result would probably not be what you wanted:
2845 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2850 Finally, sometimes only literal SQL will do. To include a random snippet
2851 of SQL verbatim, you specify it as a scalar reference. Consider this only
2852 as a last resort. Usually there is a better way. For example:
2855 priority => { '<', 2 },
2856 requestor => { -in => \'(SELECT name FROM hitmen)' },
2861 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2864 Note that in this example, you only get one bind parameter back, since
2865 the verbatim SQL is passed as part of the statement.
2869 Never use untrusted input as a literal SQL argument - this is a massive
2870 security risk (there is no way to check literal snippets for SQL
2871 injections and other nastyness). If you need to deal with untrusted input
2872 use literal SQL with placeholders as described next.
2874 =head3 Literal SQL with placeholders and bind values (subqueries)
2876 If the literal SQL to be inserted has placeholders and bind values,
2877 use a reference to an arrayref (yes this is a double reference --
2878 not so common, but perfectly legal Perl). For example, to find a date
2879 in Postgres you can use something like this:
2882 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2887 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2890 Note that you must pass the bind values in the same format as they are returned
2891 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2892 to C<columns>, you must provide the bind values in the
2893 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2894 scalar value; most commonly the column name, but you can use any scalar value
2895 (including references and blessed references), L<SQL::Abstract> will simply
2896 pass it through intact. So if C<bindtype> is set to C<columns> the above
2897 example will look like:
2900 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2903 Literal SQL is especially useful for nesting parenthesized clauses in the
2904 main SQL query. Here is a first example:
2906 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2910 bar => \["IN ($sub_stmt)" => @sub_bind],
2915 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2916 WHERE c2 < ? AND c3 LIKE ?))";
2917 @bind = (1234, 100, "foo%");
2919 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2920 are expressed in the same way. Of course the C<$sub_stmt> and
2921 its associated bind values can be generated through a former call
2924 my ($sub_stmt, @sub_bind)
2925 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2926 c3 => {-like => "foo%"}});
2929 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2932 In the examples above, the subquery was used as an operator on a column;
2933 but the same principle also applies for a clause within the main C<%where>
2934 hash, like an EXISTS subquery:
2936 my ($sub_stmt, @sub_bind)
2937 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2938 my %where = ( -and => [
2940 \["EXISTS ($sub_stmt)" => @sub_bind],
2945 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2946 WHERE c1 = ? AND c2 > t0.c0))";
2950 Observe that the condition on C<c2> in the subquery refers to
2951 column C<t0.c0> of the main query: this is I<not> a bind
2952 value, so we have to express it through a scalar ref.
2953 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2954 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2955 what we wanted here.
2957 Finally, here is an example where a subquery is used
2958 for expressing unary negation:
2960 my ($sub_stmt, @sub_bind)
2961 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2962 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2964 lname => {like => '%son%'},
2965 \["NOT ($sub_stmt)" => @sub_bind],
2970 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2971 @bind = ('%son%', 10, 20)
2973 =head3 Deprecated usage of Literal SQL
2975 Below are some examples of archaic use of literal SQL. It is shown only as
2976 reference for those who deal with legacy code. Each example has a much
2977 better, cleaner and safer alternative that users should opt for in new code.
2983 my %where = ( requestor => \'IS NOT NULL' )
2985 $stmt = "WHERE requestor IS NOT NULL"
2987 This used to be the way of generating NULL comparisons, before the handling
2988 of C<undef> got formalized. For new code please use the superior syntax as
2989 described in L</Tests for NULL values>.
2993 my %where = ( requestor => \'= submitter' )
2995 $stmt = "WHERE requestor = submitter"
2997 This used to be the only way to compare columns. Use the superior L</-ident>
2998 method for all new code. For example an identifier declared in such a way
2999 will be properly quoted if L</quote_char> is properly set, while the legacy
3000 form will remain as supplied.
3004 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3006 $stmt = "WHERE completed > ? AND is_ready"
3007 @bind = ('2012-12-21')
3009 Using an empty string literal used to be the only way to express a boolean.
3010 For all new code please use the much more readable
3011 L<-bool|/Unary operators: bool> operator.
3017 These pages could go on for a while, since the nesting of the data
3018 structures this module can handle are pretty much unlimited (the
3019 module implements the C<WHERE> expansion as a recursive function
3020 internally). Your best bet is to "play around" with the module a
3021 little to see how the data structures behave, and choose the best
3022 format for your data based on that.
3024 And of course, all the values above will probably be replaced with
3025 variables gotten from forms or the command line. After all, if you
3026 knew everything ahead of time, you wouldn't have to worry about
3027 dynamically-generating SQL and could just hardwire it into your
3030 =head1 ORDER BY CLAUSES
3032 Some functions take an order by clause. This can either be a scalar (just a
3033 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3034 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3037 Given | Will Generate
3038 ---------------------------------------------------------------
3040 'colA' | ORDER BY colA
3042 [qw/colA colB/] | ORDER BY colA, colB
3044 {-asc => 'colA'} | ORDER BY colA ASC
3046 {-desc => 'colB'} | ORDER BY colB DESC
3048 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3050 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3052 \'colA DESC' | ORDER BY colA DESC
3054 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3055 | /* ...with $x bound to ? */
3058 { -asc => 'colA' }, | colA ASC,
3059 { -desc => [qw/colB/] }, | colB DESC,
3060 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3061 \'colE DESC', | colE DESC,
3062 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3063 ] | /* ...with $x bound to ? */
3064 ===============================================================
3068 =head1 SPECIAL OPERATORS
3070 my $sqlmaker = SQL::Abstract->new(special_ops => [
3074 my ($self, $field, $op, $arg) = @_;
3080 handler => 'method_name',
3084 A "special operator" is a SQL syntactic clause that can be
3085 applied to a field, instead of a usual binary operator.
3088 WHERE field IN (?, ?, ?)
3089 WHERE field BETWEEN ? AND ?
3090 WHERE MATCH(field) AGAINST (?, ?)
3092 Special operators IN and BETWEEN are fairly standard and therefore
3093 are builtin within C<SQL::Abstract> (as the overridable methods
3094 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3095 like the MATCH .. AGAINST example above which is specific to MySQL,
3096 you can write your own operator handlers - supply a C<special_ops>
3097 argument to the C<new> method. That argument takes an arrayref of
3098 operator definitions; each operator definition is a hashref with two
3105 the regular expression to match the operator
3109 Either a coderef or a plain scalar method name. In both cases
3110 the expected return is C<< ($sql, @bind) >>.
3112 When supplied with a method name, it is simply called on the
3113 L<SQL::Abstract> object as:
3115 $self->$method_name($field, $op, $arg)
3119 $field is the LHS of the operator
3120 $op is the part that matched the handler regex
3123 When supplied with a coderef, it is called as:
3125 $coderef->($self, $field, $op, $arg)
3130 For example, here is an implementation
3131 of the MATCH .. AGAINST syntax for MySQL
3133 my $sqlmaker = SQL::Abstract->new(special_ops => [
3135 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3136 {regex => qr/^match$/i,
3138 my ($self, $field, $op, $arg) = @_;
3139 $arg = [$arg] if not ref $arg;
3140 my $label = $self->_quote($field);
3141 my ($placeholder) = $self->_convert('?');
3142 my $placeholders = join ", ", (($placeholder) x @$arg);
3143 my $sql = $self->_sqlcase('match') . " ($label) "
3144 . $self->_sqlcase('against') . " ($placeholders) ";
3145 my @bind = $self->_bindtype($field, @$arg);
3146 return ($sql, @bind);
3153 =head1 UNARY OPERATORS
3155 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3159 my ($self, $op, $arg) = @_;
3165 handler => 'method_name',
3169 A "unary operator" is a SQL syntactic clause that can be
3170 applied to a field - the operator goes before the field
3172 You can write your own operator handlers - supply a C<unary_ops>
3173 argument to the C<new> method. That argument takes an arrayref of
3174 operator definitions; each operator definition is a hashref with two
3181 the regular expression to match the operator
3185 Either a coderef or a plain scalar method name. In both cases
3186 the expected return is C<< $sql >>.
3188 When supplied with a method name, it is simply called on the
3189 L<SQL::Abstract> object as:
3191 $self->$method_name($op, $arg)
3195 $op is the part that matched the handler regex
3196 $arg is the RHS or argument of the operator
3198 When supplied with a coderef, it is called as:
3200 $coderef->($self, $op, $arg)
3208 Thanks to some benchmarking by Mark Stosberg, it turns out that
3209 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3210 I must admit this wasn't an intentional design issue, but it's a
3211 byproduct of the fact that you get to control your C<DBI> handles
3214 To maximize performance, use a code snippet like the following:
3216 # prepare a statement handle using the first row
3217 # and then reuse it for the rest of the rows
3219 for my $href (@array_of_hashrefs) {
3220 $stmt ||= $sql->insert('table', $href);
3221 $sth ||= $dbh->prepare($stmt);
3222 $sth->execute($sql->values($href));
3225 The reason this works is because the keys in your C<$href> are sorted
3226 internally by B<SQL::Abstract>. Thus, as long as your data retains
3227 the same structure, you only have to generate the SQL the first time
3228 around. On subsequent queries, simply use the C<values> function provided
3229 by this module to return your values in the correct order.
3231 However this depends on the values having the same type - if, for
3232 example, the values of a where clause may either have values
3233 (resulting in sql of the form C<column = ?> with a single bind
3234 value), or alternatively the values might be C<undef> (resulting in
3235 sql of the form C<column IS NULL> with no bind value) then the
3236 caching technique suggested will not work.
3240 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3241 really like this part (I do, at least). Building up a complex query
3242 can be as simple as the following:
3249 use CGI::FormBuilder;
3252 my $form = CGI::FormBuilder->new(...);
3253 my $sql = SQL::Abstract->new;
3255 if ($form->submitted) {
3256 my $field = $form->field;
3257 my $id = delete $field->{id};
3258 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3261 Of course, you would still have to connect using C<DBI> to run the
3262 query, but the point is that if you make your form look like your
3263 table, the actual query script can be extremely simplistic.
3265 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3266 a fast interface to returning and formatting data. I frequently
3267 use these three modules together to write complex database query
3268 apps in under 50 lines.
3270 =head1 HOW TO CONTRIBUTE
3272 Contributions are always welcome, in all usable forms (we especially
3273 welcome documentation improvements). The delivery methods include git-
3274 or unified-diff formatted patches, GitHub pull requests, or plain bug
3275 reports either via RT or the Mailing list. Contributors are generally
3276 granted full access to the official repository after their first several
3277 patches pass successful review.
3279 This project is maintained in a git repository. The code and related tools are
3280 accessible at the following locations:
3284 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3286 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3288 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3290 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3296 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3297 Great care has been taken to preserve the I<published> behavior
3298 documented in previous versions in the 1.* family; however,
3299 some features that were previously undocumented, or behaved
3300 differently from the documentation, had to be changed in order
3301 to clarify the semantics. Hence, client code that was relying
3302 on some dark areas of C<SQL::Abstract> v1.*
3303 B<might behave differently> in v1.50.
3305 The main changes are:
3311 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3315 support for the { operator => \"..." } construct (to embed literal SQL)
3319 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3323 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3327 defensive programming: check arguments
3331 fixed bug with global logic, which was previously implemented
3332 through global variables yielding side-effects. Prior versions would
3333 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3334 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3335 Now this is interpreted
3336 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3341 fixed semantics of _bindtype on array args
3345 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3346 we just avoid shifting arrays within that tree.
3350 dropped the C<_modlogic> function
3354 =head1 ACKNOWLEDGEMENTS
3356 There are a number of individuals that have really helped out with
3357 this module. Unfortunately, most of them submitted bugs via CPAN
3358 so I have no idea who they are! But the people I do know are:
3360 Ash Berlin (order_by hash term support)
3361 Matt Trout (DBIx::Class support)
3362 Mark Stosberg (benchmarking)
3363 Chas Owens (initial "IN" operator support)
3364 Philip Collins (per-field SQL functions)
3365 Eric Kolve (hashref "AND" support)
3366 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3367 Dan Kubb (support for "quote_char" and "name_sep")
3368 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3369 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3370 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3371 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3372 Oliver Charles (support for "RETURNING" after "INSERT")
3378 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3382 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3384 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3386 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3387 While not an official support venue, C<DBIx::Class> makes heavy use of
3388 C<SQL::Abstract>, and as such list members there are very familiar with
3389 how to create queries.
3393 This module is free software; you may copy this under the same
3394 terms as perl itself (either the GNU General Public License or
3395 the Artistic License)