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.86';
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) ],
187 'delete.target' => '_expand_delete_clause_target',
188 'delete.from' => '_expand_delete_clause_target',
189 'delete.where' => '_expand_delete_clause_where',
190 'delete.returning' => '_expand_delete_clause_returning',
193 'delete.target' => '_render_delete_clause_target',
197 foreach my $stmt (keys %{$Defaults{clauses_of}}) {
198 $Defaults{expand}{$stmt} = '_expand_statement';
199 $Defaults{render}{$stmt} = '_render_statement';
204 my $class = ref($self) || $self;
205 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
207 # choose our case by keeping an option around
208 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
210 # default logic for interpreting arrayrefs
211 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
213 # how to return bind vars
214 $opt{bindtype} ||= 'normal';
216 # default comparison is "=", but can be overridden
219 # try to recognize which are the 'equality' and 'inequality' ops
220 # (temporary quickfix (in 2007), should go through a more seasoned API)
221 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
222 $opt{inequality_op} = qr/^( != | <> )$/ix;
224 $opt{like_op} = qr/^ (is_)?r?like $/xi;
225 $opt{not_like_op} = qr/^ (is_)?not_r?like $/xi;
228 $opt{sqltrue} ||= '1=1';
229 $opt{sqlfalse} ||= '0=1';
232 $opt{special_ops} ||= [];
234 if ($class->isa('DBIx::Class::SQLMaker')) {
235 $opt{warn_once_on_nest} = 1;
236 $opt{disable_old_special_ops} = 1;
240 $opt{unary_ops} ||= [];
242 # rudimentary sanity-check for user supplied bits treated as functions/operators
243 # If a purported function matches this regular expression, an exception is thrown.
244 # Literal SQL is *NOT* subject to this check, only functions (and column names
245 # when quoting is not in effect)
248 # need to guard against ()'s in column names too, but this will break tons of
249 # hacks... ideas anyone?
250 $opt{injection_guard} ||= qr/
256 $opt{expand_unary} = {};
258 foreach my $name (sort keys %Defaults) {
259 $opt{$name} = { %{$Defaults{$name}} };
262 if ($opt{lazy_join_sql_parts}) {
263 my $mod = Module::Runtime::use_module('SQL::Abstract::Parts');
264 $opt{join_sql_parts} ||= sub { $mod->new(@_) };
267 $opt{join_sql_parts} ||= sub { join $_[0], @_[1..$#_] };
269 return bless \%opt, $class;
272 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
273 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
275 sub _assert_pass_injection_guard {
276 if ($_[1] =~ $_[0]->{injection_guard}) {
277 my $class = ref $_[0];
278 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
279 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
280 . "{injection_guard} attribute to ${class}->new()"
285 #======================================================================
287 #======================================================================
291 my $table = $self->_table(shift);
292 my $data = shift || return;
297 my ($f_aqt, $v_aqt) = $self->_expand_insert_values($data);
299 my @parts = ([ $self->_sqlcase('insert into').' '.$table ]);
300 push @parts, $self->render_aqt($f_aqt) if $f_aqt;
301 push @parts, [ $self->_sqlcase('values') ], $self->render_aqt($v_aqt);
303 if ($options->{returning}) {
304 push @parts, [ $self->_insert_returning($options) ];
307 my ($sql, @bind) = @{ $self->join_query_parts(' ', @parts) };
308 return wantarray ? ($sql, @bind) : $sql;
311 sub _expand_insert_values {
312 my ($self, $data) = @_;
313 if (is_literal_value($data)) {
314 (undef, $self->expand_expr($data));
316 my ($fields, $values) = (
317 ref($data) eq 'HASH' ?
318 ([ sort keys %$data ], [ @{$data}{sort keys %$data} ])
322 # no names (arrayref) means can't generate bindtype
323 !($fields) && $self->{bindtype} eq 'columns'
324 && belch "can't do 'columns' bindtype when called with arrayref";
328 ? $self->expand_expr({ -row => $fields }, -ident)
333 local our $Cur_Col_Meta = $fields->[$_];
334 $self->_expand_insert_value($values->[$_])
341 # So that subclasses can override INSERT ... RETURNING separately from
342 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
343 sub _insert_returning { shift->_returning(@_) }
346 my ($self, $options) = @_;
348 my $f = $options->{returning};
350 my ($sql, @bind) = @{ $self->render_aqt(
351 $self->_expand_maybe_list_expr($f, -ident)
353 return ($self->_sqlcase(' returning ').$sql, @bind);
356 sub _expand_insert_value {
359 my $k = our $Cur_Col_Meta;
361 if (ref($v) eq 'ARRAY') {
362 if ($self->{array_datatypes}) {
363 return +{ -bind => [ $k, $v ] };
365 my ($sql, @bind) = @$v;
366 $self->_assert_bindval_matches_bindtype(@bind);
367 return +{ -literal => $v };
369 if (ref($v) eq 'HASH') {
370 if (grep !/^-/, keys %$v) {
371 belch "HASH ref as bind value in insert is not supported";
372 return +{ -bind => [ $k, $v ] };
376 return +{ -bind => [ $k, undef ] };
378 return $self->expand_expr($v);
383 #======================================================================
385 #======================================================================
390 my $table = $self->_table(shift);
391 my $data = shift || return;
395 # first build the 'SET' part of the sql statement
396 puke "Unsupported data type specified to \$sql->update"
397 unless ref $data eq 'HASH';
399 my ($sql, @all_bind) = $self->_update_set_values($data);
400 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
404 my($where_sql, @where_bind) = $self->where($where);
406 push @all_bind, @where_bind;
409 if ($options->{returning}) {
410 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
411 $sql .= $returning_sql;
412 push @all_bind, @returning_bind;
415 return wantarray ? ($sql, @all_bind) : $sql;
418 sub _update_set_values {
419 my ($self, $data) = @_;
421 return @{ $self->render_aqt(
422 $self->_expand_update_set_values(undef, $data),
426 sub _expand_update_set_values {
427 my ($self, undef, $data) = @_;
428 $self->_expand_maybe_list_expr( [
431 $set = { -bind => $_ } unless defined $set;
432 +{ -op => [ '=', { -ident => $k }, $set ] };
438 ? ($self->{array_datatypes}
439 ? [ $k, +{ -bind => [ $k, $v ] } ]
440 : [ $k, +{ -literal => $v } ])
442 local our $Cur_Col_Meta = $k;
443 [ $k, $self->_expand_expr($v) ]
450 # So that subclasses can override UPDATE ... RETURNING separately from
452 sub _update_returning { shift->_returning(@_) }
456 #======================================================================
458 #======================================================================
463 my $table = $self->_table(shift);
464 my $fields = shift || '*';
468 my ($fields_sql, @bind) = $self->_select_fields($fields);
470 my ($where_sql, @where_bind) = $self->where($where, $order);
471 push @bind, @where_bind;
473 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
474 $self->_sqlcase('from'), $table)
477 return wantarray ? ($sql, @bind) : $sql;
481 my ($self, $fields) = @_;
482 return $fields unless ref($fields);
483 return @{ $self->render_aqt(
484 $self->_expand_maybe_list_expr($fields, '-ident')
488 #======================================================================
490 #======================================================================
493 my ($self, $table, $where, $options) = @_;
496 if (ref($table) eq 'HASH') {
499 my %clauses = (target => $table, where => $where, %{$options||{}});
503 my @rendered = $self->render_statement({ -delete => $stmt });
504 return wantarray ? @rendered : $rendered[0];
507 # So that subclasses can override DELETE ... RETURNING separately from
509 sub _delete_returning { shift->_returning(@_) }
511 sub _expand_delete_clause_target {
512 +(target => $_[0]->_expand_maybe_list_expr($_[2], -ident));
515 sub _expand_delete_clause_where { +(where => $_[0]->expand_expr($_[2])); }
517 sub _expand_delete_clause_returning {
518 +(returning => $_[0]->_expand_maybe_list_expr($_[2], -ident));
521 sub _render_delete_clause_target {
522 my ($self, undef, $from) = @_;
523 $self->join_query_parts(' ', $self->format_keyword('delete from'), $from);
526 #======================================================================
528 #======================================================================
532 # Finally, a separate routine just to handle WHERE clauses
534 my ($self, $where, $order) = @_;
536 local $self->{convert_where} = $self->{convert};
539 my ($sql, @bind) = defined($where)
540 ? $self->_recurse_where($where)
542 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
546 my ($order_sql, @order_bind) = $self->_order_by($order);
548 push @bind, @order_bind;
551 return wantarray ? ($sql, @bind) : $sql;
554 { our $Default_Scalar_To = -value }
557 my ($self, $expr, $default_scalar_to) = @_;
558 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
559 $self->_expand_expr($expr);
563 my ($self, $aqt, $top_level) = @_;
564 my ($k, $v, @rest) = %$aqt;
566 die "Not a node type: $k" unless $k =~ s/^-//;
567 if (my $meth = $self->{render}{$k}) {
568 local our $Render_Top_Level = $top_level;
569 return $self->$meth($k, $v);
571 die "notreached: $k";
575 my ($self, $expr, $default_scalar_to) = @_;
576 return @{ $self->render_aqt(
577 $self->expand_expr($expr, $default_scalar_to)
581 sub render_statement {
582 my ($self, $expr, $default_scalar_to) = @_;
584 $self->expand_expr($expr, $default_scalar_to), 1
588 sub _expand_statement {
589 my ($self, $type, $args) = @_;
590 my $ec = $self->{expand_clause};
593 $args->{$type} = delete $args->{_}
595 return +{ "-${type}" => +{
597 my $val = $args->{$_};
598 if (defined($val) and my $exp = $ec->{"${type}.$_"}) {
599 if ((my (@exp) = $self->$exp($_ => $val)) == 1) {
605 ($_ => $self->expand_expr($val))
611 sub _render_statement {
612 my ($self, $type, $args) = @_;
614 foreach my $clause (@{$self->{clauses_of}{$type}}) {
615 next unless my $clause_expr = $args->{$clause};
617 if (my $rdr = $self->{render_clause}{"${type}.${clause}"}) {
618 $self->$rdr($clause, $clause_expr);
620 my $r = $self->render_aqt($clause_expr, 1);
621 next unless defined $r->[0] and length $r->[0];
622 $self->join_query_parts(' ',
623 $self->format_keyword($clause),
630 my $q = $self->join_query_parts(' ', @parts);
631 return $self->join_query_parts('',
632 (our $Render_Top_Level ? $q : ('(', $q, ')'))
637 my ($self, $raw) = @_;
639 return $op if grep $_->{$op}, @{$self}{qw(is_op expand_op render_op)};
640 s/^-(?=.)//, s/\s+/_/g for $op;
645 my ($self, $expr) = @_;
646 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
647 return undef unless defined($expr);
648 if (ref($expr) eq 'HASH') {
649 return undef unless my $kc = keys %$expr;
651 return $self->_expand_op_andor(and => $expr);
653 my ($key, $value) = %$expr;
654 if ($key =~ /^-/ and $key =~ s/ [_\s]? \d+ $//x ) {
655 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
656 . "You probably wanted ...-and => [ $key => COND1, $key => COND2 ... ]";
658 return $self->_expand_hashpair($key, $value);
660 if (ref($expr) eq 'ARRAY') {
661 return $self->_expand_op_andor(lc($self->{logic}), $expr);
663 if (my $literal = is_literal_value($expr)) {
664 return +{ -literal => $literal };
666 if (!ref($expr) or Scalar::Util::blessed($expr)) {
667 return $self->_expand_scalar($expr);
672 sub _expand_hashpair {
673 my ($self, $k, $v) = @_;
674 unless (defined($k) and length($k)) {
675 if (defined($k) and my $literal = is_literal_value($v)) {
676 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
677 return { -literal => $literal };
679 puke "Supplying an empty left hand side argument is not supported";
682 return $self->_expand_hashpair_op($k, $v);
683 } elsif ($k =~ /^[^\w]/i) {
684 my ($lhs, @rhs) = ref($v) eq 'ARRAY' ? @$v : $v;
685 return $self->_expand_op(
686 -op, [ $k, $self->expand_expr($lhs, -ident), @rhs ]
689 return $self->_expand_hashpair_ident($k, $v);
692 sub _expand_hashpair_ident {
693 my ($self, $k, $v) = @_;
695 local our $Cur_Col_Meta = $k;
697 # hash with multiple or no elements is andor
699 if (ref($v) eq 'HASH' and keys %$v != 1) {
700 return $self->_expand_op_andor(and => $v, $k);
703 # undef needs to be re-sent with cmp to achieve IS/IS NOT NULL
705 if (is_undef_value($v)) {
706 return $self->_expand_hashpair_cmp($k => undef);
709 # scalars and objects get expanded as whatever requested or values
711 if (!ref($v) or Scalar::Util::blessed($v)) {
712 return $self->_expand_hashpair_scalar($k, $v);
715 # single key hashref is a hashtriple
717 if (ref($v) eq 'HASH') {
718 return $self->_expand_hashtriple($k, %$v);
721 # arrayref needs re-engineering over the elements
723 if (ref($v) eq 'ARRAY') {
724 return $self->sqlfalse unless @$v;
725 $self->_debug("ARRAY($k) means distribute over elements");
727 $v->[0] =~ /^-(and|or)$/i
728 ? (shift(@{$v = [ @$v ]}), $1)
729 : lc($self->{logic} || 'OR')
731 return $self->_expand_op_andor(
736 if (my $literal = is_literal_value($v)) {
738 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
741 my ($sql, @bind) = @$literal;
742 if ($self->{bindtype} eq 'columns') {
744 $self->_assert_bindval_matches_bindtype($_);
747 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
753 my ($self, $expr) = @_;
755 return $self->_expand_expr({ (our $Default_Scalar_To) => $expr });
758 sub _expand_hashpair_scalar {
759 my ($self, $k, $v) = @_;
761 return $self->_expand_hashpair_cmp(
762 $k, $self->_expand_scalar($v),
766 sub _expand_hashpair_op {
767 my ($self, $k, $v) = @_;
769 $self->_assert_pass_injection_guard($k =~ /\A-(.*)\Z/s);
771 my $op = $self->_normalize_op($k);
775 my $op = join(' ', split '_', $op);
777 # the old special op system requires illegality for top-level use
780 (our $Expand_Depth) == 1
782 List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
784 $self->{disable_old_special_ops}
785 and List::Util::first { $op =~ $_->{regex} } @BUILTIN_SPECIAL_OPS
789 puke "Illegal use of top-level '-$op'"
793 if (my $exp = $self->{expand}{$op}) {
794 return $self->$exp($op, $v);
797 # Ops prefixed with -not_ get converted
799 if (my ($rest) = $op =~/^not_(.*)$/) {
802 $self->_expand_expr({ "-${rest}", $v })
808 # the old unary op system means we should touch nothing and let it work
810 my $op = join(' ', split '_', $op);
812 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
813 return { -op => [ $op, $v ] };
817 # an explicit node type is currently assumed to be expanded (this is almost
818 # certainly wrong and there should be expansion anyway)
820 if ($self->{render}{$op}) {
824 my $type = $self->{unknown_unop_always_func} ? -func : -op;
831 and (keys %$v)[0] =~ /^-/
834 (List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}})
843 ($type eq -func and ref($v) eq 'ARRAY')
844 ? map $self->_expand_expr($_), @$v
845 : $self->_expand_expr($v)
849 sub _expand_hashpair_cmp {
850 my ($self, $k, $v) = @_;
851 $self->_expand_hashtriple($k, $self->{cmp}, $v);
854 sub _expand_hashtriple {
855 my ($self, $k, $vk, $vv) = @_;
857 my $ik = $self->_expand_expr({ -ident => $k });
859 my $op = $self->_normalize_op($vk);
860 $self->_assert_pass_injection_guard($op);
862 if ($op =~ s/ _? \d+ $//x ) {
863 return $self->_expand_expr($k, { $vk, $vv });
865 if (my $x = $self->{expand_op}{$op}) {
866 local our $Cur_Col_Meta = $k;
867 return $self->$x($op, $vv, $k);
871 my $op = join(' ', split '_', $op);
873 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
874 return { -op => [ $op, $ik, $vv ] };
876 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
880 { -op => [ $op, $vv ] }
884 if (ref($vv) eq 'ARRAY') {
886 my $logic = (defined($raw[0]) and $raw[0] =~ /^-(and|or)$/i)
887 ? (shift(@raw), lc $1) : 'or';
888 my @values = map +{ $vk => $_ }, @raw;
890 $op =~ $self->{inequality_op}
891 or $op =~ $self->{not_like_op}
893 if (lc($logic) eq 'or' and @values > 1) {
894 belch "A multi-element arrayref as an argument to the inequality op '${\uc(join ' ', split '_', $op)}' "
895 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
896 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
901 # try to DWIM on equality operators
902 return ($self->_dwim_op_to_is($op,
903 "Supplying an empty arrayref to '%s' is deprecated",
904 "operator '%s' applied on an empty array (field '$k')"
905 ) ? $self->sqlfalse : $self->sqltrue);
907 return $self->_expand_op_andor($logic => \@values, $k);
909 if (is_undef_value($vv)) {
910 my $is = ($self->_dwim_op_to_is($op,
911 "Supplying an undefined argument to '%s' is deprecated",
912 "unexpected operator '%s' with undef operand",
913 ) ? 'is' : 'is not');
915 return $self->_expand_hashpair($k => { $is, undef });
917 local our $Cur_Col_Meta = $k;
921 $self->_expand_expr($vv)
926 my ($self, $raw, $empty, $fail) = @_;
928 my $op = $self->_normalize_op($raw);
930 if ($op =~ /^not$/i) {
933 if ($op =~ $self->{equality_op}) {
936 if ($op =~ $self->{like_op}) {
937 belch(sprintf $empty, uc(join ' ', split '_', $op));
940 if ($op =~ $self->{inequality_op}) {
943 if ($op =~ $self->{not_like_op}) {
944 belch(sprintf $empty, uc(join ' ', split '_', $op));
947 puke(sprintf $fail, $op);
951 my ($self, undef, $args) = @_;
952 my ($func, @args) = @$args;
953 return +{ -func => [ $func, map $self->expand_expr($_), @args ] };
957 my ($self, undef, $body, $k) = @_;
958 return $self->_expand_hashpair_cmp(
959 $k, { -ident => $body }
961 unless (defined($body) or (ref($body) and ref($body) eq 'ARRAY')) {
962 puke "-ident requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
964 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
965 ref($body) ? @$body : $body;
966 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
967 unless ($self->{quote_char}) {
968 $self->_assert_pass_injection_guard($_) for @parts;
970 return +{ -ident => \@parts };
974 return $_[0]->_expand_hashpair_cmp(
975 $_[3], { -value => $_[2] },
977 +{ -bind => [ our $Cur_Col_Meta, $_[2] ] };
981 +{ -op => [ 'not', $_[0]->_expand_expr($_[2]) ] };
985 my ($self, undef, $args) = @_;
986 +{ -row => [ map $self->expand_expr($_), @$args ] };
990 my ($self, undef, $args) = @_;
991 my ($op, @opargs) = @$args;
992 if (my $exp = $self->{expand_op}{$op}) {
993 return $self->$exp($op, \@opargs);
995 +{ -op => [ $op, map $self->expand_expr($_), @opargs ] };
999 my ($self, undef, $v) = @_;
1001 return $self->_expand_expr($v);
1003 puke "-bool => undef not supported" unless defined($v);
1004 return $self->_expand_expr({ -ident => $v });
1007 sub _expand_op_andor {
1008 my ($self, $logop, $v, $k) = @_;
1010 $v = [ map +{ $k, $_ },
1012 ? (map +{ $_ => $v->{$_} }, sort keys %$v)
1016 if (ref($v) eq 'HASH') {
1017 return undef unless keys %$v;
1020 map $self->_expand_expr({ $_ => $v->{$_} }),
1024 if (ref($v) eq 'ARRAY') {
1025 $logop eq 'and' or $logop eq 'or' or puke "unknown logic: $logop";
1028 (ref($_) eq 'ARRAY' and @$_)
1029 or (ref($_) eq 'HASH' and %$_)
1035 while (my ($el) = splice @expr, 0, 1) {
1036 puke "Supplying an empty left hand side argument is not supported in array-pairs"
1037 unless defined($el) and length($el);
1038 my $elref = ref($el);
1040 local our $Expand_Depth = 0;
1041 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
1042 } elsif ($elref eq 'ARRAY') {
1043 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
1044 } elsif (my $l = is_literal_value($el)) {
1045 push @res, { -literal => $l };
1046 } elsif ($elref eq 'HASH') {
1047 local our $Expand_Depth = 0;
1048 push @res, grep defined, $self->_expand_expr($el) if %$el;
1054 # return $res[0] if @res == 1;
1055 return { -op => [ $logop, @res ] };
1061 my ($self, $op, $vv, $k) = @_;
1062 ($k, $vv) = @$vv unless defined $k;
1063 puke "$op can only take undef as argument"
1067 and exists($vv->{-value})
1068 and !defined($vv->{-value})
1070 return +{ -op => [ $op.'_null', $self->expand_expr($k, -ident) ] };
1073 sub _expand_between {
1074 my ($self, $op, $vv, $k) = @_;
1075 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1076 my @rhs = map $self->_expand_expr($_),
1077 ref($vv) eq 'ARRAY' ? @$vv : $vv;
1079 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
1081 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
1083 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1087 $self->expand_expr(ref($k) ? $k : { -ident => $k }),
1093 my ($self, $op, $vv, $k) = @_;
1094 $k = shift @{$vv = [ @$vv ]} unless defined $k;
1095 if (my $literal = is_literal_value($vv)) {
1096 my ($sql, @bind) = @$literal;
1097 my $opened_sql = $self->_open_outer_paren($sql);
1099 $op, $self->expand_expr($k, -ident),
1100 { -literal => [ $opened_sql, @bind ] }
1104 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1105 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1106 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1107 . 'will emit the logically correct SQL instead of raising this exception)'
1109 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
1111 my @rhs = map $self->expand_expr($_, -value),
1112 map { defined($_) ? $_: puke($undef_err) }
1113 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
1114 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
1118 $self->expand_expr($k, -ident),
1124 my ($self, undef, $v) = @_;
1125 # DBIx::Class requires a nest warning to be emitted once but the private
1126 # method it overrode to do so no longer exists
1127 if ($self->{warn_once_on_nest}) {
1128 unless (our $Nest_Warned) {
1130 "-nest in search conditions is deprecated, you most probably wanted:\n"
1131 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
1136 return $self->_expand_expr($v);
1140 my ($self, undef, $bind) = @_;
1141 return { -bind => $bind };
1144 sub _recurse_where {
1145 my ($self, $where, $logic) = @_;
1147 # Special case: top level simple string treated as literal
1149 my $where_exp = (ref($where)
1150 ? $self->_expand_expr($where, $logic)
1151 : { -literal => [ $where ] });
1153 # dispatch expanded expression
1155 my ($sql, @bind) = defined($where_exp) ? @{ $self->render_aqt($where_exp) || [] } : ();
1156 # DBIx::Class used to call _recurse_where in scalar context
1157 # something else might too...
1159 return ($sql, @bind);
1162 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
1168 my ($self, undef, $ident) = @_;
1170 return [ $self->_convert($self->_quote($ident)) ];
1174 my ($self, undef, $values) = @_;
1175 return $self->join_query_parts('',
1177 $self->_render_op(undef, [ ',', @$values ]),
1183 my ($self, undef, $rest) = @_;
1184 my ($func, @args) = @$rest;
1185 return $self->join_query_parts('',
1186 $self->_sqlcase($func),
1187 $self->join_query_parts('',
1189 $self->join_query_parts(', ', @args),
1196 my ($self, undef, $bind) = @_;
1197 return [ $self->_convert('?'), $self->_bindtype(@$bind) ];
1200 sub _render_literal {
1201 my ($self, undef, $literal) = @_;
1202 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1207 my ($self, undef, $v) = @_;
1208 my ($op, @args) = @$v;
1209 if (my $r = $self->{render_op}{$op}) {
1210 return $self->$r($op, \@args);
1215 my $op = join(' ', split '_', $op);
1217 my $ss = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1218 if ($ss and @args > 1) {
1219 puke "Special op '${op}' requires first value to be identifier"
1220 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1221 my $k = join(($self->{name_sep}||'.'), @$ident);
1222 local our $Expand_Depth = 1;
1223 return [ $self->${\($ss->{handler})}($k, $op, $args[1]) ];
1225 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1226 return [ $self->${\($us->{handler})}($op, $args[0]) ];
1229 return $self->_render_unop_paren($op, \@args);
1233 return $self->_render_unop_prefix($op, \@args);
1235 return $self->_render_op_multop($op, \@args);
1241 sub _render_op_between {
1242 my ($self, $op, $args) = @_;
1243 my ($left, $low, $high) = @$args;
1246 puke "Single arg to between must be a literal"
1247 unless $low->{-literal};
1250 +($low, $self->format_keyword('and'), $high);
1253 return $self->join_query_parts(' ',
1254 '(', $left, $self->format_keyword($op), @rh, ')',
1259 my ($self, $op, $args) = @_;
1260 my ($lhs, @rhs) = @$args;
1262 return $self->join_query_parts(' ',
1264 $self->format_keyword($op),
1265 $self->join_query_parts(' ',
1267 $self->join_query_parts(', ', @rhs),
1273 sub _render_op_andor {
1274 my ($self, $op, $args) = @_;
1275 return undef unless @$args;
1276 return $self->join_query_parts('', $args->[0]) if @$args == 1;
1277 my $inner = $self->_render_op_multop($op, $args);
1278 return undef unless defined($inner->[0]) and length($inner->[0]);
1279 return $self->join_query_parts(' ',
1284 sub _render_op_multop {
1285 my ($self, $op, $args) = @_;
1287 return undef unless @parts;
1288 return $self->render_aqt($parts[0]) if @parts == 1;
1289 my $join = ($op eq ','
1291 : ' '.$self->format_keyword($op).' '
1293 return $self->join_query_parts($join, @parts);
1296 sub join_query_parts {
1297 my ($self, $join, @parts) = @_;
1300 ? $self->render_aqt($_)
1301 : ((ref($_) eq 'ARRAY') ? $_ : [ $_ ])
1304 $self->{join_sql_parts}->($join, grep defined, map $_->[0], @final),
1305 (map @{$_}[1..$#$_], @final),
1309 sub _render_unop_paren {
1310 my ($self, $op, $v) = @_;
1311 return $self->join_query_parts('',
1312 '(', $self->_render_unop_prefix($op, $v), ')'
1316 sub _render_unop_prefix {
1317 my ($self, $op, $v) = @_;
1318 return $self->join_query_parts(' ',
1319 $self->_sqlcase($op), $v->[0]
1323 sub _render_unop_postfix {
1324 my ($self, $op, $v) = @_;
1325 return $self->join_query_parts(' ',
1326 $v->[0], $self->format_keyword($op),
1330 # Some databases (SQLite) treat col IN (1, 2) different from
1331 # col IN ( (1, 2) ). Use this to strip all outer parens while
1332 # adding them back in the corresponding method
1333 sub _open_outer_paren {
1334 my ($self, $sql) = @_;
1336 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1338 # there are closing parens inside, need the heavy duty machinery
1339 # to reevaluate the extraction starting from $sql (full reevaluation)
1340 if ($inner =~ /\)/) {
1341 require Text::Balanced;
1343 my (undef, $remainder) = do {
1344 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1346 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1349 # the entire expression needs to be a balanced bracketed thing
1350 # (after an extract no remainder sans trailing space)
1351 last if defined $remainder and $remainder =~ /\S/;
1361 #======================================================================
1363 #======================================================================
1365 sub _expand_order_by {
1366 my ($self, $arg) = @_;
1368 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1370 return $self->_expand_maybe_list_expr($arg)
1371 if ref($arg) eq 'HASH' and ($arg->{-op}||[''])->[0] eq ',';
1373 my $expander = sub {
1374 my ($self, $dir, $expr) = @_;
1375 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1376 foreach my $arg (@to_expand) {
1380 and grep /^-(asc|desc)$/, keys %$arg
1382 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1386 defined($dir) ? { -op => [ $dir =~ /^-?(.*)$/ ,=> $_ ] } : $_
1388 map $self->expand_expr($_, -ident),
1389 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
1390 return undef unless @exp;
1391 return undef if @exp == 1 and not defined($exp[0]);
1392 return +{ -op => [ ',', @exp ] };
1395 local @{$self->{expand}}{qw(asc desc)} = (($expander) x 2);
1397 return $self->$expander(undef, $arg);
1401 my ($self, $arg) = @_;
1403 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
1405 my ($sql, @bind) = @{ $self->render_aqt($expanded) };
1407 return '' unless length($sql);
1409 my $final_sql = $self->_sqlcase(' order by ').$sql;
1411 return ($final_sql, @bind);
1414 # _order_by no longer needs to call this so doesn't but DBIC uses it.
1416 sub _order_by_chunks {
1417 my ($self, $arg) = @_;
1419 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1421 my @res = $self->_chunkify_order_by($expanded);
1422 (ref() ? $_->[0] : $_) .= '' for @res;
1426 sub _chunkify_order_by {
1427 my ($self, $expanded) = @_;
1429 return grep length, @{ $self->render_aqt($expanded) }
1430 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1433 if (ref() eq 'HASH' and $_->{-op} and $_->{-op}[0] eq ',') {
1434 my ($comma, @list) = @{$_->{-op}};
1435 return map $self->_chunkify_order_by($_), @list;
1437 return $self->render_aqt($_);
1441 #======================================================================
1442 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1443 #======================================================================
1449 $self->_expand_maybe_list_expr($from, -ident)
1454 #======================================================================
1456 #======================================================================
1458 sub _expand_maybe_list_expr {
1459 my ($self, $expr, $default) = @_;
1461 ',', map $self->expand_expr($_, $default),
1462 @{$expr->{-op}}[1..$#{$expr->{-op}}]
1463 ] } if ref($expr) eq 'HASH' and ($expr->{-op}||[''])->[0] eq ',';
1464 return +{ -op => [ ',',
1465 map $self->expand_expr($_, $default),
1466 ref($expr) eq 'ARRAY' ? @$expr : $expr
1470 # highly optimized, as it's called way too often
1472 # my ($self, $label) = @_;
1474 return '' unless defined $_[1];
1475 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1476 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1478 unless ($_[0]->{quote_char}) {
1479 if (ref($_[1]) eq 'ARRAY') {
1480 return join($_[0]->{name_sep}||'.', @{$_[1]});
1482 $_[0]->_assert_pass_injection_guard($_[1]);
1487 my $qref = ref $_[0]->{quote_char};
1489 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1490 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1491 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1493 my $esc = $_[0]->{escape_char} || $r;
1495 # parts containing * are naturally unquoted
1497 $_[0]->{name_sep}||'',
1501 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1503 (ref($_[1]) eq 'ARRAY'
1507 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1515 # Conversion, if applicable
1517 #my ($self, $arg) = @_;
1518 if (my $conv = $_[0]->{convert_where}) {
1519 return @{ $_[0]->join_query_parts('',
1520 $_[0]->format_keyword($conv),
1529 #my ($self, $col, @vals) = @_;
1530 # called often - tighten code
1531 return $_[0]->{bindtype} eq 'columns'
1532 ? map {[$_[1], $_]} @_[2 .. $#_]
1537 # Dies if any element of @bind is not in [colname => value] format
1538 # if bindtype is 'columns'.
1539 sub _assert_bindval_matches_bindtype {
1540 # my ($self, @bind) = @_;
1542 if ($self->{bindtype} eq 'columns') {
1544 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1545 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1551 sub _join_sql_clauses {
1552 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1554 if (@$clauses_aref > 1) {
1555 my $join = " " . $self->_sqlcase($logic) . " ";
1556 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1557 return ($sql, @$bind_aref);
1559 elsif (@$clauses_aref) {
1560 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1563 return (); # if no SQL, ignore @$bind_aref
1568 # Fix SQL case, if so requested
1570 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1571 # don't touch the argument ... crooked logic, but let's not change it!
1572 return $_[0]->{case} ? $_[1] : uc($_[1]);
1575 sub format_keyword { $_[0]->_sqlcase(join ' ', split '_', $_[1]) }
1577 #======================================================================
1578 # DISPATCHING FROM REFKIND
1579 #======================================================================
1582 my ($self, $data) = @_;
1584 return 'UNDEF' unless defined $data;
1586 # blessed objects are treated like scalars
1587 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1589 return 'SCALAR' unless $ref;
1592 while ($ref eq 'REF') {
1594 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1598 return ($ref||'SCALAR') . ('REF' x $n_steps);
1602 my ($self, $data) = @_;
1603 my @try = ($self->_refkind($data));
1604 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1605 push @try, 'FALLBACK';
1609 sub _METHOD_FOR_refkind {
1610 my ($self, $meth_prefix, $data) = @_;
1613 for (@{$self->_try_refkind($data)}) {
1614 $method = $self->can($meth_prefix."_".$_)
1618 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1622 sub _SWITCH_refkind {
1623 my ($self, $data, $dispatch_table) = @_;
1626 for (@{$self->_try_refkind($data)}) {
1627 $coderef = $dispatch_table->{$_}
1631 puke "no dispatch entry for ".$self->_refkind($data)
1640 #======================================================================
1641 # VALUES, GENERATE, AUTOLOAD
1642 #======================================================================
1644 # LDNOTE: original code from nwiger, didn't touch code in that section
1645 # I feel the AUTOLOAD stuff should not be the default, it should
1646 # only be activated on explicit demand by user.
1650 my $data = shift || return;
1651 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1652 unless ref $data eq 'HASH';
1655 foreach my $k (sort keys %$data) {
1656 my $v = $data->{$k};
1657 $self->_SWITCH_refkind($v, {
1659 if ($self->{array_datatypes}) { # array datatype
1660 push @all_bind, $self->_bindtype($k, $v);
1662 else { # literal SQL with bind
1663 my ($sql, @bind) = @$v;
1664 $self->_assert_bindval_matches_bindtype(@bind);
1665 push @all_bind, @bind;
1668 ARRAYREFREF => sub { # literal SQL with bind
1669 my ($sql, @bind) = @${$v};
1670 $self->_assert_bindval_matches_bindtype(@bind);
1671 push @all_bind, @bind;
1673 SCALARREF => sub { # literal SQL without bind
1675 SCALAR_or_UNDEF => sub {
1676 push @all_bind, $self->_bindtype($k, $v);
1687 my(@sql, @sqlq, @sqlv);
1691 if ($ref eq 'HASH') {
1692 for my $k (sort keys %$_) {
1695 my $label = $self->_quote($k);
1696 if ($r eq 'ARRAY') {
1697 # literal SQL with bind
1698 my ($sql, @bind) = @$v;
1699 $self->_assert_bindval_matches_bindtype(@bind);
1700 push @sqlq, "$label = $sql";
1702 } elsif ($r eq 'SCALAR') {
1703 # literal SQL without bind
1704 push @sqlq, "$label = $$v";
1706 push @sqlq, "$label = ?";
1707 push @sqlv, $self->_bindtype($k, $v);
1710 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1711 } elsif ($ref eq 'ARRAY') {
1712 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1715 if ($r eq 'ARRAY') { # literal SQL with bind
1716 my ($sql, @bind) = @$v;
1717 $self->_assert_bindval_matches_bindtype(@bind);
1720 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1721 # embedded literal SQL
1728 push @sql, '(' . join(', ', @sqlq) . ')';
1729 } elsif ($ref eq 'SCALAR') {
1733 # strings get case twiddled
1734 push @sql, $self->_sqlcase($_);
1738 my $sql = join ' ', @sql;
1740 # this is pretty tricky
1741 # if ask for an array, return ($stmt, @bind)
1742 # otherwise, s/?/shift @sqlv/ to put it inline
1744 return ($sql, @sqlv);
1746 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1747 ref $d ? $d->[1] : $d/e;
1756 # This allows us to check for a local, then _form, attr
1758 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1759 puke "AUTOLOAD invoked for method name ${name} and allow_autoload option not set" unless $self->{allow_autoload};
1760 return $self->generate($name, @_);
1771 SQL::Abstract - Generate SQL from Perl data structures
1777 my $sql = SQL::Abstract->new;
1779 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1781 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1783 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1785 my($stmt, @bind) = $sql->delete($table, \%where);
1787 # Then, use these in your DBI statements
1788 my $sth = $dbh->prepare($stmt);
1789 $sth->execute(@bind);
1791 # Just generate the WHERE clause
1792 my($stmt, @bind) = $sql->where(\%where, $order);
1794 # Return values in the same order, for hashed queries
1795 # See PERFORMANCE section for more details
1796 my @bind = $sql->values(\%fieldvals);
1800 This module was inspired by the excellent L<DBIx::Abstract>.
1801 However, in using that module I found that what I really wanted
1802 to do was generate SQL, but still retain complete control over my
1803 statement handles and use the DBI interface. So, I set out to
1804 create an abstract SQL generation module.
1806 While based on the concepts used by L<DBIx::Abstract>, there are
1807 several important differences, especially when it comes to WHERE
1808 clauses. I have modified the concepts used to make the SQL easier
1809 to generate from Perl data structures and, IMO, more intuitive.
1810 The underlying idea is for this module to do what you mean, based
1811 on the data structures you provide it. The big advantage is that
1812 you don't have to modify your code every time your data changes,
1813 as this module figures it out.
1815 To begin with, an SQL INSERT is as easy as just specifying a hash
1816 of C<key=value> pairs:
1819 name => 'Jimbo Bobson',
1820 phone => '123-456-7890',
1821 address => '42 Sister Lane',
1822 city => 'St. Louis',
1823 state => 'Louisiana',
1826 The SQL can then be generated with this:
1828 my($stmt, @bind) = $sql->insert('people', \%data);
1830 Which would give you something like this:
1832 $stmt = "INSERT INTO people
1833 (address, city, name, phone, state)
1834 VALUES (?, ?, ?, ?, ?)";
1835 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1836 '123-456-7890', 'Louisiana');
1838 These are then used directly in your DBI code:
1840 my $sth = $dbh->prepare($stmt);
1841 $sth->execute(@bind);
1843 =head2 Inserting and Updating Arrays
1845 If your database has array types (like for example Postgres),
1846 activate the special option C<< array_datatypes => 1 >>
1847 when creating the C<SQL::Abstract> object.
1848 Then you may use an arrayref to insert and update database array types:
1850 my $sql = SQL::Abstract->new(array_datatypes => 1);
1852 planets => [qw/Mercury Venus Earth Mars/]
1855 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1859 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1861 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1864 =head2 Inserting and Updating SQL
1866 In order to apply SQL functions to elements of your C<%data> you may
1867 specify a reference to an arrayref for the given hash value. For example,
1868 if you need to execute the Oracle C<to_date> function on a value, you can
1869 say something like this:
1873 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1876 The first value in the array is the actual SQL. Any other values are
1877 optional and would be included in the bind values array. This gives
1880 my($stmt, @bind) = $sql->insert('people', \%data);
1882 $stmt = "INSERT INTO people (name, date_entered)
1883 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1884 @bind = ('Bill', '03/02/2003');
1886 An UPDATE is just as easy, all you change is the name of the function:
1888 my($stmt, @bind) = $sql->update('people', \%data);
1890 Notice that your C<%data> isn't touched; the module will generate
1891 the appropriately quirky SQL for you automatically. Usually you'll
1892 want to specify a WHERE clause for your UPDATE, though, which is
1893 where handling C<%where> hashes comes in handy...
1895 =head2 Complex where statements
1897 This module can generate pretty complicated WHERE statements
1898 easily. For example, simple C<key=value> pairs are taken to mean
1899 equality, and if you want to see if a field is within a set
1900 of values, you can use an arrayref. Let's say we wanted to
1901 SELECT some data based on this criteria:
1904 requestor => 'inna',
1905 worker => ['nwiger', 'rcwe', 'sfz'],
1906 status => { '!=', 'completed' }
1909 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1911 The above would give you something like this:
1913 $stmt = "SELECT * FROM tickets WHERE
1914 ( requestor = ? ) AND ( status != ? )
1915 AND ( worker = ? OR worker = ? OR worker = ? )";
1916 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1918 Which you could then use in DBI code like so:
1920 my $sth = $dbh->prepare($stmt);
1921 $sth->execute(@bind);
1927 The methods are simple. There's one for every major SQL operation,
1928 and a constructor you use first. The arguments are specified in a
1929 similar order for each method (table, then fields, then a where
1930 clause) to try and simplify things.
1932 =head2 new(option => 'value')
1934 The C<new()> function takes a list of options and values, and returns
1935 a new B<SQL::Abstract> object which can then be used to generate SQL
1936 through the methods below. The options accepted are:
1942 If set to 'lower', then SQL will be generated in all lowercase. By
1943 default SQL is generated in "textbook" case meaning something like:
1945 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1947 Any setting other than 'lower' is ignored.
1951 This determines what the default comparison operator is. By default
1952 it is C<=>, meaning that a hash like this:
1954 %where = (name => 'nwiger', email => 'nate@wiger.org');
1956 Will generate SQL like this:
1958 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1960 However, you may want loose comparisons by default, so if you set
1961 C<cmp> to C<like> you would get SQL such as:
1963 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1965 You can also override the comparison on an individual basis - see
1966 the huge section on L</"WHERE CLAUSES"> at the bottom.
1968 =item sqltrue, sqlfalse
1970 Expressions for inserting boolean values within SQL statements.
1971 By default these are C<1=1> and C<1=0>. They are used
1972 by the special operators C<-in> and C<-not_in> for generating
1973 correct SQL even when the argument is an empty array (see below).
1977 This determines the default logical operator for multiple WHERE
1978 statements in arrays or hashes. If absent, the default logic is "or"
1979 for arrays, and "and" for hashes. This means that a WHERE
1983 event_date => {'>=', '2/13/99'},
1984 event_date => {'<=', '4/24/03'},
1987 will generate SQL like this:
1989 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1991 This is probably not what you want given this query, though (look
1992 at the dates). To change the "OR" to an "AND", simply specify:
1994 my $sql = SQL::Abstract->new(logic => 'and');
1996 Which will change the above C<WHERE> to:
1998 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2000 The logic can also be changed locally by inserting
2001 a modifier in front of an arrayref:
2003 @where = (-and => [event_date => {'>=', '2/13/99'},
2004 event_date => {'<=', '4/24/03'} ]);
2006 See the L</"WHERE CLAUSES"> section for explanations.
2010 This will automatically convert comparisons using the specified SQL
2011 function for both column and value. This is mostly used with an argument
2012 of C<upper> or C<lower>, so that the SQL will have the effect of
2013 case-insensitive "searches". For example, this:
2015 $sql = SQL::Abstract->new(convert => 'upper');
2016 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2018 Will turn out the following SQL:
2020 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2022 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2023 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2024 not validate this option; it will just pass through what you specify verbatim).
2028 This is a kludge because many databases suck. For example, you can't
2029 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2030 Instead, you have to use C<bind_param()>:
2032 $sth->bind_param(1, 'reg data');
2033 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2035 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2036 which loses track of which field each slot refers to. Fear not.
2038 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2039 Currently, you can specify either C<normal> (default) or C<columns>. If you
2040 specify C<columns>, you will get an array that looks like this:
2042 my $sql = SQL::Abstract->new(bindtype => 'columns');
2043 my($stmt, @bind) = $sql->insert(...);
2046 [ 'column1', 'value1' ],
2047 [ 'column2', 'value2' ],
2048 [ 'column3', 'value3' ],
2051 You can then iterate through this manually, using DBI's C<bind_param()>.
2053 $sth->prepare($stmt);
2056 my($col, $data) = @$_;
2057 if ($col eq 'details' || $col eq 'comments') {
2058 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2059 } elsif ($col eq 'image') {
2060 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2062 $sth->bind_param($i, $data);
2066 $sth->execute; # execute without @bind now
2068 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2069 Basically, the advantage is still that you don't have to care which fields
2070 are or are not included. You could wrap that above C<for> loop in a simple
2071 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2072 get a layer of abstraction over manual SQL specification.
2074 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2075 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2076 will expect the bind values in this format.
2080 This is the character that a table or column name will be quoted
2081 with. By default this is an empty string, but you could set it to
2082 the character C<`>, to generate SQL like this:
2084 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2086 Alternatively, you can supply an array ref of two items, the first being the left
2087 hand quote character, and the second the right hand quote character. For
2088 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2089 that generates SQL like this:
2091 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2093 Quoting is useful if you have tables or columns names that are reserved
2094 words in your database's SQL dialect.
2098 This is the character that will be used to escape L</quote_char>s appearing
2099 in an identifier before it has been quoted.
2101 The parameter default in case of a single L</quote_char> character is the quote
2104 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2105 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2106 of the B<opening (left)> L</quote_char> within the identifier are currently left
2107 untouched. The default for opening-closing-style quotes may change in future
2108 versions, thus you are B<strongly encouraged> to specify the escape character
2113 This is the character that separates a table and column name. It is
2114 necessary to specify this when the C<quote_char> option is selected,
2115 so that tables and column names can be individually quoted like this:
2117 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2119 =item injection_guard
2121 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2122 column name specified in a query structure. This is a safety mechanism to avoid
2123 injection attacks when mishandling user input e.g.:
2125 my %condition_as_column_value_pairs = get_values_from_user();
2126 $sqla->select( ... , \%condition_as_column_value_pairs );
2128 If the expression matches an exception is thrown. Note that literal SQL
2129 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2131 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2133 =item array_datatypes
2135 When this option is true, arrayrefs in INSERT or UPDATE are
2136 interpreted as array datatypes and are passed directly
2138 When this option is false, arrayrefs are interpreted
2139 as literal SQL, just like refs to arrayrefs
2140 (but this behavior is for backwards compatibility; when writing
2141 new queries, use the "reference to arrayref" syntax
2147 Takes a reference to a list of "special operators"
2148 to extend the syntax understood by L<SQL::Abstract>.
2149 See section L</"SPECIAL OPERATORS"> for details.
2153 Takes a reference to a list of "unary operators"
2154 to extend the syntax understood by L<SQL::Abstract>.
2155 See section L</"UNARY OPERATORS"> for details.
2161 =head2 insert($table, \@values || \%fieldvals, \%options)
2163 This is the simplest function. You simply give it a table name
2164 and either an arrayref of values or hashref of field/value pairs.
2165 It returns an SQL INSERT statement and a list of bind values.
2166 See the sections on L</"Inserting and Updating Arrays"> and
2167 L</"Inserting and Updating SQL"> for information on how to insert
2168 with those data types.
2170 The optional C<\%options> hash reference may contain additional
2171 options to generate the insert SQL. Currently supported options
2178 Takes either a scalar of raw SQL fields, or an array reference of
2179 field names, and adds on an SQL C<RETURNING> statement at the end.
2180 This allows you to return data generated by the insert statement
2181 (such as row IDs) without performing another C<SELECT> statement.
2182 Note, however, this is not part of the SQL standard and may not
2183 be supported by all database engines.
2187 =head2 update($table, \%fieldvals, \%where, \%options)
2189 This takes a table, hashref of field/value pairs, and an optional
2190 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2192 See the sections on L</"Inserting and Updating Arrays"> and
2193 L</"Inserting and Updating SQL"> for information on how to insert
2194 with those data types.
2196 The optional C<\%options> hash reference may contain additional
2197 options to generate the update SQL. Currently supported options
2204 See the C<returning> option to
2205 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2209 =head2 select($source, $fields, $where, $order)
2211 This returns a SQL SELECT statement and associated list of bind values, as
2212 specified by the arguments:
2218 Specification of the 'FROM' part of the statement.
2219 The argument can be either a plain scalar (interpreted as a table
2220 name, will be quoted), or an arrayref (interpreted as a list
2221 of table names, joined by commas, quoted), or a scalarref
2222 (literal SQL, not quoted).
2226 Specification of the list of fields to retrieve from
2228 The argument can be either an arrayref (interpreted as a list
2229 of field names, will be joined by commas and quoted), or a
2230 plain scalar (literal SQL, not quoted).
2231 Please observe that this API is not as flexible as that of
2232 the first argument C<$source>, for backwards compatibility reasons.
2236 Optional argument to specify the WHERE part of the query.
2237 The argument is most often a hashref, but can also be
2238 an arrayref or plain scalar --
2239 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2243 Optional argument to specify the ORDER BY part of the query.
2244 The argument can be a scalar, a hashref or an arrayref
2245 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2251 =head2 delete($table, \%where, \%options)
2253 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2254 It returns an SQL DELETE statement and list of bind values.
2256 The optional C<\%options> hash reference may contain additional
2257 options to generate the delete SQL. Currently supported options
2264 See the C<returning> option to
2265 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2269 =head2 where(\%where, $order)
2271 This is used to generate just the WHERE clause. For example,
2272 if you have an arbitrary data structure and know what the
2273 rest of your SQL is going to look like, but want an easy way
2274 to produce a WHERE clause, use this. It returns an SQL WHERE
2275 clause and list of bind values.
2278 =head2 values(\%data)
2280 This just returns the values from the hash C<%data>, in the same
2281 order that would be returned from any of the other above queries.
2282 Using this allows you to markedly speed up your queries if you
2283 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2285 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2287 Warning: This is an experimental method and subject to change.
2289 This returns arbitrarily generated SQL. It's a really basic shortcut.
2290 It will return two different things, depending on return context:
2292 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2293 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2295 These would return the following:
2297 # First calling form
2298 $stmt = "CREATE TABLE test (?, ?)";
2299 @bind = (field1, field2);
2301 # Second calling form
2302 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2304 Depending on what you're trying to do, it's up to you to choose the correct
2305 format. In this example, the second form is what you would want.
2309 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2313 ALTER SESSION SET nls_date_format = 'MM/YY'
2315 You get the idea. Strings get their case twiddled, but everything
2316 else remains verbatim.
2318 =head1 EXPORTABLE FUNCTIONS
2320 =head2 is_plain_value
2322 Determines if the supplied argument is a plain value as understood by this
2327 =item * The value is C<undef>
2329 =item * The value is a non-reference
2331 =item * The value is an object with stringification overloading
2333 =item * The value is of the form C<< { -value => $anything } >>
2337 On failure returns C<undef>, on success returns a B<scalar> reference
2338 to the original supplied argument.
2344 The stringification overloading detection is rather advanced: it takes
2345 into consideration not only the presence of a C<""> overload, but if that
2346 fails also checks for enabled
2347 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2348 on either C<0+> or C<bool>.
2350 Unfortunately testing in the field indicates that this
2351 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2352 but only when very large numbers of stringifying objects are involved.
2353 At the time of writing ( Sep 2014 ) there is no clear explanation of
2354 the direct cause, nor is there a manageably small test case that reliably
2355 reproduces the problem.
2357 If you encounter any of the following exceptions in B<random places within
2358 your application stack> - this module may be to blame:
2360 Operation "ne": no method found,
2361 left argument in overloaded package <something>,
2362 right argument in overloaded package <something>
2366 Stub found while resolving method "???" overloading """" in package <something>
2368 If you fall victim to the above - please attempt to reduce the problem
2369 to something that could be sent to the L<SQL::Abstract developers
2370 |DBIx::Class/GETTING HELP/SUPPORT>
2371 (either publicly or privately). As a workaround in the meantime you can
2372 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2373 value, which will most likely eliminate your problem (at the expense of
2374 not being able to properly detect exotic forms of stringification).
2376 This notice and environment variable will be removed in a future version,
2377 as soon as the underlying problem is found and a reliable workaround is
2382 =head2 is_literal_value
2384 Determines if the supplied argument is a literal value as understood by this
2389 =item * C<\$sql_string>
2391 =item * C<\[ $sql_string, @bind_values ]>
2395 On failure returns C<undef>, on success returns an B<array> reference
2396 containing the unpacked version of the supplied literal SQL and bind values.
2398 =head1 WHERE CLAUSES
2402 This module uses a variation on the idea from L<DBIx::Abstract>. It
2403 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2404 module is that things in arrays are OR'ed, and things in hashes
2407 The easiest way to explain is to show lots of examples. After
2408 each C<%where> hash shown, it is assumed you used:
2410 my($stmt, @bind) = $sql->where(\%where);
2412 However, note that the C<%where> hash can be used directly in any
2413 of the other functions as well, as described above.
2415 =head2 Key-value pairs
2417 So, let's get started. To begin, a simple hash:
2421 status => 'completed'
2424 Is converted to SQL C<key = val> statements:
2426 $stmt = "WHERE user = ? AND status = ?";
2427 @bind = ('nwiger', 'completed');
2429 One common thing I end up doing is having a list of values that
2430 a field can be in. To do this, simply specify a list inside of
2435 status => ['assigned', 'in-progress', 'pending'];
2438 This simple code will create the following:
2440 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2441 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2443 A field associated to an empty arrayref will be considered a
2444 logical false and will generate 0=1.
2446 =head2 Tests for NULL values
2448 If the value part is C<undef> then this is converted to SQL <IS NULL>
2457 $stmt = "WHERE user = ? AND status IS NULL";
2460 To test if a column IS NOT NULL:
2464 status => { '!=', undef },
2467 =head2 Specific comparison operators
2469 If you want to specify a different type of operator for your comparison,
2470 you can use a hashref for a given column:
2474 status => { '!=', 'completed' }
2477 Which would generate:
2479 $stmt = "WHERE user = ? AND status != ?";
2480 @bind = ('nwiger', 'completed');
2482 To test against multiple values, just enclose the values in an arrayref:
2484 status => { '=', ['assigned', 'in-progress', 'pending'] };
2486 Which would give you:
2488 "WHERE status = ? OR status = ? OR status = ?"
2491 The hashref can also contain multiple pairs, in which case it is expanded
2492 into an C<AND> of its elements:
2496 status => { '!=', 'completed', -not_like => 'pending%' }
2499 # Or more dynamically, like from a form
2500 $where{user} = 'nwiger';
2501 $where{status}{'!='} = 'completed';
2502 $where{status}{'-not_like'} = 'pending%';
2504 # Both generate this
2505 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2506 @bind = ('nwiger', 'completed', 'pending%');
2509 To get an OR instead, you can combine it with the arrayref idea:
2513 priority => [ { '=', 2 }, { '>', 5 } ]
2516 Which would generate:
2518 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2519 @bind = ('2', '5', 'nwiger');
2521 If you want to include literal SQL (with or without bind values), just use a
2522 scalar reference or reference to an arrayref as the value:
2525 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2526 date_expires => { '<' => \"now()" }
2529 Which would generate:
2531 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2532 @bind = ('11/26/2008');
2535 =head2 Logic and nesting operators
2537 In the example above,
2538 there is a subtle trap if you want to say something like
2539 this (notice the C<AND>):
2541 WHERE priority != ? AND priority != ?
2543 Because, in Perl you I<can't> do this:
2545 priority => { '!=' => 2, '!=' => 1 }
2547 As the second C<!=> key will obliterate the first. The solution
2548 is to use the special C<-modifier> form inside an arrayref:
2550 priority => [ -and => {'!=', 2},
2554 Normally, these would be joined by C<OR>, but the modifier tells it
2555 to use C<AND> instead. (Hint: You can use this in conjunction with the
2556 C<logic> option to C<new()> in order to change the way your queries
2557 work by default.) B<Important:> Note that the C<-modifier> goes
2558 B<INSIDE> the arrayref, as an extra first element. This will
2559 B<NOT> do what you think it might:
2561 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2563 Here is a quick list of equivalencies, since there is some overlap:
2566 status => {'!=', 'completed', 'not like', 'pending%' }
2567 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2570 status => {'=', ['assigned', 'in-progress']}
2571 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2572 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2576 =head2 Special operators: IN, BETWEEN, etc.
2578 You can also use the hashref format to compare a list of fields using the
2579 C<IN> comparison operator, by specifying the list as an arrayref:
2582 status => 'completed',
2583 reportid => { -in => [567, 2335, 2] }
2586 Which would generate:
2588 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2589 @bind = ('completed', '567', '2335', '2');
2591 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2594 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2595 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2596 'sqltrue' (by default: C<1=1>).
2598 In addition to the array you can supply a chunk of literal sql or
2599 literal sql with bind:
2602 customer => { -in => \[
2603 'SELECT cust_id FROM cust WHERE balance > ?',
2606 status => { -in => \'SELECT status_codes FROM states' },
2612 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2613 AND status IN ( SELECT status_codes FROM states )
2617 Finally, if the argument to C<-in> is not a reference, it will be
2618 treated as a single-element array.
2620 Another pair of operators is C<-between> and C<-not_between>,
2621 used with an arrayref of two values:
2625 completion_date => {
2626 -not_between => ['2002-10-01', '2003-02-06']
2632 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2634 Just like with C<-in> all plausible combinations of literal SQL
2638 start0 => { -between => [ 1, 2 ] },
2639 start1 => { -between => \["? AND ?", 1, 2] },
2640 start2 => { -between => \"lower(x) AND upper(y)" },
2641 start3 => { -between => [
2643 \["upper(?)", 'stuff' ],
2650 ( start0 BETWEEN ? AND ? )
2651 AND ( start1 BETWEEN ? AND ? )
2652 AND ( start2 BETWEEN lower(x) AND upper(y) )
2653 AND ( start3 BETWEEN lower(x) AND upper(?) )
2655 @bind = (1, 2, 1, 2, 'stuff');
2658 These are the two builtin "special operators"; but the
2659 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2661 =head2 Unary operators: bool
2663 If you wish to test against boolean columns or functions within your
2664 database you can use the C<-bool> and C<-not_bool> operators. For
2665 example to test the column C<is_user> being true and the column
2666 C<is_enabled> being false you would use:-
2670 -not_bool => 'is_enabled',
2675 WHERE is_user AND NOT is_enabled
2677 If a more complex combination is required, testing more conditions,
2678 then you should use the and/or operators:-
2683 -not_bool => { two=> { -rlike => 'bar' } },
2684 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2695 (NOT ( three = ? OR three > ? ))
2698 =head2 Nested conditions, -and/-or prefixes
2700 So far, we've seen how multiple conditions are joined with a top-level
2701 C<AND>. We can change this by putting the different conditions we want in
2702 hashes and then putting those hashes in an array. For example:
2707 status => { -like => ['pending%', 'dispatched'] },
2711 status => 'unassigned',
2715 This data structure would create the following:
2717 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2718 OR ( user = ? AND status = ? ) )";
2719 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2722 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2723 to change the logic inside:
2729 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2730 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2737 $stmt = "WHERE ( user = ?
2738 AND ( ( workhrs > ? AND geo = ? )
2739 OR ( workhrs < ? OR geo = ? ) ) )";
2740 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2742 =head3 Algebraic inconsistency, for historical reasons
2744 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2745 operator goes C<outside> of the nested structure; whereas when connecting
2746 several constraints on one column, the C<-and> operator goes
2747 C<inside> the arrayref. Here is an example combining both features:
2750 -and => [a => 1, b => 2],
2751 -or => [c => 3, d => 4],
2752 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2757 WHERE ( ( ( a = ? AND b = ? )
2758 OR ( c = ? OR d = ? )
2759 OR ( e LIKE ? AND e LIKE ? ) ) )
2761 This difference in syntax is unfortunate but must be preserved for
2762 historical reasons. So be careful: the two examples below would
2763 seem algebraically equivalent, but they are not
2766 { -like => 'foo%' },
2767 { -like => '%bar' },
2769 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2772 { col => { -like => 'foo%' } },
2773 { col => { -like => '%bar' } },
2775 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2778 =head2 Literal SQL and value type operators
2780 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2781 side" is a column name and the "right side" is a value (normally rendered as
2782 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2783 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2784 alter this behavior. There are several ways of doing so.
2788 This is a virtual operator that signals the string to its right side is an
2789 identifier (a column name) and not a value. For example to compare two
2790 columns you would write:
2793 priority => { '<', 2 },
2794 requestor => { -ident => 'submitter' },
2799 $stmt = "WHERE priority < ? AND requestor = submitter";
2802 If you are maintaining legacy code you may see a different construct as
2803 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2808 This is a virtual operator that signals that the construct to its right side
2809 is a value to be passed to DBI. This is for example necessary when you want
2810 to write a where clause against an array (for RDBMS that support such
2811 datatypes). For example:
2814 array => { -value => [1, 2, 3] }
2819 $stmt = 'WHERE array = ?';
2820 @bind = ([1, 2, 3]);
2822 Note that if you were to simply say:
2828 the result would probably not be what you wanted:
2830 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2835 Finally, sometimes only literal SQL will do. To include a random snippet
2836 of SQL verbatim, you specify it as a scalar reference. Consider this only
2837 as a last resort. Usually there is a better way. For example:
2840 priority => { '<', 2 },
2841 requestor => { -in => \'(SELECT name FROM hitmen)' },
2846 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2849 Note that in this example, you only get one bind parameter back, since
2850 the verbatim SQL is passed as part of the statement.
2854 Never use untrusted input as a literal SQL argument - this is a massive
2855 security risk (there is no way to check literal snippets for SQL
2856 injections and other nastyness). If you need to deal with untrusted input
2857 use literal SQL with placeholders as described next.
2859 =head3 Literal SQL with placeholders and bind values (subqueries)
2861 If the literal SQL to be inserted has placeholders and bind values,
2862 use a reference to an arrayref (yes this is a double reference --
2863 not so common, but perfectly legal Perl). For example, to find a date
2864 in Postgres you can use something like this:
2867 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2872 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2875 Note that you must pass the bind values in the same format as they are returned
2876 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2877 to C<columns>, you must provide the bind values in the
2878 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2879 scalar value; most commonly the column name, but you can use any scalar value
2880 (including references and blessed references), L<SQL::Abstract> will simply
2881 pass it through intact. So if C<bindtype> is set to C<columns> the above
2882 example will look like:
2885 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2888 Literal SQL is especially useful for nesting parenthesized clauses in the
2889 main SQL query. Here is a first example:
2891 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2895 bar => \["IN ($sub_stmt)" => @sub_bind],
2900 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2901 WHERE c2 < ? AND c3 LIKE ?))";
2902 @bind = (1234, 100, "foo%");
2904 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2905 are expressed in the same way. Of course the C<$sub_stmt> and
2906 its associated bind values can be generated through a former call
2909 my ($sub_stmt, @sub_bind)
2910 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2911 c3 => {-like => "foo%"}});
2914 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2917 In the examples above, the subquery was used as an operator on a column;
2918 but the same principle also applies for a clause within the main C<%where>
2919 hash, like an EXISTS subquery:
2921 my ($sub_stmt, @sub_bind)
2922 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2923 my %where = ( -and => [
2925 \["EXISTS ($sub_stmt)" => @sub_bind],
2930 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2931 WHERE c1 = ? AND c2 > t0.c0))";
2935 Observe that the condition on C<c2> in the subquery refers to
2936 column C<t0.c0> of the main query: this is I<not> a bind
2937 value, so we have to express it through a scalar ref.
2938 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2939 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2940 what we wanted here.
2942 Finally, here is an example where a subquery is used
2943 for expressing unary negation:
2945 my ($sub_stmt, @sub_bind)
2946 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2947 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2949 lname => {like => '%son%'},
2950 \["NOT ($sub_stmt)" => @sub_bind],
2955 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2956 @bind = ('%son%', 10, 20)
2958 =head3 Deprecated usage of Literal SQL
2960 Below are some examples of archaic use of literal SQL. It is shown only as
2961 reference for those who deal with legacy code. Each example has a much
2962 better, cleaner and safer alternative that users should opt for in new code.
2968 my %where = ( requestor => \'IS NOT NULL' )
2970 $stmt = "WHERE requestor IS NOT NULL"
2972 This used to be the way of generating NULL comparisons, before the handling
2973 of C<undef> got formalized. For new code please use the superior syntax as
2974 described in L</Tests for NULL values>.
2978 my %where = ( requestor => \'= submitter' )
2980 $stmt = "WHERE requestor = submitter"
2982 This used to be the only way to compare columns. Use the superior L</-ident>
2983 method for all new code. For example an identifier declared in such a way
2984 will be properly quoted if L</quote_char> is properly set, while the legacy
2985 form will remain as supplied.
2989 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2991 $stmt = "WHERE completed > ? AND is_ready"
2992 @bind = ('2012-12-21')
2994 Using an empty string literal used to be the only way to express a boolean.
2995 For all new code please use the much more readable
2996 L<-bool|/Unary operators: bool> operator.
3002 These pages could go on for a while, since the nesting of the data
3003 structures this module can handle are pretty much unlimited (the
3004 module implements the C<WHERE> expansion as a recursive function
3005 internally). Your best bet is to "play around" with the module a
3006 little to see how the data structures behave, and choose the best
3007 format for your data based on that.
3009 And of course, all the values above will probably be replaced with
3010 variables gotten from forms or the command line. After all, if you
3011 knew everything ahead of time, you wouldn't have to worry about
3012 dynamically-generating SQL and could just hardwire it into your
3015 =head1 ORDER BY CLAUSES
3017 Some functions take an order by clause. This can either be a scalar (just a
3018 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3019 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3022 Given | Will Generate
3023 ---------------------------------------------------------------
3025 'colA' | ORDER BY colA
3027 [qw/colA colB/] | ORDER BY colA, colB
3029 {-asc => 'colA'} | ORDER BY colA ASC
3031 {-desc => 'colB'} | ORDER BY colB DESC
3033 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3035 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3037 \'colA DESC' | ORDER BY colA DESC
3039 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3040 | /* ...with $x bound to ? */
3043 { -asc => 'colA' }, | colA ASC,
3044 { -desc => [qw/colB/] }, | colB DESC,
3045 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3046 \'colE DESC', | colE DESC,
3047 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3048 ] | /* ...with $x bound to ? */
3049 ===============================================================
3053 =head1 SPECIAL OPERATORS
3055 my $sqlmaker = SQL::Abstract->new(special_ops => [
3059 my ($self, $field, $op, $arg) = @_;
3065 handler => 'method_name',
3069 A "special operator" is a SQL syntactic clause that can be
3070 applied to a field, instead of a usual binary operator.
3073 WHERE field IN (?, ?, ?)
3074 WHERE field BETWEEN ? AND ?
3075 WHERE MATCH(field) AGAINST (?, ?)
3077 Special operators IN and BETWEEN are fairly standard and therefore
3078 are builtin within C<SQL::Abstract> (as the overridable methods
3079 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3080 like the MATCH .. AGAINST example above which is specific to MySQL,
3081 you can write your own operator handlers - supply a C<special_ops>
3082 argument to the C<new> method. That argument takes an arrayref of
3083 operator definitions; each operator definition is a hashref with two
3090 the regular expression to match the operator
3094 Either a coderef or a plain scalar method name. In both cases
3095 the expected return is C<< ($sql, @bind) >>.
3097 When supplied with a method name, it is simply called on the
3098 L<SQL::Abstract> object as:
3100 $self->$method_name($field, $op, $arg)
3104 $field is the LHS of the operator
3105 $op is the part that matched the handler regex
3108 When supplied with a coderef, it is called as:
3110 $coderef->($self, $field, $op, $arg)
3115 For example, here is an implementation
3116 of the MATCH .. AGAINST syntax for MySQL
3118 my $sqlmaker = SQL::Abstract->new(special_ops => [
3120 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3121 {regex => qr/^match$/i,
3123 my ($self, $field, $op, $arg) = @_;
3124 $arg = [$arg] if not ref $arg;
3125 my $label = $self->_quote($field);
3126 my ($placeholder) = $self->_convert('?');
3127 my $placeholders = join ", ", (($placeholder) x @$arg);
3128 my $sql = $self->_sqlcase('match') . " ($label) "
3129 . $self->_sqlcase('against') . " ($placeholders) ";
3130 my @bind = $self->_bindtype($field, @$arg);
3131 return ($sql, @bind);
3138 =head1 UNARY OPERATORS
3140 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3144 my ($self, $op, $arg) = @_;
3150 handler => 'method_name',
3154 A "unary operator" is a SQL syntactic clause that can be
3155 applied to a field - the operator goes before the field
3157 You can write your own operator handlers - supply a C<unary_ops>
3158 argument to the C<new> method. That argument takes an arrayref of
3159 operator definitions; each operator definition is a hashref with two
3166 the regular expression to match the operator
3170 Either a coderef or a plain scalar method name. In both cases
3171 the expected return is C<< $sql >>.
3173 When supplied with a method name, it is simply called on the
3174 L<SQL::Abstract> object as:
3176 $self->$method_name($op, $arg)
3180 $op is the part that matched the handler regex
3181 $arg is the RHS or argument of the operator
3183 When supplied with a coderef, it is called as:
3185 $coderef->($self, $op, $arg)
3193 Thanks to some benchmarking by Mark Stosberg, it turns out that
3194 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3195 I must admit this wasn't an intentional design issue, but it's a
3196 byproduct of the fact that you get to control your C<DBI> handles
3199 To maximize performance, use a code snippet like the following:
3201 # prepare a statement handle using the first row
3202 # and then reuse it for the rest of the rows
3204 for my $href (@array_of_hashrefs) {
3205 $stmt ||= $sql->insert('table', $href);
3206 $sth ||= $dbh->prepare($stmt);
3207 $sth->execute($sql->values($href));
3210 The reason this works is because the keys in your C<$href> are sorted
3211 internally by B<SQL::Abstract>. Thus, as long as your data retains
3212 the same structure, you only have to generate the SQL the first time
3213 around. On subsequent queries, simply use the C<values> function provided
3214 by this module to return your values in the correct order.
3216 However this depends on the values having the same type - if, for
3217 example, the values of a where clause may either have values
3218 (resulting in sql of the form C<column = ?> with a single bind
3219 value), or alternatively the values might be C<undef> (resulting in
3220 sql of the form C<column IS NULL> with no bind value) then the
3221 caching technique suggested will not work.
3225 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3226 really like this part (I do, at least). Building up a complex query
3227 can be as simple as the following:
3234 use CGI::FormBuilder;
3237 my $form = CGI::FormBuilder->new(...);
3238 my $sql = SQL::Abstract->new;
3240 if ($form->submitted) {
3241 my $field = $form->field;
3242 my $id = delete $field->{id};
3243 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3246 Of course, you would still have to connect using C<DBI> to run the
3247 query, but the point is that if you make your form look like your
3248 table, the actual query script can be extremely simplistic.
3250 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3251 a fast interface to returning and formatting data. I frequently
3252 use these three modules together to write complex database query
3253 apps in under 50 lines.
3255 =head1 HOW TO CONTRIBUTE
3257 Contributions are always welcome, in all usable forms (we especially
3258 welcome documentation improvements). The delivery methods include git-
3259 or unified-diff formatted patches, GitHub pull requests, or plain bug
3260 reports either via RT or the Mailing list. Contributors are generally
3261 granted full access to the official repository after their first several
3262 patches pass successful review.
3264 This project is maintained in a git repository. The code and related tools are
3265 accessible at the following locations:
3269 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3271 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3273 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3275 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3281 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3282 Great care has been taken to preserve the I<published> behavior
3283 documented in previous versions in the 1.* family; however,
3284 some features that were previously undocumented, or behaved
3285 differently from the documentation, had to be changed in order
3286 to clarify the semantics. Hence, client code that was relying
3287 on some dark areas of C<SQL::Abstract> v1.*
3288 B<might behave differently> in v1.50.
3290 The main changes are:
3296 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3300 support for the { operator => \"..." } construct (to embed literal SQL)
3304 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3308 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3312 defensive programming: check arguments
3316 fixed bug with global logic, which was previously implemented
3317 through global variables yielding side-effects. Prior versions would
3318 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3319 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3320 Now this is interpreted
3321 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3326 fixed semantics of _bindtype on array args
3330 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3331 we just avoid shifting arrays within that tree.
3335 dropped the C<_modlogic> function
3339 =head1 ACKNOWLEDGEMENTS
3341 There are a number of individuals that have really helped out with
3342 this module. Unfortunately, most of them submitted bugs via CPAN
3343 so I have no idea who they are! But the people I do know are:
3345 Ash Berlin (order_by hash term support)
3346 Matt Trout (DBIx::Class support)
3347 Mark Stosberg (benchmarking)
3348 Chas Owens (initial "IN" operator support)
3349 Philip Collins (per-field SQL functions)
3350 Eric Kolve (hashref "AND" support)
3351 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3352 Dan Kubb (support for "quote_char" and "name_sep")
3353 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3354 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3355 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3356 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3357 Oliver Charles (support for "RETURNING" after "INSERT")
3363 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3367 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3369 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3371 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3372 While not an official support venue, C<DBIx::Class> makes heavy use of
3373 C<SQL::Abstract>, and as such list members there are very familiar with
3374 how to create queries.
3378 This module is free software; you may copy this under the same
3379 terms as perl itself (either the GNU General Public License or
3380 the Artistic License)