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.86';
32 # This would confuse some packagers
33 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
37 # special operators (-in, -between). May be extended/overridden by user.
38 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
39 my @BUILTIN_SPECIAL_OPS = (
40 {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }},
41 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
42 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
45 #======================================================================
46 # DEBUGGING AND ERROR REPORTING
47 #======================================================================
50 return unless $_[0]->{debug}; shift; # a little faster
51 my $func = (caller(1))[3];
52 warn "[$func] ", @_, "\n";
56 my($func) = (caller(1))[3];
57 Carp::carp "[$func] Warning: ", @_;
61 my($func) = (caller(1))[3];
62 Carp::croak "[$func] Fatal: ", @_;
65 sub is_literal_value ($) {
66 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
67 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
71 # FIXME XSify - this can be done so much more efficiently
72 sub is_plain_value ($) {
74 ! length ref $_[0] ? \($_[0])
76 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
78 exists $_[0]->{-value}
79 ) ? \($_[0]->{-value})
81 # reuse @_ for even moar speedz
82 defined ( $_[1] = Scalar::Util::blessed $_[0] )
84 # deliberately not using Devel::OverloadInfo - the checks we are
85 # intersted in are much more limited than the fullblown thing, and
86 # this is a very hot piece of code
88 # simply using ->can('(""') can leave behind stub methods that
89 # break actually using the overload later (see L<perldiag/Stub
90 # found while resolving method "%s" overloading "%s" in package
91 # "%s"> and the source of overload::mycan())
93 # either has stringification which DBI SHOULD prefer out of the box
94 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
96 # has nummification or boolification, AND fallback is *not* disabled
98 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
101 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
103 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
107 # no fallback specified at all
108 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
110 # fallback explicitly undef
111 ! defined ${"$_[3]::()"}
124 #======================================================================
126 #======================================================================
130 my $class = ref($self) || $self;
131 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
133 # choose our case by keeping an option around
134 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
136 # default logic for interpreting arrayrefs
137 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
139 # how to return bind vars
140 $opt{bindtype} ||= 'normal';
142 # default comparison is "=", but can be overridden
145 # try to recognize which are the 'equality' and 'inequality' ops
146 # (temporary quickfix (in 2007), should go through a more seasoned API)
147 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
148 $opt{inequality_op} = qr/^( != | <> )$/ix;
150 $opt{like_op} = qr/^ (is\s+)? r?like $/xi;
151 $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
154 $opt{sqltrue} ||= '1=1';
155 $opt{sqlfalse} ||= '0=1';
158 $opt{user_special_ops} = [ @{$opt{special_ops} ||= []} ];
159 # regexes are applied in order, thus push after user-defines
160 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
163 $opt{unary_ops} ||= [];
165 # rudimentary sanity-check for user supplied bits treated as functions/operators
166 # If a purported function matches this regular expression, an exception is thrown.
167 # Literal SQL is *NOT* subject to this check, only functions (and column names
168 # when quoting is not in effect)
171 # need to guard against ()'s in column names too, but this will break tons of
172 # hacks... ideas anyone?
173 $opt{injection_guard} ||= qr/
179 $opt{node_types} = +{
180 map +("-$_" => '_render_'.$_),
181 qw(op func value bind ident literal)
184 $opt{expand_unary} = {};
186 return bless \%opt, $class;
189 sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
190 sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
192 sub _assert_pass_injection_guard {
193 if ($_[1] =~ $_[0]->{injection_guard}) {
194 my $class = ref $_[0];
195 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
196 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
197 . "{injection_guard} attribute to ${class}->new()"
202 #======================================================================
204 #======================================================================
208 my $table = $self->_table(shift);
209 my $data = shift || return;
212 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
213 my ($sql, @bind) = $self->$method($data);
214 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
216 if ($options->{returning}) {
217 my ($s, @b) = $self->_insert_returning($options);
222 return wantarray ? ($sql, @bind) : $sql;
225 # So that subclasses can override INSERT ... RETURNING separately from
226 # UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
227 sub _insert_returning { shift->_returning(@_) }
230 my ($self, $options) = @_;
232 my $f = $options->{returning};
234 my ($sql, @bind) = $self->_render_expr(
235 $self->_expand_maybe_list_expr($f, undef, -ident)
238 ? $self->_sqlcase(' returning ') . $sql
239 : ($self->_sqlcase(' returning ').$sql, @bind);
242 sub _insert_HASHREF { # explicit list of fields and then values
243 my ($self, $data) = @_;
245 my @fields = sort keys %$data;
247 my ($sql, @bind) = $self->_insert_values($data);
250 $_ = $self->_quote($_) foreach @fields;
251 $sql = "( ".join(", ", @fields).") ".$sql;
253 return ($sql, @bind);
256 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
257 my ($self, $data) = @_;
259 # no names (arrayref) so can't generate bindtype
260 $self->{bindtype} ne 'columns'
261 or belch "can't do 'columns' bindtype when called with arrayref";
263 my (@values, @all_bind);
264 foreach my $value (@$data) {
265 my ($values, @bind) = $self->_insert_value(undef, $value);
266 push @values, $values;
267 push @all_bind, @bind;
269 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
270 return ($sql, @all_bind);
273 sub _insert_ARRAYREFREF { # literal SQL with bind
274 my ($self, $data) = @_;
276 my ($sql, @bind) = @${$data};
277 $self->_assert_bindval_matches_bindtype(@bind);
279 return ($sql, @bind);
283 sub _insert_SCALARREF { # literal SQL without bind
284 my ($self, $data) = @_;
290 my ($self, $data) = @_;
292 my (@values, @all_bind);
293 foreach my $column (sort keys %$data) {
294 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
295 push @values, $values;
296 push @all_bind, @bind;
298 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
299 return ($sql, @all_bind);
303 my ($self, $column, $v) = @_;
305 return $self->_render_expr(
306 $self->_expand_insert_value($column, $v)
310 sub _expand_insert_value {
311 my ($self, $column, $v) = @_;
313 if (ref($v) eq 'ARRAY') {
314 if ($self->{array_datatypes}) {
315 return +{ -bind => [ $column, $v ] };
317 my ($sql, @bind) = @$v;
318 $self->_assert_bindval_matches_bindtype(@bind);
319 return +{ -literal => $v };
321 if (ref($v) eq 'HASH') {
322 if (grep !/^-/, keys %$v) {
323 belch "HASH ref as bind value in insert is not supported";
324 return +{ -bind => [ $column, $v ] };
328 return +{ -bind => [ $column, undef ] };
330 local our $Cur_Col_Meta = $column;
331 return $self->_expand_expr($v);
336 #======================================================================
338 #======================================================================
343 my $table = $self->_table(shift);
344 my $data = shift || return;
348 # first build the 'SET' part of the sql statement
349 puke "Unsupported data type specified to \$sql->update"
350 unless ref $data eq 'HASH';
352 my ($sql, @all_bind) = $self->_update_set_values($data);
353 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
357 my($where_sql, @where_bind) = $self->where($where);
359 push @all_bind, @where_bind;
362 if ($options->{returning}) {
363 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
364 $sql .= $returning_sql;
365 push @all_bind, @returning_bind;
368 return wantarray ? ($sql, @all_bind) : $sql;
371 sub _update_set_values {
372 my ($self, $data) = @_;
374 return $self->_render_expr(
375 $self->_expand_update_set_values($data),
379 sub _expand_update_set_values {
380 my ($self, $data) = @_;
381 $self->_expand_maybe_list_expr( [
384 +{ -op => [ '=', { -ident => $k }, $set ] };
390 ? ($self->{array_datatypes}
391 ? [ $k, +{ -bind => [ $k, $v ] } ]
392 : [ $k, +{ -literal => $v } ])
394 local our $Cur_Col_Meta = $k;
395 [ $k, $self->_expand_expr($v) ]
402 # So that subclasses can override UPDATE ... RETURNING separately from
404 sub _update_returning { shift->_returning(@_) }
408 #======================================================================
410 #======================================================================
415 my $table = $self->_table(shift);
416 my $fields = shift || '*';
420 my ($fields_sql, @bind) = $self->_select_fields($fields);
422 my ($where_sql, @where_bind) = $self->where($where, $order);
423 push @bind, @where_bind;
425 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
426 $self->_sqlcase('from'), $table)
429 return wantarray ? ($sql, @bind) : $sql;
433 my ($self, $fields) = @_;
434 return $self->_render_expr(
435 $self->_expand_maybe_list_expr($fields, undef, '-ident')
439 #======================================================================
441 #======================================================================
446 my $table = $self->_table(shift);
450 my($where_sql, @bind) = $self->where($where);
451 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
453 if ($options->{returning}) {
454 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
455 $sql .= $returning_sql;
456 push @bind, @returning_bind;
459 return wantarray ? ($sql, @bind) : $sql;
462 # So that subclasses can override DELETE ... RETURNING separately from
464 sub _delete_returning { shift->_returning(@_) }
468 #======================================================================
470 #======================================================================
474 # Finally, a separate routine just to handle WHERE clauses
476 my ($self, $where, $order) = @_;
478 local $self->{convert_where} = $self->{convert};
481 my ($sql, @bind) = defined($where)
482 ? $self->_recurse_where($where)
484 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
488 my ($order_sql, @order_bind) = $self->_order_by($order);
490 push @bind, @order_bind;
493 return wantarray ? ($sql, @bind) : $sql;
497 my ($self, $expr, $logic, $default_scalar_to) = @_;
498 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
499 return undef unless defined($expr);
500 if (ref($expr) eq 'HASH') {
501 if (keys %$expr > 1) {
505 map $self->_expand_expr_hashpair($_ => $expr->{$_}, $logic),
509 return unless %$expr;
510 return $self->_expand_expr_hashpair(%$expr, $logic);
512 if (ref($expr) eq 'ARRAY') {
513 my $logic = lc($logic || $self->{logic});
514 $logic eq 'and' or $logic eq 'or' or puke "unknown logic: $logic";
520 while (my ($el) = splice @expr, 0, 1) {
521 puke "Supplying an empty left hand side argument is not supported in array-pairs"
522 unless defined($el) and length($el);
523 my $elref = ref($el);
525 push(@res, $self->_expand_expr({ $el, shift(@expr) }));
526 } elsif ($elref eq 'ARRAY') {
527 push(@res, $self->_expand_expr($el)) if @$el;
528 } elsif (my $l = is_literal_value($el)) {
529 push @res, { -literal => $l };
530 } elsif ($elref eq 'HASH') {
531 push @res, $self->_expand_expr($el);
536 return { -op => [ $logic, @res ] };
538 if (my $literal = is_literal_value($expr)) {
539 return +{ -literal => $literal };
541 if (!ref($expr) or Scalar::Util::blessed($expr)) {
542 if (my $d = $Default_Scalar_To) {
543 return +{ $d => $expr };
545 if (my $m = our $Cur_Col_Meta) {
546 return +{ -bind => [ $m, $expr ] };
548 return +{ -value => $expr };
553 sub _expand_expr_hashpair {
554 my ($self, $k, $v, $logic) = @_;
555 unless (defined($k) and length($k)) {
556 if (defined($k) and my $literal = is_literal_value($v)) {
557 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
558 return { -literal => $literal };
560 puke "Supplying an empty left hand side argument is not supported";
563 $self->_assert_pass_injection_guard($k =~ /^-(.*)$/s);
564 if ($k =~ s/ [_\s]? \d+ $//x ) {
565 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
566 . "You probably wanted ...-and => [ $k => COND1, $k => COND2 ... ]";
569 return $self->_expand_expr($v);
573 return $self->_expand_expr($v);
575 puke "-bool => undef not supported" unless defined($v);
576 return { -ident => $v };
579 return { -op => [ 'not', $self->_expand_expr($v) ] };
581 if (my ($rest) = $k =~/^-not[_ ](.*)$/) {
584 $self->_expand_expr_hashpair("-${rest}", $v, $logic)
587 if (my ($logic) = $k =~ /^-(and|or)$/i) {
588 if (ref($v) eq 'HASH') {
589 return $self->_expand_expr($v, $logic);
591 if (ref($v) eq 'ARRAY') {
592 return $self->_expand_expr($v, $logic);
597 $op =~ s/^-// if length($op) > 1;
599 # top level special ops are illegal in general
600 puke "Illegal use of top-level '-$op'"
601 if List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
603 if ($k eq '-value' and my $m = our $Cur_Col_Meta) {
604 return +{ -bind => [ $m, $v ] };
606 if (my $custom = $self->{expand_unary}{$k}) {
607 return $self->$custom($v);
609 if ($self->{node_types}{$k}) {
615 and (keys %$v)[0] =~ /^-/
617 my ($func) = $k =~ /^-(.*)$/;
618 return +{ -func => [ $func, $self->_expand_expr($v) ] };
620 if (!ref($v) or is_literal_value($v)) {
621 return +{ -op => [ $k =~ /^-(.*)$/, $self->_expand_expr($v) ] };
628 and exists $v->{-value}
629 and not defined $v->{-value}
632 return $self->_expand_expr_hashpair($k => { $self->{cmp} => undef });
634 if (!ref($v) or Scalar::Util::blessed($v)) {
635 my $d = our $Default_Scalar_To;
640 ($d ? { $d => $v } : { -bind => [ $k, $v ] })
644 if (ref($v) eq 'HASH') {
648 map $self->_expand_expr_hashpair($k => { $_ => $v->{$_} }),
655 $self->_assert_pass_injection_guard($vk);
656 if ($vk =~ s/ [_\s]? \d+ $//x ) {
657 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
658 . "You probably wanted ...-and => [ -$vk => COND1, -$vk => COND2 ... ]";
660 if ($vk =~ /^(?:not[ _])?between$/) {
661 local our $Cur_Col_Meta = $k;
662 my @rhs = map $self->_expand_expr($_),
663 ref($vv) eq 'ARRAY' ? @$vv : $vv;
665 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
667 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
669 puke "Operator '${\uc($vk)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
672 join(' ', split '_', $vk),
677 if ($vk =~ /^(?:not[ _])?in$/) {
678 if (my $literal = is_literal_value($vv)) {
679 my ($sql, @bind) = @$literal;
680 my $opened_sql = $self->_open_outer_paren($sql);
682 $vk, { -ident => $k },
683 [ { -literal => [ $opened_sql, @bind ] } ]
687 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
688 . "-${\uc($vk)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
689 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
690 . 'will emit the logically correct SQL instead of raising this exception)'
692 puke("Argument passed to the '${\uc($vk)}' operator can not be undefined")
694 my @rhs = map $self->_expand_expr($_),
695 map { ref($_) ? $_ : { -bind => [ $k, $_ ] } }
696 map { defined($_) ? $_: puke($undef_err) }
697 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
698 return $self->${\($vk =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
701 join(' ', split '_', $vk),
706 if ($vk eq 'ident') {
707 if (! defined $vv or (ref($vv) and ref($vv) eq 'ARRAY')) {
708 puke "-$vk requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
716 if ($vk eq 'value') {
717 return $self->_expand_expr_hashpair($k, undef) unless defined($vv);
721 { -bind => [ $k, $vv ] }
724 if ($vk =~ /^is(?:[ _]not)?$/) {
725 puke "$vk can only take undef as argument"
729 and exists($vv->{-value})
730 and !defined($vv->{-value})
733 return +{ -op => [ $vk.' null', { -ident => $k } ] };
735 if ($vk =~ /^(and|or)$/) {
736 if (ref($vv) eq 'HASH') {
739 map $self->_expand_expr_hashpair($k, { $_ => $vv->{$_} }),
744 if (my $us = List::Util::first { $vk =~ $_->{regex} } @{$self->{user_special_ops}}) {
745 return { -op => [ $vk, { -ident => $k }, $vv ] };
747 if (ref($vv) eq 'ARRAY') {
748 my ($logic, @values) = (
749 (defined($vv->[0]) and $vv->[0] =~ /^-(and|or)$/i)
754 $vk =~ $self->{inequality_op}
755 or join(' ', split '_', $vk) =~ $self->{not_like_op}
757 if (lc($logic) eq '-or' and @values > 1) {
758 my $op = uc join ' ', split '_', $vk;
759 belch "A multi-element arrayref as an argument to the inequality op '$op' "
760 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
761 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
766 # try to DWIM on equality operators
767 my $op = join ' ', split '_', $vk;
769 $op =~ $self->{equality_op} ? $self->sqlfalse
770 : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqlfalse
771 : $op =~ $self->{inequality_op} ? $self->sqltrue
772 : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqltrue
773 : puke "operator '$op' applied on an empty array (field '$k')";
777 map $self->_expand_expr_hashpair($k => { $vk => $_ }),
785 and exists $vv->{-value}
786 and not defined $vv->{-value}
789 my $op = join ' ', split '_', $vk;
791 $op =~ /^not$/i ? 'is not' # legacy
792 : $op =~ $self->{equality_op} ? 'is'
793 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
794 : $op =~ $self->{inequality_op} ? 'is not'
795 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
796 : puke "unexpected operator '$op' with undef operand";
797 return +{ -op => [ $is.' null', { -ident => $k } ] };
799 local our $Cur_Col_Meta = $k;
803 $self->_expand_expr($vv)
806 if (ref($v) eq 'ARRAY') {
807 return $self->sqlfalse unless @$v;
808 $self->_debug("ARRAY($k) means distribute over elements");
810 $v->[0] =~ /^-((?:and|or))$/i
811 ? ($v = [ @{$v}[1..$#$v] ], $1)
812 : ($self->{logic} || 'or')
816 map $self->_expand_expr({ $k => $_ }, $this_logic), @$v
819 if (my $literal = is_literal_value($v)) {
821 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
824 my ($sql, @bind) = @$literal;
825 if ($self->{bindtype} eq 'columns') {
827 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
828 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
832 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
838 my ($self, $expr) = @_;
839 my ($k, $v, @rest) = %$expr;
841 if (my $meth = $self->{node_types}{$k}) {
842 return $self->$meth($v);
844 die "notreached: $k";
848 my ($self, $where, $logic) = @_;
850 #print STDERR Data::Dumper::Concise::Dumper([ $where, $logic ]);
852 my $where_exp = $self->_expand_expr($where, $logic);
854 #print STDERR Data::Dumper::Concise::Dumper([ EXP => $where_exp ]);
856 # dispatch on appropriate method according to refkind of $where
857 # my $method = $self->_METHOD_FOR_refkind("_where", $where_exp);
859 # my ($sql, @bind) = $self->$method($where_exp, $logic);
861 my ($sql, @bind) = defined($where_exp) ? $self->_render_expr($where_exp) : (undef);
863 # DBIx::Class used to call _recurse_where in scalar context
864 # something else might too...
866 return ($sql, @bind);
869 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
875 my ($self, $ident) = @_;
877 return $self->_convert($self->_quote($ident));
881 my ($self, $value) = @_;
883 return ($self->_convert('?'), $self->_bindtype(undef, $value));
886 my %unop_postfix = map +($_ => 1),
887 'is null', 'is not null',
895 my ($self, $args) = @_;
896 my ($left, $low, $high) = @$args;
897 my ($rhsql, @rhbind) = do {
899 puke "Single arg to between must be a literal"
900 unless $low->{-literal};
903 my ($l, $h) = map [ $self->_render_expr($_) ], $low, $high;
904 (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]),
905 @{$l}[1..$#$l], @{$h}[1..$#$h])
908 my ($lhsql, @lhbind) = $self->_render_expr($left);
910 join(' ', '(', $lhsql, $self->_sqlcase($op), $rhsql, ')'),
914 }), 'between', 'not between'),
918 my ($self, $args) = @_;
919 my ($lhs, $rhs) = @$args;
922 my ($sql, @bind) = $self->_render_expr($_);
923 push @in_bind, @bind;
926 my ($lhsql, @lbind) = $self->_render_expr($lhs);
928 $lhsql.' '.$self->_sqlcase($op).' ( '
939 my ($op, @args) = @$v;
940 $op =~ s/^-// if length($op) > 1;
942 if (my $h = $special{$op}) {
943 return $self->$h(\@args);
945 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{user_special_ops}}) {
946 puke "Special op '${op}' requires first value to be identifier"
947 unless my ($k) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
948 return $self->${\($us->{handler})}($k, $op, $args[1]);
950 my $final_op = $op =~ /^(?:is|not)_/ ? join(' ', split '_', $op) : $op;
951 if (@args == 1 and $op !~ /^(and|or)$/) {
952 my ($expr_sql, @bind) = $self->_render_expr($args[0]);
953 my $op_sql = $self->_sqlcase($final_op);
955 $unop_postfix{lc($final_op)}
956 ? "${expr_sql} ${op_sql}"
957 : "${op_sql} ${expr_sql}"
959 return (($op eq 'not' ? '('.$final_sql.')' : $final_sql), @bind);
961 my @parts = map [ $self->_render_expr($_) ], @args;
962 my ($final_sql) = map +($op =~ /^(and|or)$/ ? "(${_})" : $_), join(
963 ($final_op eq ',' ? '' : ' ').$self->_sqlcase($final_op).' ',
968 map @{$_}[1..$#$_], @parts
975 my ($self, $rest) = @_;
976 my ($func, @args) = @$rest;
980 push @arg_sql, shift @x;
982 } map [ $self->_render_expr($_) ], @args;
983 return ($self->_sqlcase($func).'('.join(', ', @arg_sql).')', @bind);
987 my ($self, $bind) = @_;
988 return ($self->_convert('?'), $self->_bindtype(@$bind));
991 sub _render_literal {
992 my ($self, $literal) = @_;
993 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
997 # Some databases (SQLite) treat col IN (1, 2) different from
998 # col IN ( (1, 2) ). Use this to strip all outer parens while
999 # adding them back in the corresponding method
1000 sub _open_outer_paren {
1001 my ($self, $sql) = @_;
1003 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
1005 # there are closing parens inside, need the heavy duty machinery
1006 # to reevaluate the extraction starting from $sql (full reevaluation)
1007 if ($inner =~ /\)/) {
1008 require Text::Balanced;
1010 my (undef, $remainder) = do {
1011 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1013 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
1016 # the entire expression needs to be a balanced bracketed thing
1017 # (after an extract no remainder sans trailing space)
1018 last if defined $remainder and $remainder =~ /\S/;
1028 #======================================================================
1030 #======================================================================
1033 my ($self, $arg) = @_;
1035 return '' unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
1037 my $expander = sub {
1038 my ($self, $dir, $expr) = @_;
1039 my @exp = map +(defined($dir) ? { -op => [ $dir => $_ ] } : $_),
1040 map $self->_expand_expr($_, undef, -ident),
1041 ref($expr) eq 'ARRAY' ? @$expr : $expr;
1042 return (@exp > 1 ? { -op => [ ',', @exp ] } : $exp[0]);
1045 local @{$self->{expand_unary}}{qw(-asc -desc)} = (
1046 sub { shift->$expander(asc => @_) },
1047 sub { shift->$expander(desc => @_) },
1050 my $expanded = $self->$expander(undef, $arg);
1052 my ($sql, @bind) = $self->_render_expr($expanded);
1054 my $final_sql = $self->_sqlcase(' order by ').$sql;
1056 return wantarray ? ($final_sql, @bind) : $final_sql;
1059 #======================================================================
1060 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1061 #======================================================================
1066 ($self->_render_expr(
1067 $self->_expand_maybe_list_expr($from, undef, -ident)
1072 #======================================================================
1074 #======================================================================
1076 sub _expand_maybe_list_expr {
1077 my ($self, $expr, $logic, $default) = @_;
1079 if (ref($expr) eq 'ARRAY') {
1081 ',', map $self->_expand_expr($_, $logic, $default), @$expr
1088 return $self->_expand_expr($e, $logic, $default);
1091 # highly optimized, as it's called way too often
1093 # my ($self, $label) = @_;
1095 return '' unless defined $_[1];
1096 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1097 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
1099 unless ($_[0]->{quote_char}) {
1100 if (ref($_[1]) eq 'ARRAY') {
1101 return join($_[0]->{name_sep}||'.', @{$_[1]});
1103 $_[0]->_assert_pass_injection_guard($_[1]);
1108 my $qref = ref $_[0]->{quote_char};
1110 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1111 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1112 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1114 my $esc = $_[0]->{escape_char} || $r;
1116 # parts containing * are naturally unquoted
1118 $_[0]->{name_sep}||'',
1122 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1124 (ref($_[1]) eq 'ARRAY'
1128 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1136 # Conversion, if applicable
1138 #my ($self, $arg) = @_;
1139 if ($_[0]->{convert_where}) {
1140 return $_[0]->_sqlcase($_[0]->{convert_where}) .'(' . $_[1] . ')';
1147 #my ($self, $col, @vals) = @_;
1148 # called often - tighten code
1149 return $_[0]->{bindtype} eq 'columns'
1150 ? map {[$_[1], $_]} @_[2 .. $#_]
1155 # Dies if any element of @bind is not in [colname => value] format
1156 # if bindtype is 'columns'.
1157 sub _assert_bindval_matches_bindtype {
1158 # my ($self, @bind) = @_;
1160 if ($self->{bindtype} eq 'columns') {
1162 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1163 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1169 sub _join_sql_clauses {
1170 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1172 if (@$clauses_aref > 1) {
1173 my $join = " " . $self->_sqlcase($logic) . " ";
1174 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1175 return ($sql, @$bind_aref);
1177 elsif (@$clauses_aref) {
1178 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1181 return (); # if no SQL, ignore @$bind_aref
1186 # Fix SQL case, if so requested
1188 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1189 # don't touch the argument ... crooked logic, but let's not change it!
1190 return $_[0]->{case} ? $_[1] : uc($_[1]);
1194 #======================================================================
1195 # DISPATCHING FROM REFKIND
1196 #======================================================================
1199 my ($self, $data) = @_;
1201 return 'UNDEF' unless defined $data;
1203 # blessed objects are treated like scalars
1204 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1206 return 'SCALAR' unless $ref;
1209 while ($ref eq 'REF') {
1211 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1215 return ($ref||'SCALAR') . ('REF' x $n_steps);
1219 my ($self, $data) = @_;
1220 my @try = ($self->_refkind($data));
1221 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1222 push @try, 'FALLBACK';
1226 sub _METHOD_FOR_refkind {
1227 my ($self, $meth_prefix, $data) = @_;
1230 for (@{$self->_try_refkind($data)}) {
1231 $method = $self->can($meth_prefix."_".$_)
1235 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1239 sub _SWITCH_refkind {
1240 my ($self, $data, $dispatch_table) = @_;
1243 for (@{$self->_try_refkind($data)}) {
1244 $coderef = $dispatch_table->{$_}
1248 puke "no dispatch entry for ".$self->_refkind($data)
1257 #======================================================================
1258 # VALUES, GENERATE, AUTOLOAD
1259 #======================================================================
1261 # LDNOTE: original code from nwiger, didn't touch code in that section
1262 # I feel the AUTOLOAD stuff should not be the default, it should
1263 # only be activated on explicit demand by user.
1267 my $data = shift || return;
1268 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1269 unless ref $data eq 'HASH';
1272 foreach my $k (sort keys %$data) {
1273 my $v = $data->{$k};
1274 $self->_SWITCH_refkind($v, {
1276 if ($self->{array_datatypes}) { # array datatype
1277 push @all_bind, $self->_bindtype($k, $v);
1279 else { # literal SQL with bind
1280 my ($sql, @bind) = @$v;
1281 $self->_assert_bindval_matches_bindtype(@bind);
1282 push @all_bind, @bind;
1285 ARRAYREFREF => sub { # literal SQL with bind
1286 my ($sql, @bind) = @${$v};
1287 $self->_assert_bindval_matches_bindtype(@bind);
1288 push @all_bind, @bind;
1290 SCALARREF => sub { # literal SQL without bind
1292 SCALAR_or_UNDEF => sub {
1293 push @all_bind, $self->_bindtype($k, $v);
1304 my(@sql, @sqlq, @sqlv);
1308 if ($ref eq 'HASH') {
1309 for my $k (sort keys %$_) {
1312 my $label = $self->_quote($k);
1313 if ($r eq 'ARRAY') {
1314 # literal SQL with bind
1315 my ($sql, @bind) = @$v;
1316 $self->_assert_bindval_matches_bindtype(@bind);
1317 push @sqlq, "$label = $sql";
1319 } elsif ($r eq 'SCALAR') {
1320 # literal SQL without bind
1321 push @sqlq, "$label = $$v";
1323 push @sqlq, "$label = ?";
1324 push @sqlv, $self->_bindtype($k, $v);
1327 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1328 } elsif ($ref eq 'ARRAY') {
1329 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1332 if ($r eq 'ARRAY') { # literal SQL with bind
1333 my ($sql, @bind) = @$v;
1334 $self->_assert_bindval_matches_bindtype(@bind);
1337 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1338 # embedded literal SQL
1345 push @sql, '(' . join(', ', @sqlq) . ')';
1346 } elsif ($ref eq 'SCALAR') {
1350 # strings get case twiddled
1351 push @sql, $self->_sqlcase($_);
1355 my $sql = join ' ', @sql;
1357 # this is pretty tricky
1358 # if ask for an array, return ($stmt, @bind)
1359 # otherwise, s/?/shift @sqlv/ to put it inline
1361 return ($sql, @sqlv);
1363 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1364 ref $d ? $d->[1] : $d/e;
1373 # This allows us to check for a local, then _form, attr
1375 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1376 return $self->generate($name, @_);
1387 SQL::Abstract - Generate SQL from Perl data structures
1393 my $sql = SQL::Abstract->new;
1395 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
1397 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1399 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1401 my($stmt, @bind) = $sql->delete($table, \%where);
1403 # Then, use these in your DBI statements
1404 my $sth = $dbh->prepare($stmt);
1405 $sth->execute(@bind);
1407 # Just generate the WHERE clause
1408 my($stmt, @bind) = $sql->where(\%where, $order);
1410 # Return values in the same order, for hashed queries
1411 # See PERFORMANCE section for more details
1412 my @bind = $sql->values(\%fieldvals);
1416 This module was inspired by the excellent L<DBIx::Abstract>.
1417 However, in using that module I found that what I really wanted
1418 to do was generate SQL, but still retain complete control over my
1419 statement handles and use the DBI interface. So, I set out to
1420 create an abstract SQL generation module.
1422 While based on the concepts used by L<DBIx::Abstract>, there are
1423 several important differences, especially when it comes to WHERE
1424 clauses. I have modified the concepts used to make the SQL easier
1425 to generate from Perl data structures and, IMO, more intuitive.
1426 The underlying idea is for this module to do what you mean, based
1427 on the data structures you provide it. The big advantage is that
1428 you don't have to modify your code every time your data changes,
1429 as this module figures it out.
1431 To begin with, an SQL INSERT is as easy as just specifying a hash
1432 of C<key=value> pairs:
1435 name => 'Jimbo Bobson',
1436 phone => '123-456-7890',
1437 address => '42 Sister Lane',
1438 city => 'St. Louis',
1439 state => 'Louisiana',
1442 The SQL can then be generated with this:
1444 my($stmt, @bind) = $sql->insert('people', \%data);
1446 Which would give you something like this:
1448 $stmt = "INSERT INTO people
1449 (address, city, name, phone, state)
1450 VALUES (?, ?, ?, ?, ?)";
1451 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1452 '123-456-7890', 'Louisiana');
1454 These are then used directly in your DBI code:
1456 my $sth = $dbh->prepare($stmt);
1457 $sth->execute(@bind);
1459 =head2 Inserting and Updating Arrays
1461 If your database has array types (like for example Postgres),
1462 activate the special option C<< array_datatypes => 1 >>
1463 when creating the C<SQL::Abstract> object.
1464 Then you may use an arrayref to insert and update database array types:
1466 my $sql = SQL::Abstract->new(array_datatypes => 1);
1468 planets => [qw/Mercury Venus Earth Mars/]
1471 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1475 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1477 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1480 =head2 Inserting and Updating SQL
1482 In order to apply SQL functions to elements of your C<%data> you may
1483 specify a reference to an arrayref for the given hash value. For example,
1484 if you need to execute the Oracle C<to_date> function on a value, you can
1485 say something like this:
1489 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
1492 The first value in the array is the actual SQL. Any other values are
1493 optional and would be included in the bind values array. This gives
1496 my($stmt, @bind) = $sql->insert('people', \%data);
1498 $stmt = "INSERT INTO people (name, date_entered)
1499 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1500 @bind = ('Bill', '03/02/2003');
1502 An UPDATE is just as easy, all you change is the name of the function:
1504 my($stmt, @bind) = $sql->update('people', \%data);
1506 Notice that your C<%data> isn't touched; the module will generate
1507 the appropriately quirky SQL for you automatically. Usually you'll
1508 want to specify a WHERE clause for your UPDATE, though, which is
1509 where handling C<%where> hashes comes in handy...
1511 =head2 Complex where statements
1513 This module can generate pretty complicated WHERE statements
1514 easily. For example, simple C<key=value> pairs are taken to mean
1515 equality, and if you want to see if a field is within a set
1516 of values, you can use an arrayref. Let's say we wanted to
1517 SELECT some data based on this criteria:
1520 requestor => 'inna',
1521 worker => ['nwiger', 'rcwe', 'sfz'],
1522 status => { '!=', 'completed' }
1525 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1527 The above would give you something like this:
1529 $stmt = "SELECT * FROM tickets WHERE
1530 ( requestor = ? ) AND ( status != ? )
1531 AND ( worker = ? OR worker = ? OR worker = ? )";
1532 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1534 Which you could then use in DBI code like so:
1536 my $sth = $dbh->prepare($stmt);
1537 $sth->execute(@bind);
1543 The methods are simple. There's one for every major SQL operation,
1544 and a constructor you use first. The arguments are specified in a
1545 similar order for each method (table, then fields, then a where
1546 clause) to try and simplify things.
1548 =head2 new(option => 'value')
1550 The C<new()> function takes a list of options and values, and returns
1551 a new B<SQL::Abstract> object which can then be used to generate SQL
1552 through the methods below. The options accepted are:
1558 If set to 'lower', then SQL will be generated in all lowercase. By
1559 default SQL is generated in "textbook" case meaning something like:
1561 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1563 Any setting other than 'lower' is ignored.
1567 This determines what the default comparison operator is. By default
1568 it is C<=>, meaning that a hash like this:
1570 %where = (name => 'nwiger', email => 'nate@wiger.org');
1572 Will generate SQL like this:
1574 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1576 However, you may want loose comparisons by default, so if you set
1577 C<cmp> to C<like> you would get SQL such as:
1579 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1581 You can also override the comparison on an individual basis - see
1582 the huge section on L</"WHERE CLAUSES"> at the bottom.
1584 =item sqltrue, sqlfalse
1586 Expressions for inserting boolean values within SQL statements.
1587 By default these are C<1=1> and C<1=0>. They are used
1588 by the special operators C<-in> and C<-not_in> for generating
1589 correct SQL even when the argument is an empty array (see below).
1593 This determines the default logical operator for multiple WHERE
1594 statements in arrays or hashes. If absent, the default logic is "or"
1595 for arrays, and "and" for hashes. This means that a WHERE
1599 event_date => {'>=', '2/13/99'},
1600 event_date => {'<=', '4/24/03'},
1603 will generate SQL like this:
1605 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1607 This is probably not what you want given this query, though (look
1608 at the dates). To change the "OR" to an "AND", simply specify:
1610 my $sql = SQL::Abstract->new(logic => 'and');
1612 Which will change the above C<WHERE> to:
1614 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1616 The logic can also be changed locally by inserting
1617 a modifier in front of an arrayref:
1619 @where = (-and => [event_date => {'>=', '2/13/99'},
1620 event_date => {'<=', '4/24/03'} ]);
1622 See the L</"WHERE CLAUSES"> section for explanations.
1626 This will automatically convert comparisons using the specified SQL
1627 function for both column and value. This is mostly used with an argument
1628 of C<upper> or C<lower>, so that the SQL will have the effect of
1629 case-insensitive "searches". For example, this:
1631 $sql = SQL::Abstract->new(convert => 'upper');
1632 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1634 Will turn out the following SQL:
1636 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1638 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1639 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1640 not validate this option; it will just pass through what you specify verbatim).
1644 This is a kludge because many databases suck. For example, you can't
1645 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1646 Instead, you have to use C<bind_param()>:
1648 $sth->bind_param(1, 'reg data');
1649 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1651 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1652 which loses track of which field each slot refers to. Fear not.
1654 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1655 Currently, you can specify either C<normal> (default) or C<columns>. If you
1656 specify C<columns>, you will get an array that looks like this:
1658 my $sql = SQL::Abstract->new(bindtype => 'columns');
1659 my($stmt, @bind) = $sql->insert(...);
1662 [ 'column1', 'value1' ],
1663 [ 'column2', 'value2' ],
1664 [ 'column3', 'value3' ],
1667 You can then iterate through this manually, using DBI's C<bind_param()>.
1669 $sth->prepare($stmt);
1672 my($col, $data) = @$_;
1673 if ($col eq 'details' || $col eq 'comments') {
1674 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1675 } elsif ($col eq 'image') {
1676 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1678 $sth->bind_param($i, $data);
1682 $sth->execute; # execute without @bind now
1684 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1685 Basically, the advantage is still that you don't have to care which fields
1686 are or are not included. You could wrap that above C<for> loop in a simple
1687 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1688 get a layer of abstraction over manual SQL specification.
1690 Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
1691 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1692 will expect the bind values in this format.
1696 This is the character that a table or column name will be quoted
1697 with. By default this is an empty string, but you could set it to
1698 the character C<`>, to generate SQL like this:
1700 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1702 Alternatively, you can supply an array ref of two items, the first being the left
1703 hand quote character, and the second the right hand quote character. For
1704 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1705 that generates SQL like this:
1707 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1709 Quoting is useful if you have tables or columns names that are reserved
1710 words in your database's SQL dialect.
1714 This is the character that will be used to escape L</quote_char>s appearing
1715 in an identifier before it has been quoted.
1717 The parameter default in case of a single L</quote_char> character is the quote
1720 When opening-closing-style quoting is used (L</quote_char> is an arrayref)
1721 this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
1722 of the B<opening (left)> L</quote_char> within the identifier are currently left
1723 untouched. The default for opening-closing-style quotes may change in future
1724 versions, thus you are B<strongly encouraged> to specify the escape character
1729 This is the character that separates a table and column name. It is
1730 necessary to specify this when the C<quote_char> option is selected,
1731 so that tables and column names can be individually quoted like this:
1733 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1735 =item injection_guard
1737 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1738 column name specified in a query structure. This is a safety mechanism to avoid
1739 injection attacks when mishandling user input e.g.:
1741 my %condition_as_column_value_pairs = get_values_from_user();
1742 $sqla->select( ... , \%condition_as_column_value_pairs );
1744 If the expression matches an exception is thrown. Note that literal SQL
1745 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1747 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1749 =item array_datatypes
1751 When this option is true, arrayrefs in INSERT or UPDATE are
1752 interpreted as array datatypes and are passed directly
1754 When this option is false, arrayrefs are interpreted
1755 as literal SQL, just like refs to arrayrefs
1756 (but this behavior is for backwards compatibility; when writing
1757 new queries, use the "reference to arrayref" syntax
1763 Takes a reference to a list of "special operators"
1764 to extend the syntax understood by L<SQL::Abstract>.
1765 See section L</"SPECIAL OPERATORS"> for details.
1769 Takes a reference to a list of "unary operators"
1770 to extend the syntax understood by L<SQL::Abstract>.
1771 See section L</"UNARY OPERATORS"> for details.
1777 =head2 insert($table, \@values || \%fieldvals, \%options)
1779 This is the simplest function. You simply give it a table name
1780 and either an arrayref of values or hashref of field/value pairs.
1781 It returns an SQL INSERT statement and a list of bind values.
1782 See the sections on L</"Inserting and Updating Arrays"> and
1783 L</"Inserting and Updating SQL"> for information on how to insert
1784 with those data types.
1786 The optional C<\%options> hash reference may contain additional
1787 options to generate the insert SQL. Currently supported options
1794 Takes either a scalar of raw SQL fields, or an array reference of
1795 field names, and adds on an SQL C<RETURNING> statement at the end.
1796 This allows you to return data generated by the insert statement
1797 (such as row IDs) without performing another C<SELECT> statement.
1798 Note, however, this is not part of the SQL standard and may not
1799 be supported by all database engines.
1803 =head2 update($table, \%fieldvals, \%where, \%options)
1805 This takes a table, hashref of field/value pairs, and an optional
1806 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1808 See the sections on L</"Inserting and Updating Arrays"> and
1809 L</"Inserting and Updating SQL"> for information on how to insert
1810 with those data types.
1812 The optional C<\%options> hash reference may contain additional
1813 options to generate the update SQL. Currently supported options
1820 See the C<returning> option to
1821 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
1825 =head2 select($source, $fields, $where, $order)
1827 This returns a SQL SELECT statement and associated list of bind values, as
1828 specified by the arguments:
1834 Specification of the 'FROM' part of the statement.
1835 The argument can be either a plain scalar (interpreted as a table
1836 name, will be quoted), or an arrayref (interpreted as a list
1837 of table names, joined by commas, quoted), or a scalarref
1838 (literal SQL, not quoted).
1842 Specification of the list of fields to retrieve from
1844 The argument can be either an arrayref (interpreted as a list
1845 of field names, will be joined by commas and quoted), or a
1846 plain scalar (literal SQL, not quoted).
1847 Please observe that this API is not as flexible as that of
1848 the first argument C<$source>, for backwards compatibility reasons.
1852 Optional argument to specify the WHERE part of the query.
1853 The argument is most often a hashref, but can also be
1854 an arrayref or plain scalar --
1855 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1859 Optional argument to specify the ORDER BY part of the query.
1860 The argument can be a scalar, a hashref or an arrayref
1861 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1867 =head2 delete($table, \%where, \%options)
1869 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1870 It returns an SQL DELETE statement and list of bind values.
1872 The optional C<\%options> hash reference may contain additional
1873 options to generate the delete SQL. Currently supported options
1880 See the C<returning> option to
1881 L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
1885 =head2 where(\%where, $order)
1887 This is used to generate just the WHERE clause. For example,
1888 if you have an arbitrary data structure and know what the
1889 rest of your SQL is going to look like, but want an easy way
1890 to produce a WHERE clause, use this. It returns an SQL WHERE
1891 clause and list of bind values.
1894 =head2 values(\%data)
1896 This just returns the values from the hash C<%data>, in the same
1897 order that would be returned from any of the other above queries.
1898 Using this allows you to markedly speed up your queries if you
1899 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1901 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1903 Warning: This is an experimental method and subject to change.
1905 This returns arbitrarily generated SQL. It's a really basic shortcut.
1906 It will return two different things, depending on return context:
1908 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1909 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1911 These would return the following:
1913 # First calling form
1914 $stmt = "CREATE TABLE test (?, ?)";
1915 @bind = (field1, field2);
1917 # Second calling form
1918 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1920 Depending on what you're trying to do, it's up to you to choose the correct
1921 format. In this example, the second form is what you would want.
1925 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1929 ALTER SESSION SET nls_date_format = 'MM/YY'
1931 You get the idea. Strings get their case twiddled, but everything
1932 else remains verbatim.
1934 =head1 EXPORTABLE FUNCTIONS
1936 =head2 is_plain_value
1938 Determines if the supplied argument is a plain value as understood by this
1943 =item * The value is C<undef>
1945 =item * The value is a non-reference
1947 =item * The value is an object with stringification overloading
1949 =item * The value is of the form C<< { -value => $anything } >>
1953 On failure returns C<undef>, on success returns a B<scalar> reference
1954 to the original supplied argument.
1960 The stringification overloading detection is rather advanced: it takes
1961 into consideration not only the presence of a C<""> overload, but if that
1962 fails also checks for enabled
1963 L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
1964 on either C<0+> or C<bool>.
1966 Unfortunately testing in the field indicates that this
1967 detection B<< may tickle a latent bug in perl versions before 5.018 >>,
1968 but only when very large numbers of stringifying objects are involved.
1969 At the time of writing ( Sep 2014 ) there is no clear explanation of
1970 the direct cause, nor is there a manageably small test case that reliably
1971 reproduces the problem.
1973 If you encounter any of the following exceptions in B<random places within
1974 your application stack> - this module may be to blame:
1976 Operation "ne": no method found,
1977 left argument in overloaded package <something>,
1978 right argument in overloaded package <something>
1982 Stub found while resolving method "???" overloading """" in package <something>
1984 If you fall victim to the above - please attempt to reduce the problem
1985 to something that could be sent to the L<SQL::Abstract developers
1986 |DBIx::Class/GETTING HELP/SUPPORT>
1987 (either publicly or privately). As a workaround in the meantime you can
1988 set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
1989 value, which will most likely eliminate your problem (at the expense of
1990 not being able to properly detect exotic forms of stringification).
1992 This notice and environment variable will be removed in a future version,
1993 as soon as the underlying problem is found and a reliable workaround is
1998 =head2 is_literal_value
2000 Determines if the supplied argument is a literal value as understood by this
2005 =item * C<\$sql_string>
2007 =item * C<\[ $sql_string, @bind_values ]>
2011 On failure returns C<undef>, on success returns an B<array> reference
2012 containing the unpacked version of the supplied literal SQL and bind values.
2014 =head1 WHERE CLAUSES
2018 This module uses a variation on the idea from L<DBIx::Abstract>. It
2019 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2020 module is that things in arrays are OR'ed, and things in hashes
2023 The easiest way to explain is to show lots of examples. After
2024 each C<%where> hash shown, it is assumed you used:
2026 my($stmt, @bind) = $sql->where(\%where);
2028 However, note that the C<%where> hash can be used directly in any
2029 of the other functions as well, as described above.
2031 =head2 Key-value pairs
2033 So, let's get started. To begin, a simple hash:
2037 status => 'completed'
2040 Is converted to SQL C<key = val> statements:
2042 $stmt = "WHERE user = ? AND status = ?";
2043 @bind = ('nwiger', 'completed');
2045 One common thing I end up doing is having a list of values that
2046 a field can be in. To do this, simply specify a list inside of
2051 status => ['assigned', 'in-progress', 'pending'];
2054 This simple code will create the following:
2056 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2057 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2059 A field associated to an empty arrayref will be considered a
2060 logical false and will generate 0=1.
2062 =head2 Tests for NULL values
2064 If the value part is C<undef> then this is converted to SQL <IS NULL>
2073 $stmt = "WHERE user = ? AND status IS NULL";
2076 To test if a column IS NOT NULL:
2080 status => { '!=', undef },
2083 =head2 Specific comparison operators
2085 If you want to specify a different type of operator for your comparison,
2086 you can use a hashref for a given column:
2090 status => { '!=', 'completed' }
2093 Which would generate:
2095 $stmt = "WHERE user = ? AND status != ?";
2096 @bind = ('nwiger', 'completed');
2098 To test against multiple values, just enclose the values in an arrayref:
2100 status => { '=', ['assigned', 'in-progress', 'pending'] };
2102 Which would give you:
2104 "WHERE status = ? OR status = ? OR status = ?"
2107 The hashref can also contain multiple pairs, in which case it is expanded
2108 into an C<AND> of its elements:
2112 status => { '!=', 'completed', -not_like => 'pending%' }
2115 # Or more dynamically, like from a form
2116 $where{user} = 'nwiger';
2117 $where{status}{'!='} = 'completed';
2118 $where{status}{'-not_like'} = 'pending%';
2120 # Both generate this
2121 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2122 @bind = ('nwiger', 'completed', 'pending%');
2125 To get an OR instead, you can combine it with the arrayref idea:
2129 priority => [ { '=', 2 }, { '>', 5 } ]
2132 Which would generate:
2134 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2135 @bind = ('2', '5', 'nwiger');
2137 If you want to include literal SQL (with or without bind values), just use a
2138 scalar reference or reference to an arrayref as the value:
2141 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2142 date_expires => { '<' => \"now()" }
2145 Which would generate:
2147 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2148 @bind = ('11/26/2008');
2151 =head2 Logic and nesting operators
2153 In the example above,
2154 there is a subtle trap if you want to say something like
2155 this (notice the C<AND>):
2157 WHERE priority != ? AND priority != ?
2159 Because, in Perl you I<can't> do this:
2161 priority => { '!=' => 2, '!=' => 1 }
2163 As the second C<!=> key will obliterate the first. The solution
2164 is to use the special C<-modifier> form inside an arrayref:
2166 priority => [ -and => {'!=', 2},
2170 Normally, these would be joined by C<OR>, but the modifier tells it
2171 to use C<AND> instead. (Hint: You can use this in conjunction with the
2172 C<logic> option to C<new()> in order to change the way your queries
2173 work by default.) B<Important:> Note that the C<-modifier> goes
2174 B<INSIDE> the arrayref, as an extra first element. This will
2175 B<NOT> do what you think it might:
2177 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2179 Here is a quick list of equivalencies, since there is some overlap:
2182 status => {'!=', 'completed', 'not like', 'pending%' }
2183 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2186 status => {'=', ['assigned', 'in-progress']}
2187 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2188 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2192 =head2 Special operators: IN, BETWEEN, etc.
2194 You can also use the hashref format to compare a list of fields using the
2195 C<IN> comparison operator, by specifying the list as an arrayref:
2198 status => 'completed',
2199 reportid => { -in => [567, 2335, 2] }
2202 Which would generate:
2204 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2205 @bind = ('completed', '567', '2335', '2');
2207 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2210 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2211 (by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2212 'sqltrue' (by default: C<1=1>).
2214 In addition to the array you can supply a chunk of literal sql or
2215 literal sql with bind:
2218 customer => { -in => \[
2219 'SELECT cust_id FROM cust WHERE balance > ?',
2222 status => { -in => \'SELECT status_codes FROM states' },
2228 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2229 AND status IN ( SELECT status_codes FROM states )
2233 Finally, if the argument to C<-in> is not a reference, it will be
2234 treated as a single-element array.
2236 Another pair of operators is C<-between> and C<-not_between>,
2237 used with an arrayref of two values:
2241 completion_date => {
2242 -not_between => ['2002-10-01', '2003-02-06']
2248 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2250 Just like with C<-in> all plausible combinations of literal SQL
2254 start0 => { -between => [ 1, 2 ] },
2255 start1 => { -between => \["? AND ?", 1, 2] },
2256 start2 => { -between => \"lower(x) AND upper(y)" },
2257 start3 => { -between => [
2259 \["upper(?)", 'stuff' ],
2266 ( start0 BETWEEN ? AND ? )
2267 AND ( start1 BETWEEN ? AND ? )
2268 AND ( start2 BETWEEN lower(x) AND upper(y) )
2269 AND ( start3 BETWEEN lower(x) AND upper(?) )
2271 @bind = (1, 2, 1, 2, 'stuff');
2274 These are the two builtin "special operators"; but the
2275 list can be expanded: see section L</"SPECIAL OPERATORS"> below.
2277 =head2 Unary operators: bool
2279 If you wish to test against boolean columns or functions within your
2280 database you can use the C<-bool> and C<-not_bool> operators. For
2281 example to test the column C<is_user> being true and the column
2282 C<is_enabled> being false you would use:-
2286 -not_bool => 'is_enabled',
2291 WHERE is_user AND NOT is_enabled
2293 If a more complex combination is required, testing more conditions,
2294 then you should use the and/or operators:-
2299 -not_bool => { two=> { -rlike => 'bar' } },
2300 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
2311 (NOT ( three = ? OR three > ? ))
2314 =head2 Nested conditions, -and/-or prefixes
2316 So far, we've seen how multiple conditions are joined with a top-level
2317 C<AND>. We can change this by putting the different conditions we want in
2318 hashes and then putting those hashes in an array. For example:
2323 status => { -like => ['pending%', 'dispatched'] },
2327 status => 'unassigned',
2331 This data structure would create the following:
2333 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2334 OR ( user = ? AND status = ? ) )";
2335 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2338 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2339 to change the logic inside:
2345 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2346 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2353 $stmt = "WHERE ( user = ?
2354 AND ( ( workhrs > ? AND geo = ? )
2355 OR ( workhrs < ? OR geo = ? ) ) )";
2356 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
2358 =head3 Algebraic inconsistency, for historical reasons
2360 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2361 operator goes C<outside> of the nested structure; whereas when connecting
2362 several constraints on one column, the C<-and> operator goes
2363 C<inside> the arrayref. Here is an example combining both features:
2366 -and => [a => 1, b => 2],
2367 -or => [c => 3, d => 4],
2368 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2373 WHERE ( ( ( a = ? AND b = ? )
2374 OR ( c = ? OR d = ? )
2375 OR ( e LIKE ? AND e LIKE ? ) ) )
2377 This difference in syntax is unfortunate but must be preserved for
2378 historical reasons. So be careful: the two examples below would
2379 seem algebraically equivalent, but they are not
2382 { -like => 'foo%' },
2383 { -like => '%bar' },
2385 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
2388 { col => { -like => 'foo%' } },
2389 { col => { -like => '%bar' } },
2391 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
2394 =head2 Literal SQL and value type operators
2396 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2397 side" is a column name and the "right side" is a value (normally rendered as
2398 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2399 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2400 alter this behavior. There are several ways of doing so.
2404 This is a virtual operator that signals the string to its right side is an
2405 identifier (a column name) and not a value. For example to compare two
2406 columns you would write:
2409 priority => { '<', 2 },
2410 requestor => { -ident => 'submitter' },
2415 $stmt = "WHERE priority < ? AND requestor = submitter";
2418 If you are maintaining legacy code you may see a different construct as
2419 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2424 This is a virtual operator that signals that the construct to its right side
2425 is a value to be passed to DBI. This is for example necessary when you want
2426 to write a where clause against an array (for RDBMS that support such
2427 datatypes). For example:
2430 array => { -value => [1, 2, 3] }
2435 $stmt = 'WHERE array = ?';
2436 @bind = ([1, 2, 3]);
2438 Note that if you were to simply say:
2444 the result would probably not be what you wanted:
2446 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2451 Finally, sometimes only literal SQL will do. To include a random snippet
2452 of SQL verbatim, you specify it as a scalar reference. Consider this only
2453 as a last resort. Usually there is a better way. For example:
2456 priority => { '<', 2 },
2457 requestor => { -in => \'(SELECT name FROM hitmen)' },
2462 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2465 Note that in this example, you only get one bind parameter back, since
2466 the verbatim SQL is passed as part of the statement.
2470 Never use untrusted input as a literal SQL argument - this is a massive
2471 security risk (there is no way to check literal snippets for SQL
2472 injections and other nastyness). If you need to deal with untrusted input
2473 use literal SQL with placeholders as described next.
2475 =head3 Literal SQL with placeholders and bind values (subqueries)
2477 If the literal SQL to be inserted has placeholders and bind values,
2478 use a reference to an arrayref (yes this is a double reference --
2479 not so common, but perfectly legal Perl). For example, to find a date
2480 in Postgres you can use something like this:
2483 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
2488 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2491 Note that you must pass the bind values in the same format as they are returned
2492 by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
2493 to C<columns>, you must provide the bind values in the
2494 C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2495 scalar value; most commonly the column name, but you can use any scalar value
2496 (including references and blessed references), L<SQL::Abstract> will simply
2497 pass it through intact. So if C<bindtype> is set to C<columns> the above
2498 example will look like:
2501 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
2504 Literal SQL is especially useful for nesting parenthesized clauses in the
2505 main SQL query. Here is a first example:
2507 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2511 bar => \["IN ($sub_stmt)" => @sub_bind],
2516 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2517 WHERE c2 < ? AND c3 LIKE ?))";
2518 @bind = (1234, 100, "foo%");
2520 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2521 are expressed in the same way. Of course the C<$sub_stmt> and
2522 its associated bind values can be generated through a former call
2525 my ($sub_stmt, @sub_bind)
2526 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2527 c3 => {-like => "foo%"}});
2530 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2533 In the examples above, the subquery was used as an operator on a column;
2534 but the same principle also applies for a clause within the main C<%where>
2535 hash, like an EXISTS subquery:
2537 my ($sub_stmt, @sub_bind)
2538 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2539 my %where = ( -and => [
2541 \["EXISTS ($sub_stmt)" => @sub_bind],
2546 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2547 WHERE c1 = ? AND c2 > t0.c0))";
2551 Observe that the condition on C<c2> in the subquery refers to
2552 column C<t0.c0> of the main query: this is I<not> a bind
2553 value, so we have to express it through a scalar ref.
2554 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2555 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2556 what we wanted here.
2558 Finally, here is an example where a subquery is used
2559 for expressing unary negation:
2561 my ($sub_stmt, @sub_bind)
2562 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2563 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2565 lname => {like => '%son%'},
2566 \["NOT ($sub_stmt)" => @sub_bind],
2571 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2572 @bind = ('%son%', 10, 20)
2574 =head3 Deprecated usage of Literal SQL
2576 Below are some examples of archaic use of literal SQL. It is shown only as
2577 reference for those who deal with legacy code. Each example has a much
2578 better, cleaner and safer alternative that users should opt for in new code.
2584 my %where = ( requestor => \'IS NOT NULL' )
2586 $stmt = "WHERE requestor IS NOT NULL"
2588 This used to be the way of generating NULL comparisons, before the handling
2589 of C<undef> got formalized. For new code please use the superior syntax as
2590 described in L</Tests for NULL values>.
2594 my %where = ( requestor => \'= submitter' )
2596 $stmt = "WHERE requestor = submitter"
2598 This used to be the only way to compare columns. Use the superior L</-ident>
2599 method for all new code. For example an identifier declared in such a way
2600 will be properly quoted if L</quote_char> is properly set, while the legacy
2601 form will remain as supplied.
2605 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2607 $stmt = "WHERE completed > ? AND is_ready"
2608 @bind = ('2012-12-21')
2610 Using an empty string literal used to be the only way to express a boolean.
2611 For all new code please use the much more readable
2612 L<-bool|/Unary operators: bool> operator.
2618 These pages could go on for a while, since the nesting of the data
2619 structures this module can handle are pretty much unlimited (the
2620 module implements the C<WHERE> expansion as a recursive function
2621 internally). Your best bet is to "play around" with the module a
2622 little to see how the data structures behave, and choose the best
2623 format for your data based on that.
2625 And of course, all the values above will probably be replaced with
2626 variables gotten from forms or the command line. After all, if you
2627 knew everything ahead of time, you wouldn't have to worry about
2628 dynamically-generating SQL and could just hardwire it into your
2631 =head1 ORDER BY CLAUSES
2633 Some functions take an order by clause. This can either be a scalar (just a
2634 column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
2635 >>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
2638 Given | Will Generate
2639 ---------------------------------------------------------------
2641 'colA' | ORDER BY colA
2643 [qw/colA colB/] | ORDER BY colA, colB
2645 {-asc => 'colA'} | ORDER BY colA ASC
2647 {-desc => 'colB'} | ORDER BY colB DESC
2649 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2651 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2653 \'colA DESC' | ORDER BY colA DESC
2655 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
2656 | /* ...with $x bound to ? */
2659 { -asc => 'colA' }, | colA ASC,
2660 { -desc => [qw/colB/] }, | colB DESC,
2661 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
2662 \'colE DESC', | colE DESC,
2663 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
2664 ] | /* ...with $x bound to ? */
2665 ===============================================================
2669 =head1 SPECIAL OPERATORS
2671 my $sqlmaker = SQL::Abstract->new(special_ops => [
2675 my ($self, $field, $op, $arg) = @_;
2681 handler => 'method_name',
2685 A "special operator" is a SQL syntactic clause that can be
2686 applied to a field, instead of a usual binary operator.
2689 WHERE field IN (?, ?, ?)
2690 WHERE field BETWEEN ? AND ?
2691 WHERE MATCH(field) AGAINST (?, ?)
2693 Special operators IN and BETWEEN are fairly standard and therefore
2694 are builtin within C<SQL::Abstract> (as the overridable methods
2695 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2696 like the MATCH .. AGAINST example above which is specific to MySQL,
2697 you can write your own operator handlers - supply a C<special_ops>
2698 argument to the C<new> method. That argument takes an arrayref of
2699 operator definitions; each operator definition is a hashref with two
2706 the regular expression to match the operator
2710 Either a coderef or a plain scalar method name. In both cases
2711 the expected return is C<< ($sql, @bind) >>.
2713 When supplied with a method name, it is simply called on the
2714 L<SQL::Abstract> object as:
2716 $self->$method_name($field, $op, $arg)
2720 $field is the LHS of the operator
2721 $op is the part that matched the handler regex
2724 When supplied with a coderef, it is called as:
2726 $coderef->($self, $field, $op, $arg)
2731 For example, here is an implementation
2732 of the MATCH .. AGAINST syntax for MySQL
2734 my $sqlmaker = SQL::Abstract->new(special_ops => [
2736 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2737 {regex => qr/^match$/i,
2739 my ($self, $field, $op, $arg) = @_;
2740 $arg = [$arg] if not ref $arg;
2741 my $label = $self->_quote($field);
2742 my ($placeholder) = $self->_convert('?');
2743 my $placeholders = join ", ", (($placeholder) x @$arg);
2744 my $sql = $self->_sqlcase('match') . " ($label) "
2745 . $self->_sqlcase('against') . " ($placeholders) ";
2746 my @bind = $self->_bindtype($field, @$arg);
2747 return ($sql, @bind);
2754 =head1 UNARY OPERATORS
2756 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2760 my ($self, $op, $arg) = @_;
2766 handler => 'method_name',
2770 A "unary operator" is a SQL syntactic clause that can be
2771 applied to a field - the operator goes before the field
2773 You can write your own operator handlers - supply a C<unary_ops>
2774 argument to the C<new> method. That argument takes an arrayref of
2775 operator definitions; each operator definition is a hashref with two
2782 the regular expression to match the operator
2786 Either a coderef or a plain scalar method name. In both cases
2787 the expected return is C<< $sql >>.
2789 When supplied with a method name, it is simply called on the
2790 L<SQL::Abstract> object as:
2792 $self->$method_name($op, $arg)
2796 $op is the part that matched the handler regex
2797 $arg is the RHS or argument of the operator
2799 When supplied with a coderef, it is called as:
2801 $coderef->($self, $op, $arg)
2809 Thanks to some benchmarking by Mark Stosberg, it turns out that
2810 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2811 I must admit this wasn't an intentional design issue, but it's a
2812 byproduct of the fact that you get to control your C<DBI> handles
2815 To maximize performance, use a code snippet like the following:
2817 # prepare a statement handle using the first row
2818 # and then reuse it for the rest of the rows
2820 for my $href (@array_of_hashrefs) {
2821 $stmt ||= $sql->insert('table', $href);
2822 $sth ||= $dbh->prepare($stmt);
2823 $sth->execute($sql->values($href));
2826 The reason this works is because the keys in your C<$href> are sorted
2827 internally by B<SQL::Abstract>. Thus, as long as your data retains
2828 the same structure, you only have to generate the SQL the first time
2829 around. On subsequent queries, simply use the C<values> function provided
2830 by this module to return your values in the correct order.
2832 However this depends on the values having the same type - if, for
2833 example, the values of a where clause may either have values
2834 (resulting in sql of the form C<column = ?> with a single bind
2835 value), or alternatively the values might be C<undef> (resulting in
2836 sql of the form C<column IS NULL> with no bind value) then the
2837 caching technique suggested will not work.
2841 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2842 really like this part (I do, at least). Building up a complex query
2843 can be as simple as the following:
2850 use CGI::FormBuilder;
2853 my $form = CGI::FormBuilder->new(...);
2854 my $sql = SQL::Abstract->new;
2856 if ($form->submitted) {
2857 my $field = $form->field;
2858 my $id = delete $field->{id};
2859 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2862 Of course, you would still have to connect using C<DBI> to run the
2863 query, but the point is that if you make your form look like your
2864 table, the actual query script can be extremely simplistic.
2866 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2867 a fast interface to returning and formatting data. I frequently
2868 use these three modules together to write complex database query
2869 apps in under 50 lines.
2871 =head1 HOW TO CONTRIBUTE
2873 Contributions are always welcome, in all usable forms (we especially
2874 welcome documentation improvements). The delivery methods include git-
2875 or unified-diff formatted patches, GitHub pull requests, or plain bug
2876 reports either via RT or the Mailing list. Contributors are generally
2877 granted full access to the official repository after their first several
2878 patches pass successful review.
2880 This project is maintained in a git repository. The code and related tools are
2881 accessible at the following locations:
2885 =item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2887 =item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2889 =item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
2891 =item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
2897 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2898 Great care has been taken to preserve the I<published> behavior
2899 documented in previous versions in the 1.* family; however,
2900 some features that were previously undocumented, or behaved
2901 differently from the documentation, had to be changed in order
2902 to clarify the semantics. Hence, client code that was relying
2903 on some dark areas of C<SQL::Abstract> v1.*
2904 B<might behave differently> in v1.50.
2906 The main changes are:
2912 support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
2916 support for the { operator => \"..." } construct (to embed literal SQL)
2920 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2924 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2928 defensive programming: check arguments
2932 fixed bug with global logic, which was previously implemented
2933 through global variables yielding side-effects. Prior versions would
2934 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2935 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2936 Now this is interpreted
2937 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2942 fixed semantics of _bindtype on array args
2946 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2947 we just avoid shifting arrays within that tree.
2951 dropped the C<_modlogic> function
2955 =head1 ACKNOWLEDGEMENTS
2957 There are a number of individuals that have really helped out with
2958 this module. Unfortunately, most of them submitted bugs via CPAN
2959 so I have no idea who they are! But the people I do know are:
2961 Ash Berlin (order_by hash term support)
2962 Matt Trout (DBIx::Class support)
2963 Mark Stosberg (benchmarking)
2964 Chas Owens (initial "IN" operator support)
2965 Philip Collins (per-field SQL functions)
2966 Eric Kolve (hashref "AND" support)
2967 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2968 Dan Kubb (support for "quote_char" and "name_sep")
2969 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2970 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2971 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2972 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2973 Oliver Charles (support for "RETURNING" after "INSERT")
2979 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2983 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2985 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2987 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2988 While not an official support venue, C<DBIx::Class> makes heavy use of
2989 C<SQL::Abstract>, and as such list members there are very familiar with
2990 how to create queries.
2994 This module is free software; you may copy this under the same
2995 terms as perl itself (either the GNU General Public License or
2996 the Artistic License)