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
17 use Data::Query::ExprHelpers qw(perl_scalar_value);
19 #======================================================================
21 #======================================================================
23 our $VERSION = '1.72';
25 # This would confuse some packagers
26 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
30 # special operators (-in, -between). May be extended/overridden by user.
31 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
32 my @BUILTIN_SPECIAL_OPS = ();
34 # unaryish operators - key maps to handler
35 my @BUILTIN_UNARY_OPS = (
36 # the digits are backcompat stuff
37 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
38 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
39 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
40 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
41 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
42 { regex => qr/^ value $/ix, handler => '_where_op_VALUE' },
45 #======================================================================
46 # DEBUGGING AND ERROR REPORTING
47 #======================================================================
50 return unless $_[0]->{debug}; shift; # a little faster
51 my $func = (caller(1))[3];
52 warn "[$func] ", @_, "\n";
56 my($func) = (caller(1))[3];
57 Carp::carp "[$func] Warning: ", @_;
61 my($func) = (caller(1))[3];
62 Carp::croak "[$func] Fatal: ", @_;
66 #======================================================================
68 #======================================================================
72 my $class = ref($self) || $self;
73 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
75 # choose our case by keeping an option around
76 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
78 # default logic for interpreting arrayrefs
79 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
81 # how to return bind vars
82 # LDNOTE: changed nwiger code : why this 'delete' ??
83 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
84 $opt{bindtype} ||= 'normal';
86 # default comparison is "=", but can be overridden
89 # try to recognize which are the 'equality' and 'unequality' ops
90 # (temporary quickfix, should go through a more seasoned API)
91 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
92 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
95 $opt{sqltrue} ||= '1=1';
96 $opt{sqlfalse} ||= '0=1';
99 $opt{special_ops} ||= [];
100 # regexes are applied in order, thus push after user-defines
101 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
104 $opt{unary_ops} ||= [];
105 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
107 # rudimentary saniy-check for user supplied bits treated as functions/operators
108 # If a purported function matches this regular expression, an exception is thrown.
109 # Literal SQL is *NOT* subject to this check, only functions (and column names
110 # when quoting is not in effect)
113 # need to guard against ()'s in column names too, but this will break tons of
114 # hacks... ideas anyone?
115 $opt{injection_guard} ||= qr/
121 $opt{name_sep} ||= '.';
123 $opt{renderer} ||= do {
124 require Data::Query::Renderer::SQL::Naive;
125 my ($always, $chars);
126 for ($opt{quote_char}) {
127 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
130 Data::Query::Renderer::SQL::Naive->new({
131 quote_chars => $chars, always_quote => $always,
132 ($opt{case} ? (lc_keywords => 1) : ()), # always 'lower' if it exists
136 return bless \%opt, $class;
140 my ($self, $dq) = @_;
141 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
143 ($self->{bindtype} eq 'normal'
144 ? ($sql, map $_->{value}, @bind)
145 : ($sql, map [ $_->{value_meta}, $_->{value} ], @bind)
151 my ($self, $literal) = @_;
153 ($literal, @bind) = @$literal if ref($literal) eq 'ARRAY';
158 (@bind ? (values => [ $self->_bind_to_dq(@bind) ]) : ()),
163 my ($self, @bind) = @_;
165 $self->{bindtype} eq 'normal'
166 ? map perl_scalar_value($_), @bind
168 $self->_assert_bindval_matches_bindtype(@bind);
169 map perl_scalar_value(reverse @$_), @bind
174 my ($self, $value) = @_;
175 $self->_maybe_convert_dq(perl_scalar_value($value, our $Cur_Col_Meta));
179 my ($self, $ident) = @_;
180 $self->_assert_pass_injection_guard($ident)
181 unless $self->{renderer}{always_quote};
182 $self->_maybe_convert_dq({
183 type => DQ_IDENTIFIER,
184 elements => [ split /\Q$self->{name_sep}/, $ident ],
188 sub _maybe_convert_dq {
189 my ($self, $dq) = @_;
190 if (my $c = $self->{where_convert}) {
193 operator => { 'SQL.Naive' => 'apply' },
195 { type => DQ_IDENTIFIER, elements => [ $self->_sqlcase($c) ] },
205 my ($self, $op, @args) = @_;
206 $self->_assert_pass_injection_guard($op);
209 operator => { 'SQL.Naive' => $op },
214 sub _assert_pass_injection_guard {
215 if ($_[1] =~ $_[0]->{injection_guard}) {
216 my $class = ref $_[0];
217 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
218 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
219 . "{injection_guard} attribute to ${class}->new()"
224 #======================================================================
226 #======================================================================
230 my $table = $self->_table(shift);
231 my $data = shift || return;
234 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
235 my ($sql, @bind) = $self->$method($data);
236 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
238 if ($options->{returning}) {
239 my ($s, @b) = $self->_insert_returning ($options);
244 return wantarray ? ($sql, @bind) : $sql;
247 sub _insert_returning {
248 my ($self, $options) = @_;
250 my $f = $options->{returning};
252 my $fieldlist = $self->_SWITCH_refkind($f, {
253 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
254 SCALAR => sub {$self->_quote($f)},
255 SCALARREF => sub {$$f},
257 return $self->_sqlcase(' returning ') . $fieldlist;
260 sub _insert_HASHREF { # explicit list of fields and then values
261 my ($self, $data) = @_;
263 my @fields = sort keys %$data;
265 my ($sql, @bind) = $self->_insert_values($data);
268 $_ = $self->_quote($_) foreach @fields;
269 $sql = "( ".join(", ", @fields).") ".$sql;
271 return ($sql, @bind);
274 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
275 my ($self, $data) = @_;
277 # no names (arrayref) so can't generate bindtype
278 $self->{bindtype} ne 'columns'
279 or belch "can't do 'columns' bindtype when called with arrayref";
281 # fold the list of values into a hash of column name - value pairs
282 # (where the column names are artificially generated, and their
283 # lexicographical ordering keep the ordering of the original list)
284 my $i = "a"; # incremented values will be in lexicographical order
285 my $data_in_hash = { map { ($i++ => $_) } @$data };
287 return $self->_insert_values($data_in_hash);
290 sub _insert_ARRAYREFREF { # literal SQL with bind
291 my ($self, $data) = @_;
293 my ($sql, @bind) = @${$data};
294 $self->_assert_bindval_matches_bindtype(@bind);
296 return ($sql, @bind);
300 sub _insert_SCALARREF { # literal SQL without bind
301 my ($self, $data) = @_;
307 my ($self, $data) = @_;
309 my (@values, @all_bind);
310 foreach my $column (sort keys %$data) {
311 my $v = $data->{$column};
313 $self->_SWITCH_refkind($v, {
316 if ($self->{array_datatypes}) { # if array datatype are activated
318 push @all_bind, $self->_bindtype($column, $v);
320 else { # else literal SQL with bind
321 my ($sql, @bind) = @$v;
322 $self->_assert_bindval_matches_bindtype(@bind);
324 push @all_bind, @bind;
328 ARRAYREFREF => sub { # literal SQL with bind
329 my ($sql, @bind) = @${$v};
330 $self->_assert_bindval_matches_bindtype(@bind);
332 push @all_bind, @bind;
335 # THINK : anything useful to do with a HASHREF ?
336 HASHREF => sub { # (nothing, but old SQLA passed it through)
337 #TODO in SQLA >= 2.0 it will die instead
338 belch "HASH ref as bind value in insert is not supported";
340 push @all_bind, $self->_bindtype($column, $v);
343 SCALARREF => sub { # literal SQL without bind
347 SCALAR_or_UNDEF => sub {
349 push @all_bind, $self->_bindtype($column, $v);
356 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
357 return ($sql, @all_bind);
362 #======================================================================
364 #======================================================================
369 my $table = $self->_table(shift);
370 my $data = shift || return;
373 # first build the 'SET' part of the sql statement
374 my (@set, @all_bind);
375 puke "Unsupported data type specified to \$sql->update"
376 unless ref $data eq 'HASH';
378 for my $k (sort keys %$data) {
381 my $label = $self->_quote($k);
383 $self->_SWITCH_refkind($v, {
385 if ($self->{array_datatypes}) { # array datatype
386 push @set, "$label = ?";
387 push @all_bind, $self->_bindtype($k, $v);
389 else { # literal SQL with bind
390 my ($sql, @bind) = @$v;
391 $self->_assert_bindval_matches_bindtype(@bind);
392 push @set, "$label = $sql";
393 push @all_bind, @bind;
396 ARRAYREFREF => sub { # literal SQL with bind
397 my ($sql, @bind) = @${$v};
398 $self->_assert_bindval_matches_bindtype(@bind);
399 push @set, "$label = $sql";
400 push @all_bind, @bind;
402 SCALARREF => sub { # literal SQL without bind
403 push @set, "$label = $$v";
406 my ($op, $arg, @rest) = %$v;
408 puke 'Operator calls in update must be in the form { -op => $arg }'
409 if (@rest or not $op =~ /^\-(.+)/);
411 local $self->{_nested_func_lhs} = $k;
412 local our $Cur_Col_Meta = $k;
413 my ($sql, @bind) = $self->_render_dq($self->_expr_to_dq({ $op => $arg }));
415 push @set, "$label = $sql";
416 push @all_bind, @bind;
418 SCALAR_or_UNDEF => sub {
419 push @set, "$label = ?";
420 push @all_bind, $self->_bindtype($k, $v);
426 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
430 my($where_sql, @where_bind) = $self->where($where);
432 push @all_bind, @where_bind;
435 return wantarray ? ($sql, @all_bind) : $sql;
441 #======================================================================
443 #======================================================================
449 my $fields = shift || '*';
453 my $source_dq = $self->_table_to_dq($table);
455 if (defined($where) and my $where_dq = $self->_where_to_dq($where)) {
466 map $self->_ident_to_dq($_),
467 ref($fields) eq 'ARRAY' ? @$fields : $fields
473 $final_dq = $self->_order_by_to_dq($order, undef, $final_dq);
476 return $self->_render_dq($final_dq);
479 #======================================================================
481 #======================================================================
486 my $table = $self->_table(shift);
490 my($where_sql, @bind) = $self->where($where);
491 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
493 return wantarray ? ($sql, @bind) : $sql;
497 #======================================================================
499 #======================================================================
503 # Finally, a separate routine just to handle WHERE clauses
505 my ($self, $where, $order) = @_;
511 ($sql, @bind) = $self->_recurse_where($where) if defined($where);
512 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
516 $sql .= $self->_order_by($order);
519 return wantarray ? ($sql, @bind) : $sql;
523 my ($self, $where, $logic) = @_;
525 return $self->_render_dq($self->_where_to_dq($where, $logic));
529 my ($self, $where, $logic) = @_;
531 # turn the convert misfeature on - only used in WHERE clauses
532 local $self->{where_convert} = $self->{convert};
534 return $self->_expr_to_dq($where, $logic);
538 my ($self, $where, $logic) = @_;
540 if (ref($where) eq 'ARRAY') {
541 return $self->_expr_to_dq_ARRAYREF($where, $logic);
542 } elsif (ref($where) eq 'HASH') {
543 return $self->_expr_to_dq_HASHREF($where, $logic);
545 ref($where) eq 'SCALAR'
546 or (ref($where) eq 'REF' and ref($$where) eq 'ARRAY')
548 return $self->_literal_to_dq($$where);
549 } elsif (!ref($where) or Scalar::Util::blessed($where)) {
550 return $self->_value_to_dq($where);
552 die "Can't handle $where";
555 sub _expr_to_dq_ARRAYREF {
556 my ($self, $where, $logic) = @_;
558 $logic = uc($logic || $self->{logic} || 'OR');
559 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
561 return unless @$where;
563 my ($first, @rest) = @$where;
565 return $self->_expr_to_dq($first) unless @rest;
569 $self->_where_hashpair_to_dq($first => shift(@rest));
571 $self->_expr_to_dq($first);
575 return $self->_expr_to_dq_ARRAYREF(\@rest, $logic) unless $first_dq;
578 $logic, $first_dq, $self->_expr_to_dq_ARRAYREF(\@rest, $logic)
582 sub _expr_to_dq_HASHREF {
583 my ($self, $where, $logic) = @_;
585 $logic = uc($logic) if $logic;
588 $self->_where_hashpair_to_dq($_ => $where->{$_}, $logic)
591 return $dq[0] unless @dq > 1;
593 my $final = pop(@dq);
595 foreach my $dq (reverse @dq) {
596 $final = $self->_op_to_dq($logic||'AND', $dq, $final);
602 sub _where_to_dq_SCALAR {
603 shift->_value_to_dq(@_);
606 sub _where_op_IDENT {
608 my ($op, $rhs) = splice @_, -2;
610 puke "-$op takes a single scalar argument (a quotable identifier)";
613 # in case we are called as a top level special op (no '=')
616 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
624 sub _where_op_VALUE {
626 my ($op, $rhs) = splice @_, -2;
628 # in case we are called as a top level special op (no '=')
633 ($lhs || $self->{_nested_func_lhs}),
640 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
644 $self->_convert('?'),
650 sub _where_hashpair_to_dq {
651 my ($self, $k, $v, $logic) = @_;
653 if ($k =~ /^-(.*)/s) {
655 if ($op eq 'AND' or $op eq 'OR') {
656 return $self->_expr_to_dq($v, $op);
657 } elsif ($op eq 'NEST') {
658 return $self->_expr_to_dq($v);
659 } elsif ($op eq 'NOT') {
660 return $self->_op_to_dq(NOT => $self->_expr_to_dq($v));
661 } elsif ($op eq 'BOOL') {
662 return ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v);
663 } elsif ($op eq 'NOT_BOOL') {
664 return $self->_op_to_dq(
665 NOT => ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v)
667 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+/) {
668 die "Use of [and|or|nest]_N modifiers is no longer supported";
671 if (ref($v) eq 'HASH' and keys(%$v) == 1 and (keys %$v)[0] =~ /^-(.*)/s) {
673 my ($inner) = values %$v;
676 (map $self->_expr_to_dq($_),
677 (ref($inner) eq 'ARRAY' ? @$inner : $inner))
680 (map $self->_expr_to_dq($_), (ref($v) eq 'ARRAY' ? @$v : $v))
683 $self->_assert_pass_injection_guard($op);
684 return $self->_op_to_dq(
685 apply => $self->_ident_to_dq($op), @args
689 local our $Cur_Col_Meta = $k;
690 if (ref($v) eq 'ARRAY') {
692 return $self->_literal_to_dq($self->{sqlfalse});
693 } elsif (defined($v->[0]) && $v->[0] =~ /-(and|or)/i) {
694 return $self->_expr_to_dq_ARRAYREF([
695 map +{ $k => $_ }, @{$v}[1..$#$v]
698 return $self->_expr_to_dq_ARRAYREF([
699 map +{ $k => $_ }, @$v
701 } elsif (ref($v) eq 'SCALAR' or (ref($v) eq 'REF' and ref($$v) eq 'ARRAY')) {
705 parts => [ $self->_ident_to_dq($k), $self->_literal_to_dq($$v) ]
708 my ($op, $rhs) = do {
709 if (ref($v) eq 'HASH') {
711 return $self->_expr_to_dq_ARRAYREF([
712 map +{ $k => { $_ => $v->{$_} } }, sort keys %$v
715 my ($op, $value) = %$v;
716 s/^-//, s/_/ /g for $op;
717 if ($op =~ /^(and|or)$/i) {
718 return $self->_expr_to_dq({ $k => $value }, $op);
720 my $special_op = List::Util::first {$op =~ $_->{regex}}
721 @{$self->{special_ops}}
723 return $self->_literal_to_dq(
724 [ $self->${\$special_op->{handler}}($k, $op, $value) ]
726 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+$/i) {
727 die "Use of [and|or|nest]_N modifiers is no longer supported";
734 if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
735 if (ref($rhs) ne 'ARRAY') {
737 # have to add parens if none present because -in => \"SELECT ..."
738 # got documented. mst hates everything.
739 if (ref($rhs) eq 'SCALAR') {
741 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
744 my ($x, @rest) = @{$$rhs};
745 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
746 $rhs = \[ $x, @rest ];
749 return $self->_op_to_dq(
750 $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
753 return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
754 return $self->_op_to_dq(
755 $op, $self->_ident_to_dq($k), map $self->_expr_to_dq($_), @$rhs
757 } elsif ($op =~ s/^NOT (?!LIKE)//) {
758 return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
759 } elsif (!defined($rhs)) {
761 if ($op eq '=' or $op eq 'LIKE') {
763 } elsif ($op eq '!=') {
766 die "Can't do undef -> NULL transform for operator ${op}";
769 return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
771 if (ref($rhs) eq 'ARRAY') {
773 return $self->_literal_to_dq(
774 $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
776 } elsif (defined($rhs->[0]) and $rhs->[0] =~ /^-(and|or)$/i) {
777 return $self->_expr_to_dq_ARRAYREF([
778 map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
780 } elsif ($op =~ /^-(?:AND|OR|NEST)_?\d+/) {
781 die "Use of [and|or|nest]_N modifiers is no longer supported";
783 return $self->_expr_to_dq_ARRAYREF([
784 map +{ $k => { $op => $_ } }, @$rhs
787 return $self->_op_to_dq(
788 $op, $self->_ident_to_dq($k), $self->_expr_to_dq($rhs)
793 #======================================================================
795 #======================================================================
798 my ($self, $arg) = @_;
799 if (my $dq = $self->_order_by_to_dq($arg)) {
800 # SQLA generates ' ORDER BY foo'. The hilarity.
802 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
803 : ' '.$self->_render_dq($dq);
809 sub _order_by_to_dq {
810 my ($self, $arg, $dir, $from) = @_;
816 ($dir ? (direction => $dir) : ()),
817 ($from ? (from => $from) : ()),
821 $dq->{by} = $self->_ident_to_dq($arg);
822 } elsif (ref($arg) eq 'ARRAY') {
824 local our $Order_Inner unless our $Order_Recursing;
825 local $Order_Recursing = 1;
827 foreach my $member (@$arg) {
829 my $next = $self->_order_by_to_dq($member, $dir, $from);
831 $inner->{from} = $next if $inner;
832 $inner = $Order_Inner || $next;
834 $Order_Inner = $inner;
836 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
837 $dq->{by} = $self->_literal_to_dq($$arg);
838 } elsif (ref($arg) eq 'SCALAR') {
839 $dq->{by} = $self->_literal_to_dq($$arg);
840 } elsif (ref($arg) eq 'HASH') {
841 my ($key, $val, @rest) = %$arg;
845 if (@rest or not $key =~ /^-(desc|asc)/i) {
846 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
849 return $self->_order_by_to_dq($val, $dir, $from);
851 die "Can't handle $arg in _order_by_to_dq";
856 #======================================================================
857 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
858 #======================================================================
861 my ($self, $from) = @_;
862 $self->_render_dq($self->_table_to_dq($from));
866 my ($self, $from) = @_;
867 $self->_SWITCH_refkind($from, {
869 die "Empty FROM list" unless my @f = @$from;
870 my $dq = $self->_ident_to_dq(shift @f);
871 while (my $x = shift @f) {
874 join => [ $dq, $self->_ident_to_dq($x) ]
879 SCALAR => sub { $self->_ident_to_dq($from) },
891 #======================================================================
893 #======================================================================
895 # highly optimized, as it's called way too often
897 # my ($self, $label) = @_;
899 return '' unless defined $_[1];
900 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
902 unless ($_[0]->{quote_char}) {
903 $_[0]->_assert_pass_injection_guard($_[1]);
907 my $qref = ref $_[0]->{quote_char};
910 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
912 elsif ($qref eq 'ARRAY') {
913 ($l, $r) = @{$_[0]->{quote_char}};
916 puke "Unsupported quote_char format: $_[0]->{quote_char}";
919 # parts containing * are naturally unquoted
920 return join( $_[0]->{name_sep}||'', map
921 { $_ eq '*' ? $_ : $l . $_ . $r }
922 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
927 # Conversion, if applicable
929 #my ($self, $arg) = @_;
931 # LDNOTE : modified the previous implementation below because
932 # it was not consistent : the first "return" is always an array,
933 # the second "return" is context-dependent. Anyway, _convert
934 # seems always used with just a single argument, so make it a
936 # return @_ unless $self->{convert};
937 # my $conv = $self->_sqlcase($self->{convert});
938 # my @ret = map { $conv.'('.$_.')' } @_;
939 # return wantarray ? @ret : $ret[0];
940 if ($_[0]->{convert}) {
941 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
948 #my ($self, $col, @vals) = @_;
950 #LDNOTE : changed original implementation below because it did not make
951 # sense when bindtype eq 'columns' and @vals > 1.
952 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
954 # called often - tighten code
955 return $_[0]->{bindtype} eq 'columns'
956 ? map {[$_[1], $_]} @_[2 .. $#_]
961 # Dies if any element of @bind is not in [colname => value] format
962 # if bindtype is 'columns'.
963 sub _assert_bindval_matches_bindtype {
964 # my ($self, @bind) = @_;
966 if ($self->{bindtype} eq 'columns') {
968 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
969 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
975 sub _join_sql_clauses {
976 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
978 if (@$clauses_aref > 1) {
979 my $join = " " . $self->_sqlcase($logic) . " ";
980 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
981 return ($sql, @$bind_aref);
983 elsif (@$clauses_aref) {
984 return ($clauses_aref->[0], @$bind_aref); # no parentheses
987 return (); # if no SQL, ignore @$bind_aref
992 # Fix SQL case, if so requested
994 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
995 # don't touch the argument ... crooked logic, but let's not change it!
996 return $_[0]->{case} ? $_[1] : uc($_[1]);
1000 #======================================================================
1001 # DISPATCHING FROM REFKIND
1002 #======================================================================
1005 my ($self, $data) = @_;
1007 return 'UNDEF' unless defined $data;
1009 # blessed objects are treated like scalars
1010 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1012 return 'SCALAR' unless $ref;
1015 while ($ref eq 'REF') {
1017 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1021 return ($ref||'SCALAR') . ('REF' x $n_steps);
1025 my ($self, $data) = @_;
1026 my @try = ($self->_refkind($data));
1027 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1028 push @try, 'FALLBACK';
1032 sub _METHOD_FOR_refkind {
1033 my ($self, $meth_prefix, $data) = @_;
1036 for (@{$self->_try_refkind($data)}) {
1037 $method = $self->can($meth_prefix."_".$_)
1041 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1045 sub _SWITCH_refkind {
1046 my ($self, $data, $dispatch_table) = @_;
1049 for (@{$self->_try_refkind($data)}) {
1050 $coderef = $dispatch_table->{$_}
1054 puke "no dispatch entry for ".$self->_refkind($data)
1063 #======================================================================
1064 # VALUES, GENERATE, AUTOLOAD
1065 #======================================================================
1067 # LDNOTE: original code from nwiger, didn't touch code in that section
1068 # I feel the AUTOLOAD stuff should not be the default, it should
1069 # only be activated on explicit demand by user.
1073 my $data = shift || return;
1074 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1075 unless ref $data eq 'HASH';
1078 foreach my $k ( sort keys %$data ) {
1079 my $v = $data->{$k};
1080 $self->_SWITCH_refkind($v, {
1082 if ($self->{array_datatypes}) { # array datatype
1083 push @all_bind, $self->_bindtype($k, $v);
1085 else { # literal SQL with bind
1086 my ($sql, @bind) = @$v;
1087 $self->_assert_bindval_matches_bindtype(@bind);
1088 push @all_bind, @bind;
1091 ARRAYREFREF => sub { # literal SQL with bind
1092 my ($sql, @bind) = @${$v};
1093 $self->_assert_bindval_matches_bindtype(@bind);
1094 push @all_bind, @bind;
1096 SCALARREF => sub { # literal SQL without bind
1098 SCALAR_or_UNDEF => sub {
1099 push @all_bind, $self->_bindtype($k, $v);
1110 my(@sql, @sqlq, @sqlv);
1114 if ($ref eq 'HASH') {
1115 for my $k (sort keys %$_) {
1118 my $label = $self->_quote($k);
1119 if ($r eq 'ARRAY') {
1120 # literal SQL with bind
1121 my ($sql, @bind) = @$v;
1122 $self->_assert_bindval_matches_bindtype(@bind);
1123 push @sqlq, "$label = $sql";
1125 } elsif ($r eq 'SCALAR') {
1126 # literal SQL without bind
1127 push @sqlq, "$label = $$v";
1129 push @sqlq, "$label = ?";
1130 push @sqlv, $self->_bindtype($k, $v);
1133 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1134 } elsif ($ref eq 'ARRAY') {
1135 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1138 if ($r eq 'ARRAY') { # literal SQL with bind
1139 my ($sql, @bind) = @$v;
1140 $self->_assert_bindval_matches_bindtype(@bind);
1143 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1144 # embedded literal SQL
1151 push @sql, '(' . join(', ', @sqlq) . ')';
1152 } elsif ($ref eq 'SCALAR') {
1156 # strings get case twiddled
1157 push @sql, $self->_sqlcase($_);
1161 my $sql = join ' ', @sql;
1163 # this is pretty tricky
1164 # if ask for an array, return ($stmt, @bind)
1165 # otherwise, s/?/shift @sqlv/ to put it inline
1167 return ($sql, @sqlv);
1169 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1170 ref $d ? $d->[1] : $d/e;
1179 # This allows us to check for a local, then _form, attr
1181 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1182 return $self->generate($name, @_);
1193 SQL::Abstract - Generate SQL from Perl data structures
1199 my $sql = SQL::Abstract->new;
1201 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1203 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1205 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1207 my($stmt, @bind) = $sql->delete($table, \%where);
1209 # Then, use these in your DBI statements
1210 my $sth = $dbh->prepare($stmt);
1211 $sth->execute(@bind);
1213 # Just generate the WHERE clause
1214 my($stmt, @bind) = $sql->where(\%where, \@order);
1216 # Return values in the same order, for hashed queries
1217 # See PERFORMANCE section for more details
1218 my @bind = $sql->values(\%fieldvals);
1222 This module was inspired by the excellent L<DBIx::Abstract>.
1223 However, in using that module I found that what I really wanted
1224 to do was generate SQL, but still retain complete control over my
1225 statement handles and use the DBI interface. So, I set out to
1226 create an abstract SQL generation module.
1228 While based on the concepts used by L<DBIx::Abstract>, there are
1229 several important differences, especially when it comes to WHERE
1230 clauses. I have modified the concepts used to make the SQL easier
1231 to generate from Perl data structures and, IMO, more intuitive.
1232 The underlying idea is for this module to do what you mean, based
1233 on the data structures you provide it. The big advantage is that
1234 you don't have to modify your code every time your data changes,
1235 as this module figures it out.
1237 To begin with, an SQL INSERT is as easy as just specifying a hash
1238 of C<key=value> pairs:
1241 name => 'Jimbo Bobson',
1242 phone => '123-456-7890',
1243 address => '42 Sister Lane',
1244 city => 'St. Louis',
1245 state => 'Louisiana',
1248 The SQL can then be generated with this:
1250 my($stmt, @bind) = $sql->insert('people', \%data);
1252 Which would give you something like this:
1254 $stmt = "INSERT INTO people
1255 (address, city, name, phone, state)
1256 VALUES (?, ?, ?, ?, ?)";
1257 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1258 '123-456-7890', 'Louisiana');
1260 These are then used directly in your DBI code:
1262 my $sth = $dbh->prepare($stmt);
1263 $sth->execute(@bind);
1265 =head2 Inserting and Updating Arrays
1267 If your database has array types (like for example Postgres),
1268 activate the special option C<< array_datatypes => 1 >>
1269 when creating the C<SQL::Abstract> object.
1270 Then you may use an arrayref to insert and update database array types:
1272 my $sql = SQL::Abstract->new(array_datatypes => 1);
1274 planets => [qw/Mercury Venus Earth Mars/]
1277 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1281 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1283 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1286 =head2 Inserting and Updating SQL
1288 In order to apply SQL functions to elements of your C<%data> you may
1289 specify a reference to an arrayref for the given hash value. For example,
1290 if you need to execute the Oracle C<to_date> function on a value, you can
1291 say something like this:
1295 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1298 The first value in the array is the actual SQL. Any other values are
1299 optional and would be included in the bind values array. This gives
1302 my($stmt, @bind) = $sql->insert('people', \%data);
1304 $stmt = "INSERT INTO people (name, date_entered)
1305 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1306 @bind = ('Bill', '03/02/2003');
1308 An UPDATE is just as easy, all you change is the name of the function:
1310 my($stmt, @bind) = $sql->update('people', \%data);
1312 Notice that your C<%data> isn't touched; the module will generate
1313 the appropriately quirky SQL for you automatically. Usually you'll
1314 want to specify a WHERE clause for your UPDATE, though, which is
1315 where handling C<%where> hashes comes in handy...
1317 =head2 Complex where statements
1319 This module can generate pretty complicated WHERE statements
1320 easily. For example, simple C<key=value> pairs are taken to mean
1321 equality, and if you want to see if a field is within a set
1322 of values, you can use an arrayref. Let's say we wanted to
1323 SELECT some data based on this criteria:
1326 requestor => 'inna',
1327 worker => ['nwiger', 'rcwe', 'sfz'],
1328 status => { '!=', 'completed' }
1331 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1333 The above would give you something like this:
1335 $stmt = "SELECT * FROM tickets WHERE
1336 ( requestor = ? ) AND ( status != ? )
1337 AND ( worker = ? OR worker = ? OR worker = ? )";
1338 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1340 Which you could then use in DBI code like so:
1342 my $sth = $dbh->prepare($stmt);
1343 $sth->execute(@bind);
1349 The functions are simple. There's one for each major SQL operation,
1350 and a constructor you use first. The arguments are specified in a
1351 similar order to each function (table, then fields, then a where
1352 clause) to try and simplify things.
1357 =head2 new(option => 'value')
1359 The C<new()> function takes a list of options and values, and returns
1360 a new B<SQL::Abstract> object which can then be used to generate SQL
1361 through the methods below. The options accepted are:
1367 If set to 'lower', then SQL will be generated in all lowercase. By
1368 default SQL is generated in "textbook" case meaning something like:
1370 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1372 Any setting other than 'lower' is ignored.
1376 This determines what the default comparison operator is. By default
1377 it is C<=>, meaning that a hash like this:
1379 %where = (name => 'nwiger', email => 'nate@wiger.org');
1381 Will generate SQL like this:
1383 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1385 However, you may want loose comparisons by default, so if you set
1386 C<cmp> to C<like> you would get SQL such as:
1388 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1390 You can also override the comparsion on an individual basis - see
1391 the huge section on L</"WHERE CLAUSES"> at the bottom.
1393 =item sqltrue, sqlfalse
1395 Expressions for inserting boolean values within SQL statements.
1396 By default these are C<1=1> and C<1=0>. They are used
1397 by the special operators C<-in> and C<-not_in> for generating
1398 correct SQL even when the argument is an empty array (see below).
1402 This determines the default logical operator for multiple WHERE
1403 statements in arrays or hashes. If absent, the default logic is "or"
1404 for arrays, and "and" for hashes. This means that a WHERE
1408 event_date => {'>=', '2/13/99'},
1409 event_date => {'<=', '4/24/03'},
1412 will generate SQL like this:
1414 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1416 This is probably not what you want given this query, though (look
1417 at the dates). To change the "OR" to an "AND", simply specify:
1419 my $sql = SQL::Abstract->new(logic => 'and');
1421 Which will change the above C<WHERE> to:
1423 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1425 The logic can also be changed locally by inserting
1426 a modifier in front of an arrayref :
1428 @where = (-and => [event_date => {'>=', '2/13/99'},
1429 event_date => {'<=', '4/24/03'} ]);
1431 See the L</"WHERE CLAUSES"> section for explanations.
1435 This will automatically convert comparisons using the specified SQL
1436 function for both column and value. This is mostly used with an argument
1437 of C<upper> or C<lower>, so that the SQL will have the effect of
1438 case-insensitive "searches". For example, this:
1440 $sql = SQL::Abstract->new(convert => 'upper');
1441 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1443 Will turn out the following SQL:
1445 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1447 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1448 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1449 not validate this option; it will just pass through what you specify verbatim).
1453 This is a kludge because many databases suck. For example, you can't
1454 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1455 Instead, you have to use C<bind_param()>:
1457 $sth->bind_param(1, 'reg data');
1458 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1460 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1461 which loses track of which field each slot refers to. Fear not.
1463 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1464 Currently, you can specify either C<normal> (default) or C<columns>. If you
1465 specify C<columns>, you will get an array that looks like this:
1467 my $sql = SQL::Abstract->new(bindtype => 'columns');
1468 my($stmt, @bind) = $sql->insert(...);
1471 [ 'column1', 'value1' ],
1472 [ 'column2', 'value2' ],
1473 [ 'column3', 'value3' ],
1476 You can then iterate through this manually, using DBI's C<bind_param()>.
1478 $sth->prepare($stmt);
1481 my($col, $data) = @$_;
1482 if ($col eq 'details' || $col eq 'comments') {
1483 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1484 } elsif ($col eq 'image') {
1485 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1487 $sth->bind_param($i, $data);
1491 $sth->execute; # execute without @bind now
1493 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1494 Basically, the advantage is still that you don't have to care which fields
1495 are or are not included. You could wrap that above C<for> loop in a simple
1496 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1497 get a layer of abstraction over manual SQL specification.
1499 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1500 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1501 will expect the bind values in this format.
1505 This is the character that a table or column name will be quoted
1506 with. By default this is an empty string, but you could set it to
1507 the character C<`>, to generate SQL like this:
1509 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1511 Alternatively, you can supply an array ref of two items, the first being the left
1512 hand quote character, and the second the right hand quote character. For
1513 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1514 that generates SQL like this:
1516 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1518 Quoting is useful if you have tables or columns names that are reserved
1519 words in your database's SQL dialect.
1523 This is the character that separates a table and column name. It is
1524 necessary to specify this when the C<quote_char> option is selected,
1525 so that tables and column names can be individually quoted like this:
1527 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1529 =item injection_guard
1531 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1532 column name specified in a query structure. This is a safety mechanism to avoid
1533 injection attacks when mishandling user input e.g.:
1535 my %condition_as_column_value_pairs = get_values_from_user();
1536 $sqla->select( ... , \%condition_as_column_value_pairs );
1538 If the expression matches an exception is thrown. Note that literal SQL
1539 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1541 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1543 =item array_datatypes
1545 When this option is true, arrayrefs in INSERT or UPDATE are
1546 interpreted as array datatypes and are passed directly
1548 When this option is false, arrayrefs are interpreted
1549 as literal SQL, just like refs to arrayrefs
1550 (but this behavior is for backwards compatibility; when writing
1551 new queries, use the "reference to arrayref" syntax
1557 Takes a reference to a list of "special operators"
1558 to extend the syntax understood by L<SQL::Abstract>.
1559 See section L</"SPECIAL OPERATORS"> for details.
1563 Takes a reference to a list of "unary operators"
1564 to extend the syntax understood by L<SQL::Abstract>.
1565 See section L</"UNARY OPERATORS"> for details.
1571 =head2 insert($table, \@values || \%fieldvals, \%options)
1573 This is the simplest function. You simply give it a table name
1574 and either an arrayref of values or hashref of field/value pairs.
1575 It returns an SQL INSERT statement and a list of bind values.
1576 See the sections on L</"Inserting and Updating Arrays"> and
1577 L</"Inserting and Updating SQL"> for information on how to insert
1578 with those data types.
1580 The optional C<\%options> hash reference may contain additional
1581 options to generate the insert SQL. Currently supported options
1588 Takes either a scalar of raw SQL fields, or an array reference of
1589 field names, and adds on an SQL C<RETURNING> statement at the end.
1590 This allows you to return data generated by the insert statement
1591 (such as row IDs) without performing another C<SELECT> statement.
1592 Note, however, this is not part of the SQL standard and may not
1593 be supported by all database engines.
1597 =head2 update($table, \%fieldvals, \%where)
1599 This takes a table, hashref of field/value pairs, and an optional
1600 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1602 See the sections on L</"Inserting and Updating Arrays"> and
1603 L</"Inserting and Updating SQL"> for information on how to insert
1604 with those data types.
1606 =head2 select($source, $fields, $where, $order)
1608 This returns a SQL SELECT statement and associated list of bind values, as
1609 specified by the arguments :
1615 Specification of the 'FROM' part of the statement.
1616 The argument can be either a plain scalar (interpreted as a table
1617 name, will be quoted), or an arrayref (interpreted as a list
1618 of table names, joined by commas, quoted), or a scalarref
1619 (literal table name, not quoted), or a ref to an arrayref
1620 (list of literal table names, joined by commas, not quoted).
1624 Specification of the list of fields to retrieve from
1626 The argument can be either an arrayref (interpreted as a list
1627 of field names, will be joined by commas and quoted), or a
1628 plain scalar (literal SQL, not quoted).
1629 Please observe that this API is not as flexible as for
1630 the first argument C<$table>, for backwards compatibility reasons.
1634 Optional argument to specify the WHERE part of the query.
1635 The argument is most often a hashref, but can also be
1636 an arrayref or plain scalar --
1637 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1641 Optional argument to specify the ORDER BY part of the query.
1642 The argument can be a scalar, a hashref or an arrayref
1643 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1649 =head2 delete($table, \%where)
1651 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1652 It returns an SQL DELETE statement and list of bind values.
1654 =head2 where(\%where, \@order)
1656 This is used to generate just the WHERE clause. For example,
1657 if you have an arbitrary data structure and know what the
1658 rest of your SQL is going to look like, but want an easy way
1659 to produce a WHERE clause, use this. It returns an SQL WHERE
1660 clause and list of bind values.
1663 =head2 values(\%data)
1665 This just returns the values from the hash C<%data>, in the same
1666 order that would be returned from any of the other above queries.
1667 Using this allows you to markedly speed up your queries if you
1668 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1670 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1672 Warning: This is an experimental method and subject to change.
1674 This returns arbitrarily generated SQL. It's a really basic shortcut.
1675 It will return two different things, depending on return context:
1677 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1678 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1680 These would return the following:
1682 # First calling form
1683 $stmt = "CREATE TABLE test (?, ?)";
1684 @bind = (field1, field2);
1686 # Second calling form
1687 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1689 Depending on what you're trying to do, it's up to you to choose the correct
1690 format. In this example, the second form is what you would want.
1694 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1698 ALTER SESSION SET nls_date_format = 'MM/YY'
1700 You get the idea. Strings get their case twiddled, but everything
1701 else remains verbatim.
1703 =head1 WHERE CLAUSES
1707 This module uses a variation on the idea from L<DBIx::Abstract>. It
1708 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1709 module is that things in arrays are OR'ed, and things in hashes
1712 The easiest way to explain is to show lots of examples. After
1713 each C<%where> hash shown, it is assumed you used:
1715 my($stmt, @bind) = $sql->where(\%where);
1717 However, note that the C<%where> hash can be used directly in any
1718 of the other functions as well, as described above.
1720 =head2 Key-value pairs
1722 So, let's get started. To begin, a simple hash:
1726 status => 'completed'
1729 Is converted to SQL C<key = val> statements:
1731 $stmt = "WHERE user = ? AND status = ?";
1732 @bind = ('nwiger', 'completed');
1734 One common thing I end up doing is having a list of values that
1735 a field can be in. To do this, simply specify a list inside of
1740 status => ['assigned', 'in-progress', 'pending'];
1743 This simple code will create the following:
1745 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1746 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1748 A field associated to an empty arrayref will be considered a
1749 logical false and will generate 0=1.
1751 =head2 Tests for NULL values
1753 If the value part is C<undef> then this is converted to SQL <IS NULL>
1762 $stmt = "WHERE user = ? AND status IS NULL";
1765 To test if a column IS NOT NULL:
1769 status => { '!=', undef },
1772 =head2 Specific comparison operators
1774 If you want to specify a different type of operator for your comparison,
1775 you can use a hashref for a given column:
1779 status => { '!=', 'completed' }
1782 Which would generate:
1784 $stmt = "WHERE user = ? AND status != ?";
1785 @bind = ('nwiger', 'completed');
1787 To test against multiple values, just enclose the values in an arrayref:
1789 status => { '=', ['assigned', 'in-progress', 'pending'] };
1791 Which would give you:
1793 "WHERE status = ? OR status = ? OR status = ?"
1796 The hashref can also contain multiple pairs, in which case it is expanded
1797 into an C<AND> of its elements:
1801 status => { '!=', 'completed', -not_like => 'pending%' }
1804 # Or more dynamically, like from a form
1805 $where{user} = 'nwiger';
1806 $where{status}{'!='} = 'completed';
1807 $where{status}{'-not_like'} = 'pending%';
1809 # Both generate this
1810 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1811 @bind = ('nwiger', 'completed', 'pending%');
1814 To get an OR instead, you can combine it with the arrayref idea:
1818 priority => [ { '=', 2 }, { '>', 5 } ]
1821 Which would generate:
1823 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1824 @bind = ('2', '5', 'nwiger');
1826 If you want to include literal SQL (with or without bind values), just use a
1827 scalar reference or array reference as the value:
1830 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1831 date_expires => { '<' => \"now()" }
1834 Which would generate:
1836 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1837 @bind = ('11/26/2008');
1840 =head2 Logic and nesting operators
1842 In the example above,
1843 there is a subtle trap if you want to say something like
1844 this (notice the C<AND>):
1846 WHERE priority != ? AND priority != ?
1848 Because, in Perl you I<can't> do this:
1850 priority => { '!=', 2, '!=', 1 }
1852 As the second C<!=> key will obliterate the first. The solution
1853 is to use the special C<-modifier> form inside an arrayref:
1855 priority => [ -and => {'!=', 2},
1859 Normally, these would be joined by C<OR>, but the modifier tells it
1860 to use C<AND> instead. (Hint: You can use this in conjunction with the
1861 C<logic> option to C<new()> in order to change the way your queries
1862 work by default.) B<Important:> Note that the C<-modifier> goes
1863 B<INSIDE> the arrayref, as an extra first element. This will
1864 B<NOT> do what you think it might:
1866 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1868 Here is a quick list of equivalencies, since there is some overlap:
1871 status => {'!=', 'completed', 'not like', 'pending%' }
1872 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1875 status => {'=', ['assigned', 'in-progress']}
1876 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1877 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1881 =head2 Special operators : IN, BETWEEN, etc.
1883 You can also use the hashref format to compare a list of fields using the
1884 C<IN> comparison operator, by specifying the list as an arrayref:
1887 status => 'completed',
1888 reportid => { -in => [567, 2335, 2] }
1891 Which would generate:
1893 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1894 @bind = ('completed', '567', '2335', '2');
1896 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1899 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1900 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1901 'sqltrue' (by default : C<1=1>).
1903 In addition to the array you can supply a chunk of literal sql or
1904 literal sql with bind:
1907 customer => { -in => \[
1908 'SELECT cust_id FROM cust WHERE balance > ?',
1911 status => { -in => \'SELECT status_codes FROM states' },
1917 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1918 AND status IN ( SELECT status_codes FROM states )
1924 Another pair of operators is C<-between> and C<-not_between>,
1925 used with an arrayref of two values:
1929 completion_date => {
1930 -not_between => ['2002-10-01', '2003-02-06']
1936 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1938 Just like with C<-in> all plausible combinations of literal SQL
1942 start0 => { -between => [ 1, 2 ] },
1943 start1 => { -between => \["? AND ?", 1, 2] },
1944 start2 => { -between => \"lower(x) AND upper(y)" },
1945 start3 => { -between => [
1947 \["upper(?)", 'stuff' ],
1954 ( start0 BETWEEN ? AND ? )
1955 AND ( start1 BETWEEN ? AND ? )
1956 AND ( start2 BETWEEN lower(x) AND upper(y) )
1957 AND ( start3 BETWEEN lower(x) AND upper(?) )
1959 @bind = (1, 2, 1, 2, 'stuff');
1962 These are the two builtin "special operators"; but the
1963 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1965 =head2 Unary operators: bool
1967 If you wish to test against boolean columns or functions within your
1968 database you can use the C<-bool> and C<-not_bool> operators. For
1969 example to test the column C<is_user> being true and the column
1970 C<is_enabled> being false you would use:-
1974 -not_bool => 'is_enabled',
1979 WHERE is_user AND NOT is_enabled
1981 If a more complex combination is required, testing more conditions,
1982 then you should use the and/or operators:-
1989 -not_bool => 'four',
1995 WHERE one AND two AND three AND NOT four
1998 =head2 Nested conditions, -and/-or prefixes
2000 So far, we've seen how multiple conditions are joined with a top-level
2001 C<AND>. We can change this by putting the different conditions we want in
2002 hashes and then putting those hashes in an array. For example:
2007 status => { -like => ['pending%', 'dispatched'] },
2011 status => 'unassigned',
2015 This data structure would create the following:
2017 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2018 OR ( user = ? AND status = ? ) )";
2019 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2022 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2023 to change the logic inside :
2029 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2030 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2037 WHERE ( user = ? AND (
2038 ( workhrs > ? AND geo = ? )
2039 OR ( workhrs < ? OR geo = ? )
2042 =head3 Algebraic inconsistency, for historical reasons
2044 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2045 operator goes C<outside> of the nested structure; whereas when connecting
2046 several constraints on one column, the C<-and> operator goes
2047 C<inside> the arrayref. Here is an example combining both features :
2050 -and => [a => 1, b => 2],
2051 -or => [c => 3, d => 4],
2052 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2057 WHERE ( ( ( a = ? AND b = ? )
2058 OR ( c = ? OR d = ? )
2059 OR ( e LIKE ? AND e LIKE ? ) ) )
2061 This difference in syntax is unfortunate but must be preserved for
2062 historical reasons. So be careful : the two examples below would
2063 seem algebraically equivalent, but they are not
2065 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2066 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2068 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2069 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2072 =head2 Literal SQL and value type operators
2074 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2075 side" is a column name and the "right side" is a value (normally rendered as
2076 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2077 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2078 alter this behavior. There are several ways of doing so.
2082 This is a virtual operator that signals the string to its right side is an
2083 identifier (a column name) and not a value. For example to compare two
2084 columns you would write:
2087 priority => { '<', 2 },
2088 requestor => { -ident => 'submitter' },
2093 $stmt = "WHERE priority < ? AND requestor = submitter";
2096 If you are maintaining legacy code you may see a different construct as
2097 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2102 This is a virtual operator that signals that the construct to its right side
2103 is a value to be passed to DBI. This is for example necessary when you want
2104 to write a where clause against an array (for RDBMS that support such
2105 datatypes). For example:
2108 array => { -value => [1, 2, 3] }
2113 $stmt = 'WHERE array = ?';
2114 @bind = ([1, 2, 3]);
2116 Note that if you were to simply say:
2122 the result would porbably be not what you wanted:
2124 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2129 Finally, sometimes only literal SQL will do. To include a random snippet
2130 of SQL verbatim, you specify it as a scalar reference. Consider this only
2131 as a last resort. Usually there is a better way. For example:
2134 priority => { '<', 2 },
2135 requestor => { -in => \'(SELECT name FROM hitmen)' },
2140 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2143 Note that in this example, you only get one bind parameter back, since
2144 the verbatim SQL is passed as part of the statement.
2148 Never use untrusted input as a literal SQL argument - this is a massive
2149 security risk (there is no way to check literal snippets for SQL
2150 injections and other nastyness). If you need to deal with untrusted input
2151 use literal SQL with placeholders as described next.
2153 =head3 Literal SQL with placeholders and bind values (subqueries)
2155 If the literal SQL to be inserted has placeholders and bind values,
2156 use a reference to an arrayref (yes this is a double reference --
2157 not so common, but perfectly legal Perl). For example, to find a date
2158 in Postgres you can use something like this:
2161 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2166 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2169 Note that you must pass the bind values in the same format as they are returned
2170 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2171 provide the bind values in the C<< [ column_meta => value ] >> format, where
2172 C<column_meta> is an opaque scalar value; most commonly the column name, but
2173 you can use any scalar value (including references and blessed references),
2174 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2175 to C<columns> the above example will look like:
2178 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2181 Literal SQL is especially useful for nesting parenthesized clauses in the
2182 main SQL query. Here is a first example :
2184 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2188 bar => \["IN ($sub_stmt)" => @sub_bind],
2193 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2194 WHERE c2 < ? AND c3 LIKE ?))";
2195 @bind = (1234, 100, "foo%");
2197 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2198 are expressed in the same way. Of course the C<$sub_stmt> and
2199 its associated bind values can be generated through a former call
2202 my ($sub_stmt, @sub_bind)
2203 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2204 c3 => {-like => "foo%"}});
2207 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2210 In the examples above, the subquery was used as an operator on a column;
2211 but the same principle also applies for a clause within the main C<%where>
2212 hash, like an EXISTS subquery :
2214 my ($sub_stmt, @sub_bind)
2215 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2216 my %where = ( -and => [
2218 \["EXISTS ($sub_stmt)" => @sub_bind],
2223 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2224 WHERE c1 = ? AND c2 > t0.c0))";
2228 Observe that the condition on C<c2> in the subquery refers to
2229 column C<t0.c0> of the main query : this is I<not> a bind
2230 value, so we have to express it through a scalar ref.
2231 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2232 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2233 what we wanted here.
2235 Finally, here is an example where a subquery is used
2236 for expressing unary negation:
2238 my ($sub_stmt, @sub_bind)
2239 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2240 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2242 lname => {like => '%son%'},
2243 \["NOT ($sub_stmt)" => @sub_bind],
2248 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2249 @bind = ('%son%', 10, 20)
2251 =head3 Deprecated usage of Literal SQL
2253 Below are some examples of archaic use of literal SQL. It is shown only as
2254 reference for those who deal with legacy code. Each example has a much
2255 better, cleaner and safer alternative that users should opt for in new code.
2261 my %where = ( requestor => \'IS NOT NULL' )
2263 $stmt = "WHERE requestor IS NOT NULL"
2265 This used to be the way of generating NULL comparisons, before the handling
2266 of C<undef> got formalized. For new code please use the superior syntax as
2267 described in L</Tests for NULL values>.
2271 my %where = ( requestor => \'= submitter' )
2273 $stmt = "WHERE requestor = submitter"
2275 This used to be the only way to compare columns. Use the superior L</-ident>
2276 method for all new code. For example an identifier declared in such a way
2277 will be properly quoted if L</quote_char> is properly set, while the legacy
2278 form will remain as supplied.
2282 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2284 $stmt = "WHERE completed > ? AND is_ready"
2285 @bind = ('2012-12-21')
2287 Using an empty string literal used to be the only way to express a boolean.
2288 For all new code please use the much more readable
2289 L<-bool|/Unary operators: bool> operator.
2295 These pages could go on for a while, since the nesting of the data
2296 structures this module can handle are pretty much unlimited (the
2297 module implements the C<WHERE> expansion as a recursive function
2298 internally). Your best bet is to "play around" with the module a
2299 little to see how the data structures behave, and choose the best
2300 format for your data based on that.
2302 And of course, all the values above will probably be replaced with
2303 variables gotten from forms or the command line. After all, if you
2304 knew everything ahead of time, you wouldn't have to worry about
2305 dynamically-generating SQL and could just hardwire it into your
2308 =head1 ORDER BY CLAUSES
2310 Some functions take an order by clause. This can either be a scalar (just a
2311 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2312 or an array of either of the two previous forms. Examples:
2314 Given | Will Generate
2315 ----------------------------------------------------------
2317 \'colA DESC' | ORDER BY colA DESC
2319 'colA' | ORDER BY colA
2321 [qw/colA colB/] | ORDER BY colA, colB
2323 {-asc => 'colA'} | ORDER BY colA ASC
2325 {-desc => 'colB'} | ORDER BY colB DESC
2327 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2329 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2332 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2333 { -desc => [qw/colB/], | colC ASC, colD ASC
2334 { -asc => [qw/colC colD/],|
2336 ===========================================================
2340 =head1 SPECIAL OPERATORS
2342 my $sqlmaker = SQL::Abstract->new(special_ops => [
2346 my ($self, $field, $op, $arg) = @_;
2352 handler => 'method_name',
2356 A "special operator" is a SQL syntactic clause that can be
2357 applied to a field, instead of a usual binary operator.
2360 WHERE field IN (?, ?, ?)
2361 WHERE field BETWEEN ? AND ?
2362 WHERE MATCH(field) AGAINST (?, ?)
2364 Special operators IN and BETWEEN are fairly standard and therefore
2365 are builtin within C<SQL::Abstract> (as the overridable methods
2366 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2367 like the MATCH .. AGAINST example above which is specific to MySQL,
2368 you can write your own operator handlers - supply a C<special_ops>
2369 argument to the C<new> method. That argument takes an arrayref of
2370 operator definitions; each operator definition is a hashref with two
2377 the regular expression to match the operator
2381 Either a coderef or a plain scalar method name. In both cases
2382 the expected return is C<< ($sql, @bind) >>.
2384 When supplied with a method name, it is simply called on the
2385 L<SQL::Abstract/> object as:
2387 $self->$method_name ($field, $op, $arg)
2391 $op is the part that matched the handler regex
2392 $field is the LHS of the operator
2395 When supplied with a coderef, it is called as:
2397 $coderef->($self, $field, $op, $arg)
2402 For example, here is an implementation
2403 of the MATCH .. AGAINST syntax for MySQL
2405 my $sqlmaker = SQL::Abstract->new(special_ops => [
2407 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2408 {regex => qr/^match$/i,
2410 my ($self, $field, $op, $arg) = @_;
2411 $arg = [$arg] if not ref $arg;
2412 my $label = $self->_quote($field);
2413 my ($placeholder) = $self->_convert('?');
2414 my $placeholders = join ", ", (($placeholder) x @$arg);
2415 my $sql = $self->_sqlcase('match') . " ($label) "
2416 . $self->_sqlcase('against') . " ($placeholders) ";
2417 my @bind = $self->_bindtype($field, @$arg);
2418 return ($sql, @bind);
2425 =head1 UNARY OPERATORS
2427 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2431 my ($self, $op, $arg) = @_;
2437 handler => 'method_name',
2441 A "unary operator" is a SQL syntactic clause that can be
2442 applied to a field - the operator goes before the field
2444 You can write your own operator handlers - supply a C<unary_ops>
2445 argument to the C<new> method. That argument takes an arrayref of
2446 operator definitions; each operator definition is a hashref with two
2453 the regular expression to match the operator
2457 Either a coderef or a plain scalar method name. In both cases
2458 the expected return is C<< $sql >>.
2460 When supplied with a method name, it is simply called on the
2461 L<SQL::Abstract/> object as:
2463 $self->$method_name ($op, $arg)
2467 $op is the part that matched the handler regex
2468 $arg is the RHS or argument of the operator
2470 When supplied with a coderef, it is called as:
2472 $coderef->($self, $op, $arg)
2480 Thanks to some benchmarking by Mark Stosberg, it turns out that
2481 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2482 I must admit this wasn't an intentional design issue, but it's a
2483 byproduct of the fact that you get to control your C<DBI> handles
2486 To maximize performance, use a code snippet like the following:
2488 # prepare a statement handle using the first row
2489 # and then reuse it for the rest of the rows
2491 for my $href (@array_of_hashrefs) {
2492 $stmt ||= $sql->insert('table', $href);
2493 $sth ||= $dbh->prepare($stmt);
2494 $sth->execute($sql->values($href));
2497 The reason this works is because the keys in your C<$href> are sorted
2498 internally by B<SQL::Abstract>. Thus, as long as your data retains
2499 the same structure, you only have to generate the SQL the first time
2500 around. On subsequent queries, simply use the C<values> function provided
2501 by this module to return your values in the correct order.
2503 However this depends on the values having the same type - if, for
2504 example, the values of a where clause may either have values
2505 (resulting in sql of the form C<column = ?> with a single bind
2506 value), or alternatively the values might be C<undef> (resulting in
2507 sql of the form C<column IS NULL> with no bind value) then the
2508 caching technique suggested will not work.
2512 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2513 really like this part (I do, at least). Building up a complex query
2514 can be as simple as the following:
2518 use CGI::FormBuilder;
2521 my $form = CGI::FormBuilder->new(...);
2522 my $sql = SQL::Abstract->new;
2524 if ($form->submitted) {
2525 my $field = $form->field;
2526 my $id = delete $field->{id};
2527 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2530 Of course, you would still have to connect using C<DBI> to run the
2531 query, but the point is that if you make your form look like your
2532 table, the actual query script can be extremely simplistic.
2534 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2535 a fast interface to returning and formatting data. I frequently
2536 use these three modules together to write complex database query
2537 apps in under 50 lines.
2543 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2545 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2551 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2552 Great care has been taken to preserve the I<published> behavior
2553 documented in previous versions in the 1.* family; however,
2554 some features that were previously undocumented, or behaved
2555 differently from the documentation, had to be changed in order
2556 to clarify the semantics. Hence, client code that was relying
2557 on some dark areas of C<SQL::Abstract> v1.*
2558 B<might behave differently> in v1.50.
2560 The main changes are :
2566 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2570 support for the { operator => \"..." } construct (to embed literal SQL)
2574 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2578 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2582 defensive programming : check arguments
2586 fixed bug with global logic, which was previously implemented
2587 through global variables yielding side-effects. Prior versions would
2588 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2589 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2590 Now this is interpreted
2591 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2596 fixed semantics of _bindtype on array args
2600 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2601 we just avoid shifting arrays within that tree.
2605 dropped the C<_modlogic> function
2609 =head1 ACKNOWLEDGEMENTS
2611 There are a number of individuals that have really helped out with
2612 this module. Unfortunately, most of them submitted bugs via CPAN
2613 so I have no idea who they are! But the people I do know are:
2615 Ash Berlin (order_by hash term support)
2616 Matt Trout (DBIx::Class support)
2617 Mark Stosberg (benchmarking)
2618 Chas Owens (initial "IN" operator support)
2619 Philip Collins (per-field SQL functions)
2620 Eric Kolve (hashref "AND" support)
2621 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2622 Dan Kubb (support for "quote_char" and "name_sep")
2623 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2624 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2625 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2626 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2627 Oliver Charles (support for "RETURNING" after "INSERT")
2633 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2637 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2639 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2641 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2642 While not an official support venue, C<DBIx::Class> makes heavy use of
2643 C<SQL::Abstract>, and as such list members there are very familiar with
2644 how to create queries.
2648 This module is free software; you may copy this under the same
2649 terms as perl itself (either the GNU General Public License or
2650 the Artistic License)