1 package SQL::Abstract; # see doc at end of file
10 our @EXPORT_OK = qw(is_plain_value is_literal_value);
20 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
26 #======================================================================
28 #======================================================================
30 our $VERSION = '1.87';
32 # This would confuse some packagers
33 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
37 # special operators (-in, -between). May be extended/overridden by user.
38 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
39 my @BUILTIN_SPECIAL_OPS = (
40 {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }},
41 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ ident $/ix, handler => sub { die "NOPE" }},
43 {regex => qr/^ value $/ix, handler => sub { die "NOPE" }},
44 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
47 # unaryish operators - key maps to handler
48 my @BUILTIN_UNARY_OPS = (
49 # the digits are backcompat stuff
50 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
51 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
52 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
53 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
54 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
55 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
56 { regex => qr/^ op $/xi, handler => '_where_op_OP' },
57 { regex => qr/^ bind $/xi, handler => '_where_op_BIND' },
58 { regex => qr/^ literal $/xi, handler => '_where_op_LITERAL' },
61 #======================================================================
62 # DEBUGGING AND ERROR REPORTING
63 #======================================================================
66 return unless $_[0]->{debug}; shift; # a little faster
67 my $func = (caller(1))[3];
68 warn "[$func] ", @_, "\n";
72 my($func) = (caller(1))[3];
73 Carp::carp "[$func] Warning: ", @_;
77 my($func) = (caller(1))[3];
78 Carp::croak "[$func] Fatal: ", @_;
81 sub is_literal_value ($) {
82 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
83 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
87 # FIXME XSify - this can be done so much more efficiently
88 sub is_plain_value ($) {
90 ! length ref $_[0] ? \($_[0])
92 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
94 exists $_[0]->{-value}
95 ) ? \($_[0]->{-value})
97 # reuse @_ for even moar speedz
98 defined ( $_[1] = Scalar::Util::blessed $_[0] )
100 # deliberately not using Devel::OverloadInfo - the checks we are
101 # intersted in are much more limited than the fullblown thing, and
102 # this is a very hot piece of code
104 # simply using ->can('(""') can leave behind stub methods that
105 # break actually using the overload later (see L<perldiag/Stub
106 # found while resolving method "%s" overloading "%s" in package
107 # "%s"> and the source of overload::mycan())
109 # either has stringification which DBI SHOULD prefer out of the box
110 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
112 # has nummification or boolification, AND fallback is *not* disabled
114 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
117 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
119 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
123 # no fallback specified at all
124 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
126 # fallback explicitly undef
127 ! defined ${"$_[3]::()"}
140 #======================================================================
142 #======================================================================
146 my $class = ref($self) || $self;
147 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
149 # choose our case by keeping an option around
150 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
152 # default logic for interpreting arrayrefs
153 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
155 # how to return bind vars
156 $opt{bindtype} ||= 'normal';
158 # default comparison is "=", but can be overridden
161 # try to recognize which are the 'equality' and 'inequality' ops
162 # (temporary quickfix (in 2007), should go through a more seasoned API)
163 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
164 $opt{inequality_op} = qr/^( != | <> )$/ix;
166 $opt{like_op} = qr/^ (is\s+)? r?like $/xi;
167 $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
170 $opt{sqltrue} ||= '1=1';
171 $opt{sqlfalse} ||= '0=1';
174 $opt{user_special_ops} = [ @{$opt{special_ops} ||= []} ];
175 # regexes are applied in order, thus push after user-defines
176 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
179 $opt{unary_ops} ||= [];
180 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
182 # rudimentary sanity-check for user supplied bits treated as functions/operators
183 # If a purported function matches this regular expression, an exception is thrown.
184 # Literal SQL is *NOT* subject to this check, only functions (and column names
185 # when quoting is not in effect)
188 # need to guard against ()'s in column names too, but this will break tons of
189 # hacks... ideas anyone?
190 $opt{injection_guard} ||= qr/
196 return bless \%opt, $class;
200 sub _assert_pass_injection_guard {
201 if ($_[1] =~ $_[0]->{injection_guard}) {
202 my $class = ref $_[0];
203 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
204 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
205 . "{injection_guard} attribute to ${class}->new()"
210 #======================================================================
212 #======================================================================
216 my $table = $self->_table(shift);
217 my $data = shift || return;
220 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
221 my ($sql, @bind) = $self->$method($data);
222 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
224 if ($options->{returning}) {
225 my ($s, @b) = $self->_insert_returning($options);
230 return wantarray ? ($sql, @bind) : $sql;
233 # So that subclasses can override INSERT ... RETURNING separately from
234 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
235 sub _insert_returning { shift->_returning(@_) }
238 my ($self, $options) = @_;
240 my $f = $options->{returning};
242 my $fieldlist = $self->_SWITCH_refkind($f, {
243 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
244 SCALAR => sub {$self->_quote($f)},
245 SCALARREF => sub {$$f},
247 return $self->_sqlcase(' returning ') . $fieldlist;
250 sub _insert_HASHREF { # explicit list of fields and then values
251 my ($self, $data) = @_;
253 my @fields = sort keys %$data;
255 my ($sql, @bind) = $self->_insert_values($data);
258 $_ = $self->_quote($_) foreach @fields;
259 $sql = "( ".join(", ", @fields).") ".$sql;
261 return ($sql, @bind);
264 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
265 my ($self, $data) = @_;
267 # no names (arrayref) so can't generate bindtype
268 $self->{bindtype} ne 'columns'
269 or belch "can't do 'columns' bindtype when called with arrayref";
271 my (@values, @all_bind);
272 foreach my $value (@$data) {
273 my ($values, @bind) = $self->_insert_value(undef, $value);
274 push @values, $values;
275 push @all_bind, @bind;
277 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
278 return ($sql, @all_bind);
281 sub _insert_ARRAYREFREF { # literal SQL with bind
282 my ($self, $data) = @_;
284 my ($sql, @bind) = @${$data};
285 $self->_assert_bindval_matches_bindtype(@bind);
287 return ($sql, @bind);
291 sub _insert_SCALARREF { # literal SQL without bind
292 my ($self, $data) = @_;
298 my ($self, $data) = @_;
300 my (@values, @all_bind);
301 foreach my $column (sort keys %$data) {
302 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
303 push @values, $values;
304 push @all_bind, @bind;
306 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
307 return ($sql, @all_bind);
311 my ($self, $column, $v) = @_;
313 my (@values, @all_bind);
314 $self->_SWITCH_refkind($v, {
317 if ($self->{array_datatypes}) { # if array datatype are activated
319 push @all_bind, $self->_bindtype($column, $v);
321 else { # else literal SQL with bind
322 my ($sql, @bind) = @$v;
323 $self->_assert_bindval_matches_bindtype(@bind);
325 push @all_bind, @bind;
329 ARRAYREFREF => sub { # literal SQL with bind
330 my ($sql, @bind) = @${$v};
331 $self->_assert_bindval_matches_bindtype(@bind);
333 push @all_bind, @bind;
336 # THINK: anything useful to do with a HASHREF ?
337 HASHREF => sub { # (nothing, but old SQLA passed it through)
338 #TODO in SQLA >= 2.0 it will die instead
339 belch "HASH ref as bind value in insert is not supported";
341 push @all_bind, $self->_bindtype($column, $v);
344 SCALARREF => sub { # literal SQL without bind
348 SCALAR_or_UNDEF => sub {
350 push @all_bind, $self->_bindtype($column, $v);
355 my $sql = join(", ", @values);
356 return ($sql, @all_bind);
361 #======================================================================
363 #======================================================================
368 my $table = $self->_table(shift);
369 my $data = shift || return;
373 # first build the 'SET' part of the sql statement
374 puke "Unsupported data type specified to \$sql->update"
375 unless ref $data eq 'HASH';
377 my ($sql, @all_bind) = $self->_update_set_values($data);
378 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
382 my($where_sql, @where_bind) = $self->where($where);
384 push @all_bind, @where_bind;
387 if ($options->{returning}) {
388 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
389 $sql .= $returning_sql;
390 push @all_bind, @returning_bind;
393 return wantarray ? ($sql, @all_bind) : $sql;
396 sub _update_set_values {
397 my ($self, $data) = @_;
399 my (@set, @all_bind);
400 for my $k (sort keys %$data) {
403 my $label = $self->_quote($k);
405 $self->_SWITCH_refkind($v, {
407 if ($self->{array_datatypes}) { # array datatype
408 push @set, "$label = ?";
409 push @all_bind, $self->_bindtype($k, $v);
411 else { # literal SQL with bind
412 my ($sql, @bind) = @$v;
413 $self->_assert_bindval_matches_bindtype(@bind);
414 push @set, "$label = $sql";
415 push @all_bind, @bind;
418 ARRAYREFREF => sub { # literal SQL with bind
419 my ($sql, @bind) = @${$v};
420 $self->_assert_bindval_matches_bindtype(@bind);
421 push @set, "$label = $sql";
422 push @all_bind, @bind;
424 SCALARREF => sub { # literal SQL without bind
425 push @set, "$label = $$v";
428 my ($op, $arg, @rest) = %$v;
430 puke 'Operator calls in update must be in the form { -op => $arg }'
431 if (@rest or not $op =~ /^\-(.+)/);
433 local $self->{_nested_func_lhs} = $k;
434 my ($sql, @bind) = $self->_where_unary_op($1, $arg);
436 push @set, "$label = $sql";
437 push @all_bind, @bind;
439 SCALAR_or_UNDEF => sub {
440 push @set, "$label = ?";
441 push @all_bind, $self->_bindtype($k, $v);
447 my $sql = join ', ', @set;
449 return ($sql, @all_bind);
452 # So that subclasses can override UPDATE ... RETURNING separately from
454 sub _update_returning { shift->_returning(@_) }
458 #======================================================================
460 #======================================================================
465 my $table = $self->_table(shift);
466 my $fields = shift || '*';
470 my ($fields_sql, @bind) = $self->_select_fields($fields);
472 my ($where_sql, @where_bind) = $self->where($where, $order);
473 push @bind, @where_bind;
475 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
476 $self->_sqlcase('from'), $table)
479 return wantarray ? ($sql, @bind) : $sql;
483 my ($self, $fields) = @_;
484 return ref $fields eq 'ARRAY' ? join ', ', map { $self->_quote($_) } @$fields
488 #======================================================================
490 #======================================================================
495 my $table = $self->_table(shift);
499 my($where_sql, @bind) = $self->where($where);
500 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
502 if ($options->{returning}) {
503 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
504 $sql .= $returning_sql;
505 push @bind, @returning_bind;
508 return wantarray ? ($sql, @bind) : $sql;
511 # So that subclasses can override DELETE ... RETURNING separately from
513 sub _delete_returning { shift->_returning(@_) }
517 #======================================================================
519 #======================================================================
523 # Finally, a separate routine just to handle WHERE clauses
525 my ($self, $where, $order) = @_;
528 my ($sql, @bind) = $self->_recurse_where($where);
529 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
533 my ($order_sql, @order_bind) = $self->_order_by($order);
535 push @bind, @order_bind;
538 return wantarray ? ($sql, @bind) : $sql;
542 my ($self, $expr, $logic) = @_;
543 return undef unless defined($expr);
544 if (ref($expr) eq 'HASH') {
545 if (keys %$expr > 1) {
547 return +{ "-${logic}" => [
548 map $self->_expand_expr_hashpair($_ => $expr->{$_}, $logic),
552 return unless %$expr;
553 return $self->_expand_expr_hashpair(%$expr, $logic);
555 if (ref($expr) eq 'ARRAY') {
556 my $logic = lc($logic || $self->{logic});
557 $logic eq 'and' or $logic eq 'or' or puke "unknown logic: $logic";
563 while (my ($el) = splice @expr, 0, 1) {
564 puke "Supplying an empty left hand side argument is not supported in array-pairs"
565 unless defined($el) and length($el);
566 my $elref = ref($el);
568 push(@res, $self->_expand_expr({ $el, shift(@expr) }));
569 } elsif ($elref eq 'ARRAY') {
570 push(@res, $self->_expand_expr($el)) if @$el;
571 } elsif (is_literal_value($el)) {
573 } elsif ($elref eq 'HASH') {
574 push @res, $self->_expand_expr($el);
579 return { '-'.$logic => \@res };
581 if (my $literal = is_literal_value($expr)) {
582 return +{ -literal => $literal };
584 if (!ref($expr) or Scalar::Util::blessed($expr)) {
585 if (my $m = our $Cur_Col_Meta) {
586 return +{ -bind => [ $m, $expr ] };
588 return +{ -value => $expr };
590 #::Ddie([ HUH => $expr ]);
594 sub _expand_expr_hashpair {
595 my ($self, $k, $v, $logic) = @_;
596 unless (defined($k) and length($k)) {
597 if (defined($k) and my $literal = is_literal_value($v)) {
598 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
599 return { -literal => $literal };
601 puke "Supplying an empty left hand side argument is not supported";
604 $self->_assert_pass_injection_guard($k =~ /^-(.*)$/s);
605 if ($k =~ s/ [_\s]? \d+ $//x ) {
606 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
607 . "You probably wanted ...-and => [ $k => COND1, $k => COND2 ... ]";
610 return $self->_expand_expr($v);
614 return $self->_expand_expr($v);
616 puke "-bool => undef not supported" unless defined($v);
617 return { -ident => $v };
620 return { -not => $self->_expand_expr($v) };
622 if (my ($rest) = $k =~/^-not[_ ](.*)$/) {
624 $self->_expand_expr_hashpair("-${rest}", $v, $logic)
627 if (my ($logic) = $k =~ /^-(and|or)$/i) {
628 if (ref($v) eq 'HASH') {
629 return $self->_expand_expr($v, $logic);
631 if (ref($v) eq 'ARRAY') {
632 return $self->_expand_expr($v, $logic);
637 $op =~ s/^-// if length($op) > 1;
639 # top level special ops are illegal in general
640 puke "Illegal use of top-level '-$op'"
641 if !(defined $self->{_nested_func_lhs})
642 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
643 and not List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}};
645 if ($k eq '-value' and my $m = our $Cur_Col_Meta) {
646 return +{ -bind => [ $m, $v ] };
648 if ($k eq '-op' or $k eq '-ident' or $k eq '-value' or $k eq '-bind' or $k eq '-literal') {
652 return +{ -op => [ $k =~ /^-(.*)$/, $self->_expand_expr($v) ] };
659 and exists $v->{-value}
660 and not defined $v->{-value}
663 return $self->_expand_expr_hashpair($k => { $self->{cmp} => undef });
665 if (!ref($v) or Scalar::Util::blessed($v)) {
670 { -bind => [ $k, $v ] }
674 if (ref($v) eq 'HASH') {
677 map $self->_expand_expr_hashpair($k => { $_ => $v->{$_} }),
684 $self->_assert_pass_injection_guard($vk);
685 if ($vk =~ s/ [_\s]? \d+ $//x ) {
686 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
687 . "You probably wanted ...-and => [ -$vk => COND1, -$vk => COND2 ... ]";
689 if ($vk =~ /^(?:not[ _])?between$/) {
690 local our $Cur_Col_Meta = $k;
691 my @rhs = map $self->_expand_expr($_),
692 ref($vv) eq 'ARRAY' ? @$vv : $vv;
694 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
696 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
698 puke "Operator '${\uc($vk)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
701 join(' ', split '_', $vk),
706 if ($vk =~ /^(?:not[ _])?in$/) {
707 if (my $literal = is_literal_value($vv)) {
708 my ($sql, @bind) = @$literal;
709 my $opened_sql = $self->_open_outer_paren($sql);
711 $vk, { -ident => $k },
712 [ { -literal => [ $opened_sql, @bind ] } ]
716 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
717 . "-${\uc($vk)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
718 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
719 . 'will emit the logically correct SQL instead of raising this exception)'
721 puke("Argument passed to the '${\uc($vk)}' operator can not be undefined")
723 my @rhs = map $self->_expand_expr($_),
724 map { ref($_) ? $_ : { -bind => [ $k, $_ ] } }
725 map { defined($_) ? $_: puke($undef_err) }
726 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
728 -literal => [ $self->{$vk =~ /^not/ ? 'sqltrue' : 'sqlfalse'} ]
732 join(' ', split '_', $vk),
737 if ($vk eq 'ident') {
738 if (! defined $vv or ref $vv) {
739 puke "-$vk requires a single plain scalar argument (a quotable identifier)";
747 if ($vk eq 'value') {
748 return $self->_expand_expr_hashpair($k, undef) unless defined($vv);
752 { -bind => [ $k, $vv ] }
755 if ($vk =~ /^is(?:[ _]not)?$/) {
756 puke "$vk can only take undef as argument"
760 and exists($vv->{-value})
761 and !defined($vv->{-value})
764 return +{ -op => [ $vk.' null', { -ident => $k } ] };
766 if ($vk =~ /^(and|or)$/) {
767 if (ref($vv) eq 'HASH') {
768 return +{ "-${vk}" => [
769 map $self->_expand_expr_hashpair($k, { $_ => $vv->{$_} }),
774 if (my $us = List::Util::first { $vk =~ $_->{regex} } @{$self->{user_special_ops}}) {
775 return { -op => [ $vk, { -ident => $k }, $vv ] };
777 if (ref($vv) eq 'ARRAY') {
778 my ($logic, @values) = (
779 (defined($vv->[0]) and $vv->[0] =~ /^-(and|or)$/i)
784 $vk =~ $self->{inequality_op}
785 or join(' ', split '_', $vk) =~ $self->{not_like_op}
787 if (lc($logic) eq '-or' and @values > 1) {
788 my $op = uc join ' ', split '_', $vk;
789 belch "A multi-element arrayref as an argument to the inequality op '$op' "
790 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
791 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
794 return $self->{sqltrue} unless @values;
796 return $self->{sqlfalse} unless @values;
797 return +{ $logic => [
798 map $self->_expand_expr_hashpair($k => { $vk => $_ }),
806 and exists $vv->{-value}
807 and not defined $vv->{-value}
810 my $op = join ' ', split '_', $vk;
812 $op =~ /^not$/i ? 'is not' # legacy
813 : $op =~ $self->{equality_op} ? 'is'
814 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
815 : $op =~ $self->{inequality_op} ? 'is not'
816 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
817 : puke "unexpected operator '$op' with undef operand";
818 return +{ -op => [ $is.' null', { -ident => $k } ] };
820 local our $Cur_Col_Meta = $k;
824 $self->_expand_expr($vv)
827 if (ref($v) eq 'ARRAY') {
828 return $self->{sqlfalse} unless @$v;
829 $self->_debug("ARRAY($k) means distribute over elements");
831 $v->[0] =~ /^-((?:and|or))$/i
832 ? ($v = [ @{$v}[1..$#$v] ], $1)
833 : ($self->{logic} || 'or')
835 return +{ "-${this_logic}" => [ map $self->_expand_expr({ $k => $_ }, $this_logic), @$v ] };
837 if (my $literal = is_literal_value($v)) {
839 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
842 my ($sql, @bind) = @$literal;
843 if ($self->{bindtype} eq 'columns') {
845 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
846 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
850 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
852 ::Ddie([ HUH => { $k => $v } ]);
858 my ($self, $where, $logic) = @_;
860 #print STDERR Data::Dumper::Concise::Dumper([ $where, $logic ]);
862 my $where_exp = $self->_expand_expr($where, $logic);
864 #print STDERR Data::Dumper::Concise::Dumper([ EXP => $where_exp ]);
866 # dispatch on appropriate method according to refkind of $where
867 my $method = $self->_METHOD_FOR_refkind("_where", $where_exp);
869 my ($sql, @bind) = $self->$method($where_exp, $logic);
871 # DBIx::Class used to call _recurse_where in scalar context
872 # something else might too...
874 return ($sql, @bind);
877 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
884 #======================================================================
885 # WHERE: top-level ARRAYREF
886 #======================================================================
889 sub _where_ARRAYREF {
890 my ($self, $where, $logic) = @_;
892 $logic = uc($logic || $self->{logic});
893 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
895 my @clauses = @$where;
897 my (@sql_clauses, @all_bind);
898 # need to use while() so can shift() for pairs
900 my $el = shift @clauses;
902 $el = undef if (defined $el and ! length $el);
904 # switch according to kind of $el and get corresponding ($sql, @bind)
905 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
907 # skip empty elements, otherwise get invalid trailing AND stuff
908 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
912 $self->_assert_bindval_matches_bindtype(@b);
916 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
918 SCALARREF => sub { ($$el); },
921 # top-level arrayref with scalars, recurse in pairs
922 $self->_recurse_where({$el => shift(@clauses)})
925 UNDEF => sub {puke "Supplying an empty left hand side argument is not supported in array-pairs" },
929 push @sql_clauses, $sql;
930 push @all_bind, @bind;
934 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
937 #======================================================================
938 # WHERE: top-level ARRAYREFREF
939 #======================================================================
941 sub _where_ARRAYREFREF {
942 my ($self, $where) = @_;
943 my ($sql, @bind) = @$$where;
944 $self->_assert_bindval_matches_bindtype(@bind);
945 return ($sql, @bind);
948 #======================================================================
949 # WHERE: top-level HASHREF
950 #======================================================================
953 my ($self, $where) = @_;
954 my (@sql_clauses, @all_bind);
956 for my $k (sort keys %$where) {
957 my $v = $where->{$k};
959 # ($k => $v) is either a special unary op or a regular hashpair
960 my ($sql, @bind) = do {
962 # put the operator in canonical form
964 $op = substr $op, 1; # remove initial dash
965 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
966 $op =~ s/\s+/ /g; # compress whitespace
968 # so that -not_foo works correctly
969 $op =~ s/^not_/NOT /i;
971 $self->_debug("Unary OP(-$op) within hashref, recursing...");
972 my ($s, @b) = $self->_where_unary_op($op, $v);
974 # top level vs nested
975 # we assume that handled unary ops will take care of their ()s
977 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
979 ( defined $self->{_nested_func_lhs} and $self->{_nested_func_lhs} eq $k )
985 if (is_literal_value ($v) ) {
986 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
989 puke "Supplying an empty left hand side argument is not supported in hash-pairs";
993 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
994 $self->$method($k, $v);
998 push @sql_clauses, $sql;
999 push @all_bind, @bind;
1002 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
1005 sub _where_unary_op {
1006 my ($self, $op, $rhs) = @_;
1008 $op =~ s/^-// if length($op) > 1;
1010 # top level special ops are illegal in general
1011 puke "Illegal use of top-level '-$op'"
1012 if !(defined $self->{_nested_func_lhs})
1013 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
1014 and not List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}};
1016 if (my $op_entry = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1017 my $handler = $op_entry->{handler};
1019 if (not ref $handler) {
1020 if ($op =~ s/ [_\s]? \d+ $//x ) {
1021 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
1022 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
1024 return $self->$handler($op, $rhs);
1026 elsif (ref $handler eq 'CODE') {
1027 return $handler->($self, $op, $rhs);
1030 puke "Illegal handler for operator $op - expecting a method name or a coderef";
1034 $self->_debug("Generic unary OP: $op - recursing as function");
1036 $self->_assert_pass_injection_guard($op);
1038 my ($sql, @bind) = $self->_SWITCH_refkind($rhs, {
1040 puke "Illegal use of top-level '-$op'"
1041 unless defined $self->{_nested_func_lhs};
1044 $self->_convert('?'),
1045 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
1049 $self->_recurse_where($rhs)
1053 $sql = sprintf('%s %s',
1054 $self->_sqlcase($op),
1058 return ($sql, @bind);
1061 sub _where_op_ANDOR {
1062 my ($self, $op, $v) = @_;
1064 $self->_SWITCH_refkind($v, {
1066 return $self->_where_ARRAYREF($v, $op);
1070 return ($op =~ /^or/i)
1071 ? $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], $op)
1072 : $self->_where_HASHREF($v);
1076 puke "-$op => \\\$scalar makes little sense, use " .
1078 ? '[ \$scalar, \%rest_of_conditions ] instead'
1079 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
1083 ARRAYREFREF => sub {
1084 puke "-$op => \\[...] makes little sense, use " .
1086 ? '[ \[...], \%rest_of_conditions ] instead'
1087 : '-and => [ \[...], \%rest_of_conditions ] instead'
1091 SCALAR => sub { # permissively interpreted as SQL
1092 puke "-$op => \$value makes little sense, use -bool => \$value instead";
1096 puke "-$op => undef not supported";
1101 sub _where_op_NEST {
1102 my ($self, $op, $v) = @_;
1104 $self->_SWITCH_refkind($v, {
1106 SCALAR => sub { # permissively interpreted as SQL
1107 belch "literal SQL should be -nest => \\'scalar' "
1108 . "instead of -nest => 'scalar' ";
1113 puke "-$op => undef not supported";
1117 $self->_recurse_where($v);
1124 sub _where_op_BOOL {
1125 my ($self, $op, $v) = @_;
1127 my ($s, @b) = $self->_SWITCH_refkind($v, {
1128 SCALAR => sub { # interpreted as SQL column
1129 $self->_convert($self->_quote($v));
1133 puke "-$op => undef not supported";
1137 $self->_recurse_where($v);
1141 $s = "(NOT $s)" if $op =~ /^not/i;
1146 sub _where_op_IDENT {
1148 my ($op, $rhs) = splice @_, -2;
1149 if (! defined $rhs or length ref $rhs) {
1150 puke "-$op requires a single plain scalar argument (a quotable identifier)";
1153 # in case we are called as a top level special op (no '=')
1154 my $has_lhs = my $lhs = shift;
1156 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
1164 sub _where_op_VALUE {
1166 my ($op, $rhs) = splice @_, -2;
1168 # in case we are called as a top level special op (no '=')
1172 if (! defined $rhs) {
1174 ? $self->_where_hashpair_HASHREF($lhs, { -is => undef })
1181 (defined $lhs ? $lhs : $self->{_nested_func_lhs}),
1188 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
1192 $self->_convert('?'),
1199 my %unop_postfix = map +($_ => 1), 'is null', 'is not null';
1205 my ($self, $args) = @_;
1206 my ($left, $low, $high) = @$args;
1207 my ($rhsql, @rhbind) = do {
1209 puke "Single arg to between must be a literal"
1210 unless $low->{-literal};
1213 local $self->{_nested_func_lhs} = $left->{-ident}
1214 if ref($left) eq 'HASH' and $left->{-ident};
1215 my ($l, $h) = map [ $self->_where_unary_op(%$_) ], $low, $high;
1216 (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]),
1217 @{$l}[1..$#$l], @{$h}[1..$#$h])
1220 my ($lhsql, @lhbind) = $self->_recurse_where($left);
1222 join(' ', '(', $lhsql, $self->_sqlcase($op), $rhsql, ')'),
1226 }), 'between', 'not between'),
1230 my ($self, $args) = @_;
1231 my ($lhs, $rhs) = @$args;
1234 local $self->{_nested_func_lhs} = $lhs->{-ident}
1235 if ref($lhs) eq 'HASH' and $lhs->{-ident};
1236 my ($sql, @bind) = $self->_where_unary_op(%$_);
1237 push @in_bind, @bind;
1240 my ($lhsql, @lbind) = $self->_recurse_where($lhs);
1242 $lhsql.' '.$self->_sqlcase($op).' ( '
1243 .join(', ', @in_sql)
1248 }), 'in', 'not in'),
1252 my ($self, undef, $v) = @_;
1253 my ($op, @args) = @$v;
1254 $op =~ s/^-// if length($op) > 1;
1255 local $self->{_nested_func_lhs};
1256 if (my $h = $special{$op}) {
1257 return $self->$h(\@args);
1259 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{user_special_ops}}) {
1260 puke "Special op '${op}' requires first value to be identifier"
1261 unless my ($k) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1262 return $self->${\($us->{handler})}($k, $op, $args[1]);
1264 my $final_op = $op =~ /^(?:is|not)_/ ? join(' ', split '_', $op) : $op;
1266 my ($expr_sql, @bind) = $self->_recurse_where($args[0]);
1267 my $op_sql = $self->_sqlcase($final_op);
1269 $unop_postfix{lc($final_op)}
1270 ? "${expr_sql} ${op_sql}"
1271 : "${op_sql} ${expr_sql}"
1273 return ($final_sql, @bind);
1274 } elsif (@args == 2) {
1275 my ($l, $r) = map [ $self->_recurse_where($_) ], @args;
1277 $l->[0].' '.$self->_sqlcase($final_op).' '.$r->[0],
1278 @{$l}[1..$#$l], @{$r}[1..$#$r]
1284 sub _where_op_BIND {
1285 my ($self, undef, $bind) = @_;
1286 return ($self->_convert('?'), $self->_bindtype(@$bind));
1289 sub _where_op_LITERAL {
1290 my ($self, undef, $literal) = @_;
1291 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
1295 sub _where_hashpair_ARRAYREF {
1296 my ($self, $k, $v) = @_;
1299 my @v = @$v; # need copy because of shift below
1300 $self->_debug("ARRAY($k) means distribute over elements");
1302 # put apart first element if it is an operator (-and, -or)
1304 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
1308 my @distributed = map { {$k => $_} } @v;
1311 $self->_debug("OP($op) reinjected into the distributed array");
1312 unshift @distributed, $op;
1315 my $logic = $op ? substr($op, 1) : '';
1317 return $self->_recurse_where(\@distributed, $logic);
1320 $self->_debug("empty ARRAY($k) means 0=1");
1321 return ($self->{sqlfalse});
1325 sub _where_hashpair_HASHREF {
1326 my ($self, $k, $v, $logic) = @_;
1329 local $self->{_nested_func_lhs} = defined $self->{_nested_func_lhs}
1330 ? $self->{_nested_func_lhs}
1334 my ($all_sql, @all_bind);
1336 for my $orig_op (sort keys %$v) {
1337 my $val = $v->{$orig_op};
1339 # put the operator in canonical form
1342 # FIXME - we need to phase out dash-less ops
1343 $op =~ s/^-//; # remove possible initial dash
1344 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
1345 $op =~ s/\s+/ /g; # compress whitespace
1347 $self->_assert_pass_injection_guard($op);
1350 $op =~ s/^is_not/IS NOT/i;
1352 # so that -not_foo works correctly
1353 $op =~ s/^not_/NOT /i;
1355 # another retarded special case: foo => { $op => { -value => undef } }
1356 if (ref $val eq 'HASH' and keys %$val == 1 and exists $val->{-value} and ! defined $val->{-value} ) {
1362 # CASE: col-value logic modifiers
1363 if ($orig_op =~ /^ \- (and|or) $/xi) {
1364 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
1366 # CASE: special operators like -in or -between
1367 elsif (my $special_op = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
1368 my $handler = $special_op->{handler};
1370 puke "No handler supplied for special operator $orig_op";
1372 elsif (not ref $handler) {
1373 ($sql, @bind) = $self->$handler($k, $op, $val);
1375 elsif (ref $handler eq 'CODE') {
1376 ($sql, @bind) = $handler->($self, $k, $op, $val);
1379 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
1383 $self->_SWITCH_refkind($val, {
1385 ARRAYREF => sub { # CASE: col => {op => \@vals}
1386 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
1389 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
1390 my ($sub_sql, @sub_bind) = @$$val;
1391 $self->_assert_bindval_matches_bindtype(@sub_bind);
1392 $sql = join ' ', $self->_convert($self->_quote($k)),
1393 $self->_sqlcase($op),
1398 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
1400 $op =~ /^not$/i ? 'is not' # legacy
1401 : $op =~ $self->{equality_op} ? 'is'
1402 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
1403 : $op =~ $self->{inequality_op} ? 'is not'
1404 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
1405 : puke "unexpected operator '$orig_op' with undef operand";
1407 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
1410 FALLBACK => sub { # CASE: col => {op/func => $stuff}
1411 ($sql, @bind) = $self->_where_unary_op($op, $val);
1414 $self->_convert($self->_quote($k)),
1415 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
1421 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
1422 push @all_bind, @bind;
1424 return ($all_sql, @all_bind);
1427 sub _where_field_IS {
1428 my ($self, $k, $op, $v) = @_;
1430 my ($s) = $self->_SWITCH_refkind($v, {
1433 $self->_convert($self->_quote($k)),
1434 map { $self->_sqlcase($_)} ($op, 'null')
1437 puke "$op can only take undef as argument";
1444 sub _where_field_op_ARRAYREF {
1445 my ($self, $k, $op, $vals) = @_;
1447 my @vals = @$vals; #always work on a copy
1450 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
1452 join(', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
1455 # see if the first element is an -and/-or op
1457 if (defined $vals[0] && $vals[0] =~ /^ - (AND|OR) $/ix) {
1462 # a long standing API wart - an attempt to change this behavior during
1463 # the 1.50 series failed *spectacularly*. Warn instead and leave the
1468 (!$logic or $logic eq 'OR')
1470 ($op =~ $self->{inequality_op} or $op =~ $self->{not_like_op})
1473 belch "A multi-element arrayref as an argument to the inequality op '$o' "
1474 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
1475 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
1479 # distribute $op over each remaining member of @vals, append logic if exists
1480 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
1484 # try to DWIM on equality operators
1486 $op =~ $self->{equality_op} ? $self->{sqlfalse}
1487 : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqlfalse}
1488 : $op =~ $self->{inequality_op} ? $self->{sqltrue}
1489 : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->{sqltrue}
1490 : puke "operator '$op' applied on an empty array (field '$k')";
1495 sub _where_hashpair_SCALARREF {
1496 my ($self, $k, $v) = @_;
1497 $self->_debug("SCALAR($k) means literal SQL: $$v");
1498 my $sql = $self->_quote($k) . " " . $$v;
1502 # literal SQL with bind
1503 sub _where_hashpair_ARRAYREFREF {
1504 my ($self, $k, $v) = @_;
1505 $self->_debug("REF($k) means literal SQL: @${$v}");
1506 my ($sql, @bind) = @$$v;
1507 $self->_assert_bindval_matches_bindtype(@bind);
1508 $sql = $self->_quote($k) . " " . $sql;
1509 return ($sql, @bind );
1512 # literal SQL without bind
1513 sub _where_hashpair_SCALAR {
1514 my ($self, $k, $v) = @_;
1515 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
1516 return ($self->_where_hashpair_HASHREF($k, { $self->{cmp} => $v }));
1520 sub _where_hashpair_UNDEF {
1521 my ($self, $k, $v) = @_;
1522 $self->_debug("UNDEF($k) means IS NULL");
1523 return $self->_where_hashpair_HASHREF($k, { -is => undef });
1526 #======================================================================
1527 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
1528 #======================================================================
1531 sub _where_SCALARREF {
1532 my ($self, $where) = @_;
1535 $self->_debug("SCALAR(*top) means literal SQL: $$where");
1541 my ($self, $where) = @_;
1544 $self->_debug("NOREF(*top) means literal SQL: $where");
1555 #======================================================================
1556 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
1557 #======================================================================
1560 sub _where_field_BETWEEN {
1561 my ($self, $k, $op, $vals) = @_;
1563 my ($label, $and, $placeholder);
1564 $label = $self->_convert($self->_quote($k));
1565 $and = ' ' . $self->_sqlcase('and') . ' ';
1566 $placeholder = $self->_convert('?');
1567 $op = $self->_sqlcase($op);
1569 my $invalid_args = "Operator '$op' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
1571 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
1572 ARRAYREFREF => sub {
1573 my ($s, @b) = @$$vals;
1574 $self->_assert_bindval_matches_bindtype(@b);
1581 puke $invalid_args if @$vals != 2;
1583 my (@all_sql, @all_bind);
1584 foreach my $val (@$vals) {
1585 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1587 return ($placeholder, $self->_bindtype($k, $val) );
1592 ARRAYREFREF => sub {
1593 my ($sql, @bind) = @$$val;
1594 $self->_assert_bindval_matches_bindtype(@bind);
1595 return ($sql, @bind);
1598 my ($func, $arg, @rest) = %$val;
1599 puke "Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN"
1600 if (@rest or $func !~ /^ \- (.+)/x);
1601 $self->_where_unary_op($1 => $arg);
1607 push @all_sql, $sql;
1608 push @all_bind, @bind;
1612 (join $and, @all_sql),
1621 my $sql = "( $label $op $clause )";
1622 return ($sql, @bind)
1626 sub _where_field_IN {
1627 my ($self, $k, $op, $vals) = @_;
1629 # backwards compatibility: if scalar, force into an arrayref
1630 $vals = [$vals] if defined $vals && ! ref $vals;
1632 my ($label) = $self->_convert($self->_quote($k));
1633 my ($placeholder) = $self->_convert('?');
1634 $op = $self->_sqlcase($op);
1636 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1637 ARRAYREF => sub { # list of choices
1638 if (@$vals) { # nonempty list
1639 my (@all_sql, @all_bind);
1641 for my $val (@$vals) {
1642 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1644 return ($placeholder, $val);
1649 ARRAYREFREF => sub {
1650 my ($sql, @bind) = @$$val;
1651 $self->_assert_bindval_matches_bindtype(@bind);
1652 return ($sql, @bind);
1655 my ($func, $arg, @rest) = %$val;
1656 puke "Only simple { -func => arg } functions accepted as sub-arguments to IN"
1657 if (@rest or $func !~ /^ \- (.+)/x);
1658 $self->_where_unary_op($1 => $arg);
1662 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
1663 . "-$op operator was given an undef-containing list: !!!AUDIT YOUR CODE "
1664 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
1665 . 'will emit the logically correct SQL instead of raising this exception)'
1669 push @all_sql, $sql;
1670 push @all_bind, @bind;
1674 sprintf('%s %s ( %s )',
1677 join(', ', @all_sql)
1679 $self->_bindtype($k, @all_bind),
1682 else { # empty list: some databases won't understand "IN ()", so DWIM
1683 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1688 SCALARREF => sub { # literal SQL
1689 my $sql = $self->_open_outer_paren($$vals);
1690 return ("$label $op ( $sql )");
1692 ARRAYREFREF => sub { # literal SQL with bind
1693 my ($sql, @bind) = @$$vals;
1694 $self->_assert_bindval_matches_bindtype(@bind);
1695 $sql = $self->_open_outer_paren($sql);
1696 return ("$label $op ( $sql )", @bind);
1700 puke "Argument passed to the '$op' operator can not be undefined";
1704 puke "special op $op requires an arrayref (or scalarref/arrayref-ref)";
1708 return ($sql, @bind);
1711 # Some databases (SQLite) treat col IN (1, 2) different from
1712 # col IN ( (1, 2) ). Use this to strip all outer parens while
1713 # adding them back in the corresponding method
1714 sub _open_outer_paren {
1715 my ($self, $sql) = @_;
1717 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1719 # there are closing parens inside, need the heavy duty machinery
1720 # to reevaluate the extraction starting from $sql (full reevaluation)
1721 if ($inner =~ /\)/) {
1722 require Text::Balanced;
1724 my (undef, $remainder) = do {
1725 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1727 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1730 # the entire expression needs to be a balanced bracketed thing
1731 # (after an extract no remainder sans trailing space)
1732 last if defined $remainder and $remainder =~ /\S/;
1742 #======================================================================
1744 #======================================================================
1747 my ($self, $arg) = @_;
1750 for my $c ($self->_order_by_chunks($arg) ) {
1751 $self->_SWITCH_refkind($c, {
1752 SCALAR => sub { push @sql, $c },
1753 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1759 $self->_sqlcase(' order by'),
1765 return wantarray ? ($sql, @bind) : $sql;
1768 sub _order_by_chunks {
1769 my ($self, $arg) = @_;
1771 return $self->_SWITCH_refkind($arg, {
1774 map { $self->_order_by_chunks($_ ) } @$arg;
1777 ARRAYREFREF => sub {
1778 my ($s, @b) = @$$arg;
1779 $self->_assert_bindval_matches_bindtype(@b);
1783 SCALAR => sub {$self->_quote($arg)},
1785 UNDEF => sub {return () },
1787 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1790 # get first pair in hash
1791 my ($key, $val, @rest) = %$arg;
1793 return () unless $key;
1795 if (@rest or not $key =~ /^-(desc|asc)/i) {
1796 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1802 for my $c ($self->_order_by_chunks($val)) {
1805 $self->_SWITCH_refkind($c, {
1810 ($sql, @bind) = @$c;
1814 $sql = $sql . ' ' . $self->_sqlcase($direction);
1816 push @ret, [ $sql, @bind];
1825 #======================================================================
1826 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1827 #======================================================================
1832 $self->_SWITCH_refkind($from, {
1833 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1834 SCALAR => sub {$self->_quote($from)},
1835 SCALARREF => sub {$$from},
1840 #======================================================================
1842 #======================================================================
1844 # highly optimized, as it's called way too often
1846 # my ($self, $label) = @_;
1848 return '' unless defined $_[1];
1849 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1851 $_[0]->{quote_char} or
1852 ($_[0]->_assert_pass_injection_guard($_[1]), return $_[1]);
1854 my $qref = ref $_[0]->{quote_char};
1856 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1857 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1858 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1860 my $esc = $_[0]->{escape_char} || $r;
1862 # parts containing * are naturally unquoted
1863 return join($_[0]->{name_sep}||'', map
1864 +( $_ eq '*' ? $_ : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r } ),
1865 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1870 # Conversion, if applicable
1872 #my ($self, $arg) = @_;
1873 if ($_[0]->{convert}) {
1874 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1881 #my ($self, $col, @vals) = @_;
1882 # called often - tighten code
1883 return $_[0]->{bindtype} eq 'columns'
1884 ? map {[$_[1], $_]} @_[2 .. $#_]
1889 # Dies if any element of @bind is not in [colname => value] format
1890 # if bindtype is 'columns'.
1891 sub _assert_bindval_matches_bindtype {
1892 # my ($self, @bind) = @_;
1894 if ($self->{bindtype} eq 'columns') {
1896 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1897 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1903 sub _join_sql_clauses {
1904 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1906 if (@$clauses_aref > 1) {
1907 my $join = " " . $self->_sqlcase($logic) . " ";
1908 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1909 return ($sql, @$bind_aref);
1911 elsif (@$clauses_aref) {
1912 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1915 return (); # if no SQL, ignore @$bind_aref
1920 # Fix SQL case, if so requested
1922 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1923 # don't touch the argument ... crooked logic, but let's not change it!
1924 return $_[0]->{case} ? $_[1] : uc($_[1]);
1928 #======================================================================
1929 # DISPATCHING FROM REFKIND
1930 #======================================================================
1933 my ($self, $data) = @_;
1935 return 'UNDEF' unless defined $data;
1937 # blessed objects are treated like scalars
1938 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1940 return 'SCALAR' unless $ref;
1943 while ($ref eq 'REF') {
1945 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1949 return ($ref||'SCALAR') . ('REF' x $n_steps);
1953 my ($self, $data) = @_;
1954 my @try = ($self->_refkind($data));
1955 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1956 push @try, 'FALLBACK';
1960 sub _METHOD_FOR_refkind {
1961 my ($self, $meth_prefix, $data) = @_;
1964 for (@{$self->_try_refkind($data)}) {
1965 $method = $self->can($meth_prefix."_".$_)
1969 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1973 sub _SWITCH_refkind {
1974 my ($self, $data, $dispatch_table) = @_;
1977 for (@{$self->_try_refkind($data)}) {
1978 $coderef = $dispatch_table->{$_}
1982 puke "no dispatch entry for ".$self->_refkind($data)
1991 #======================================================================
1992 # VALUES, GENERATE, AUTOLOAD
1993 #======================================================================
1995 # LDNOTE: original code from nwiger, didn't touch code in that section
1996 # I feel the AUTOLOAD stuff should not be the default, it should
1997 # only be activated on explicit demand by user.
2001 my $data = shift || return;
2002 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
2003 unless ref $data eq 'HASH';
2006 foreach my $k (sort keys %$data) {
2007 my $v = $data->{$k};
2008 $self->_SWITCH_refkind($v, {
2010 if ($self->{array_datatypes}) { # array datatype
2011 push @all_bind, $self->_bindtype($k, $v);
2013 else { # literal SQL with bind
2014 my ($sql, @bind) = @$v;
2015 $self->_assert_bindval_matches_bindtype(@bind);
2016 push @all_bind, @bind;
2019 ARRAYREFREF => sub { # literal SQL with bind
2020 my ($sql, @bind) = @${$v};
2021 $self->_assert_bindval_matches_bindtype(@bind);
2022 push @all_bind, @bind;
2024 SCALARREF => sub { # literal SQL without bind
2026 SCALAR_or_UNDEF => sub {
2027 push @all_bind, $self->_bindtype($k, $v);
2038 my(@sql, @sqlq, @sqlv);
2042 if ($ref eq 'HASH') {
2043 for my $k (sort keys %$_) {
2046 my $label = $self->_quote($k);
2047 if ($r eq 'ARRAY') {
2048 # literal SQL with bind
2049 my ($sql, @bind) = @$v;
2050 $self->_assert_bindval_matches_bindtype(@bind);
2051 push @sqlq, "$label = $sql";
2053 } elsif ($r eq 'SCALAR') {
2054 # literal SQL without bind
2055 push @sqlq, "$label = $$v";
2057 push @sqlq, "$label = ?";
2058 push @sqlv, $self->_bindtype($k, $v);
2061 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
2062 } elsif ($ref eq 'ARRAY') {
2063 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
2066 if ($r eq 'ARRAY') { # literal SQL with bind
2067 my ($sql, @bind) = @$v;
2068 $self->_assert_bindval_matches_bindtype(@bind);
2071 } elsif ($r eq 'SCALAR') { # literal SQL without bind
2072 # embedded literal SQL
2079 push @sql, '(' . join(', ', @sqlq) . ')';
2080 } elsif ($ref eq 'SCALAR') {
2084 # strings get case twiddled
2085 push @sql, $self->_sqlcase($_);
2089 my $sql = join ' ', @sql;
2091 # this is pretty tricky
2092 # if ask for an array, return ($stmt, @bind)
2093 # otherwise, s/?/shift @sqlv/ to put it inline
2095 return ($sql, @sqlv);
2097 1 while $sql =~ s/\?/my $d = shift(@sqlv);
2098 ref $d ? $d->[1] : $d/e;
2107 # This allows us to check for a local, then _form, attr
2109 my($name) = $AUTOLOAD =~ /.*::(.+)/;
2110 return $self->generate($name, @_);
2121 SQL::Abstract - Generate SQL from Perl data structures
2127 my $sql = SQL::Abstract->new;
2129 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
2131 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
2133 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
2135 my($stmt, @bind) = $sql->delete($table, \%where);
2137 # Then, use these in your DBI statements
2138 my $sth = $dbh->prepare($stmt);
2139 $sth->execute(@bind);
2141 # Just generate the WHERE clause
2142 my($stmt, @bind) = $sql->where(\%where, $order);
2144 # Return values in the same order, for hashed queries
2145 # See PERFORMANCE section for more details
2146 my @bind = $sql->values(\%fieldvals);
2150 This module was inspired by the excellent L<DBIx::Abstract>.
2151 However, in using that module I found that what I really wanted
2152 to do was generate SQL, but still retain complete control over my
2153 statement handles and use the DBI interface. So, I set out to
2154 create an abstract SQL generation module.
2156 While based on the concepts used by L<DBIx::Abstract>, there are
2157 several important differences, especially when it comes to WHERE
2158 clauses. I have modified the concepts used to make the SQL easier
2159 to generate from Perl data structures and, IMO, more intuitive.
2160 The underlying idea is for this module to do what you mean, based
2161 on the data structures you provide it. The big advantage is that
2162 you don't have to modify your code every time your data changes,
2163 as this module figures it out.
2165 To begin with, an SQL INSERT is as easy as just specifying a hash
2166 of C<key=value> pairs:
2169 name => 'Jimbo Bobson',
2170 phone => '123-456-7890',
2171 address => '42 Sister Lane',
2172 city => 'St. Louis',
2173 state => 'Louisiana',
2176 The SQL can then be generated with this:
2178 my($stmt, @bind) = $sql->insert('people', \%data);
2180 Which would give you something like this:
2182 $stmt = "INSERT INTO people
2183 (address, city, name, phone, state)
2184 VALUES (?, ?, ?, ?, ?)";
2185 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
2186 '123-456-7890', 'Louisiana');
2188 These are then used directly in your DBI code:
2190 my $sth = $dbh->prepare($stmt);
2191 $sth->execute(@bind);
2193 =head2 Inserting and Updating Arrays
2195 If your database has array types (like for example Postgres),
2196 activate the special option C<< array_datatypes => 1 >>
2197 when creating the C<SQL::Abstract> object.
2198 Then you may use an arrayref to insert and update database array types:
2200 my $sql = SQL::Abstract->new(array_datatypes => 1);
2202 planets => [qw/Mercury Venus Earth Mars/]
2205 my($stmt, @bind) = $sql->insert('solar_system', \%data);
2209 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
2211 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
2214 =head2 Inserting and Updating SQL
2216 In order to apply SQL functions to elements of your C<%data> you may
2217 specify a reference to an arrayref for the given hash value. For example,
2218 if you need to execute the Oracle C<to_date> function on a value, you can
2219 say something like this:
2223 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
2226 The first value in the array is the actual SQL. Any other values are
2227 optional and would be included in the bind values array. This gives
2230 my($stmt, @bind) = $sql->insert('people', \%data);
2232 $stmt = "INSERT INTO people (name, date_entered)
2233 VALUES (?, to_date(?,'MM/DD/YYYY'))";
2234 @bind = ('Bill', '03/02/2003');
2236 An UPDATE is just as easy, all you change is the name of the function:
2238 my($stmt, @bind) = $sql->update('people', \%data);
2240 Notice that your C<%data> isn't touched; the module will generate
2241 the appropriately quirky SQL for you automatically. Usually you'll
2242 want to specify a WHERE clause for your UPDATE, though, which is
2243 where handling C<%where> hashes comes in handy...
2245 =head2 Complex where statements
2247 This module can generate pretty complicated WHERE statements
2248 easily. For example, simple C<key=value> pairs are taken to mean
2249 equality, and if you want to see if a field is within a set
2250 of values, you can use an arrayref. Let's say we wanted to
2251 SELECT some data based on this criteria:
2254 requestor => 'inna',
2255 worker => ['nwiger', 'rcwe', 'sfz'],
2256 status => { '!=', 'completed' }
2259 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
2261 The above would give you something like this:
2263 $stmt = "SELECT * FROM tickets WHERE
2264 ( requestor = ? ) AND ( status != ? )
2265 AND ( worker = ? OR worker = ? OR worker = ? )";
2266 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
2268 Which you could then use in DBI code like so:
2270 my $sth = $dbh->prepare($stmt);
2271 $sth->execute(@bind);
2277 The methods are simple. There's one for every major SQL operation,
2278 and a constructor you use first. The arguments are specified in a
2279 similar order for each method (table, then fields, then a where
2280 clause) to try and simplify things.
2282 =head2 new(option => 'value')
2284 The C<new()> function takes a list of options and values, and returns
2285 a new B<SQL::Abstract> object which can then be used to generate SQL
2286 through the methods below. The options accepted are:
2292 If set to 'lower', then SQL will be generated in all lowercase. By
2293 default SQL is generated in "textbook" case meaning something like:
2295 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
2297 Any setting other than 'lower' is ignored.
2301 This determines what the default comparison operator is. By default
2302 it is C<=>, meaning that a hash like this:
2304 %where = (name => 'nwiger', email => 'nate@wiger.org');
2306 Will generate SQL like this:
2308 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
2310 However, you may want loose comparisons by default, so if you set
2311 C<cmp> to C<like> you would get SQL such as:
2313 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
2315 You can also override the comparison on an individual basis - see
2316 the huge section on L</"WHERE CLAUSES"> at the bottom.
2318 =item sqltrue, sqlfalse
2320 Expressions for inserting boolean values within SQL statements.
2321 By default these are C<1=1> and C<1=0>. They are used
2322 by the special operators C<-in> and C<-not_in> for generating
2323 correct SQL even when the argument is an empty array (see below).
2327 This determines the default logical operator for multiple WHERE
2328 statements in arrays or hashes. If absent, the default logic is "or"
2329 for arrays, and "and" for hashes. This means that a WHERE
2333 event_date => {'>=', '2/13/99'},
2334 event_date => {'<=', '4/24/03'},
2337 will generate SQL like this:
2339 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
2341 This is probably not what you want given this query, though (look
2342 at the dates). To change the "OR" to an "AND", simply specify:
2344 my $sql = SQL::Abstract->new(logic => 'and');
2346 Which will change the above C<WHERE> to:
2348 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
2350 The logic can also be changed locally by inserting
2351 a modifier in front of an arrayref:
2353 @where = (-and => [event_date => {'>=', '2/13/99'},
2354 event_date => {'<=', '4/24/03'} ]);
2356 See the L</"WHERE CLAUSES"> section for explanations.
2360 This will automatically convert comparisons using the specified SQL
2361 function for both column and value. This is mostly used with an argument
2362 of C<upper> or C<lower>, so that the SQL will have the effect of
2363 case-insensitive "searches". For example, this:
2365 $sql = SQL::Abstract->new(convert => 'upper');
2366 %where = (keywords => 'MaKe iT CAse inSeNSItive');
2368 Will turn out the following SQL:
2370 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
2372 The conversion can be C<upper()>, C<lower()>, or any other SQL function
2373 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
2374 not validate this option; it will just pass through what you specify verbatim).
2378 This is a kludge because many databases suck. For example, you can't
2379 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
2380 Instead, you have to use C<bind_param()>:
2382 $sth->bind_param(1, 'reg data');
2383 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
2385 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
2386 which loses track of which field each slot refers to. Fear not.
2388 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
2389 Currently, you can specify either C<normal> (default) or C<columns>. If you
2390 specify C<columns>, you will get an array that looks like this:
2392 my $sql = SQL::Abstract->new(bindtype => 'columns');
2393 my($stmt, @bind) = $sql->insert(...);
2396 [ 'column1', 'value1' ],
2397 [ 'column2', 'value2' ],
2398 [ 'column3', 'value3' ],
2401 You can then iterate through this manually, using DBI's C<bind_param()>.
2403 $sth->prepare($stmt);
2406 my($col, $data) = @$_;
2407 if ($col eq 'details' || $col eq 'comments') {
2408 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
2409 } elsif ($col eq 'image') {
2410 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
2412 $sth->bind_param($i, $data);
2416 $sth->execute; # execute without @bind now
2418 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
2419 Basically, the advantage is still that you don't have to care which fields
2420 are or are not included. You could wrap that above C<for> loop in a simple
2421 sub called C<bind_fields()> or something and reuse it repeatedly. You still
2422 get a layer of abstraction over manual SQL specification.
2424 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
2425 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
2426 will expect the bind values in this format.
2430 This is the character that a table or column name will be quoted
2431 with. By default this is an empty string, but you could set it to
2432 the character C<`>, to generate SQL like this:
2434 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
2436 Alternatively, you can supply an array ref of two items, the first being the left
2437 hand quote character, and the second the right hand quote character. For
2438 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
2439 that generates SQL like this:
2441 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
2443 Quoting is useful if you have tables or columns names that are reserved
2444 words in your database's SQL dialect.
2448 This is the character that will be used to escape L</quote_char>s appearing
2449 in an identifier before it has been quoted.
2451 The parameter default in case of a single L</quote_char> character is the quote
2454 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
2455 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
2456 of the B<opening (left)> L</quote_char> within the identifier are currently left
2457 untouched. The default for opening-closing-style quotes may change in future
2458 versions, thus you are B<strongly encouraged> to specify the escape character
2463 This is the character that separates a table and column name. It is
2464 necessary to specify this when the C<quote_char> option is selected,
2465 so that tables and column names can be individually quoted like this:
2467 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
2469 =item injection_guard
2471 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
2472 column name specified in a query structure. This is a safety mechanism to avoid
2473 injection attacks when mishandling user input e.g.:
2475 my %condition_as_column_value_pairs = get_values_from_user();
2476 $sqla->select( ... , \%condition_as_column_value_pairs );
2478 If the expression matches an exception is thrown. Note that literal SQL
2479 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
2481 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
2483 =item array_datatypes
2485 When this option is true, arrayrefs in INSERT or UPDATE are
2486 interpreted as array datatypes and are passed directly
2488 When this option is false, arrayrefs are interpreted
2489 as literal SQL, just like refs to arrayrefs
2490 (but this behavior is for backwards compatibility; when writing
2491 new queries, use the "reference to arrayref" syntax
2497 Takes a reference to a list of "special operators"
2498 to extend the syntax understood by L<SQL::Abstract>.
2499 See section L</"SPECIAL OPERATORS"> for details.
2503 Takes a reference to a list of "unary operators"
2504 to extend the syntax understood by L<SQL::Abstract>.
2505 See section L</"UNARY OPERATORS"> for details.
2511 =head2 insert($table, \@values || \%fieldvals, \%options)
2513 This is the simplest function. You simply give it a table name
2514 and either an arrayref of values or hashref of field/value pairs.
2515 It returns an SQL INSERT statement and a list of bind values.
2516 See the sections on L</"Inserting and Updating Arrays"> and
2517 L</"Inserting and Updating SQL"> for information on how to insert
2518 with those data types.
2520 The optional C<\%options> hash reference may contain additional
2521 options to generate the insert SQL. Currently supported options
2528 Takes either a scalar of raw SQL fields, or an array reference of
2529 field names, and adds on an SQL C<RETURNING> statement at the end.
2530 This allows you to return data generated by the insert statement
2531 (such as row IDs) without performing another C<SELECT> statement.
2532 Note, however, this is not part of the SQL standard and may not
2533 be supported by all database engines.
2537 =head2 update($table, \%fieldvals, \%where, \%options)
2539 This takes a table, hashref of field/value pairs, and an optional
2540 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
2542 See the sections on L</"Inserting and Updating Arrays"> and
2543 L</"Inserting and Updating SQL"> for information on how to insert
2544 with those data types.
2546 The optional C<\%options> hash reference may contain additional
2547 options to generate the update SQL. Currently supported options
2554 See the C<returning> option to
2555 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2559 =head2 select($source, $fields, $where, $order)
2561 This returns a SQL SELECT statement and associated list of bind values, as
2562 specified by the arguments:
2568 Specification of the 'FROM' part of the statement.
2569 The argument can be either a plain scalar (interpreted as a table
2570 name, will be quoted), or an arrayref (interpreted as a list
2571 of table names, joined by commas, quoted), or a scalarref
2572 (literal SQL, not quoted).
2576 Specification of the list of fields to retrieve from
2578 The argument can be either an arrayref (interpreted as a list
2579 of field names, will be joined by commas and quoted), or a
2580 plain scalar (literal SQL, not quoted).
2581 Please observe that this API is not as flexible as that of
2582 the first argument C<$source>, for backwards compatibility reasons.
2586 Optional argument to specify the WHERE part of the query.
2587 The argument is most often a hashref, but can also be
2588 an arrayref or plain scalar --
2589 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2593 Optional argument to specify the ORDER BY part of the query.
2594 The argument can be a scalar, a hashref or an arrayref
2595 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2601 =head2 delete($table, \%where, \%options)
2603 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2604 It returns an SQL DELETE statement and list of bind values.
2606 The optional C<\%options> hash reference may contain additional
2607 options to generate the delete SQL. Currently supported options
2614 See the C<returning> option to
2615 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2619 =head2 where(\%where, $order)
2621 This is used to generate just the WHERE clause. For example,
2622 if you have an arbitrary data structure and know what the
2623 rest of your SQL is going to look like, but want an easy way
2624 to produce a WHERE clause, use this. It returns an SQL WHERE
2625 clause and list of bind values.
2628 =head2 values(\%data)
2630 This just returns the values from the hash C<%data>, in the same
2631 order that would be returned from any of the other above queries.
2632 Using this allows you to markedly speed up your queries if you
2633 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2635 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2637 Warning: This is an experimental method and subject to change.
2639 This returns arbitrarily generated SQL. It's a really basic shortcut.
2640 It will return two different things, depending on return context:
2642 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2643 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2645 These would return the following:
2647 # First calling form
2648 $stmt = "CREATE TABLE test (?, ?)";
2649 @bind = (field1, field2);
2651 # Second calling form
2652 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2654 Depending on what you're trying to do, it's up to you to choose the correct
2655 format. In this example, the second form is what you would want.
2659 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2663 ALTER SESSION SET nls_date_format = 'MM/YY'
2665 You get the idea. Strings get their case twiddled, but everything
2666 else remains verbatim.
2668 =head1 EXPORTABLE FUNCTIONS
2670 =head2 is_plain_value
2672 Determines if the supplied argument is a plain value as understood by this
2677 =item * The value is C<undef>
2679 =item * The value is a non-reference
2681 =item * The value is an object with stringification overloading
2683 =item * The value is of the form C<< { -value => $anything } >>
2687 On failure returns C<undef>, on success returns a B<scalar> reference
2688 to the original supplied argument.
2694 The stringification overloading detection is rather advanced: it takes
2695 into consideration not only the presence of a C<""> overload, but if that
2696 fails also checks for enabled
2697 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2698 on either C<0+> or C<bool>.
2700 Unfortunately testing in the field indicates that this
2701 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2702 but only when very large numbers of stringifying objects are involved.
2703 At the time of writing ( Sep 2014 ) there is no clear explanation of
2704 the direct cause, nor is there a manageably small test case that reliably
2705 reproduces the problem.
2707 If you encounter any of the following exceptions in B<random places within
2708 your application stack> - this module may be to blame:
2710 Operation "ne": no method found,
2711 left argument in overloaded package <something>,
2712 right argument in overloaded package <something>
2716 Stub found while resolving method "???" overloading """" in package <something>
2718 If you fall victim to the above - please attempt to reduce the problem
2719 to something that could be sent to the L<SQL::Abstract developers
2720 |DBIx::Class/GETTING HELP/SUPPORT>
2721 (either publicly or privately). As a workaround in the meantime you can
2722 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2723 value, which will most likely eliminate your problem (at the expense of
2724 not being able to properly detect exotic forms of stringification).
2726 This notice and environment variable will be removed in a future version,
2727 as soon as the underlying problem is found and a reliable workaround is
2732 =head2 is_literal_value
2734 Determines if the supplied argument is a literal value as understood by this
2739 =item * C<\$sql_string>
2741 =item * C<\[ $sql_string, @bind_values ]>
2745 On failure returns C<undef>, on success returns an B<array> reference
2746 containing the unpacked version of the supplied literal SQL and bind values.
2748 =head1 WHERE CLAUSES
2752 This module uses a variation on the idea from L<DBIx::Abstract>. It
2753 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2754 module is that things in arrays are OR'ed, and things in hashes
2757 The easiest way to explain is to show lots of examples. After
2758 each C<%where> hash shown, it is assumed you used:
2760 my($stmt, @bind) = $sql->where(\%where);
2762 However, note that the C<%where> hash can be used directly in any
2763 of the other functions as well, as described above.
2765 =head2 Key-value pairs
2767 So, let's get started. To begin, a simple hash:
2771 status => 'completed'
2774 Is converted to SQL C<key = val> statements:
2776 $stmt = "WHERE user = ? AND status = ?";
2777 @bind = ('nwiger', 'completed');
2779 One common thing I end up doing is having a list of values that
2780 a field can be in. To do this, simply specify a list inside of
2785 status => ['assigned', 'in-progress', 'pending'];
2788 This simple code will create the following:
2790 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2791 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2793 A field associated to an empty arrayref will be considered a
2794 logical false and will generate 0=1.
2796 =head2 Tests for NULL values
2798 If the value part is C<undef> then this is converted to SQL <IS NULL>
2807 $stmt = "WHERE user = ? AND status IS NULL";
2810 To test if a column IS NOT NULL:
2814 status => { '!=', undef },
2817 =head2 Specific comparison operators
2819 If you want to specify a different type of operator for your comparison,
2820 you can use a hashref for a given column:
2824 status => { '!=', 'completed' }
2827 Which would generate:
2829 $stmt = "WHERE user = ? AND status != ?";
2830 @bind = ('nwiger', 'completed');
2832 To test against multiple values, just enclose the values in an arrayref:
2834 status => { '=', ['assigned', 'in-progress', 'pending'] };
2836 Which would give you:
2838 "WHERE status = ? OR status = ? OR status = ?"
2841 The hashref can also contain multiple pairs, in which case it is expanded
2842 into an C<AND> of its elements:
2846 status => { '!=', 'completed', -not_like => 'pending%' }
2849 # Or more dynamically, like from a form
2850 $where{user} = 'nwiger';
2851 $where{status}{'!='} = 'completed';
2852 $where{status}{'-not_like'} = 'pending%';
2854 # Both generate this
2855 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2856 @bind = ('nwiger', 'completed', 'pending%');
2859 To get an OR instead, you can combine it with the arrayref idea:
2863 priority => [ { '=', 2 }, { '>', 5 } ]
2866 Which would generate:
2868 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2869 @bind = ('2', '5', 'nwiger');
2871 If you want to include literal SQL (with or without bind values), just use a
2872 scalar reference or reference to an arrayref as the value:
2875 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2876 date_expires => { '<' => \"now()" }
2879 Which would generate:
2881 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2882 @bind = ('11/26/2008');
2885 =head2 Logic and nesting operators
2887 In the example above,
2888 there is a subtle trap if you want to say something like
2889 this (notice the C<AND>):
2891 WHERE priority != ? AND priority != ?
2893 Because, in Perl you I<can't> do this:
2895 priority => { '!=' => 2, '!=' => 1 }
2897 As the second C<!=> key will obliterate the first. The solution
2898 is to use the special C<-modifier> form inside an arrayref:
2900 priority => [ -and => {'!=', 2},
2904 Normally, these would be joined by C<OR>, but the modifier tells it
2905 to use C<AND> instead. (Hint: You can use this in conjunction with the
2906 C<logic> option to C<new()> in order to change the way your queries
2907 work by default.) B<Important:> Note that the C<-modifier> goes
2908 B<INSIDE> the arrayref, as an extra first element. This will
2909 B<NOT> do what you think it might:
2911 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2913 Here is a quick list of equivalencies, since there is some overlap:
2916 status => {'!=', 'completed', 'not like', 'pending%' }
2917 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2920 status => {'=', ['assigned', 'in-progress']}
2921 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2922 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2926 =head2 Special operators: IN, BETWEEN, etc.
2928 You can also use the hashref format to compare a list of fields using the
2929 C<IN> comparison operator, by specifying the list as an arrayref:
2932 status => 'completed',
2933 reportid => { -in => [567, 2335, 2] }
2936 Which would generate:
2938 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2939 @bind = ('completed', '567', '2335', '2');
2941 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2944 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2945 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2946 'sqltrue' (by default: C<1=1>).
2948 In addition to the array you can supply a chunk of literal sql or
2949 literal sql with bind:
2952 customer => { -in => \[
2953 'SELECT cust_id FROM cust WHERE balance > ?',
2956 status => { -in => \'SELECT status_codes FROM states' },
2962 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2963 AND status IN ( SELECT status_codes FROM states )
2967 Finally, if the argument to C<-in> is not a reference, it will be
2968 treated as a single-element array.
2970 Another pair of operators is C<-between> and C<-not_between>,
2971 used with an arrayref of two values:
2975 completion_date => {
2976 -not_between => ['2002-10-01', '2003-02-06']
2982 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2984 Just like with C<-in> all plausible combinations of literal SQL
2988 start0 => { -between => [ 1, 2 ] },
2989 start1 => { -between => \["? AND ?", 1, 2] },
2990 start2 => { -between => \"lower(x) AND upper(y)" },
2991 start3 => { -between => [
2993 \["upper(?)", 'stuff' ],
3000 ( start0 BETWEEN ? AND ? )
3001 AND ( start1 BETWEEN ? AND ? )
3002 AND ( start2 BETWEEN lower(x) AND upper(y) )
3003 AND ( start3 BETWEEN lower(x) AND upper(?) )
3005 @bind = (1, 2, 1, 2, 'stuff');
3008 These are the two builtin "special operators"; but the
3009 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
3011 =head2 Unary operators: bool
3013 If you wish to test against boolean columns or functions within your
3014 database you can use the C<-bool> and C<-not_bool> operators. For
3015 example to test the column C<is_user> being true and the column
3016 C<is_enabled> being false you would use:-
3020 -not_bool => 'is_enabled',
3025 WHERE is_user AND NOT is_enabled
3027 If a more complex combination is required, testing more conditions,
3028 then you should use the and/or operators:-
3033 -not_bool => { two=> { -rlike => 'bar' } },
3034 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
3045 (NOT ( three = ? OR three > ? ))
3048 =head2 Nested conditions, -and/-or prefixes
3050 So far, we've seen how multiple conditions are joined with a top-level
3051 C<AND>. We can change this by putting the different conditions we want in
3052 hashes and then putting those hashes in an array. For example:
3057 status => { -like => ['pending%', 'dispatched'] },
3061 status => 'unassigned',
3065 This data structure would create the following:
3067 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
3068 OR ( user = ? AND status = ? ) )";
3069 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
3072 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
3073 to change the logic inside:
3079 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
3080 -or => { workhrs => {'<', 50}, geo => 'EURO' },
3087 $stmt = "WHERE ( user = ?
3088 AND ( ( workhrs > ? AND geo = ? )
3089 OR ( workhrs < ? OR geo = ? ) ) )";
3090 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
3092 =head3 Algebraic inconsistency, for historical reasons
3094 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
3095 operator goes C<outside> of the nested structure; whereas when connecting
3096 several constraints on one column, the C<-and> operator goes
3097 C<inside> the arrayref. Here is an example combining both features:
3100 -and => [a => 1, b => 2],
3101 -or => [c => 3, d => 4],
3102 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
3107 WHERE ( ( ( a = ? AND b = ? )
3108 OR ( c = ? OR d = ? )
3109 OR ( e LIKE ? AND e LIKE ? ) ) )
3111 This difference in syntax is unfortunate but must be preserved for
3112 historical reasons. So be careful: the two examples below would
3113 seem algebraically equivalent, but they are not
3116 { -like => 'foo%' },
3117 { -like => '%bar' },
3119 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
3122 { col => { -like => 'foo%' } },
3123 { col => { -like => '%bar' } },
3125 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
3128 =head2 Literal SQL and value type operators
3130 The basic premise of SQL::Abstract is that in WHERE specifications the "left
3131 side" is a column name and the "right side" is a value (normally rendered as
3132 a placeholder). This holds true for both hashrefs and arrayref pairs as you
3133 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
3134 alter this behavior. There are several ways of doing so.
3138 This is a virtual operator that signals the string to its right side is an
3139 identifier (a column name) and not a value. For example to compare two
3140 columns you would write:
3143 priority => { '<', 2 },
3144 requestor => { -ident => 'submitter' },
3149 $stmt = "WHERE priority < ? AND requestor = submitter";
3152 If you are maintaining legacy code you may see a different construct as
3153 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
3158 This is a virtual operator that signals that the construct to its right side
3159 is a value to be passed to DBI. This is for example necessary when you want
3160 to write a where clause against an array (for RDBMS that support such
3161 datatypes). For example:
3164 array => { -value => [1, 2, 3] }
3169 $stmt = 'WHERE array = ?';
3170 @bind = ([1, 2, 3]);
3172 Note that if you were to simply say:
3178 the result would probably not be what you wanted:
3180 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
3185 Finally, sometimes only literal SQL will do. To include a random snippet
3186 of SQL verbatim, you specify it as a scalar reference. Consider this only
3187 as a last resort. Usually there is a better way. For example:
3190 priority => { '<', 2 },
3191 requestor => { -in => \'(SELECT name FROM hitmen)' },
3196 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
3199 Note that in this example, you only get one bind parameter back, since
3200 the verbatim SQL is passed as part of the statement.
3204 Never use untrusted input as a literal SQL argument - this is a massive
3205 security risk (there is no way to check literal snippets for SQL
3206 injections and other nastyness). If you need to deal with untrusted input
3207 use literal SQL with placeholders as described next.
3209 =head3 Literal SQL with placeholders and bind values (subqueries)
3211 If the literal SQL to be inserted has placeholders and bind values,
3212 use a reference to an arrayref (yes this is a double reference --
3213 not so common, but perfectly legal Perl). For example, to find a date
3214 in Postgres you can use something like this:
3217 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
3222 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
3225 Note that you must pass the bind values in the same format as they are returned
3226 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
3227 to C<columns>, you must provide the bind values in the
3228 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
3229 scalar value; most commonly the column name, but you can use any scalar value
3230 (including references and blessed references), L<SQL::Abstract> will simply
3231 pass it through intact. So if C<bindtype> is set to C<columns> the above
3232 example will look like:
3235 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
3238 Literal SQL is especially useful for nesting parenthesized clauses in the
3239 main SQL query. Here is a first example:
3241 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
3245 bar => \["IN ($sub_stmt)" => @sub_bind],
3250 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
3251 WHERE c2 < ? AND c3 LIKE ?))";
3252 @bind = (1234, 100, "foo%");
3254 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
3255 are expressed in the same way. Of course the C<$sub_stmt> and
3256 its associated bind values can be generated through a former call
3259 my ($sub_stmt, @sub_bind)
3260 = $sql->select("t1", "c1", {c2 => {"<" => 100},
3261 c3 => {-like => "foo%"}});
3264 bar => \["> ALL ($sub_stmt)" => @sub_bind],
3267 In the examples above, the subquery was used as an operator on a column;
3268 but the same principle also applies for a clause within the main C<%where>
3269 hash, like an EXISTS subquery:
3271 my ($sub_stmt, @sub_bind)
3272 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
3273 my %where = ( -and => [
3275 \["EXISTS ($sub_stmt)" => @sub_bind],
3280 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
3281 WHERE c1 = ? AND c2 > t0.c0))";
3285 Observe that the condition on C<c2> in the subquery refers to
3286 column C<t0.c0> of the main query: this is I<not> a bind
3287 value, so we have to express it through a scalar ref.
3288 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
3289 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
3290 what we wanted here.
3292 Finally, here is an example where a subquery is used
3293 for expressing unary negation:
3295 my ($sub_stmt, @sub_bind)
3296 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
3297 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
3299 lname => {like => '%son%'},
3300 \["NOT ($sub_stmt)" => @sub_bind],
3305 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
3306 @bind = ('%son%', 10, 20)
3308 =head3 Deprecated usage of Literal SQL
3310 Below are some examples of archaic use of literal SQL. It is shown only as
3311 reference for those who deal with legacy code. Each example has a much
3312 better, cleaner and safer alternative that users should opt for in new code.
3318 my %where = ( requestor => \'IS NOT NULL' )
3320 $stmt = "WHERE requestor IS NOT NULL"
3322 This used to be the way of generating NULL comparisons, before the handling
3323 of C<undef> got formalized. For new code please use the superior syntax as
3324 described in L</Tests for NULL values>.
3328 my %where = ( requestor => \'= submitter' )
3330 $stmt = "WHERE requestor = submitter"
3332 This used to be the only way to compare columns. Use the superior L</-ident>
3333 method for all new code. For example an identifier declared in such a way
3334 will be properly quoted if L</quote_char> is properly set, while the legacy
3335 form will remain as supplied.
3339 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
3341 $stmt = "WHERE completed > ? AND is_ready"
3342 @bind = ('2012-12-21')
3344 Using an empty string literal used to be the only way to express a boolean.
3345 For all new code please use the much more readable
3346 L<-bool|/Unary operators: bool> operator.
3352 These pages could go on for a while, since the nesting of the data
3353 structures this module can handle are pretty much unlimited (the
3354 module implements the C<WHERE> expansion as a recursive function
3355 internally). Your best bet is to "play around" with the module a
3356 little to see how the data structures behave, and choose the best
3357 format for your data based on that.
3359 And of course, all the values above will probably be replaced with
3360 variables gotten from forms or the command line. After all, if you
3361 knew everything ahead of time, you wouldn't have to worry about
3362 dynamically-generating SQL and could just hardwire it into your
3365 =head1 ORDER BY CLAUSES
3367 Some functions take an order by clause. This can either be a scalar (just a
3368 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
3369 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
3372 Given | Will Generate
3373 ---------------------------------------------------------------
3375 'colA' | ORDER BY colA
3377 [qw/colA colB/] | ORDER BY colA, colB
3379 {-asc => 'colA'} | ORDER BY colA ASC
3381 {-desc => 'colB'} | ORDER BY colB DESC
3383 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
3385 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
3387 \'colA DESC' | ORDER BY colA DESC
3389 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
3390 | /* ...with $x bound to ? */
3393 { -asc => 'colA' }, | colA ASC,
3394 { -desc => [qw/colB/] }, | colB DESC,
3395 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
3396 \'colE DESC', | colE DESC,
3397 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
3398 ] | /* ...with $x bound to ? */
3399 ===============================================================
3403 =head1 SPECIAL OPERATORS
3405 my $sqlmaker = SQL::Abstract->new(special_ops => [
3409 my ($self, $field, $op, $arg) = @_;
3415 handler => 'method_name',
3419 A "special operator" is a SQL syntactic clause that can be
3420 applied to a field, instead of a usual binary operator.
3423 WHERE field IN (?, ?, ?)
3424 WHERE field BETWEEN ? AND ?
3425 WHERE MATCH(field) AGAINST (?, ?)
3427 Special operators IN and BETWEEN are fairly standard and therefore
3428 are builtin within C<SQL::Abstract> (as the overridable methods
3429 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
3430 like the MATCH .. AGAINST example above which is specific to MySQL,
3431 you can write your own operator handlers - supply a C<special_ops>
3432 argument to the C<new> method. That argument takes an arrayref of
3433 operator definitions; each operator definition is a hashref with two
3440 the regular expression to match the operator
3444 Either a coderef or a plain scalar method name. In both cases
3445 the expected return is C<< ($sql, @bind) >>.
3447 When supplied with a method name, it is simply called on the
3448 L<SQL::Abstract> object as:
3450 $self->$method_name($field, $op, $arg)
3454 $field is the LHS of the operator
3455 $op is the part that matched the handler regex
3458 When supplied with a coderef, it is called as:
3460 $coderef->($self, $field, $op, $arg)
3465 For example, here is an implementation
3466 of the MATCH .. AGAINST syntax for MySQL
3468 my $sqlmaker = SQL::Abstract->new(special_ops => [
3470 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
3471 {regex => qr/^match$/i,
3473 my ($self, $field, $op, $arg) = @_;
3474 $arg = [$arg] if not ref $arg;
3475 my $label = $self->_quote($field);
3476 my ($placeholder) = $self->_convert('?');
3477 my $placeholders = join ", ", (($placeholder) x @$arg);
3478 my $sql = $self->_sqlcase('match') . " ($label) "
3479 . $self->_sqlcase('against') . " ($placeholders) ";
3480 my @bind = $self->_bindtype($field, @$arg);
3481 return ($sql, @bind);
3488 =head1 UNARY OPERATORS
3490 my $sqlmaker = SQL::Abstract->new(unary_ops => [
3494 my ($self, $op, $arg) = @_;
3500 handler => 'method_name',
3504 A "unary operator" is a SQL syntactic clause that can be
3505 applied to a field - the operator goes before the field
3507 You can write your own operator handlers - supply a C<unary_ops>
3508 argument to the C<new> method. That argument takes an arrayref of
3509 operator definitions; each operator definition is a hashref with two
3516 the regular expression to match the operator
3520 Either a coderef or a plain scalar method name. In both cases
3521 the expected return is C<< $sql >>.
3523 When supplied with a method name, it is simply called on the
3524 L<SQL::Abstract> object as:
3526 $self->$method_name($op, $arg)
3530 $op is the part that matched the handler regex
3531 $arg is the RHS or argument of the operator
3533 When supplied with a coderef, it is called as:
3535 $coderef->($self, $op, $arg)
3543 Thanks to some benchmarking by Mark Stosberg, it turns out that
3544 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
3545 I must admit this wasn't an intentional design issue, but it's a
3546 byproduct of the fact that you get to control your C<DBI> handles
3549 To maximize performance, use a code snippet like the following:
3551 # prepare a statement handle using the first row
3552 # and then reuse it for the rest of the rows
3554 for my $href (@array_of_hashrefs) {
3555 $stmt ||= $sql->insert('table', $href);
3556 $sth ||= $dbh->prepare($stmt);
3557 $sth->execute($sql->values($href));
3560 The reason this works is because the keys in your C<$href> are sorted
3561 internally by B<SQL::Abstract>. Thus, as long as your data retains
3562 the same structure, you only have to generate the SQL the first time
3563 around. On subsequent queries, simply use the C<values> function provided
3564 by this module to return your values in the correct order.
3566 However this depends on the values having the same type - if, for
3567 example, the values of a where clause may either have values
3568 (resulting in sql of the form C<column = ?> with a single bind
3569 value), or alternatively the values might be C<undef> (resulting in
3570 sql of the form C<column IS NULL> with no bind value) then the
3571 caching technique suggested will not work.
3575 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
3576 really like this part (I do, at least). Building up a complex query
3577 can be as simple as the following:
3584 use CGI::FormBuilder;
3587 my $form = CGI::FormBuilder->new(...);
3588 my $sql = SQL::Abstract->new;
3590 if ($form->submitted) {
3591 my $field = $form->field;
3592 my $id = delete $field->{id};
3593 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
3596 Of course, you would still have to connect using C<DBI> to run the
3597 query, but the point is that if you make your form look like your
3598 table, the actual query script can be extremely simplistic.
3600 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
3601 a fast interface to returning and formatting data. I frequently
3602 use these three modules together to write complex database query
3603 apps in under 50 lines.
3605 =head1 HOW TO CONTRIBUTE
3607 Contributions are always welcome, in all usable forms (we especially
3608 welcome documentation improvements). The delivery methods include git-
3609 or unified-diff formatted patches, GitHub pull requests, or plain bug
3610 reports either via RT or the Mailing list. Contributors are generally
3611 granted full access to the official repository after their first several
3612 patches pass successful review.
3614 This project is maintained in a git repository. The code and related tools are
3615 accessible at the following locations:
3619 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3621 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3623 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
3625 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
3631 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3632 Great care has been taken to preserve the I<published> behavior
3633 documented in previous versions in the 1.* family; however,
3634 some features that were previously undocumented, or behaved
3635 differently from the documentation, had to be changed in order
3636 to clarify the semantics. Hence, client code that was relying
3637 on some dark areas of C<SQL::Abstract> v1.*
3638 B<might behave differently> in v1.50.
3640 The main changes are:
3646 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
3650 support for the { operator => \"..." } construct (to embed literal SQL)
3654 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3658 optional support for L<array datatypes|/"Inserting and Updating Arrays">
3662 defensive programming: check arguments
3666 fixed bug with global logic, which was previously implemented
3667 through global variables yielding side-effects. Prior versions would
3668 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3669 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3670 Now this is interpreted
3671 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3676 fixed semantics of _bindtype on array args
3680 dropped the C<_anoncopy> of the %where tree. No longer necessary,
3681 we just avoid shifting arrays within that tree.
3685 dropped the C<_modlogic> function
3689 =head1 ACKNOWLEDGEMENTS
3691 There are a number of individuals that have really helped out with
3692 this module. Unfortunately, most of them submitted bugs via CPAN
3693 so I have no idea who they are! But the people I do know are:
3695 Ash Berlin (order_by hash term support)
3696 Matt Trout (DBIx::Class support)
3697 Mark Stosberg (benchmarking)
3698 Chas Owens (initial "IN" operator support)
3699 Philip Collins (per-field SQL functions)
3700 Eric Kolve (hashref "AND" support)
3701 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3702 Dan Kubb (support for "quote_char" and "name_sep")
3703 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
3704 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
3705 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
3706 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
3707 Oliver Charles (support for "RETURNING" after "INSERT")
3713 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3717 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3719 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3721 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3722 While not an official support venue, C<DBIx::Class> makes heavy use of
3723 C<SQL::Abstract>, and as such list members there are very familiar with
3724 how to create queries.
3728 This module is free software; you may copy this under the same
3729 terms as perl itself (either the GNU General Public License or
3730 the Artistic License)