1 package SQL::Abstract; # see doc at end of file
3 # LDNOTE : this code is heavy refactoring from original SQLA.
4 # Several design decisions will need discussion during
5 # the test / diffusion / acceptance phase; those are marked with flag
6 # 'LDNOTE' (note by laurent.dami AT free.fr)
10 use warnings FATAL => 'all';
13 use Data::Query::Constants qw(
14 DQ_IDENTIFIER DQ_OPERATOR DQ_VALUE DQ_LITERAL DQ_JOIN DQ_SELECT DQ_ORDER
16 use Data::Query::ExprHelpers qw(perl_scalar_value);
18 #======================================================================
20 #======================================================================
22 our $VERSION = '1.72';
24 # This would confuse some packagers
25 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
29 # special operators (-in, -between). May be extended/overridden by user.
30 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
31 my @BUILTIN_SPECIAL_OPS = (
32 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
33 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
34 {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
35 {regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
38 # unaryish operators - key maps to handler
39 my @BUILTIN_UNARY_OPS = (
40 # the digits are backcompat stuff
41 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
42 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
43 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
44 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
45 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
46 { regex => qr/^ value $/ix, handler => '_where_op_VALUE' },
49 #======================================================================
50 # DEBUGGING AND ERROR REPORTING
51 #======================================================================
54 return unless $_[0]->{debug}; shift; # a little faster
55 my $func = (caller(1))[3];
56 warn "[$func] ", @_, "\n";
60 my($func) = (caller(1))[3];
61 Carp::carp "[$func] Warning: ", @_;
65 my($func) = (caller(1))[3];
66 Carp::croak "[$func] Fatal: ", @_;
70 #======================================================================
72 #======================================================================
76 my $class = ref($self) || $self;
77 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
79 # choose our case by keeping an option around
80 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
82 # default logic for interpreting arrayrefs
83 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
85 # how to return bind vars
86 # LDNOTE: changed nwiger code : why this 'delete' ??
87 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
88 $opt{bindtype} ||= 'normal';
90 # default comparison is "=", but can be overridden
93 # try to recognize which are the 'equality' and 'unequality' ops
94 # (temporary quickfix, should go through a more seasoned API)
95 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
96 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
99 $opt{sqltrue} ||= '1=1';
100 $opt{sqlfalse} ||= '0=1';
103 $opt{special_ops} ||= [];
104 # regexes are applied in order, thus push after user-defines
105 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
108 $opt{unary_ops} ||= [];
109 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
111 # rudimentary saniy-check for user supplied bits treated as functions/operators
112 # If a purported function matches this regular expression, an exception is thrown.
113 # Literal SQL is *NOT* subject to this check, only functions (and column names
114 # when quoting is not in effect)
117 # need to guard against ()'s in column names too, but this will break tons of
118 # hacks... ideas anyone?
119 $opt{injection_guard} ||= qr/
125 $opt{name_sep} ||= '.';
127 $opt{renderer} ||= do {
128 require Data::Query::Renderer::SQL::Naive;
129 my ($always, $chars);
130 for ($opt{quote_char}) {
131 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
134 Data::Query::Renderer::SQL::Naive->new({
135 quote_chars => $chars, always_quote => $always,
139 return bless \%opt, $class;
143 my ($self, $dq) = @_;
144 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
146 ($self->{bindtype} eq 'normal'
147 ? ($sql, map $_->{value}, @bind)
148 : ($sql, map [ $_->{value_meta}, $_->{value} ], @bind)
154 my ($self, $literal) = @_;
156 ($literal, @bind) = @$literal if ref($literal) eq 'ARRAY';
161 (@bind ? (values => [ $self->_bind_to_dq(@bind) ]) : ()),
166 my ($self, @bind) = @_;
168 $self->{bindtype} eq 'normal'
169 ? map perl_scalar_value($_), @bind
171 $self->_assert_bindval_matches_bindtype(@bind);
172 map perl_scalar_value(reverse @$_), @bind
177 my ($self, $value) = @_;
178 perl_scalar_value($value, our $Cur_Col_Meta);
182 my ($self, $ident) = @_;
183 $self->_assert_pass_injection_guard($ident)
184 unless $self->{renderer}{always_quote};
186 type => DQ_IDENTIFIER,
187 elements => [ split /\Q$self->{name_sep}/, $ident ],
192 my ($self, $op, @args) = @_;
193 $self->_assert_pass_injection_guard($op);
196 operator => { 'SQL.Naive' => $op },
201 sub _assert_pass_injection_guard {
202 if ($_[1] =~ $_[0]->{injection_guard}) {
203 my $class = ref $_[0];
204 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
205 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
206 . "{injection_guard} attribute to ${class}->new()"
211 #======================================================================
213 #======================================================================
217 my $table = $self->_table(shift);
218 my $data = shift || return;
221 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
222 my ($sql, @bind) = $self->$method($data);
223 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
225 if ($options->{returning}) {
226 my ($s, @b) = $self->_insert_returning ($options);
231 return wantarray ? ($sql, @bind) : $sql;
234 sub _insert_returning {
235 my ($self, $options) = @_;
237 my $f = $options->{returning};
239 my $fieldlist = $self->_SWITCH_refkind($f, {
240 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
241 SCALAR => sub {$self->_quote($f)},
242 SCALARREF => sub {$$f},
244 return $self->_sqlcase(' returning ') . $fieldlist;
247 sub _insert_HASHREF { # explicit list of fields and then values
248 my ($self, $data) = @_;
250 my @fields = sort keys %$data;
252 my ($sql, @bind) = $self->_insert_values($data);
255 $_ = $self->_quote($_) foreach @fields;
256 $sql = "( ".join(", ", @fields).") ".$sql;
258 return ($sql, @bind);
261 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
262 my ($self, $data) = @_;
264 # no names (arrayref) so can't generate bindtype
265 $self->{bindtype} ne 'columns'
266 or belch "can't do 'columns' bindtype when called with arrayref";
268 # fold the list of values into a hash of column name - value pairs
269 # (where the column names are artificially generated, and their
270 # lexicographical ordering keep the ordering of the original list)
271 my $i = "a"; # incremented values will be in lexicographical order
272 my $data_in_hash = { map { ($i++ => $_) } @$data };
274 return $self->_insert_values($data_in_hash);
277 sub _insert_ARRAYREFREF { # literal SQL with bind
278 my ($self, $data) = @_;
280 my ($sql, @bind) = @${$data};
281 $self->_assert_bindval_matches_bindtype(@bind);
283 return ($sql, @bind);
287 sub _insert_SCALARREF { # literal SQL without bind
288 my ($self, $data) = @_;
294 my ($self, $data) = @_;
296 my (@values, @all_bind);
297 foreach my $column (sort keys %$data) {
298 my $v = $data->{$column};
300 $self->_SWITCH_refkind($v, {
303 if ($self->{array_datatypes}) { # if array datatype are activated
305 push @all_bind, $self->_bindtype($column, $v);
307 else { # else literal SQL with bind
308 my ($sql, @bind) = @$v;
309 $self->_assert_bindval_matches_bindtype(@bind);
311 push @all_bind, @bind;
315 ARRAYREFREF => sub { # literal SQL with bind
316 my ($sql, @bind) = @${$v};
317 $self->_assert_bindval_matches_bindtype(@bind);
319 push @all_bind, @bind;
322 # THINK : anything useful to do with a HASHREF ?
323 HASHREF => sub { # (nothing, but old SQLA passed it through)
324 #TODO in SQLA >= 2.0 it will die instead
325 belch "HASH ref as bind value in insert is not supported";
327 push @all_bind, $self->_bindtype($column, $v);
330 SCALARREF => sub { # literal SQL without bind
334 SCALAR_or_UNDEF => sub {
336 push @all_bind, $self->_bindtype($column, $v);
343 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
344 return ($sql, @all_bind);
349 #======================================================================
351 #======================================================================
356 my $table = $self->_table(shift);
357 my $data = shift || return;
360 # first build the 'SET' part of the sql statement
361 my (@set, @all_bind);
362 puke "Unsupported data type specified to \$sql->update"
363 unless ref $data eq 'HASH';
365 for my $k (sort keys %$data) {
368 my $label = $self->_quote($k);
370 $self->_SWITCH_refkind($v, {
372 if ($self->{array_datatypes}) { # array datatype
373 push @set, "$label = ?";
374 push @all_bind, $self->_bindtype($k, $v);
376 else { # literal SQL with bind
377 my ($sql, @bind) = @$v;
378 $self->_assert_bindval_matches_bindtype(@bind);
379 push @set, "$label = $sql";
380 push @all_bind, @bind;
383 ARRAYREFREF => sub { # literal SQL with bind
384 my ($sql, @bind) = @${$v};
385 $self->_assert_bindval_matches_bindtype(@bind);
386 push @set, "$label = $sql";
387 push @all_bind, @bind;
389 SCALARREF => sub { # literal SQL without bind
390 push @set, "$label = $$v";
393 my ($op, $arg, @rest) = %$v;
395 puke 'Operator calls in update must be in the form { -op => $arg }'
396 if (@rest or not $op =~ /^\-(.+)/);
398 local $self->{_nested_func_lhs} = $k;
399 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
401 push @set, "$label = $sql";
402 push @all_bind, @bind;
404 SCALAR_or_UNDEF => sub {
405 push @set, "$label = ?";
406 push @all_bind, $self->_bindtype($k, $v);
412 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
416 my($where_sql, @where_bind) = $self->where($where);
418 push @all_bind, @where_bind;
421 return wantarray ? ($sql, @all_bind) : $sql;
427 #======================================================================
429 #======================================================================
435 my $fields = shift || '*';
439 my($where_sql, @bind) = $self->where($where, $order);
441 my $sql = $self->_render_dq({
444 map $self->_ident_to_dq($_),
445 ref($fields) eq 'ARRAY' ? @$fields : $fields
447 from => $self->_table_to_dq($table),
452 return wantarray ? ($sql, @bind) : $sql;
455 #======================================================================
457 #======================================================================
462 my $table = $self->_table(shift);
466 my($where_sql, @bind) = $self->where($where);
467 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
469 return wantarray ? ($sql, @bind) : $sql;
473 #======================================================================
475 #======================================================================
479 # Finally, a separate routine just to handle WHERE clauses
481 my ($self, $where, $order) = @_;
487 ($sql, @bind) = $self->_recurse_where($where) if defined($where);
488 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
492 $sql .= $self->_order_by($order);
495 return wantarray ? ($sql, @bind) : $sql;
500 my ($self, $where, $logic) = @_;
502 return $self->_render_dq($self->_where_to_dq($where, $logic));
506 my ($self, $where, $logic) = @_;
508 if (ref($where) eq 'ARRAY') {
509 return $self->_where_to_dq_ARRAYREF($where, $logic);
510 } elsif (ref($where) eq 'HASH') {
511 return $self->_where_to_dq_HASHREF($where, $logic);
513 ref($where) eq 'SCALAR'
514 or (ref($where) eq 'REF' and ref($$where) eq 'ARRAY')
516 return $self->_literal_to_dq($$where);
517 } elsif (!ref($where) or Scalar::Util::blessed($where)) {
518 return $self->_value_to_dq($where);
520 die "Can't handle $where";
523 sub _where_to_dq_ARRAYREF {
524 my ($self, $where, $logic) = @_;
526 $logic = uc($logic || 'OR');
527 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
529 return unless @$where;
531 my ($first, @rest) = @$where;
533 return $self->_where_to_dq($first) unless @rest;
537 $self->_where_hashpair_to_dq($first => shift(@rest));
539 $self->_where_to_dq($first);
543 return $self->_where_to_dq_ARRAYREF(\@rest, $logic) unless $first_dq;
546 $logic, $first_dq, $self->_where_to_dq_ARRAYREF(\@rest, $logic)
550 sub _where_to_dq_HASHREF {
551 my ($self, $where, $logic) = @_;
553 $logic = uc($logic || 'AND');
556 $self->_where_hashpair_to_dq($_ => $where->{$_})
559 return $dq[0] unless @dq > 1;
561 my $final = pop(@dq);
563 foreach my $dq (reverse @dq) {
564 $final = $self->_op_to_dq($logic, $dq, $final);
570 sub _where_to_dq_SCALAR {
571 shift->_value_to_dq(@_);
574 sub _where_op_IDENT {
576 my ($op, $rhs) = splice @_, -2;
578 puke "-$op takes a single scalar argument (a quotable identifier)";
581 # in case we are called as a top level special op (no '=')
584 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
592 sub _where_op_VALUE {
594 my ($op, $rhs) = splice @_, -2;
596 # in case we are called as a top level special op (no '=')
601 ($lhs || $self->{_nested_func_lhs}),
608 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
612 $self->_convert('?'),
618 sub _where_hashpair_to_dq {
619 my ($self, $k, $v) = @_;
621 if ($k =~ /^-(.*)/s) {
623 if ($op eq 'AND' or $op eq 'OR') {
624 return $self->_where_to_dq($v, $op);
625 } elsif ($op eq 'NEST') {
626 return $self->_where_to_dq($v);
627 } elsif ($op eq 'NOT') {
628 return $self->_op_to_dq(NOT => $self->_where_to_dq($v));
629 } elsif ($op eq 'BOOL') {
630 return ref($v) ? $self->_where_to_dq($v) : $self->_ident_to_dq($v);
631 } elsif ($op eq 'NOT_BOOL') {
632 return $self->_op_to_dq(
633 NOT => ref($v) ? $self->_where_to_dq($v) : $self->_ident_to_dq($v)
637 if (ref($v) eq 'HASH' and keys(%$v) == 1 and (keys %$v)[0] =~ /^-(.*)/s) {
639 my ($inner) = values %$v;
642 (map $self->_where_to_dq($_),
643 (ref($inner) eq 'ARRAY' ? @$inner : $inner))
646 (map $self->_where_to_dq($_), (ref($v) eq 'ARRAY' ? @$v : $v))
649 $self->_assert_pass_injection_guard($op);
650 return $self->_op_to_dq(
651 apply => $self->_ident_to_dq($op), @args
655 local our $Cur_Col_Meta = $k;
656 if (ref($v) eq 'ARRAY') {
658 return $self->_literal_to_dq($self->{sqlfalse});
659 } elsif (defined($v->[0]) && $v->[0] =~ /-(and|or)/i) {
660 return $self->_where_to_dq_ARRAYREF([
661 map +{ $k => $_ }, @{$v}[1..$#$v]
664 return $self->_where_to_dq_ARRAYREF([
665 map +{ $k => $_ }, @$v
667 } elsif (ref($v) eq 'SCALAR' or (ref($v) eq 'REF' and ref($$v) eq 'ARRAY')) {
671 parts => [ $self->_ident_to_dq($k), $self->_literal_to_dq($$v) ]
674 my ($op, $rhs) = do {
675 if (ref($v) eq 'HASH') {
677 return $self->_where_to_dq_ARRAYREF([
678 map +{ $k => { $_ => $v->{$_} } }, sort keys %$v
681 my ($op, $value) = %$v;
682 s/^-//, s/_/ /g for $op;
684 my $special_op = List::Util::first {$op =~ $_->{regex}}
685 @{$self->{special_ops}}
687 return $self->_literal_to_dq(
688 [ $self->${\$special_op->{handler}}($k, $op, $value) ]
696 if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
697 if (ref($rhs) ne 'ARRAY') {
699 # have to add parens if none present because -in => \"SELECT ..."
700 # got documented. mst hates everything.
701 if (ref($rhs) eq 'SCALAR') {
703 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
706 my ($x, @rest) = @{$$rhs};
707 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
708 $rhs = \[ $x, @rest ];
711 return $self->_op_to_dq(
712 $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
715 return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
716 return $self->_op_to_dq(
717 $op, $self->_ident_to_dq($k), map $self->_where_to_dq($_), @$rhs
719 } elsif ($op =~ s/^NOT (?!LIKE)//) {
720 return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
721 } elsif (!defined($rhs)) {
723 if ($op eq '=' or $op eq 'LIKE') {
725 } elsif ($op eq '!=') {
728 die "Can't do undef -> NULL transform for operator ${op}";
731 return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
733 if (ref($rhs) eq 'ARRAY') {
735 return $self->_literal_to_dq(
736 $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
738 } elsif (defined($rhs->[0]) and $rhs->[0] =~ /-(and|or)/i) {
739 return $self->_where_to_dq_ARRAYREF([
740 map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
743 return $self->_where_to_dq_ARRAYREF([
744 map +{ $k => { $op => $_ } }, @$rhs
747 return $self->_op_to_dq(
748 $op, $self->_ident_to_dq($k), $self->_where_to_dq($rhs)
753 #======================================================================
755 #======================================================================
758 my ($self, $arg) = @_;
759 if (my $dq = $self->_order_by_to_dq($arg)) {
760 # SQLA generates ' ORDER BY foo'. The hilarity.
762 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
763 : ' '.$self->_render_dq($dq);
769 sub _order_by_to_dq {
770 my ($self, $arg, $dir) = @_;
776 ($dir ? (direction => $dir) : ()),
780 $dq->{by} = $self->_ident_to_dq($arg);
781 } elsif (ref($arg) eq 'ARRAY') {
783 local our $Order_Inner unless our $Order_Recursing;
784 local $Order_Recursing = 1;
786 foreach my $member (@$arg) {
788 my $next = $self->_order_by_to_dq($member, $dir);
790 $inner->{from} = $next if $inner;
791 $inner = $Order_Inner || $next;
793 $Order_Inner = $inner;
795 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
796 $dq->{by} = $self->_literal_to_dq($$arg);
797 } elsif (ref($arg) eq 'SCALAR') {
798 $dq->{by} = $self->_literal_to_dq($$arg);
799 } elsif (ref($arg) eq 'HASH') {
800 my ($key, $val, @rest) = %$arg;
804 if (@rest or not $key =~ /^-(desc|asc)/i) {
805 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
808 return $self->_order_by_to_dq($val, $dir);
810 die "Can't handle $arg in _order_by_to_dq";
815 #======================================================================
816 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
817 #======================================================================
820 my ($self, $from) = @_;
821 $self->_render_dq($self->_table_to_dq($from));
825 my ($self, $from) = @_;
826 $self->_SWITCH_refkind($from, {
828 die "Empty FROM list" unless my @f = @$from;
829 my $dq = $self->_ident_to_dq(shift @f);
830 while (my $x = shift @f) {
833 join => [ $dq, $self->_ident_to_dq($x) ]
838 SCALAR => sub { $self->_ident_to_dq($from) },
850 #======================================================================
852 #======================================================================
854 # highly optimized, as it's called way too often
856 # my ($self, $label) = @_;
858 return '' unless defined $_[1];
859 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
861 unless ($_[0]->{quote_char}) {
862 $_[0]->_assert_pass_injection_guard($_[1]);
866 my $qref = ref $_[0]->{quote_char};
869 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
871 elsif ($qref eq 'ARRAY') {
872 ($l, $r) = @{$_[0]->{quote_char}};
875 puke "Unsupported quote_char format: $_[0]->{quote_char}";
878 # parts containing * are naturally unquoted
879 return join( $_[0]->{name_sep}||'', map
880 { $_ eq '*' ? $_ : $l . $_ . $r }
881 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
886 # Conversion, if applicable
888 #my ($self, $arg) = @_;
890 # LDNOTE : modified the previous implementation below because
891 # it was not consistent : the first "return" is always an array,
892 # the second "return" is context-dependent. Anyway, _convert
893 # seems always used with just a single argument, so make it a
895 # return @_ unless $self->{convert};
896 # my $conv = $self->_sqlcase($self->{convert});
897 # my @ret = map { $conv.'('.$_.')' } @_;
898 # return wantarray ? @ret : $ret[0];
899 if ($_[0]->{convert}) {
900 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
907 #my ($self, $col, @vals) = @_;
909 #LDNOTE : changed original implementation below because it did not make
910 # sense when bindtype eq 'columns' and @vals > 1.
911 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
913 # called often - tighten code
914 return $_[0]->{bindtype} eq 'columns'
915 ? map {[$_[1], $_]} @_[2 .. $#_]
920 # Dies if any element of @bind is not in [colname => value] format
921 # if bindtype is 'columns'.
922 sub _assert_bindval_matches_bindtype {
923 # my ($self, @bind) = @_;
925 if ($self->{bindtype} eq 'columns') {
927 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
928 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
934 sub _join_sql_clauses {
935 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
937 if (@$clauses_aref > 1) {
938 my $join = " " . $self->_sqlcase($logic) . " ";
939 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
940 return ($sql, @$bind_aref);
942 elsif (@$clauses_aref) {
943 return ($clauses_aref->[0], @$bind_aref); # no parentheses
946 return (); # if no SQL, ignore @$bind_aref
951 # Fix SQL case, if so requested
953 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
954 # don't touch the argument ... crooked logic, but let's not change it!
955 return $_[0]->{case} ? $_[1] : uc($_[1]);
959 #======================================================================
960 # DISPATCHING FROM REFKIND
961 #======================================================================
964 my ($self, $data) = @_;
966 return 'UNDEF' unless defined $data;
968 # blessed objects are treated like scalars
969 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
971 return 'SCALAR' unless $ref;
974 while ($ref eq 'REF') {
976 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
980 return ($ref||'SCALAR') . ('REF' x $n_steps);
984 my ($self, $data) = @_;
985 my @try = ($self->_refkind($data));
986 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
987 push @try, 'FALLBACK';
991 sub _METHOD_FOR_refkind {
992 my ($self, $meth_prefix, $data) = @_;
995 for (@{$self->_try_refkind($data)}) {
996 $method = $self->can($meth_prefix."_".$_)
1000 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1004 sub _SWITCH_refkind {
1005 my ($self, $data, $dispatch_table) = @_;
1008 for (@{$self->_try_refkind($data)}) {
1009 $coderef = $dispatch_table->{$_}
1013 puke "no dispatch entry for ".$self->_refkind($data)
1022 #======================================================================
1023 # VALUES, GENERATE, AUTOLOAD
1024 #======================================================================
1026 # LDNOTE: original code from nwiger, didn't touch code in that section
1027 # I feel the AUTOLOAD stuff should not be the default, it should
1028 # only be activated on explicit demand by user.
1032 my $data = shift || return;
1033 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1034 unless ref $data eq 'HASH';
1037 foreach my $k ( sort keys %$data ) {
1038 my $v = $data->{$k};
1039 $self->_SWITCH_refkind($v, {
1041 if ($self->{array_datatypes}) { # array datatype
1042 push @all_bind, $self->_bindtype($k, $v);
1044 else { # literal SQL with bind
1045 my ($sql, @bind) = @$v;
1046 $self->_assert_bindval_matches_bindtype(@bind);
1047 push @all_bind, @bind;
1050 ARRAYREFREF => sub { # literal SQL with bind
1051 my ($sql, @bind) = @${$v};
1052 $self->_assert_bindval_matches_bindtype(@bind);
1053 push @all_bind, @bind;
1055 SCALARREF => sub { # literal SQL without bind
1057 SCALAR_or_UNDEF => sub {
1058 push @all_bind, $self->_bindtype($k, $v);
1069 my(@sql, @sqlq, @sqlv);
1073 if ($ref eq 'HASH') {
1074 for my $k (sort keys %$_) {
1077 my $label = $self->_quote($k);
1078 if ($r eq 'ARRAY') {
1079 # literal SQL with bind
1080 my ($sql, @bind) = @$v;
1081 $self->_assert_bindval_matches_bindtype(@bind);
1082 push @sqlq, "$label = $sql";
1084 } elsif ($r eq 'SCALAR') {
1085 # literal SQL without bind
1086 push @sqlq, "$label = $$v";
1088 push @sqlq, "$label = ?";
1089 push @sqlv, $self->_bindtype($k, $v);
1092 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1093 } elsif ($ref eq 'ARRAY') {
1094 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1097 if ($r eq 'ARRAY') { # literal SQL with bind
1098 my ($sql, @bind) = @$v;
1099 $self->_assert_bindval_matches_bindtype(@bind);
1102 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1103 # embedded literal SQL
1110 push @sql, '(' . join(', ', @sqlq) . ')';
1111 } elsif ($ref eq 'SCALAR') {
1115 # strings get case twiddled
1116 push @sql, $self->_sqlcase($_);
1120 my $sql = join ' ', @sql;
1122 # this is pretty tricky
1123 # if ask for an array, return ($stmt, @bind)
1124 # otherwise, s/?/shift @sqlv/ to put it inline
1126 return ($sql, @sqlv);
1128 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1129 ref $d ? $d->[1] : $d/e;
1138 # This allows us to check for a local, then _form, attr
1140 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1141 return $self->generate($name, @_);
1152 SQL::Abstract - Generate SQL from Perl data structures
1158 my $sql = SQL::Abstract->new;
1160 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1162 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1164 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1166 my($stmt, @bind) = $sql->delete($table, \%where);
1168 # Then, use these in your DBI statements
1169 my $sth = $dbh->prepare($stmt);
1170 $sth->execute(@bind);
1172 # Just generate the WHERE clause
1173 my($stmt, @bind) = $sql->where(\%where, \@order);
1175 # Return values in the same order, for hashed queries
1176 # See PERFORMANCE section for more details
1177 my @bind = $sql->values(\%fieldvals);
1181 This module was inspired by the excellent L<DBIx::Abstract>.
1182 However, in using that module I found that what I really wanted
1183 to do was generate SQL, but still retain complete control over my
1184 statement handles and use the DBI interface. So, I set out to
1185 create an abstract SQL generation module.
1187 While based on the concepts used by L<DBIx::Abstract>, there are
1188 several important differences, especially when it comes to WHERE
1189 clauses. I have modified the concepts used to make the SQL easier
1190 to generate from Perl data structures and, IMO, more intuitive.
1191 The underlying idea is for this module to do what you mean, based
1192 on the data structures you provide it. The big advantage is that
1193 you don't have to modify your code every time your data changes,
1194 as this module figures it out.
1196 To begin with, an SQL INSERT is as easy as just specifying a hash
1197 of C<key=value> pairs:
1200 name => 'Jimbo Bobson',
1201 phone => '123-456-7890',
1202 address => '42 Sister Lane',
1203 city => 'St. Louis',
1204 state => 'Louisiana',
1207 The SQL can then be generated with this:
1209 my($stmt, @bind) = $sql->insert('people', \%data);
1211 Which would give you something like this:
1213 $stmt = "INSERT INTO people
1214 (address, city, name, phone, state)
1215 VALUES (?, ?, ?, ?, ?)";
1216 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1217 '123-456-7890', 'Louisiana');
1219 These are then used directly in your DBI code:
1221 my $sth = $dbh->prepare($stmt);
1222 $sth->execute(@bind);
1224 =head2 Inserting and Updating Arrays
1226 If your database has array types (like for example Postgres),
1227 activate the special option C<< array_datatypes => 1 >>
1228 when creating the C<SQL::Abstract> object.
1229 Then you may use an arrayref to insert and update database array types:
1231 my $sql = SQL::Abstract->new(array_datatypes => 1);
1233 planets => [qw/Mercury Venus Earth Mars/]
1236 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1240 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1242 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1245 =head2 Inserting and Updating SQL
1247 In order to apply SQL functions to elements of your C<%data> you may
1248 specify a reference to an arrayref for the given hash value. For example,
1249 if you need to execute the Oracle C<to_date> function on a value, you can
1250 say something like this:
1254 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1257 The first value in the array is the actual SQL. Any other values are
1258 optional and would be included in the bind values array. This gives
1261 my($stmt, @bind) = $sql->insert('people', \%data);
1263 $stmt = "INSERT INTO people (name, date_entered)
1264 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1265 @bind = ('Bill', '03/02/2003');
1267 An UPDATE is just as easy, all you change is the name of the function:
1269 my($stmt, @bind) = $sql->update('people', \%data);
1271 Notice that your C<%data> isn't touched; the module will generate
1272 the appropriately quirky SQL for you automatically. Usually you'll
1273 want to specify a WHERE clause for your UPDATE, though, which is
1274 where handling C<%where> hashes comes in handy...
1276 =head2 Complex where statements
1278 This module can generate pretty complicated WHERE statements
1279 easily. For example, simple C<key=value> pairs are taken to mean
1280 equality, and if you want to see if a field is within a set
1281 of values, you can use an arrayref. Let's say we wanted to
1282 SELECT some data based on this criteria:
1285 requestor => 'inna',
1286 worker => ['nwiger', 'rcwe', 'sfz'],
1287 status => { '!=', 'completed' }
1290 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1292 The above would give you something like this:
1294 $stmt = "SELECT * FROM tickets WHERE
1295 ( requestor = ? ) AND ( status != ? )
1296 AND ( worker = ? OR worker = ? OR worker = ? )";
1297 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1299 Which you could then use in DBI code like so:
1301 my $sth = $dbh->prepare($stmt);
1302 $sth->execute(@bind);
1308 The functions are simple. There's one for each major SQL operation,
1309 and a constructor you use first. The arguments are specified in a
1310 similar order to each function (table, then fields, then a where
1311 clause) to try and simplify things.
1316 =head2 new(option => 'value')
1318 The C<new()> function takes a list of options and values, and returns
1319 a new B<SQL::Abstract> object which can then be used to generate SQL
1320 through the methods below. The options accepted are:
1326 If set to 'lower', then SQL will be generated in all lowercase. By
1327 default SQL is generated in "textbook" case meaning something like:
1329 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1331 Any setting other than 'lower' is ignored.
1335 This determines what the default comparison operator is. By default
1336 it is C<=>, meaning that a hash like this:
1338 %where = (name => 'nwiger', email => 'nate@wiger.org');
1340 Will generate SQL like this:
1342 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1344 However, you may want loose comparisons by default, so if you set
1345 C<cmp> to C<like> you would get SQL such as:
1347 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1349 You can also override the comparsion on an individual basis - see
1350 the huge section on L</"WHERE CLAUSES"> at the bottom.
1352 =item sqltrue, sqlfalse
1354 Expressions for inserting boolean values within SQL statements.
1355 By default these are C<1=1> and C<1=0>. They are used
1356 by the special operators C<-in> and C<-not_in> for generating
1357 correct SQL even when the argument is an empty array (see below).
1361 This determines the default logical operator for multiple WHERE
1362 statements in arrays or hashes. If absent, the default logic is "or"
1363 for arrays, and "and" for hashes. This means that a WHERE
1367 event_date => {'>=', '2/13/99'},
1368 event_date => {'<=', '4/24/03'},
1371 will generate SQL like this:
1373 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1375 This is probably not what you want given this query, though (look
1376 at the dates). To change the "OR" to an "AND", simply specify:
1378 my $sql = SQL::Abstract->new(logic => 'and');
1380 Which will change the above C<WHERE> to:
1382 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1384 The logic can also be changed locally by inserting
1385 a modifier in front of an arrayref :
1387 @where = (-and => [event_date => {'>=', '2/13/99'},
1388 event_date => {'<=', '4/24/03'} ]);
1390 See the L</"WHERE CLAUSES"> section for explanations.
1394 This will automatically convert comparisons using the specified SQL
1395 function for both column and value. This is mostly used with an argument
1396 of C<upper> or C<lower>, so that the SQL will have the effect of
1397 case-insensitive "searches". For example, this:
1399 $sql = SQL::Abstract->new(convert => 'upper');
1400 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1402 Will turn out the following SQL:
1404 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1406 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1407 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1408 not validate this option; it will just pass through what you specify verbatim).
1412 This is a kludge because many databases suck. For example, you can't
1413 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1414 Instead, you have to use C<bind_param()>:
1416 $sth->bind_param(1, 'reg data');
1417 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1419 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1420 which loses track of which field each slot refers to. Fear not.
1422 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1423 Currently, you can specify either C<normal> (default) or C<columns>. If you
1424 specify C<columns>, you will get an array that looks like this:
1426 my $sql = SQL::Abstract->new(bindtype => 'columns');
1427 my($stmt, @bind) = $sql->insert(...);
1430 [ 'column1', 'value1' ],
1431 [ 'column2', 'value2' ],
1432 [ 'column3', 'value3' ],
1435 You can then iterate through this manually, using DBI's C<bind_param()>.
1437 $sth->prepare($stmt);
1440 my($col, $data) = @$_;
1441 if ($col eq 'details' || $col eq 'comments') {
1442 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1443 } elsif ($col eq 'image') {
1444 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1446 $sth->bind_param($i, $data);
1450 $sth->execute; # execute without @bind now
1452 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1453 Basically, the advantage is still that you don't have to care which fields
1454 are or are not included. You could wrap that above C<for> loop in a simple
1455 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1456 get a layer of abstraction over manual SQL specification.
1458 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1459 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1460 will expect the bind values in this format.
1464 This is the character that a table or column name will be quoted
1465 with. By default this is an empty string, but you could set it to
1466 the character C<`>, to generate SQL like this:
1468 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1470 Alternatively, you can supply an array ref of two items, the first being the left
1471 hand quote character, and the second the right hand quote character. For
1472 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1473 that generates SQL like this:
1475 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1477 Quoting is useful if you have tables or columns names that are reserved
1478 words in your database's SQL dialect.
1482 This is the character that separates a table and column name. It is
1483 necessary to specify this when the C<quote_char> option is selected,
1484 so that tables and column names can be individually quoted like this:
1486 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1488 =item injection_guard
1490 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1491 column name specified in a query structure. This is a safety mechanism to avoid
1492 injection attacks when mishandling user input e.g.:
1494 my %condition_as_column_value_pairs = get_values_from_user();
1495 $sqla->select( ... , \%condition_as_column_value_pairs );
1497 If the expression matches an exception is thrown. Note that literal SQL
1498 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1500 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1502 =item array_datatypes
1504 When this option is true, arrayrefs in INSERT or UPDATE are
1505 interpreted as array datatypes and are passed directly
1507 When this option is false, arrayrefs are interpreted
1508 as literal SQL, just like refs to arrayrefs
1509 (but this behavior is for backwards compatibility; when writing
1510 new queries, use the "reference to arrayref" syntax
1516 Takes a reference to a list of "special operators"
1517 to extend the syntax understood by L<SQL::Abstract>.
1518 See section L</"SPECIAL OPERATORS"> for details.
1522 Takes a reference to a list of "unary operators"
1523 to extend the syntax understood by L<SQL::Abstract>.
1524 See section L</"UNARY OPERATORS"> for details.
1530 =head2 insert($table, \@values || \%fieldvals, \%options)
1532 This is the simplest function. You simply give it a table name
1533 and either an arrayref of values or hashref of field/value pairs.
1534 It returns an SQL INSERT statement and a list of bind values.
1535 See the sections on L</"Inserting and Updating Arrays"> and
1536 L</"Inserting and Updating SQL"> for information on how to insert
1537 with those data types.
1539 The optional C<\%options> hash reference may contain additional
1540 options to generate the insert SQL. Currently supported options
1547 Takes either a scalar of raw SQL fields, or an array reference of
1548 field names, and adds on an SQL C<RETURNING> statement at the end.
1549 This allows you to return data generated by the insert statement
1550 (such as row IDs) without performing another C<SELECT> statement.
1551 Note, however, this is not part of the SQL standard and may not
1552 be supported by all database engines.
1556 =head2 update($table, \%fieldvals, \%where)
1558 This takes a table, hashref of field/value pairs, and an optional
1559 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1561 See the sections on L</"Inserting and Updating Arrays"> and
1562 L</"Inserting and Updating SQL"> for information on how to insert
1563 with those data types.
1565 =head2 select($source, $fields, $where, $order)
1567 This returns a SQL SELECT statement and associated list of bind values, as
1568 specified by the arguments :
1574 Specification of the 'FROM' part of the statement.
1575 The argument can be either a plain scalar (interpreted as a table
1576 name, will be quoted), or an arrayref (interpreted as a list
1577 of table names, joined by commas, quoted), or a scalarref
1578 (literal table name, not quoted), or a ref to an arrayref
1579 (list of literal table names, joined by commas, not quoted).
1583 Specification of the list of fields to retrieve from
1585 The argument can be either an arrayref (interpreted as a list
1586 of field names, will be joined by commas and quoted), or a
1587 plain scalar (literal SQL, not quoted).
1588 Please observe that this API is not as flexible as for
1589 the first argument C<$table>, for backwards compatibility reasons.
1593 Optional argument to specify the WHERE part of the query.
1594 The argument is most often a hashref, but can also be
1595 an arrayref or plain scalar --
1596 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1600 Optional argument to specify the ORDER BY part of the query.
1601 The argument can be a scalar, a hashref or an arrayref
1602 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1608 =head2 delete($table, \%where)
1610 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1611 It returns an SQL DELETE statement and list of bind values.
1613 =head2 where(\%where, \@order)
1615 This is used to generate just the WHERE clause. For example,
1616 if you have an arbitrary data structure and know what the
1617 rest of your SQL is going to look like, but want an easy way
1618 to produce a WHERE clause, use this. It returns an SQL WHERE
1619 clause and list of bind values.
1622 =head2 values(\%data)
1624 This just returns the values from the hash C<%data>, in the same
1625 order that would be returned from any of the other above queries.
1626 Using this allows you to markedly speed up your queries if you
1627 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1629 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1631 Warning: This is an experimental method and subject to change.
1633 This returns arbitrarily generated SQL. It's a really basic shortcut.
1634 It will return two different things, depending on return context:
1636 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1637 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1639 These would return the following:
1641 # First calling form
1642 $stmt = "CREATE TABLE test (?, ?)";
1643 @bind = (field1, field2);
1645 # Second calling form
1646 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1648 Depending on what you're trying to do, it's up to you to choose the correct
1649 format. In this example, the second form is what you would want.
1653 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1657 ALTER SESSION SET nls_date_format = 'MM/YY'
1659 You get the idea. Strings get their case twiddled, but everything
1660 else remains verbatim.
1662 =head1 WHERE CLAUSES
1666 This module uses a variation on the idea from L<DBIx::Abstract>. It
1667 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1668 module is that things in arrays are OR'ed, and things in hashes
1671 The easiest way to explain is to show lots of examples. After
1672 each C<%where> hash shown, it is assumed you used:
1674 my($stmt, @bind) = $sql->where(\%where);
1676 However, note that the C<%where> hash can be used directly in any
1677 of the other functions as well, as described above.
1679 =head2 Key-value pairs
1681 So, let's get started. To begin, a simple hash:
1685 status => 'completed'
1688 Is converted to SQL C<key = val> statements:
1690 $stmt = "WHERE user = ? AND status = ?";
1691 @bind = ('nwiger', 'completed');
1693 One common thing I end up doing is having a list of values that
1694 a field can be in. To do this, simply specify a list inside of
1699 status => ['assigned', 'in-progress', 'pending'];
1702 This simple code will create the following:
1704 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1705 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1707 A field associated to an empty arrayref will be considered a
1708 logical false and will generate 0=1.
1710 =head2 Tests for NULL values
1712 If the value part is C<undef> then this is converted to SQL <IS NULL>
1721 $stmt = "WHERE user = ? AND status IS NULL";
1724 To test if a column IS NOT NULL:
1728 status => { '!=', undef },
1731 =head2 Specific comparison operators
1733 If you want to specify a different type of operator for your comparison,
1734 you can use a hashref for a given column:
1738 status => { '!=', 'completed' }
1741 Which would generate:
1743 $stmt = "WHERE user = ? AND status != ?";
1744 @bind = ('nwiger', 'completed');
1746 To test against multiple values, just enclose the values in an arrayref:
1748 status => { '=', ['assigned', 'in-progress', 'pending'] };
1750 Which would give you:
1752 "WHERE status = ? OR status = ? OR status = ?"
1755 The hashref can also contain multiple pairs, in which case it is expanded
1756 into an C<AND> of its elements:
1760 status => { '!=', 'completed', -not_like => 'pending%' }
1763 # Or more dynamically, like from a form
1764 $where{user} = 'nwiger';
1765 $where{status}{'!='} = 'completed';
1766 $where{status}{'-not_like'} = 'pending%';
1768 # Both generate this
1769 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1770 @bind = ('nwiger', 'completed', 'pending%');
1773 To get an OR instead, you can combine it with the arrayref idea:
1777 priority => [ { '=', 2 }, { '>', 5 } ]
1780 Which would generate:
1782 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1783 @bind = ('2', '5', 'nwiger');
1785 If you want to include literal SQL (with or without bind values), just use a
1786 scalar reference or array reference as the value:
1789 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1790 date_expires => { '<' => \"now()" }
1793 Which would generate:
1795 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1796 @bind = ('11/26/2008');
1799 =head2 Logic and nesting operators
1801 In the example above,
1802 there is a subtle trap if you want to say something like
1803 this (notice the C<AND>):
1805 WHERE priority != ? AND priority != ?
1807 Because, in Perl you I<can't> do this:
1809 priority => { '!=', 2, '!=', 1 }
1811 As the second C<!=> key will obliterate the first. The solution
1812 is to use the special C<-modifier> form inside an arrayref:
1814 priority => [ -and => {'!=', 2},
1818 Normally, these would be joined by C<OR>, but the modifier tells it
1819 to use C<AND> instead. (Hint: You can use this in conjunction with the
1820 C<logic> option to C<new()> in order to change the way your queries
1821 work by default.) B<Important:> Note that the C<-modifier> goes
1822 B<INSIDE> the arrayref, as an extra first element. This will
1823 B<NOT> do what you think it might:
1825 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1827 Here is a quick list of equivalencies, since there is some overlap:
1830 status => {'!=', 'completed', 'not like', 'pending%' }
1831 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1834 status => {'=', ['assigned', 'in-progress']}
1835 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1836 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1840 =head2 Special operators : IN, BETWEEN, etc.
1842 You can also use the hashref format to compare a list of fields using the
1843 C<IN> comparison operator, by specifying the list as an arrayref:
1846 status => 'completed',
1847 reportid => { -in => [567, 2335, 2] }
1850 Which would generate:
1852 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1853 @bind = ('completed', '567', '2335', '2');
1855 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1858 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1859 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1860 'sqltrue' (by default : C<1=1>).
1862 In addition to the array you can supply a chunk of literal sql or
1863 literal sql with bind:
1866 customer => { -in => \[
1867 'SELECT cust_id FROM cust WHERE balance > ?',
1870 status => { -in => \'SELECT status_codes FROM states' },
1876 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1877 AND status IN ( SELECT status_codes FROM states )
1883 Another pair of operators is C<-between> and C<-not_between>,
1884 used with an arrayref of two values:
1888 completion_date => {
1889 -not_between => ['2002-10-01', '2003-02-06']
1895 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1897 Just like with C<-in> all plausible combinations of literal SQL
1901 start0 => { -between => [ 1, 2 ] },
1902 start1 => { -between => \["? AND ?", 1, 2] },
1903 start2 => { -between => \"lower(x) AND upper(y)" },
1904 start3 => { -between => [
1906 \["upper(?)", 'stuff' ],
1913 ( start0 BETWEEN ? AND ? )
1914 AND ( start1 BETWEEN ? AND ? )
1915 AND ( start2 BETWEEN lower(x) AND upper(y) )
1916 AND ( start3 BETWEEN lower(x) AND upper(?) )
1918 @bind = (1, 2, 1, 2, 'stuff');
1921 These are the two builtin "special operators"; but the
1922 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1924 =head2 Unary operators: bool
1926 If you wish to test against boolean columns or functions within your
1927 database you can use the C<-bool> and C<-not_bool> operators. For
1928 example to test the column C<is_user> being true and the column
1929 C<is_enabled> being false you would use:-
1933 -not_bool => 'is_enabled',
1938 WHERE is_user AND NOT is_enabled
1940 If a more complex combination is required, testing more conditions,
1941 then you should use the and/or operators:-
1948 -not_bool => 'four',
1954 WHERE one AND two AND three AND NOT four
1957 =head2 Nested conditions, -and/-or prefixes
1959 So far, we've seen how multiple conditions are joined with a top-level
1960 C<AND>. We can change this by putting the different conditions we want in
1961 hashes and then putting those hashes in an array. For example:
1966 status => { -like => ['pending%', 'dispatched'] },
1970 status => 'unassigned',
1974 This data structure would create the following:
1976 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1977 OR ( user = ? AND status = ? ) )";
1978 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1981 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
1982 to change the logic inside :
1988 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1989 -or => { workhrs => {'<', 50}, geo => 'EURO' },
1996 WHERE ( user = ? AND (
1997 ( workhrs > ? AND geo = ? )
1998 OR ( workhrs < ? OR geo = ? )
2001 =head3 Algebraic inconsistency, for historical reasons
2003 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2004 operator goes C<outside> of the nested structure; whereas when connecting
2005 several constraints on one column, the C<-and> operator goes
2006 C<inside> the arrayref. Here is an example combining both features :
2009 -and => [a => 1, b => 2],
2010 -or => [c => 3, d => 4],
2011 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2016 WHERE ( ( ( a = ? AND b = ? )
2017 OR ( c = ? OR d = ? )
2018 OR ( e LIKE ? AND e LIKE ? ) ) )
2020 This difference in syntax is unfortunate but must be preserved for
2021 historical reasons. So be careful : the two examples below would
2022 seem algebraically equivalent, but they are not
2024 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2025 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2027 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2028 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2031 =head2 Literal SQL and value type operators
2033 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2034 side" is a column name and the "right side" is a value (normally rendered as
2035 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2036 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2037 alter this behavior. There are several ways of doing so.
2041 This is a virtual operator that signals the string to its right side is an
2042 identifier (a column name) and not a value. For example to compare two
2043 columns you would write:
2046 priority => { '<', 2 },
2047 requestor => { -ident => 'submitter' },
2052 $stmt = "WHERE priority < ? AND requestor = submitter";
2055 If you are maintaining legacy code you may see a different construct as
2056 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2061 This is a virtual operator that signals that the construct to its right side
2062 is a value to be passed to DBI. This is for example necessary when you want
2063 to write a where clause against an array (for RDBMS that support such
2064 datatypes). For example:
2067 array => { -value => [1, 2, 3] }
2072 $stmt = 'WHERE array = ?';
2073 @bind = ([1, 2, 3]);
2075 Note that if you were to simply say:
2081 the result would porbably be not what you wanted:
2083 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2088 Finally, sometimes only literal SQL will do. To include a random snippet
2089 of SQL verbatim, you specify it as a scalar reference. Consider this only
2090 as a last resort. Usually there is a better way. For example:
2093 priority => { '<', 2 },
2094 requestor => { -in => \'(SELECT name FROM hitmen)' },
2099 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2102 Note that in this example, you only get one bind parameter back, since
2103 the verbatim SQL is passed as part of the statement.
2107 Never use untrusted input as a literal SQL argument - this is a massive
2108 security risk (there is no way to check literal snippets for SQL
2109 injections and other nastyness). If you need to deal with untrusted input
2110 use literal SQL with placeholders as described next.
2112 =head3 Literal SQL with placeholders and bind values (subqueries)
2114 If the literal SQL to be inserted has placeholders and bind values,
2115 use a reference to an arrayref (yes this is a double reference --
2116 not so common, but perfectly legal Perl). For example, to find a date
2117 in Postgres you can use something like this:
2120 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2125 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2128 Note that you must pass the bind values in the same format as they are returned
2129 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2130 provide the bind values in the C<< [ column_meta => value ] >> format, where
2131 C<column_meta> is an opaque scalar value; most commonly the column name, but
2132 you can use any scalar value (including references and blessed references),
2133 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2134 to C<columns> the above example will look like:
2137 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2140 Literal SQL is especially useful for nesting parenthesized clauses in the
2141 main SQL query. Here is a first example :
2143 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2147 bar => \["IN ($sub_stmt)" => @sub_bind],
2152 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2153 WHERE c2 < ? AND c3 LIKE ?))";
2154 @bind = (1234, 100, "foo%");
2156 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2157 are expressed in the same way. Of course the C<$sub_stmt> and
2158 its associated bind values can be generated through a former call
2161 my ($sub_stmt, @sub_bind)
2162 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2163 c3 => {-like => "foo%"}});
2166 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2169 In the examples above, the subquery was used as an operator on a column;
2170 but the same principle also applies for a clause within the main C<%where>
2171 hash, like an EXISTS subquery :
2173 my ($sub_stmt, @sub_bind)
2174 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2175 my %where = ( -and => [
2177 \["EXISTS ($sub_stmt)" => @sub_bind],
2182 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2183 WHERE c1 = ? AND c2 > t0.c0))";
2187 Observe that the condition on C<c2> in the subquery refers to
2188 column C<t0.c0> of the main query : this is I<not> a bind
2189 value, so we have to express it through a scalar ref.
2190 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2191 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2192 what we wanted here.
2194 Finally, here is an example where a subquery is used
2195 for expressing unary negation:
2197 my ($sub_stmt, @sub_bind)
2198 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2199 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2201 lname => {like => '%son%'},
2202 \["NOT ($sub_stmt)" => @sub_bind],
2207 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2208 @bind = ('%son%', 10, 20)
2210 =head3 Deprecated usage of Literal SQL
2212 Below are some examples of archaic use of literal SQL. It is shown only as
2213 reference for those who deal with legacy code. Each example has a much
2214 better, cleaner and safer alternative that users should opt for in new code.
2220 my %where = ( requestor => \'IS NOT NULL' )
2222 $stmt = "WHERE requestor IS NOT NULL"
2224 This used to be the way of generating NULL comparisons, before the handling
2225 of C<undef> got formalized. For new code please use the superior syntax as
2226 described in L</Tests for NULL values>.
2230 my %where = ( requestor => \'= submitter' )
2232 $stmt = "WHERE requestor = submitter"
2234 This used to be the only way to compare columns. Use the superior L</-ident>
2235 method for all new code. For example an identifier declared in such a way
2236 will be properly quoted if L</quote_char> is properly set, while the legacy
2237 form will remain as supplied.
2241 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2243 $stmt = "WHERE completed > ? AND is_ready"
2244 @bind = ('2012-12-21')
2246 Using an empty string literal used to be the only way to express a boolean.
2247 For all new code please use the much more readable
2248 L<-bool|/Unary operators: bool> operator.
2254 These pages could go on for a while, since the nesting of the data
2255 structures this module can handle are pretty much unlimited (the
2256 module implements the C<WHERE> expansion as a recursive function
2257 internally). Your best bet is to "play around" with the module a
2258 little to see how the data structures behave, and choose the best
2259 format for your data based on that.
2261 And of course, all the values above will probably be replaced with
2262 variables gotten from forms or the command line. After all, if you
2263 knew everything ahead of time, you wouldn't have to worry about
2264 dynamically-generating SQL and could just hardwire it into your
2267 =head1 ORDER BY CLAUSES
2269 Some functions take an order by clause. This can either be a scalar (just a
2270 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2271 or an array of either of the two previous forms. Examples:
2273 Given | Will Generate
2274 ----------------------------------------------------------
2276 \'colA DESC' | ORDER BY colA DESC
2278 'colA' | ORDER BY colA
2280 [qw/colA colB/] | ORDER BY colA, colB
2282 {-asc => 'colA'} | ORDER BY colA ASC
2284 {-desc => 'colB'} | ORDER BY colB DESC
2286 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2288 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2291 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2292 { -desc => [qw/colB/], | colC ASC, colD ASC
2293 { -asc => [qw/colC colD/],|
2295 ===========================================================
2299 =head1 SPECIAL OPERATORS
2301 my $sqlmaker = SQL::Abstract->new(special_ops => [
2305 my ($self, $field, $op, $arg) = @_;
2311 handler => 'method_name',
2315 A "special operator" is a SQL syntactic clause that can be
2316 applied to a field, instead of a usual binary operator.
2319 WHERE field IN (?, ?, ?)
2320 WHERE field BETWEEN ? AND ?
2321 WHERE MATCH(field) AGAINST (?, ?)
2323 Special operators IN and BETWEEN are fairly standard and therefore
2324 are builtin within C<SQL::Abstract> (as the overridable methods
2325 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2326 like the MATCH .. AGAINST example above which is specific to MySQL,
2327 you can write your own operator handlers - supply a C<special_ops>
2328 argument to the C<new> method. That argument takes an arrayref of
2329 operator definitions; each operator definition is a hashref with two
2336 the regular expression to match the operator
2340 Either a coderef or a plain scalar method name. In both cases
2341 the expected return is C<< ($sql, @bind) >>.
2343 When supplied with a method name, it is simply called on the
2344 L<SQL::Abstract/> object as:
2346 $self->$method_name ($field, $op, $arg)
2350 $op is the part that matched the handler regex
2351 $field is the LHS of the operator
2354 When supplied with a coderef, it is called as:
2356 $coderef->($self, $field, $op, $arg)
2361 For example, here is an implementation
2362 of the MATCH .. AGAINST syntax for MySQL
2364 my $sqlmaker = SQL::Abstract->new(special_ops => [
2366 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2367 {regex => qr/^match$/i,
2369 my ($self, $field, $op, $arg) = @_;
2370 $arg = [$arg] if not ref $arg;
2371 my $label = $self->_quote($field);
2372 my ($placeholder) = $self->_convert('?');
2373 my $placeholders = join ", ", (($placeholder) x @$arg);
2374 my $sql = $self->_sqlcase('match') . " ($label) "
2375 . $self->_sqlcase('against') . " ($placeholders) ";
2376 my @bind = $self->_bindtype($field, @$arg);
2377 return ($sql, @bind);
2384 =head1 UNARY OPERATORS
2386 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2390 my ($self, $op, $arg) = @_;
2396 handler => 'method_name',
2400 A "unary operator" is a SQL syntactic clause that can be
2401 applied to a field - the operator goes before the field
2403 You can write your own operator handlers - supply a C<unary_ops>
2404 argument to the C<new> method. That argument takes an arrayref of
2405 operator definitions; each operator definition is a hashref with two
2412 the regular expression to match the operator
2416 Either a coderef or a plain scalar method name. In both cases
2417 the expected return is C<< $sql >>.
2419 When supplied with a method name, it is simply called on the
2420 L<SQL::Abstract/> object as:
2422 $self->$method_name ($op, $arg)
2426 $op is the part that matched the handler regex
2427 $arg is the RHS or argument of the operator
2429 When supplied with a coderef, it is called as:
2431 $coderef->($self, $op, $arg)
2439 Thanks to some benchmarking by Mark Stosberg, it turns out that
2440 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2441 I must admit this wasn't an intentional design issue, but it's a
2442 byproduct of the fact that you get to control your C<DBI> handles
2445 To maximize performance, use a code snippet like the following:
2447 # prepare a statement handle using the first row
2448 # and then reuse it for the rest of the rows
2450 for my $href (@array_of_hashrefs) {
2451 $stmt ||= $sql->insert('table', $href);
2452 $sth ||= $dbh->prepare($stmt);
2453 $sth->execute($sql->values($href));
2456 The reason this works is because the keys in your C<$href> are sorted
2457 internally by B<SQL::Abstract>. Thus, as long as your data retains
2458 the same structure, you only have to generate the SQL the first time
2459 around. On subsequent queries, simply use the C<values> function provided
2460 by this module to return your values in the correct order.
2462 However this depends on the values having the same type - if, for
2463 example, the values of a where clause may either have values
2464 (resulting in sql of the form C<column = ?> with a single bind
2465 value), or alternatively the values might be C<undef> (resulting in
2466 sql of the form C<column IS NULL> with no bind value) then the
2467 caching technique suggested will not work.
2471 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2472 really like this part (I do, at least). Building up a complex query
2473 can be as simple as the following:
2477 use CGI::FormBuilder;
2480 my $form = CGI::FormBuilder->new(...);
2481 my $sql = SQL::Abstract->new;
2483 if ($form->submitted) {
2484 my $field = $form->field;
2485 my $id = delete $field->{id};
2486 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2489 Of course, you would still have to connect using C<DBI> to run the
2490 query, but the point is that if you make your form look like your
2491 table, the actual query script can be extremely simplistic.
2493 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2494 a fast interface to returning and formatting data. I frequently
2495 use these three modules together to write complex database query
2496 apps in under 50 lines.
2502 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2504 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2510 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2511 Great care has been taken to preserve the I<published> behavior
2512 documented in previous versions in the 1.* family; however,
2513 some features that were previously undocumented, or behaved
2514 differently from the documentation, had to be changed in order
2515 to clarify the semantics. Hence, client code that was relying
2516 on some dark areas of C<SQL::Abstract> v1.*
2517 B<might behave differently> in v1.50.
2519 The main changes are :
2525 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2529 support for the { operator => \"..." } construct (to embed literal SQL)
2533 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2537 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2541 defensive programming : check arguments
2545 fixed bug with global logic, which was previously implemented
2546 through global variables yielding side-effects. Prior versions would
2547 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2548 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2549 Now this is interpreted
2550 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2555 fixed semantics of _bindtype on array args
2559 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2560 we just avoid shifting arrays within that tree.
2564 dropped the C<_modlogic> function
2568 =head1 ACKNOWLEDGEMENTS
2570 There are a number of individuals that have really helped out with
2571 this module. Unfortunately, most of them submitted bugs via CPAN
2572 so I have no idea who they are! But the people I do know are:
2574 Ash Berlin (order_by hash term support)
2575 Matt Trout (DBIx::Class support)
2576 Mark Stosberg (benchmarking)
2577 Chas Owens (initial "IN" operator support)
2578 Philip Collins (per-field SQL functions)
2579 Eric Kolve (hashref "AND" support)
2580 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2581 Dan Kubb (support for "quote_char" and "name_sep")
2582 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2583 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2584 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2585 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2586 Oliver Charles (support for "RETURNING" after "INSERT")
2592 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2596 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2598 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2600 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2601 While not an official support venue, C<DBIx::Class> makes heavy use of
2602 C<SQL::Abstract>, and as such list members there are very familiar with
2603 how to create queries.
2607 This module is free software; you may copy this under the same
2608 terms as perl itself (either the GNU General Public License or
2609 the Artistic License)