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) = @_;
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] =~ /-(.*)/) {
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 (uc((keys %$v)[0]), (values %$v)[0]);
686 s/^-//, s/_/ /g for $op;
687 if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
688 if (ref($rhs) ne 'ARRAY') {
690 # have to add parens if none present because -in => \"SELECT ..."
691 # got documented. mst hates everything.
692 if (ref($rhs) eq 'SCALAR') {
694 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
697 my ($x, @rest) = @{$$rhs};
698 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
699 $rhs = \[ $x, @rest ];
702 return $self->_op_to_dq(
703 $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
706 return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
707 return $self->_op_to_dq(
708 $op, $self->_ident_to_dq($k), map $self->_where_to_dq($_), @$rhs
710 } elsif ($op =~ s/^NOT (?!LIKE)//) {
711 return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
712 } elsif (!defined($rhs)) {
714 if ($op eq '=' or $op eq 'LIKE') {
716 } elsif ($op eq '!=') {
719 die "Can't do undef -> NULL transform for operator ${op}";
722 return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
724 if (ref($rhs) eq 'ARRAY') {
726 return $self->_literal_to_dq(
727 $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
729 } elsif (defined($rhs->[0]) and $rhs->[0] =~ /-(and|or)/i) {
730 return $self->_where_to_dq_ARRAYREF([
731 map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
734 return $self->_where_to_dq_ARRAYREF([
735 map +{ $k => { $op => $_ } }, @$rhs
738 return $self->_op_to_dq(
739 $op, $self->_ident_to_dq($k), $self->_where_to_dq($rhs)
744 #======================================================================
746 #======================================================================
749 my ($self, $arg) = @_;
750 if (my $dq = $self->_order_by_to_dq($arg)) {
751 # SQLA generates ' ORDER BY foo'. The hilarity.
753 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
754 : ' '.$self->_render_dq($dq);
760 sub _order_by_to_dq {
761 my ($self, $arg, $dir) = @_;
767 ($dir ? (direction => $dir) : ()),
771 $dq->{by} = $self->_ident_to_dq($arg);
772 } elsif (ref($arg) eq 'ARRAY') {
774 local our $Order_Inner unless our $Order_Recursing;
775 local $Order_Recursing = 1;
777 foreach my $member (@$arg) {
779 my $next = $self->_order_by_to_dq($member, $dir);
781 $inner->{from} = $next if $inner;
782 $inner = $Order_Inner || $next;
784 $Order_Inner = $inner;
786 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
787 $dq->{by} = $self->_literal_to_dq($$arg);
788 } elsif (ref($arg) eq 'SCALAR') {
789 $dq->{by} = $self->_literal_to_dq($$arg);
790 } elsif (ref($arg) eq 'HASH') {
791 my ($key, $val, @rest) = %$arg;
795 if (@rest or not $key =~ /^-(desc|asc)/i) {
796 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
799 return $self->_order_by_to_dq($val, $dir);
801 die "Can't handle $arg in _order_by_to_dq";
806 #======================================================================
807 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
808 #======================================================================
811 my ($self, $from) = @_;
812 $self->_render_dq($self->_table_to_dq($from));
816 my ($self, $from) = @_;
817 $self->_SWITCH_refkind($from, {
819 die "Empty FROM list" unless my @f = @$from;
820 my $dq = $self->_ident_to_dq(shift @f);
821 while (my $x = shift @f) {
824 join => [ $dq, $self->_ident_to_dq($x) ]
829 SCALAR => sub { $self->_ident_to_dq($from) },
841 #======================================================================
843 #======================================================================
845 # highly optimized, as it's called way too often
847 # my ($self, $label) = @_;
849 return '' unless defined $_[1];
850 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
852 unless ($_[0]->{quote_char}) {
853 $_[0]->_assert_pass_injection_guard($_[1]);
857 my $qref = ref $_[0]->{quote_char};
860 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
862 elsif ($qref eq 'ARRAY') {
863 ($l, $r) = @{$_[0]->{quote_char}};
866 puke "Unsupported quote_char format: $_[0]->{quote_char}";
869 # parts containing * are naturally unquoted
870 return join( $_[0]->{name_sep}||'', map
871 { $_ eq '*' ? $_ : $l . $_ . $r }
872 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
877 # Conversion, if applicable
879 #my ($self, $arg) = @_;
881 # LDNOTE : modified the previous implementation below because
882 # it was not consistent : the first "return" is always an array,
883 # the second "return" is context-dependent. Anyway, _convert
884 # seems always used with just a single argument, so make it a
886 # return @_ unless $self->{convert};
887 # my $conv = $self->_sqlcase($self->{convert});
888 # my @ret = map { $conv.'('.$_.')' } @_;
889 # return wantarray ? @ret : $ret[0];
890 if ($_[0]->{convert}) {
891 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
898 #my ($self, $col, @vals) = @_;
900 #LDNOTE : changed original implementation below because it did not make
901 # sense when bindtype eq 'columns' and @vals > 1.
902 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
904 # called often - tighten code
905 return $_[0]->{bindtype} eq 'columns'
906 ? map {[$_[1], $_]} @_[2 .. $#_]
911 # Dies if any element of @bind is not in [colname => value] format
912 # if bindtype is 'columns'.
913 sub _assert_bindval_matches_bindtype {
914 # my ($self, @bind) = @_;
916 if ($self->{bindtype} eq 'columns') {
918 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
919 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
925 sub _join_sql_clauses {
926 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
928 if (@$clauses_aref > 1) {
929 my $join = " " . $self->_sqlcase($logic) . " ";
930 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
931 return ($sql, @$bind_aref);
933 elsif (@$clauses_aref) {
934 return ($clauses_aref->[0], @$bind_aref); # no parentheses
937 return (); # if no SQL, ignore @$bind_aref
942 # Fix SQL case, if so requested
944 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
945 # don't touch the argument ... crooked logic, but let's not change it!
946 return $_[0]->{case} ? $_[1] : uc($_[1]);
950 #======================================================================
951 # DISPATCHING FROM REFKIND
952 #======================================================================
955 my ($self, $data) = @_;
957 return 'UNDEF' unless defined $data;
959 # blessed objects are treated like scalars
960 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
962 return 'SCALAR' unless $ref;
965 while ($ref eq 'REF') {
967 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
971 return ($ref||'SCALAR') . ('REF' x $n_steps);
975 my ($self, $data) = @_;
976 my @try = ($self->_refkind($data));
977 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
978 push @try, 'FALLBACK';
982 sub _METHOD_FOR_refkind {
983 my ($self, $meth_prefix, $data) = @_;
986 for (@{$self->_try_refkind($data)}) {
987 $method = $self->can($meth_prefix."_".$_)
991 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
995 sub _SWITCH_refkind {
996 my ($self, $data, $dispatch_table) = @_;
999 for (@{$self->_try_refkind($data)}) {
1000 $coderef = $dispatch_table->{$_}
1004 puke "no dispatch entry for ".$self->_refkind($data)
1013 #======================================================================
1014 # VALUES, GENERATE, AUTOLOAD
1015 #======================================================================
1017 # LDNOTE: original code from nwiger, didn't touch code in that section
1018 # I feel the AUTOLOAD stuff should not be the default, it should
1019 # only be activated on explicit demand by user.
1023 my $data = shift || return;
1024 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1025 unless ref $data eq 'HASH';
1028 foreach my $k ( sort keys %$data ) {
1029 my $v = $data->{$k};
1030 $self->_SWITCH_refkind($v, {
1032 if ($self->{array_datatypes}) { # array datatype
1033 push @all_bind, $self->_bindtype($k, $v);
1035 else { # literal SQL with bind
1036 my ($sql, @bind) = @$v;
1037 $self->_assert_bindval_matches_bindtype(@bind);
1038 push @all_bind, @bind;
1041 ARRAYREFREF => sub { # literal SQL with bind
1042 my ($sql, @bind) = @${$v};
1043 $self->_assert_bindval_matches_bindtype(@bind);
1044 push @all_bind, @bind;
1046 SCALARREF => sub { # literal SQL without bind
1048 SCALAR_or_UNDEF => sub {
1049 push @all_bind, $self->_bindtype($k, $v);
1060 my(@sql, @sqlq, @sqlv);
1064 if ($ref eq 'HASH') {
1065 for my $k (sort keys %$_) {
1068 my $label = $self->_quote($k);
1069 if ($r eq 'ARRAY') {
1070 # literal SQL with bind
1071 my ($sql, @bind) = @$v;
1072 $self->_assert_bindval_matches_bindtype(@bind);
1073 push @sqlq, "$label = $sql";
1075 } elsif ($r eq 'SCALAR') {
1076 # literal SQL without bind
1077 push @sqlq, "$label = $$v";
1079 push @sqlq, "$label = ?";
1080 push @sqlv, $self->_bindtype($k, $v);
1083 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1084 } elsif ($ref eq 'ARRAY') {
1085 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1088 if ($r eq 'ARRAY') { # literal SQL with bind
1089 my ($sql, @bind) = @$v;
1090 $self->_assert_bindval_matches_bindtype(@bind);
1093 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1094 # embedded literal SQL
1101 push @sql, '(' . join(', ', @sqlq) . ')';
1102 } elsif ($ref eq 'SCALAR') {
1106 # strings get case twiddled
1107 push @sql, $self->_sqlcase($_);
1111 my $sql = join ' ', @sql;
1113 # this is pretty tricky
1114 # if ask for an array, return ($stmt, @bind)
1115 # otherwise, s/?/shift @sqlv/ to put it inline
1117 return ($sql, @sqlv);
1119 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1120 ref $d ? $d->[1] : $d/e;
1129 # This allows us to check for a local, then _form, attr
1131 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1132 return $self->generate($name, @_);
1143 SQL::Abstract - Generate SQL from Perl data structures
1149 my $sql = SQL::Abstract->new;
1151 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1153 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1155 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1157 my($stmt, @bind) = $sql->delete($table, \%where);
1159 # Then, use these in your DBI statements
1160 my $sth = $dbh->prepare($stmt);
1161 $sth->execute(@bind);
1163 # Just generate the WHERE clause
1164 my($stmt, @bind) = $sql->where(\%where, \@order);
1166 # Return values in the same order, for hashed queries
1167 # See PERFORMANCE section for more details
1168 my @bind = $sql->values(\%fieldvals);
1172 This module was inspired by the excellent L<DBIx::Abstract>.
1173 However, in using that module I found that what I really wanted
1174 to do was generate SQL, but still retain complete control over my
1175 statement handles and use the DBI interface. So, I set out to
1176 create an abstract SQL generation module.
1178 While based on the concepts used by L<DBIx::Abstract>, there are
1179 several important differences, especially when it comes to WHERE
1180 clauses. I have modified the concepts used to make the SQL easier
1181 to generate from Perl data structures and, IMO, more intuitive.
1182 The underlying idea is for this module to do what you mean, based
1183 on the data structures you provide it. The big advantage is that
1184 you don't have to modify your code every time your data changes,
1185 as this module figures it out.
1187 To begin with, an SQL INSERT is as easy as just specifying a hash
1188 of C<key=value> pairs:
1191 name => 'Jimbo Bobson',
1192 phone => '123-456-7890',
1193 address => '42 Sister Lane',
1194 city => 'St. Louis',
1195 state => 'Louisiana',
1198 The SQL can then be generated with this:
1200 my($stmt, @bind) = $sql->insert('people', \%data);
1202 Which would give you something like this:
1204 $stmt = "INSERT INTO people
1205 (address, city, name, phone, state)
1206 VALUES (?, ?, ?, ?, ?)";
1207 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1208 '123-456-7890', 'Louisiana');
1210 These are then used directly in your DBI code:
1212 my $sth = $dbh->prepare($stmt);
1213 $sth->execute(@bind);
1215 =head2 Inserting and Updating Arrays
1217 If your database has array types (like for example Postgres),
1218 activate the special option C<< array_datatypes => 1 >>
1219 when creating the C<SQL::Abstract> object.
1220 Then you may use an arrayref to insert and update database array types:
1222 my $sql = SQL::Abstract->new(array_datatypes => 1);
1224 planets => [qw/Mercury Venus Earth Mars/]
1227 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1231 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1233 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1236 =head2 Inserting and Updating SQL
1238 In order to apply SQL functions to elements of your C<%data> you may
1239 specify a reference to an arrayref for the given hash value. For example,
1240 if you need to execute the Oracle C<to_date> function on a value, you can
1241 say something like this:
1245 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1248 The first value in the array is the actual SQL. Any other values are
1249 optional and would be included in the bind values array. This gives
1252 my($stmt, @bind) = $sql->insert('people', \%data);
1254 $stmt = "INSERT INTO people (name, date_entered)
1255 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1256 @bind = ('Bill', '03/02/2003');
1258 An UPDATE is just as easy, all you change is the name of the function:
1260 my($stmt, @bind) = $sql->update('people', \%data);
1262 Notice that your C<%data> isn't touched; the module will generate
1263 the appropriately quirky SQL for you automatically. Usually you'll
1264 want to specify a WHERE clause for your UPDATE, though, which is
1265 where handling C<%where> hashes comes in handy...
1267 =head2 Complex where statements
1269 This module can generate pretty complicated WHERE statements
1270 easily. For example, simple C<key=value> pairs are taken to mean
1271 equality, and if you want to see if a field is within a set
1272 of values, you can use an arrayref. Let's say we wanted to
1273 SELECT some data based on this criteria:
1276 requestor => 'inna',
1277 worker => ['nwiger', 'rcwe', 'sfz'],
1278 status => { '!=', 'completed' }
1281 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1283 The above would give you something like this:
1285 $stmt = "SELECT * FROM tickets WHERE
1286 ( requestor = ? ) AND ( status != ? )
1287 AND ( worker = ? OR worker = ? OR worker = ? )";
1288 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1290 Which you could then use in DBI code like so:
1292 my $sth = $dbh->prepare($stmt);
1293 $sth->execute(@bind);
1299 The functions are simple. There's one for each major SQL operation,
1300 and a constructor you use first. The arguments are specified in a
1301 similar order to each function (table, then fields, then a where
1302 clause) to try and simplify things.
1307 =head2 new(option => 'value')
1309 The C<new()> function takes a list of options and values, and returns
1310 a new B<SQL::Abstract> object which can then be used to generate SQL
1311 through the methods below. The options accepted are:
1317 If set to 'lower', then SQL will be generated in all lowercase. By
1318 default SQL is generated in "textbook" case meaning something like:
1320 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1322 Any setting other than 'lower' is ignored.
1326 This determines what the default comparison operator is. By default
1327 it is C<=>, meaning that a hash like this:
1329 %where = (name => 'nwiger', email => 'nate@wiger.org');
1331 Will generate SQL like this:
1333 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1335 However, you may want loose comparisons by default, so if you set
1336 C<cmp> to C<like> you would get SQL such as:
1338 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1340 You can also override the comparsion on an individual basis - see
1341 the huge section on L</"WHERE CLAUSES"> at the bottom.
1343 =item sqltrue, sqlfalse
1345 Expressions for inserting boolean values within SQL statements.
1346 By default these are C<1=1> and C<1=0>. They are used
1347 by the special operators C<-in> and C<-not_in> for generating
1348 correct SQL even when the argument is an empty array (see below).
1352 This determines the default logical operator for multiple WHERE
1353 statements in arrays or hashes. If absent, the default logic is "or"
1354 for arrays, and "and" for hashes. This means that a WHERE
1358 event_date => {'>=', '2/13/99'},
1359 event_date => {'<=', '4/24/03'},
1362 will generate SQL like this:
1364 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1366 This is probably not what you want given this query, though (look
1367 at the dates). To change the "OR" to an "AND", simply specify:
1369 my $sql = SQL::Abstract->new(logic => 'and');
1371 Which will change the above C<WHERE> to:
1373 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1375 The logic can also be changed locally by inserting
1376 a modifier in front of an arrayref :
1378 @where = (-and => [event_date => {'>=', '2/13/99'},
1379 event_date => {'<=', '4/24/03'} ]);
1381 See the L</"WHERE CLAUSES"> section for explanations.
1385 This will automatically convert comparisons using the specified SQL
1386 function for both column and value. This is mostly used with an argument
1387 of C<upper> or C<lower>, so that the SQL will have the effect of
1388 case-insensitive "searches". For example, this:
1390 $sql = SQL::Abstract->new(convert => 'upper');
1391 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1393 Will turn out the following SQL:
1395 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1397 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1398 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1399 not validate this option; it will just pass through what you specify verbatim).
1403 This is a kludge because many databases suck. For example, you can't
1404 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1405 Instead, you have to use C<bind_param()>:
1407 $sth->bind_param(1, 'reg data');
1408 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1410 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1411 which loses track of which field each slot refers to. Fear not.
1413 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1414 Currently, you can specify either C<normal> (default) or C<columns>. If you
1415 specify C<columns>, you will get an array that looks like this:
1417 my $sql = SQL::Abstract->new(bindtype => 'columns');
1418 my($stmt, @bind) = $sql->insert(...);
1421 [ 'column1', 'value1' ],
1422 [ 'column2', 'value2' ],
1423 [ 'column3', 'value3' ],
1426 You can then iterate through this manually, using DBI's C<bind_param()>.
1428 $sth->prepare($stmt);
1431 my($col, $data) = @$_;
1432 if ($col eq 'details' || $col eq 'comments') {
1433 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1434 } elsif ($col eq 'image') {
1435 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1437 $sth->bind_param($i, $data);
1441 $sth->execute; # execute without @bind now
1443 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1444 Basically, the advantage is still that you don't have to care which fields
1445 are or are not included. You could wrap that above C<for> loop in a simple
1446 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1447 get a layer of abstraction over manual SQL specification.
1449 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1450 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1451 will expect the bind values in this format.
1455 This is the character that a table or column name will be quoted
1456 with. By default this is an empty string, but you could set it to
1457 the character C<`>, to generate SQL like this:
1459 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1461 Alternatively, you can supply an array ref of two items, the first being the left
1462 hand quote character, and the second the right hand quote character. For
1463 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1464 that generates SQL like this:
1466 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1468 Quoting is useful if you have tables or columns names that are reserved
1469 words in your database's SQL dialect.
1473 This is the character that separates a table and column name. It is
1474 necessary to specify this when the C<quote_char> option is selected,
1475 so that tables and column names can be individually quoted like this:
1477 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1479 =item injection_guard
1481 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1482 column name specified in a query structure. This is a safety mechanism to avoid
1483 injection attacks when mishandling user input e.g.:
1485 my %condition_as_column_value_pairs = get_values_from_user();
1486 $sqla->select( ... , \%condition_as_column_value_pairs );
1488 If the expression matches an exception is thrown. Note that literal SQL
1489 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1491 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1493 =item array_datatypes
1495 When this option is true, arrayrefs in INSERT or UPDATE are
1496 interpreted as array datatypes and are passed directly
1498 When this option is false, arrayrefs are interpreted
1499 as literal SQL, just like refs to arrayrefs
1500 (but this behavior is for backwards compatibility; when writing
1501 new queries, use the "reference to arrayref" syntax
1507 Takes a reference to a list of "special operators"
1508 to extend the syntax understood by L<SQL::Abstract>.
1509 See section L</"SPECIAL OPERATORS"> for details.
1513 Takes a reference to a list of "unary operators"
1514 to extend the syntax understood by L<SQL::Abstract>.
1515 See section L</"UNARY OPERATORS"> for details.
1521 =head2 insert($table, \@values || \%fieldvals, \%options)
1523 This is the simplest function. You simply give it a table name
1524 and either an arrayref of values or hashref of field/value pairs.
1525 It returns an SQL INSERT statement and a list of bind values.
1526 See the sections on L</"Inserting and Updating Arrays"> and
1527 L</"Inserting and Updating SQL"> for information on how to insert
1528 with those data types.
1530 The optional C<\%options> hash reference may contain additional
1531 options to generate the insert SQL. Currently supported options
1538 Takes either a scalar of raw SQL fields, or an array reference of
1539 field names, and adds on an SQL C<RETURNING> statement at the end.
1540 This allows you to return data generated by the insert statement
1541 (such as row IDs) without performing another C<SELECT> statement.
1542 Note, however, this is not part of the SQL standard and may not
1543 be supported by all database engines.
1547 =head2 update($table, \%fieldvals, \%where)
1549 This takes a table, hashref of field/value pairs, and an optional
1550 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1552 See the sections on L</"Inserting and Updating Arrays"> and
1553 L</"Inserting and Updating SQL"> for information on how to insert
1554 with those data types.
1556 =head2 select($source, $fields, $where, $order)
1558 This returns a SQL SELECT statement and associated list of bind values, as
1559 specified by the arguments :
1565 Specification of the 'FROM' part of the statement.
1566 The argument can be either a plain scalar (interpreted as a table
1567 name, will be quoted), or an arrayref (interpreted as a list
1568 of table names, joined by commas, quoted), or a scalarref
1569 (literal table name, not quoted), or a ref to an arrayref
1570 (list of literal table names, joined by commas, not quoted).
1574 Specification of the list of fields to retrieve from
1576 The argument can be either an arrayref (interpreted as a list
1577 of field names, will be joined by commas and quoted), or a
1578 plain scalar (literal SQL, not quoted).
1579 Please observe that this API is not as flexible as for
1580 the first argument C<$table>, for backwards compatibility reasons.
1584 Optional argument to specify the WHERE part of the query.
1585 The argument is most often a hashref, but can also be
1586 an arrayref or plain scalar --
1587 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1591 Optional argument to specify the ORDER BY part of the query.
1592 The argument can be a scalar, a hashref or an arrayref
1593 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1599 =head2 delete($table, \%where)
1601 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1602 It returns an SQL DELETE statement and list of bind values.
1604 =head2 where(\%where, \@order)
1606 This is used to generate just the WHERE clause. For example,
1607 if you have an arbitrary data structure and know what the
1608 rest of your SQL is going to look like, but want an easy way
1609 to produce a WHERE clause, use this. It returns an SQL WHERE
1610 clause and list of bind values.
1613 =head2 values(\%data)
1615 This just returns the values from the hash C<%data>, in the same
1616 order that would be returned from any of the other above queries.
1617 Using this allows you to markedly speed up your queries if you
1618 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1620 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1622 Warning: This is an experimental method and subject to change.
1624 This returns arbitrarily generated SQL. It's a really basic shortcut.
1625 It will return two different things, depending on return context:
1627 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1628 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1630 These would return the following:
1632 # First calling form
1633 $stmt = "CREATE TABLE test (?, ?)";
1634 @bind = (field1, field2);
1636 # Second calling form
1637 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1639 Depending on what you're trying to do, it's up to you to choose the correct
1640 format. In this example, the second form is what you would want.
1644 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1648 ALTER SESSION SET nls_date_format = 'MM/YY'
1650 You get the idea. Strings get their case twiddled, but everything
1651 else remains verbatim.
1653 =head1 WHERE CLAUSES
1657 This module uses a variation on the idea from L<DBIx::Abstract>. It
1658 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1659 module is that things in arrays are OR'ed, and things in hashes
1662 The easiest way to explain is to show lots of examples. After
1663 each C<%where> hash shown, it is assumed you used:
1665 my($stmt, @bind) = $sql->where(\%where);
1667 However, note that the C<%where> hash can be used directly in any
1668 of the other functions as well, as described above.
1670 =head2 Key-value pairs
1672 So, let's get started. To begin, a simple hash:
1676 status => 'completed'
1679 Is converted to SQL C<key = val> statements:
1681 $stmt = "WHERE user = ? AND status = ?";
1682 @bind = ('nwiger', 'completed');
1684 One common thing I end up doing is having a list of values that
1685 a field can be in. To do this, simply specify a list inside of
1690 status => ['assigned', 'in-progress', 'pending'];
1693 This simple code will create the following:
1695 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1696 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1698 A field associated to an empty arrayref will be considered a
1699 logical false and will generate 0=1.
1701 =head2 Tests for NULL values
1703 If the value part is C<undef> then this is converted to SQL <IS NULL>
1712 $stmt = "WHERE user = ? AND status IS NULL";
1715 To test if a column IS NOT NULL:
1719 status => { '!=', undef },
1722 =head2 Specific comparison operators
1724 If you want to specify a different type of operator for your comparison,
1725 you can use a hashref for a given column:
1729 status => { '!=', 'completed' }
1732 Which would generate:
1734 $stmt = "WHERE user = ? AND status != ?";
1735 @bind = ('nwiger', 'completed');
1737 To test against multiple values, just enclose the values in an arrayref:
1739 status => { '=', ['assigned', 'in-progress', 'pending'] };
1741 Which would give you:
1743 "WHERE status = ? OR status = ? OR status = ?"
1746 The hashref can also contain multiple pairs, in which case it is expanded
1747 into an C<AND> of its elements:
1751 status => { '!=', 'completed', -not_like => 'pending%' }
1754 # Or more dynamically, like from a form
1755 $where{user} = 'nwiger';
1756 $where{status}{'!='} = 'completed';
1757 $where{status}{'-not_like'} = 'pending%';
1759 # Both generate this
1760 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1761 @bind = ('nwiger', 'completed', 'pending%');
1764 To get an OR instead, you can combine it with the arrayref idea:
1768 priority => [ { '=', 2 }, { '>', 5 } ]
1771 Which would generate:
1773 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1774 @bind = ('2', '5', 'nwiger');
1776 If you want to include literal SQL (with or without bind values), just use a
1777 scalar reference or array reference as the value:
1780 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1781 date_expires => { '<' => \"now()" }
1784 Which would generate:
1786 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1787 @bind = ('11/26/2008');
1790 =head2 Logic and nesting operators
1792 In the example above,
1793 there is a subtle trap if you want to say something like
1794 this (notice the C<AND>):
1796 WHERE priority != ? AND priority != ?
1798 Because, in Perl you I<can't> do this:
1800 priority => { '!=', 2, '!=', 1 }
1802 As the second C<!=> key will obliterate the first. The solution
1803 is to use the special C<-modifier> form inside an arrayref:
1805 priority => [ -and => {'!=', 2},
1809 Normally, these would be joined by C<OR>, but the modifier tells it
1810 to use C<AND> instead. (Hint: You can use this in conjunction with the
1811 C<logic> option to C<new()> in order to change the way your queries
1812 work by default.) B<Important:> Note that the C<-modifier> goes
1813 B<INSIDE> the arrayref, as an extra first element. This will
1814 B<NOT> do what you think it might:
1816 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1818 Here is a quick list of equivalencies, since there is some overlap:
1821 status => {'!=', 'completed', 'not like', 'pending%' }
1822 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1825 status => {'=', ['assigned', 'in-progress']}
1826 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1827 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1831 =head2 Special operators : IN, BETWEEN, etc.
1833 You can also use the hashref format to compare a list of fields using the
1834 C<IN> comparison operator, by specifying the list as an arrayref:
1837 status => 'completed',
1838 reportid => { -in => [567, 2335, 2] }
1841 Which would generate:
1843 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1844 @bind = ('completed', '567', '2335', '2');
1846 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1849 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1850 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1851 'sqltrue' (by default : C<1=1>).
1853 In addition to the array you can supply a chunk of literal sql or
1854 literal sql with bind:
1857 customer => { -in => \[
1858 'SELECT cust_id FROM cust WHERE balance > ?',
1861 status => { -in => \'SELECT status_codes FROM states' },
1867 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1868 AND status IN ( SELECT status_codes FROM states )
1874 Another pair of operators is C<-between> and C<-not_between>,
1875 used with an arrayref of two values:
1879 completion_date => {
1880 -not_between => ['2002-10-01', '2003-02-06']
1886 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1888 Just like with C<-in> all plausible combinations of literal SQL
1892 start0 => { -between => [ 1, 2 ] },
1893 start1 => { -between => \["? AND ?", 1, 2] },
1894 start2 => { -between => \"lower(x) AND upper(y)" },
1895 start3 => { -between => [
1897 \["upper(?)", 'stuff' ],
1904 ( start0 BETWEEN ? AND ? )
1905 AND ( start1 BETWEEN ? AND ? )
1906 AND ( start2 BETWEEN lower(x) AND upper(y) )
1907 AND ( start3 BETWEEN lower(x) AND upper(?) )
1909 @bind = (1, 2, 1, 2, 'stuff');
1912 These are the two builtin "special operators"; but the
1913 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1915 =head2 Unary operators: bool
1917 If you wish to test against boolean columns or functions within your
1918 database you can use the C<-bool> and C<-not_bool> operators. For
1919 example to test the column C<is_user> being true and the column
1920 C<is_enabled> being false you would use:-
1924 -not_bool => 'is_enabled',
1929 WHERE is_user AND NOT is_enabled
1931 If a more complex combination is required, testing more conditions,
1932 then you should use the and/or operators:-
1939 -not_bool => 'four',
1945 WHERE one AND two AND three AND NOT four
1948 =head2 Nested conditions, -and/-or prefixes
1950 So far, we've seen how multiple conditions are joined with a top-level
1951 C<AND>. We can change this by putting the different conditions we want in
1952 hashes and then putting those hashes in an array. For example:
1957 status => { -like => ['pending%', 'dispatched'] },
1961 status => 'unassigned',
1965 This data structure would create the following:
1967 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1968 OR ( user = ? AND status = ? ) )";
1969 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1972 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
1973 to change the logic inside :
1979 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1980 -or => { workhrs => {'<', 50}, geo => 'EURO' },
1987 WHERE ( user = ? AND (
1988 ( workhrs > ? AND geo = ? )
1989 OR ( workhrs < ? OR geo = ? )
1992 =head3 Algebraic inconsistency, for historical reasons
1994 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
1995 operator goes C<outside> of the nested structure; whereas when connecting
1996 several constraints on one column, the C<-and> operator goes
1997 C<inside> the arrayref. Here is an example combining both features :
2000 -and => [a => 1, b => 2],
2001 -or => [c => 3, d => 4],
2002 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2007 WHERE ( ( ( a = ? AND b = ? )
2008 OR ( c = ? OR d = ? )
2009 OR ( e LIKE ? AND e LIKE ? ) ) )
2011 This difference in syntax is unfortunate but must be preserved for
2012 historical reasons. So be careful : the two examples below would
2013 seem algebraically equivalent, but they are not
2015 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2016 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2018 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2019 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2022 =head2 Literal SQL and value type operators
2024 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2025 side" is a column name and the "right side" is a value (normally rendered as
2026 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2027 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2028 alter this behavior. There are several ways of doing so.
2032 This is a virtual operator that signals the string to its right side is an
2033 identifier (a column name) and not a value. For example to compare two
2034 columns you would write:
2037 priority => { '<', 2 },
2038 requestor => { -ident => 'submitter' },
2043 $stmt = "WHERE priority < ? AND requestor = submitter";
2046 If you are maintaining legacy code you may see a different construct as
2047 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2052 This is a virtual operator that signals that the construct to its right side
2053 is a value to be passed to DBI. This is for example necessary when you want
2054 to write a where clause against an array (for RDBMS that support such
2055 datatypes). For example:
2058 array => { -value => [1, 2, 3] }
2063 $stmt = 'WHERE array = ?';
2064 @bind = ([1, 2, 3]);
2066 Note that if you were to simply say:
2072 the result would porbably be not what you wanted:
2074 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2079 Finally, sometimes only literal SQL will do. To include a random snippet
2080 of SQL verbatim, you specify it as a scalar reference. Consider this only
2081 as a last resort. Usually there is a better way. For example:
2084 priority => { '<', 2 },
2085 requestor => { -in => \'(SELECT name FROM hitmen)' },
2090 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2093 Note that in this example, you only get one bind parameter back, since
2094 the verbatim SQL is passed as part of the statement.
2098 Never use untrusted input as a literal SQL argument - this is a massive
2099 security risk (there is no way to check literal snippets for SQL
2100 injections and other nastyness). If you need to deal with untrusted input
2101 use literal SQL with placeholders as described next.
2103 =head3 Literal SQL with placeholders and bind values (subqueries)
2105 If the literal SQL to be inserted has placeholders and bind values,
2106 use a reference to an arrayref (yes this is a double reference --
2107 not so common, but perfectly legal Perl). For example, to find a date
2108 in Postgres you can use something like this:
2111 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2116 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2119 Note that you must pass the bind values in the same format as they are returned
2120 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2121 provide the bind values in the C<< [ column_meta => value ] >> format, where
2122 C<column_meta> is an opaque scalar value; most commonly the column name, but
2123 you can use any scalar value (including references and blessed references),
2124 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2125 to C<columns> the above example will look like:
2128 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2131 Literal SQL is especially useful for nesting parenthesized clauses in the
2132 main SQL query. Here is a first example :
2134 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2138 bar => \["IN ($sub_stmt)" => @sub_bind],
2143 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2144 WHERE c2 < ? AND c3 LIKE ?))";
2145 @bind = (1234, 100, "foo%");
2147 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2148 are expressed in the same way. Of course the C<$sub_stmt> and
2149 its associated bind values can be generated through a former call
2152 my ($sub_stmt, @sub_bind)
2153 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2154 c3 => {-like => "foo%"}});
2157 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2160 In the examples above, the subquery was used as an operator on a column;
2161 but the same principle also applies for a clause within the main C<%where>
2162 hash, like an EXISTS subquery :
2164 my ($sub_stmt, @sub_bind)
2165 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2166 my %where = ( -and => [
2168 \["EXISTS ($sub_stmt)" => @sub_bind],
2173 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2174 WHERE c1 = ? AND c2 > t0.c0))";
2178 Observe that the condition on C<c2> in the subquery refers to
2179 column C<t0.c0> of the main query : this is I<not> a bind
2180 value, so we have to express it through a scalar ref.
2181 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2182 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2183 what we wanted here.
2185 Finally, here is an example where a subquery is used
2186 for expressing unary negation:
2188 my ($sub_stmt, @sub_bind)
2189 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2190 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2192 lname => {like => '%son%'},
2193 \["NOT ($sub_stmt)" => @sub_bind],
2198 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2199 @bind = ('%son%', 10, 20)
2201 =head3 Deprecated usage of Literal SQL
2203 Below are some examples of archaic use of literal SQL. It is shown only as
2204 reference for those who deal with legacy code. Each example has a much
2205 better, cleaner and safer alternative that users should opt for in new code.
2211 my %where = ( requestor => \'IS NOT NULL' )
2213 $stmt = "WHERE requestor IS NOT NULL"
2215 This used to be the way of generating NULL comparisons, before the handling
2216 of C<undef> got formalized. For new code please use the superior syntax as
2217 described in L</Tests for NULL values>.
2221 my %where = ( requestor => \'= submitter' )
2223 $stmt = "WHERE requestor = submitter"
2225 This used to be the only way to compare columns. Use the superior L</-ident>
2226 method for all new code. For example an identifier declared in such a way
2227 will be properly quoted if L</quote_char> is properly set, while the legacy
2228 form will remain as supplied.
2232 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2234 $stmt = "WHERE completed > ? AND is_ready"
2235 @bind = ('2012-12-21')
2237 Using an empty string literal used to be the only way to express a boolean.
2238 For all new code please use the much more readable
2239 L<-bool|/Unary operators: bool> operator.
2245 These pages could go on for a while, since the nesting of the data
2246 structures this module can handle are pretty much unlimited (the
2247 module implements the C<WHERE> expansion as a recursive function
2248 internally). Your best bet is to "play around" with the module a
2249 little to see how the data structures behave, and choose the best
2250 format for your data based on that.
2252 And of course, all the values above will probably be replaced with
2253 variables gotten from forms or the command line. After all, if you
2254 knew everything ahead of time, you wouldn't have to worry about
2255 dynamically-generating SQL and could just hardwire it into your
2258 =head1 ORDER BY CLAUSES
2260 Some functions take an order by clause. This can either be a scalar (just a
2261 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2262 or an array of either of the two previous forms. Examples:
2264 Given | Will Generate
2265 ----------------------------------------------------------
2267 \'colA DESC' | ORDER BY colA DESC
2269 'colA' | ORDER BY colA
2271 [qw/colA colB/] | ORDER BY colA, colB
2273 {-asc => 'colA'} | ORDER BY colA ASC
2275 {-desc => 'colB'} | ORDER BY colB DESC
2277 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2279 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2282 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2283 { -desc => [qw/colB/], | colC ASC, colD ASC
2284 { -asc => [qw/colC colD/],|
2286 ===========================================================
2290 =head1 SPECIAL OPERATORS
2292 my $sqlmaker = SQL::Abstract->new(special_ops => [
2296 my ($self, $field, $op, $arg) = @_;
2302 handler => 'method_name',
2306 A "special operator" is a SQL syntactic clause that can be
2307 applied to a field, instead of a usual binary operator.
2310 WHERE field IN (?, ?, ?)
2311 WHERE field BETWEEN ? AND ?
2312 WHERE MATCH(field) AGAINST (?, ?)
2314 Special operators IN and BETWEEN are fairly standard and therefore
2315 are builtin within C<SQL::Abstract> (as the overridable methods
2316 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2317 like the MATCH .. AGAINST example above which is specific to MySQL,
2318 you can write your own operator handlers - supply a C<special_ops>
2319 argument to the C<new> method. That argument takes an arrayref of
2320 operator definitions; each operator definition is a hashref with two
2327 the regular expression to match the operator
2331 Either a coderef or a plain scalar method name. In both cases
2332 the expected return is C<< ($sql, @bind) >>.
2334 When supplied with a method name, it is simply called on the
2335 L<SQL::Abstract/> object as:
2337 $self->$method_name ($field, $op, $arg)
2341 $op is the part that matched the handler regex
2342 $field is the LHS of the operator
2345 When supplied with a coderef, it is called as:
2347 $coderef->($self, $field, $op, $arg)
2352 For example, here is an implementation
2353 of the MATCH .. AGAINST syntax for MySQL
2355 my $sqlmaker = SQL::Abstract->new(special_ops => [
2357 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2358 {regex => qr/^match$/i,
2360 my ($self, $field, $op, $arg) = @_;
2361 $arg = [$arg] if not ref $arg;
2362 my $label = $self->_quote($field);
2363 my ($placeholder) = $self->_convert('?');
2364 my $placeholders = join ", ", (($placeholder) x @$arg);
2365 my $sql = $self->_sqlcase('match') . " ($label) "
2366 . $self->_sqlcase('against') . " ($placeholders) ";
2367 my @bind = $self->_bindtype($field, @$arg);
2368 return ($sql, @bind);
2375 =head1 UNARY OPERATORS
2377 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2381 my ($self, $op, $arg) = @_;
2387 handler => 'method_name',
2391 A "unary operator" is a SQL syntactic clause that can be
2392 applied to a field - the operator goes before the field
2394 You can write your own operator handlers - supply a C<unary_ops>
2395 argument to the C<new> method. That argument takes an arrayref of
2396 operator definitions; each operator definition is a hashref with two
2403 the regular expression to match the operator
2407 Either a coderef or a plain scalar method name. In both cases
2408 the expected return is C<< $sql >>.
2410 When supplied with a method name, it is simply called on the
2411 L<SQL::Abstract/> object as:
2413 $self->$method_name ($op, $arg)
2417 $op is the part that matched the handler regex
2418 $arg is the RHS or argument of the operator
2420 When supplied with a coderef, it is called as:
2422 $coderef->($self, $op, $arg)
2430 Thanks to some benchmarking by Mark Stosberg, it turns out that
2431 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2432 I must admit this wasn't an intentional design issue, but it's a
2433 byproduct of the fact that you get to control your C<DBI> handles
2436 To maximize performance, use a code snippet like the following:
2438 # prepare a statement handle using the first row
2439 # and then reuse it for the rest of the rows
2441 for my $href (@array_of_hashrefs) {
2442 $stmt ||= $sql->insert('table', $href);
2443 $sth ||= $dbh->prepare($stmt);
2444 $sth->execute($sql->values($href));
2447 The reason this works is because the keys in your C<$href> are sorted
2448 internally by B<SQL::Abstract>. Thus, as long as your data retains
2449 the same structure, you only have to generate the SQL the first time
2450 around. On subsequent queries, simply use the C<values> function provided
2451 by this module to return your values in the correct order.
2453 However this depends on the values having the same type - if, for
2454 example, the values of a where clause may either have values
2455 (resulting in sql of the form C<column = ?> with a single bind
2456 value), or alternatively the values might be C<undef> (resulting in
2457 sql of the form C<column IS NULL> with no bind value) then the
2458 caching technique suggested will not work.
2462 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2463 really like this part (I do, at least). Building up a complex query
2464 can be as simple as the following:
2468 use CGI::FormBuilder;
2471 my $form = CGI::FormBuilder->new(...);
2472 my $sql = SQL::Abstract->new;
2474 if ($form->submitted) {
2475 my $field = $form->field;
2476 my $id = delete $field->{id};
2477 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2480 Of course, you would still have to connect using C<DBI> to run the
2481 query, but the point is that if you make your form look like your
2482 table, the actual query script can be extremely simplistic.
2484 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2485 a fast interface to returning and formatting data. I frequently
2486 use these three modules together to write complex database query
2487 apps in under 50 lines.
2493 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2495 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2501 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2502 Great care has been taken to preserve the I<published> behavior
2503 documented in previous versions in the 1.* family; however,
2504 some features that were previously undocumented, or behaved
2505 differently from the documentation, had to be changed in order
2506 to clarify the semantics. Hence, client code that was relying
2507 on some dark areas of C<SQL::Abstract> v1.*
2508 B<might behave differently> in v1.50.
2510 The main changes are :
2516 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2520 support for the { operator => \"..." } construct (to embed literal SQL)
2524 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2528 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2532 defensive programming : check arguments
2536 fixed bug with global logic, which was previously implemented
2537 through global variables yielding side-effects. Prior versions would
2538 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2539 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2540 Now this is interpreted
2541 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2546 fixed semantics of _bindtype on array args
2550 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2551 we just avoid shifting arrays within that tree.
2555 dropped the C<_modlogic> function
2559 =head1 ACKNOWLEDGEMENTS
2561 There are a number of individuals that have really helped out with
2562 this module. Unfortunately, most of them submitted bugs via CPAN
2563 so I have no idea who they are! But the people I do know are:
2565 Ash Berlin (order_by hash term support)
2566 Matt Trout (DBIx::Class support)
2567 Mark Stosberg (benchmarking)
2568 Chas Owens (initial "IN" operator support)
2569 Philip Collins (per-field SQL functions)
2570 Eric Kolve (hashref "AND" support)
2571 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2572 Dan Kubb (support for "quote_char" and "name_sep")
2573 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2574 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2575 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2576 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2577 Oliver Charles (support for "RETURNING" after "INSERT")
2583 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2587 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2589 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2591 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2592 While not an official support venue, C<DBIx::Class> makes heavy use of
2593 C<SQL::Abstract>, and as such list members there are very familiar with
2594 how to create queries.
2598 This module is free software; you may copy this under the same
2599 terms as perl itself (either the GNU General Public License or
2600 the Artistic License)