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
15 DQ_WHERE DQ_DELETE DQ_UPDATE DQ_INSERT
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 = ();
37 #======================================================================
38 # DEBUGGING AND ERROR REPORTING
39 #======================================================================
42 return unless $_[0]->{debug}; shift; # a little faster
43 my $func = (caller(1))[3];
44 warn "[$func] ", @_, "\n";
48 my($func) = (caller(1))[3];
49 Carp::carp "[$func] Warning: ", @_;
53 my($func) = (caller(1))[3];
54 Carp::croak "[$func] Fatal: ", @_;
58 #======================================================================
60 #======================================================================
64 my $class = ref($self) || $self;
65 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
67 # choose our case by keeping an option around
68 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
70 # default logic for interpreting arrayrefs
71 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
73 # how to return bind vars
74 # LDNOTE: changed nwiger code : why this 'delete' ??
75 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
76 $opt{bindtype} ||= 'normal';
78 # default comparison is "=", but can be overridden
81 # try to recognize which are the 'equality' and 'unequality' ops
82 # (temporary quickfix, should go through a more seasoned API)
83 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
84 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
87 $opt{sqltrue} ||= '1=1';
88 $opt{sqlfalse} ||= '0=1';
91 $opt{special_ops} ||= [];
92 # regexes are applied in order, thus push after user-defines
93 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
96 $opt{unary_ops} ||= [];
97 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
99 # rudimentary saniy-check for user supplied bits treated as functions/operators
100 # If a purported function matches this regular expression, an exception is thrown.
101 # Literal SQL is *NOT* subject to this check, only functions (and column names
102 # when quoting is not in effect)
105 # need to guard against ()'s in column names too, but this will break tons of
106 # hacks... ideas anyone?
107 $opt{injection_guard} ||= qr/
113 $opt{name_sep} ||= '.';
115 $opt{renderer} ||= do {
116 require Data::Query::Renderer::SQL::Naive;
117 my ($always, $chars);
118 for ($opt{quote_char}) {
119 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
122 Data::Query::Renderer::SQL::Naive->new({
123 quote_chars => $chars, always_quote => $always,
124 ($opt{case} ? (lc_keywords => 1) : ()), # always 'lower' if it exists
128 return bless \%opt, $class;
132 my ($self, $dq) = @_;
136 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
138 ($self->{bindtype} eq 'normal'
139 ? ($sql, map $_->{value}, @bind)
140 : ($sql, map [ $_->{value_meta}, $_->{value} ], @bind)
146 my ($self, $literal) = @_;
148 ($literal, @bind) = @$literal if ref($literal) eq 'ARRAY';
153 (@bind ? (values => [ $self->_bind_to_dq(@bind) ]) : ()),
158 my ($self, @bind) = @_;
160 $self->{bindtype} eq 'normal'
161 ? map perl_scalar_value($_), @bind
163 $self->_assert_bindval_matches_bindtype(@bind);
164 map perl_scalar_value(reverse @$_), @bind
169 my ($self, $value) = @_;
170 $self->_maybe_convert_dq(perl_scalar_value($value, our $Cur_Col_Meta));
174 my ($self, $ident) = @_;
175 $self->_assert_pass_injection_guard($ident)
176 unless $self->{renderer}{always_quote};
177 $self->_maybe_convert_dq({
178 type => DQ_IDENTIFIER,
179 elements => [ split /\Q$self->{name_sep}/, $ident ],
183 sub _maybe_convert_dq {
184 my ($self, $dq) = @_;
185 if (my $c = $self->{where_convert}) {
188 operator => { 'SQL.Naive' => 'apply' },
190 { type => DQ_IDENTIFIER, elements => [ $self->_sqlcase($c) ] },
200 my ($self, $op, @args) = @_;
201 $self->_assert_pass_injection_guard($op);
204 operator => { 'SQL.Naive' => $op },
209 sub _assert_pass_injection_guard {
210 if ($_[1] =~ $_[0]->{injection_guard}) {
211 my $class = ref $_[0];
212 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
213 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
214 . "{injection_guard} attribute to ${class}->new()"
219 #======================================================================
221 #======================================================================
225 $self->_render_dq($self->_insert_to_dq(@_));
229 my ($self, $table, $data, $options) = @_;
230 my (@names, @values);
231 if (ref($data) eq 'HASH') {
232 @names = sort keys %$data;
233 foreach my $k (@names) {
234 local our $Cur_Col_Meta = $k;
235 push @values, $self->_mutation_rhs_to_dq($data->{$k});
237 } elsif (ref($data) eq 'ARRAY') {
238 local our $Cur_Col_Meta;
239 @values = map $self->_mutation_rhs_to_dq($_), @$data;
241 die "Not handled yet";
244 if (my $r_source = $options->{returning}) {
246 map +(ref($_) ? $self->_expr_to_dq($_) : $self->_ident_to_dq($_)),
247 (ref($r_source) eq 'ARRAY' ? @$r_source : $r_source),
252 target => $self->_ident_to_dq($table),
253 (@names ? (names => [ map $self->_ident_to_dq($_), @names ]) : ()),
254 values => [ \@values ],
255 ($returning ? (returning => $returning) : ()),
259 sub _mutation_rhs_to_dq {
261 if (ref($v) eq 'ARRAY') {
262 if ($self->{array_datatypes}) {
263 return $self->_value_to_dq($v);
265 $v = \do { my $x = $v };
267 if (ref($v) eq 'HASH') {
268 my ($op, $arg, @rest) = %$v;
270 puke 'Operator calls in update/insert must be in the form { -op => $arg }'
271 if (@rest or not $op =~ /^\-(.+)/);
273 return $self->_expr_to_dq($v);
276 #======================================================================
278 #======================================================================
283 $self->_render_dq($self->_update_to_dq(@_));
287 my ($self, $table, $data, $where) = @_;
289 puke "Unsupported data type specified to \$sql->update"
290 unless ref $data eq 'HASH';
294 foreach my $k (sort keys %$data) {
296 local our $Cur_Col_Meta = $k;
297 push @set, [ $self->_ident_to_dq($k), $self->_mutation_rhs_to_dq($v) ];
302 target => $self->_ident_to_dq($table),
304 where => $self->_where_to_dq($where),
309 #======================================================================
311 #======================================================================
314 my ($self, $table, $where) = @_;
316 my $source_dq = $self->_table_to_dq($table);
318 if (my $where_dq = $self->_where_to_dq($where)) {
331 return $self->_render_dq($self->_select_to_dq(@_));
335 my ($self, $table, $fields, $where, $order) = @_;
338 my $source_dq = $self->_source_to_dq($table, $where);
343 map $self->_ident_to_dq($_),
344 ref($fields) eq 'ARRAY' ? @$fields : $fields
350 $final_dq = $self->_order_by_to_dq($order, undef, $final_dq);
356 #======================================================================
358 #======================================================================
363 $self->_render_dq($self->_delete_to_dq(@_));
367 my ($self, $table, $where) = @_;
370 target => $self->_table_to_dq($table),
371 where => $self->_where_to_dq($where),
376 #======================================================================
378 #======================================================================
382 # Finally, a separate routine just to handle WHERE clauses
384 my ($self, $where, $order) = @_;
390 ($sql, @bind) = $self->_recurse_where($where) if defined($where);
391 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
395 $sql .= $self->_order_by($order);
398 return wantarray ? ($sql, @bind) : $sql;
402 my ($self, $where, $logic) = @_;
404 return $self->_render_dq($self->_where_to_dq($where, $logic));
408 my ($self, $where, $logic) = @_;
410 return undef unless defined($where);
412 # turn the convert misfeature on - only used in WHERE clauses
413 local $self->{where_convert} = $self->{convert};
415 return $self->_expr_to_dq($where, $logic);
419 my ($self, $where, $logic) = @_;
421 if (ref($where) eq 'ARRAY') {
422 return $self->_expr_to_dq_ARRAYREF($where, $logic);
423 } elsif (ref($where) eq 'HASH') {
424 return $self->_expr_to_dq_HASHREF($where, $logic);
426 ref($where) eq 'SCALAR'
427 or (ref($where) eq 'REF' and ref($$where) eq 'ARRAY')
429 return $self->_literal_to_dq($$where);
430 } elsif (!ref($where) or Scalar::Util::blessed($where)) {
431 return $self->_value_to_dq($where);
433 die "Can't handle $where";
436 sub _expr_to_dq_ARRAYREF {
437 my ($self, $where, $logic) = @_;
439 $logic = uc($logic || $self->{logic} || 'OR');
440 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
442 return unless @$where;
444 my ($first, @rest) = @$where;
446 return $self->_expr_to_dq($first) unless @rest;
450 $self->_where_hashpair_to_dq($first => shift(@rest));
452 $self->_expr_to_dq($first);
456 return $self->_expr_to_dq_ARRAYREF(\@rest, $logic) unless $first_dq;
459 $logic, $first_dq, $self->_expr_to_dq_ARRAYREF(\@rest, $logic)
463 sub _expr_to_dq_HASHREF {
464 my ($self, $where, $logic) = @_;
466 $logic = uc($logic) if $logic;
469 $self->_where_hashpair_to_dq($_ => $where->{$_}, $logic)
472 return $dq[0] unless @dq > 1;
474 my $final = pop(@dq);
476 foreach my $dq (reverse @dq) {
477 $final = $self->_op_to_dq($logic||'AND', $dq, $final);
483 sub _where_to_dq_SCALAR {
484 shift->_value_to_dq(@_);
487 sub _where_op_IDENT {
489 my ($op, $rhs) = splice @_, -2;
491 puke "-$op takes a single scalar argument (a quotable identifier)";
494 # in case we are called as a top level special op (no '=')
497 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
505 sub _where_op_VALUE {
507 my ($op, $rhs) = splice @_, -2;
509 # in case we are called as a top level special op (no '=')
514 ($lhs || $self->{_nested_func_lhs}),
521 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
525 $self->_convert('?'),
531 sub _where_hashpair_to_dq {
532 my ($self, $k, $v, $logic) = @_;
534 if ($k =~ /^-(.*)/s) {
536 if ($op eq 'AND' or $op eq 'OR') {
537 return $self->_expr_to_dq($v, $op);
538 } elsif ($op eq 'NEST') {
539 return $self->_expr_to_dq($v);
540 } elsif ($op eq 'NOT') {
541 return $self->_op_to_dq(NOT => $self->_expr_to_dq($v));
542 } elsif ($op eq 'BOOL') {
543 return ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v);
544 } elsif ($op eq 'NOT_BOOL') {
545 return $self->_op_to_dq(
546 NOT => ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v)
548 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+/) {
549 die "Use of [and|or|nest]_N modifiers is no longer supported";
552 if (ref($v) eq 'HASH' and keys(%$v) == 1 and (keys %$v)[0] =~ /^-(.*)/s) {
554 my ($inner) = values %$v;
557 (map $self->_expr_to_dq($_),
558 (ref($inner) eq 'ARRAY' ? @$inner : $inner))
561 (map $self->_expr_to_dq($_), (ref($v) eq 'ARRAY' ? @$v : $v))
564 $self->_assert_pass_injection_guard($op);
565 return $self->_op_to_dq(
566 apply => $self->_ident_to_dq($op), @args
570 local our $Cur_Col_Meta = $k;
571 if (ref($v) eq 'ARRAY') {
573 return $self->_literal_to_dq($self->{sqlfalse});
574 } elsif (defined($v->[0]) && $v->[0] =~ /-(and|or)/i) {
575 return $self->_expr_to_dq_ARRAYREF([
576 map +{ $k => $_ }, @{$v}[1..$#$v]
579 return $self->_expr_to_dq_ARRAYREF([
580 map +{ $k => $_ }, @$v
582 } elsif (ref($v) eq 'SCALAR' or (ref($v) eq 'REF' and ref($$v) eq 'ARRAY')) {
586 parts => [ $self->_ident_to_dq($k), $self->_literal_to_dq($$v) ]
589 my ($op, $rhs) = do {
590 if (ref($v) eq 'HASH') {
592 return $self->_expr_to_dq_ARRAYREF([
593 map +{ $k => { $_ => $v->{$_} } }, sort keys %$v
596 my ($op, $value) = %$v;
597 s/^-//, s/_/ /g for $op;
598 if ($op =~ /^(and|or)$/i) {
599 return $self->_expr_to_dq({ $k => $value }, $op);
601 my $special_op = List::Util::first {$op =~ $_->{regex}}
602 @{$self->{special_ops}}
604 return $self->_literal_to_dq(
605 [ $self->${\$special_op->{handler}}($k, $op, $value) ]
607 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+$/i) {
608 die "Use of [and|or|nest]_N modifiers is no longer supported";
615 if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
616 if (ref($rhs) ne 'ARRAY') {
618 # have to add parens if none present because -in => \"SELECT ..."
619 # got documented. mst hates everything.
620 if (ref($rhs) eq 'SCALAR') {
622 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
625 my ($x, @rest) = @{$$rhs};
626 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
627 $rhs = \[ $x, @rest ];
630 return $self->_op_to_dq(
631 $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
634 return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
635 return $self->_op_to_dq(
636 $op, $self->_ident_to_dq($k), map $self->_expr_to_dq($_), @$rhs
638 } elsif ($op =~ s/^NOT (?!LIKE)//) {
639 return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
640 } elsif (!defined($rhs)) {
642 if ($op eq '=' or $op eq 'LIKE') {
644 } elsif ($op eq '!=') {
647 die "Can't do undef -> NULL transform for operator ${op}";
650 return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
652 if (ref($rhs) eq 'ARRAY') {
654 return $self->_literal_to_dq(
655 $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
657 } elsif (defined($rhs->[0]) and $rhs->[0] =~ /^-(and|or)$/i) {
658 return $self->_expr_to_dq_ARRAYREF([
659 map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
661 } elsif ($op =~ /^-(?:AND|OR|NEST)_?\d+/) {
662 die "Use of [and|or|nest]_N modifiers is no longer supported";
664 return $self->_expr_to_dq_ARRAYREF([
665 map +{ $k => { $op => $_ } }, @$rhs
668 return $self->_op_to_dq(
669 $op, $self->_ident_to_dq($k), $self->_expr_to_dq($rhs)
674 #======================================================================
676 #======================================================================
679 my ($self, $arg) = @_;
680 if (my $dq = $self->_order_by_to_dq($arg)) {
681 # SQLA generates ' ORDER BY foo'. The hilarity.
683 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
684 : ' '.$self->_render_dq($dq);
690 sub _order_by_to_dq {
691 my ($self, $arg, $dir, $from) = @_;
697 ($dir ? (direction => $dir) : ()),
698 ($from ? (from => $from) : ()),
702 $dq->{by} = $self->_ident_to_dq($arg);
703 } elsif (ref($arg) eq 'ARRAY') {
705 local our $Order_Inner unless our $Order_Recursing;
706 local $Order_Recursing = 1;
708 foreach my $member (@$arg) {
710 my $next = $self->_order_by_to_dq($member, $dir, $from);
712 $inner->{from} = $next if $inner;
713 $inner = $Order_Inner || $next;
715 $Order_Inner = $inner;
717 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
718 $dq->{by} = $self->_literal_to_dq($$arg);
719 } elsif (ref($arg) eq 'SCALAR') {
720 $dq->{by} = $self->_literal_to_dq($$arg);
721 } elsif (ref($arg) eq 'HASH') {
722 my ($key, $val, @rest) = %$arg;
726 if (@rest or not $key =~ /^-(desc|asc)/i) {
727 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
730 return $self->_order_by_to_dq($val, $dir, $from);
732 die "Can't handle $arg in _order_by_to_dq";
737 #======================================================================
738 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
739 #======================================================================
742 my ($self, $from) = @_;
743 $self->_render_dq($self->_table_to_dq($from));
747 my ($self, $from) = @_;
748 if (ref($from) eq 'ARRAY') {
749 die "Empty FROM list" unless my @f = @$from;
750 my $dq = $self->_ident_to_dq(shift @f);
751 while (my $x = shift @f) {
754 join => [ $dq, $self->_ident_to_dq($x) ]
758 } elsif (ref($from) eq 'SCALAR') {
765 $self->_ident_to_dq($from);
770 #======================================================================
772 #======================================================================
774 # highly optimized, as it's called way too often
776 # my ($self, $label) = @_;
778 return '' unless defined $_[1];
779 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
781 unless ($_[0]->{quote_char}) {
782 $_[0]->_assert_pass_injection_guard($_[1]);
786 my $qref = ref $_[0]->{quote_char};
789 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
791 elsif ($qref eq 'ARRAY') {
792 ($l, $r) = @{$_[0]->{quote_char}};
795 puke "Unsupported quote_char format: $_[0]->{quote_char}";
798 # parts containing * are naturally unquoted
799 return join( $_[0]->{name_sep}||'', map
800 { $_ eq '*' ? $_ : $l . $_ . $r }
801 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
806 # Conversion, if applicable
808 #my ($self, $arg) = @_;
810 # LDNOTE : modified the previous implementation below because
811 # it was not consistent : the first "return" is always an array,
812 # the second "return" is context-dependent. Anyway, _convert
813 # seems always used with just a single argument, so make it a
815 # return @_ unless $self->{convert};
816 # my $conv = $self->_sqlcase($self->{convert});
817 # my @ret = map { $conv.'('.$_.')' } @_;
818 # return wantarray ? @ret : $ret[0];
819 if ($_[0]->{convert}) {
820 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
827 #my ($self, $col, @vals) = @_;
829 #LDNOTE : changed original implementation below because it did not make
830 # sense when bindtype eq 'columns' and @vals > 1.
831 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
833 # called often - tighten code
834 return $_[0]->{bindtype} eq 'columns'
835 ? map {[$_[1], $_]} @_[2 .. $#_]
840 # Dies if any element of @bind is not in [colname => value] format
841 # if bindtype is 'columns'.
842 sub _assert_bindval_matches_bindtype {
843 # my ($self, @bind) = @_;
845 if ($self->{bindtype} eq 'columns') {
847 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
848 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
854 sub _join_sql_clauses {
855 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
857 if (@$clauses_aref > 1) {
858 my $join = " " . $self->_sqlcase($logic) . " ";
859 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
860 return ($sql, @$bind_aref);
862 elsif (@$clauses_aref) {
863 return ($clauses_aref->[0], @$bind_aref); # no parentheses
866 return (); # if no SQL, ignore @$bind_aref
871 # Fix SQL case, if so requested
873 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
874 # don't touch the argument ... crooked logic, but let's not change it!
875 return $_[0]->{case} ? $_[1] : uc($_[1]);
879 #======================================================================
880 # DISPATCHING FROM REFKIND
881 #======================================================================
884 my ($self, $data) = @_;
886 return 'UNDEF' unless defined $data;
888 # blessed objects are treated like scalars
889 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
891 return 'SCALAR' unless $ref;
894 while ($ref eq 'REF') {
896 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
900 return ($ref||'SCALAR') . ('REF' x $n_steps);
904 my ($self, $data) = @_;
905 my @try = ($self->_refkind($data));
906 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
907 push @try, 'FALLBACK';
911 sub _METHOD_FOR_refkind {
912 my ($self, $meth_prefix, $data) = @_;
915 for (@{$self->_try_refkind($data)}) {
916 $method = $self->can($meth_prefix."_".$_)
920 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
924 sub _SWITCH_refkind {
925 my ($self, $data, $dispatch_table) = @_;
928 for (@{$self->_try_refkind($data)}) {
929 $coderef = $dispatch_table->{$_}
933 puke "no dispatch entry for ".$self->_refkind($data)
942 #======================================================================
943 # VALUES, GENERATE, AUTOLOAD
944 #======================================================================
946 # LDNOTE: original code from nwiger, didn't touch code in that section
947 # I feel the AUTOLOAD stuff should not be the default, it should
948 # only be activated on explicit demand by user.
952 my $data = shift || return;
953 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
954 unless ref $data eq 'HASH';
957 foreach my $k ( sort keys %$data ) {
959 local our $Cur_Col_Meta = $k;
960 my ($sql, @bind) = $self->_render_dq(
961 $self->_mutation_rhs_to_dq($v)
963 push @all_bind, @bind;
972 my(@sql, @sqlq, @sqlv);
976 if ($ref eq 'HASH') {
977 for my $k (sort keys %$_) {
980 my $label = $self->_quote($k);
982 # literal SQL with bind
983 my ($sql, @bind) = @$v;
984 $self->_assert_bindval_matches_bindtype(@bind);
985 push @sqlq, "$label = $sql";
987 } elsif ($r eq 'SCALAR') {
988 # literal SQL without bind
989 push @sqlq, "$label = $$v";
991 push @sqlq, "$label = ?";
992 push @sqlv, $self->_bindtype($k, $v);
995 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
996 } elsif ($ref eq 'ARRAY') {
997 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1000 if ($r eq 'ARRAY') { # literal SQL with bind
1001 my ($sql, @bind) = @$v;
1002 $self->_assert_bindval_matches_bindtype(@bind);
1005 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1006 # embedded literal SQL
1013 push @sql, '(' . join(', ', @sqlq) . ')';
1014 } elsif ($ref eq 'SCALAR') {
1018 # strings get case twiddled
1019 push @sql, $self->_sqlcase($_);
1023 my $sql = join ' ', @sql;
1025 # this is pretty tricky
1026 # if ask for an array, return ($stmt, @bind)
1027 # otherwise, s/?/shift @sqlv/ to put it inline
1029 return ($sql, @sqlv);
1031 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1032 ref $d ? $d->[1] : $d/e;
1041 # # This allows us to check for a local, then _form, attr
1043 # my($name) = $AUTOLOAD =~ /.*::(.+)/;
1044 # return $self->generate($name, @_);
1055 SQL::Abstract - Generate SQL from Perl data structures
1061 my $sql = SQL::Abstract->new;
1063 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1065 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1067 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1069 my($stmt, @bind) = $sql->delete($table, \%where);
1071 # Then, use these in your DBI statements
1072 my $sth = $dbh->prepare($stmt);
1073 $sth->execute(@bind);
1075 # Just generate the WHERE clause
1076 my($stmt, @bind) = $sql->where(\%where, \@order);
1078 # Return values in the same order, for hashed queries
1079 # See PERFORMANCE section for more details
1080 my @bind = $sql->values(\%fieldvals);
1084 This module was inspired by the excellent L<DBIx::Abstract>.
1085 However, in using that module I found that what I really wanted
1086 to do was generate SQL, but still retain complete control over my
1087 statement handles and use the DBI interface. So, I set out to
1088 create an abstract SQL generation module.
1090 While based on the concepts used by L<DBIx::Abstract>, there are
1091 several important differences, especially when it comes to WHERE
1092 clauses. I have modified the concepts used to make the SQL easier
1093 to generate from Perl data structures and, IMO, more intuitive.
1094 The underlying idea is for this module to do what you mean, based
1095 on the data structures you provide it. The big advantage is that
1096 you don't have to modify your code every time your data changes,
1097 as this module figures it out.
1099 To begin with, an SQL INSERT is as easy as just specifying a hash
1100 of C<key=value> pairs:
1103 name => 'Jimbo Bobson',
1104 phone => '123-456-7890',
1105 address => '42 Sister Lane',
1106 city => 'St. Louis',
1107 state => 'Louisiana',
1110 The SQL can then be generated with this:
1112 my($stmt, @bind) = $sql->insert('people', \%data);
1114 Which would give you something like this:
1116 $stmt = "INSERT INTO people
1117 (address, city, name, phone, state)
1118 VALUES (?, ?, ?, ?, ?)";
1119 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1120 '123-456-7890', 'Louisiana');
1122 These are then used directly in your DBI code:
1124 my $sth = $dbh->prepare($stmt);
1125 $sth->execute(@bind);
1127 =head2 Inserting and Updating Arrays
1129 If your database has array types (like for example Postgres),
1130 activate the special option C<< array_datatypes => 1 >>
1131 when creating the C<SQL::Abstract> object.
1132 Then you may use an arrayref to insert and update database array types:
1134 my $sql = SQL::Abstract->new(array_datatypes => 1);
1136 planets => [qw/Mercury Venus Earth Mars/]
1139 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1143 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1145 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1148 =head2 Inserting and Updating SQL
1150 In order to apply SQL functions to elements of your C<%data> you may
1151 specify a reference to an arrayref for the given hash value. For example,
1152 if you need to execute the Oracle C<to_date> function on a value, you can
1153 say something like this:
1157 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1160 The first value in the array is the actual SQL. Any other values are
1161 optional and would be included in the bind values array. This gives
1164 my($stmt, @bind) = $sql->insert('people', \%data);
1166 $stmt = "INSERT INTO people (name, date_entered)
1167 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1168 @bind = ('Bill', '03/02/2003');
1170 An UPDATE is just as easy, all you change is the name of the function:
1172 my($stmt, @bind) = $sql->update('people', \%data);
1174 Notice that your C<%data> isn't touched; the module will generate
1175 the appropriately quirky SQL for you automatically. Usually you'll
1176 want to specify a WHERE clause for your UPDATE, though, which is
1177 where handling C<%where> hashes comes in handy...
1179 =head2 Complex where statements
1181 This module can generate pretty complicated WHERE statements
1182 easily. For example, simple C<key=value> pairs are taken to mean
1183 equality, and if you want to see if a field is within a set
1184 of values, you can use an arrayref. Let's say we wanted to
1185 SELECT some data based on this criteria:
1188 requestor => 'inna',
1189 worker => ['nwiger', 'rcwe', 'sfz'],
1190 status => { '!=', 'completed' }
1193 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1195 The above would give you something like this:
1197 $stmt = "SELECT * FROM tickets WHERE
1198 ( requestor = ? ) AND ( status != ? )
1199 AND ( worker = ? OR worker = ? OR worker = ? )";
1200 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1202 Which you could then use in DBI code like so:
1204 my $sth = $dbh->prepare($stmt);
1205 $sth->execute(@bind);
1211 The functions are simple. There's one for each major SQL operation,
1212 and a constructor you use first. The arguments are specified in a
1213 similar order to each function (table, then fields, then a where
1214 clause) to try and simplify things.
1219 =head2 new(option => 'value')
1221 The C<new()> function takes a list of options and values, and returns
1222 a new B<SQL::Abstract> object which can then be used to generate SQL
1223 through the methods below. The options accepted are:
1229 If set to 'lower', then SQL will be generated in all lowercase. By
1230 default SQL is generated in "textbook" case meaning something like:
1232 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1234 Any setting other than 'lower' is ignored.
1238 This determines what the default comparison operator is. By default
1239 it is C<=>, meaning that a hash like this:
1241 %where = (name => 'nwiger', email => 'nate@wiger.org');
1243 Will generate SQL like this:
1245 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1247 However, you may want loose comparisons by default, so if you set
1248 C<cmp> to C<like> you would get SQL such as:
1250 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1252 You can also override the comparsion on an individual basis - see
1253 the huge section on L</"WHERE CLAUSES"> at the bottom.
1255 =item sqltrue, sqlfalse
1257 Expressions for inserting boolean values within SQL statements.
1258 By default these are C<1=1> and C<1=0>. They are used
1259 by the special operators C<-in> and C<-not_in> for generating
1260 correct SQL even when the argument is an empty array (see below).
1264 This determines the default logical operator for multiple WHERE
1265 statements in arrays or hashes. If absent, the default logic is "or"
1266 for arrays, and "and" for hashes. This means that a WHERE
1270 event_date => {'>=', '2/13/99'},
1271 event_date => {'<=', '4/24/03'},
1274 will generate SQL like this:
1276 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1278 This is probably not what you want given this query, though (look
1279 at the dates). To change the "OR" to an "AND", simply specify:
1281 my $sql = SQL::Abstract->new(logic => 'and');
1283 Which will change the above C<WHERE> to:
1285 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1287 The logic can also be changed locally by inserting
1288 a modifier in front of an arrayref :
1290 @where = (-and => [event_date => {'>=', '2/13/99'},
1291 event_date => {'<=', '4/24/03'} ]);
1293 See the L</"WHERE CLAUSES"> section for explanations.
1297 This will automatically convert comparisons using the specified SQL
1298 function for both column and value. This is mostly used with an argument
1299 of C<upper> or C<lower>, so that the SQL will have the effect of
1300 case-insensitive "searches". For example, this:
1302 $sql = SQL::Abstract->new(convert => 'upper');
1303 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1305 Will turn out the following SQL:
1307 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1309 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1310 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1311 not validate this option; it will just pass through what you specify verbatim).
1315 This is a kludge because many databases suck. For example, you can't
1316 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1317 Instead, you have to use C<bind_param()>:
1319 $sth->bind_param(1, 'reg data');
1320 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1322 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1323 which loses track of which field each slot refers to. Fear not.
1325 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1326 Currently, you can specify either C<normal> (default) or C<columns>. If you
1327 specify C<columns>, you will get an array that looks like this:
1329 my $sql = SQL::Abstract->new(bindtype => 'columns');
1330 my($stmt, @bind) = $sql->insert(...);
1333 [ 'column1', 'value1' ],
1334 [ 'column2', 'value2' ],
1335 [ 'column3', 'value3' ],
1338 You can then iterate through this manually, using DBI's C<bind_param()>.
1340 $sth->prepare($stmt);
1343 my($col, $data) = @$_;
1344 if ($col eq 'details' || $col eq 'comments') {
1345 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1346 } elsif ($col eq 'image') {
1347 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1349 $sth->bind_param($i, $data);
1353 $sth->execute; # execute without @bind now
1355 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1356 Basically, the advantage is still that you don't have to care which fields
1357 are or are not included. You could wrap that above C<for> loop in a simple
1358 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1359 get a layer of abstraction over manual SQL specification.
1361 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1362 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1363 will expect the bind values in this format.
1367 This is the character that a table or column name will be quoted
1368 with. By default this is an empty string, but you could set it to
1369 the character C<`>, to generate SQL like this:
1371 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1373 Alternatively, you can supply an array ref of two items, the first being the left
1374 hand quote character, and the second the right hand quote character. For
1375 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1376 that generates SQL like this:
1378 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1380 Quoting is useful if you have tables or columns names that are reserved
1381 words in your database's SQL dialect.
1385 This is the character that separates a table and column name. It is
1386 necessary to specify this when the C<quote_char> option is selected,
1387 so that tables and column names can be individually quoted like this:
1389 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1391 =item injection_guard
1393 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1394 column name specified in a query structure. This is a safety mechanism to avoid
1395 injection attacks when mishandling user input e.g.:
1397 my %condition_as_column_value_pairs = get_values_from_user();
1398 $sqla->select( ... , \%condition_as_column_value_pairs );
1400 If the expression matches an exception is thrown. Note that literal SQL
1401 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1403 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1405 =item array_datatypes
1407 When this option is true, arrayrefs in INSERT or UPDATE are
1408 interpreted as array datatypes and are passed directly
1410 When this option is false, arrayrefs are interpreted
1411 as literal SQL, just like refs to arrayrefs
1412 (but this behavior is for backwards compatibility; when writing
1413 new queries, use the "reference to arrayref" syntax
1419 Takes a reference to a list of "special operators"
1420 to extend the syntax understood by L<SQL::Abstract>.
1421 See section L</"SPECIAL OPERATORS"> for details.
1425 Takes a reference to a list of "unary operators"
1426 to extend the syntax understood by L<SQL::Abstract>.
1427 See section L</"UNARY OPERATORS"> for details.
1433 =head2 insert($table, \@values || \%fieldvals, \%options)
1435 This is the simplest function. You simply give it a table name
1436 and either an arrayref of values or hashref of field/value pairs.
1437 It returns an SQL INSERT statement and a list of bind values.
1438 See the sections on L</"Inserting and Updating Arrays"> and
1439 L</"Inserting and Updating SQL"> for information on how to insert
1440 with those data types.
1442 The optional C<\%options> hash reference may contain additional
1443 options to generate the insert SQL. Currently supported options
1450 Takes either a scalar of raw SQL fields, or an array reference of
1451 field names, and adds on an SQL C<RETURNING> statement at the end.
1452 This allows you to return data generated by the insert statement
1453 (such as row IDs) without performing another C<SELECT> statement.
1454 Note, however, this is not part of the SQL standard and may not
1455 be supported by all database engines.
1459 =head2 update($table, \%fieldvals, \%where)
1461 This takes a table, hashref of field/value pairs, and an optional
1462 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1464 See the sections on L</"Inserting and Updating Arrays"> and
1465 L</"Inserting and Updating SQL"> for information on how to insert
1466 with those data types.
1468 =head2 select($source, $fields, $where, $order)
1470 This returns a SQL SELECT statement and associated list of bind values, as
1471 specified by the arguments :
1477 Specification of the 'FROM' part of the statement.
1478 The argument can be either a plain scalar (interpreted as a table
1479 name, will be quoted), or an arrayref (interpreted as a list
1480 of table names, joined by commas, quoted), or a scalarref
1481 (literal table name, not quoted), or a ref to an arrayref
1482 (list of literal table names, joined by commas, not quoted).
1486 Specification of the list of fields to retrieve from
1488 The argument can be either an arrayref (interpreted as a list
1489 of field names, will be joined by commas and quoted), or a
1490 plain scalar (literal SQL, not quoted).
1491 Please observe that this API is not as flexible as for
1492 the first argument C<$table>, for backwards compatibility reasons.
1496 Optional argument to specify the WHERE part of the query.
1497 The argument is most often a hashref, but can also be
1498 an arrayref or plain scalar --
1499 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1503 Optional argument to specify the ORDER BY part of the query.
1504 The argument can be a scalar, a hashref or an arrayref
1505 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1511 =head2 delete($table, \%where)
1513 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1514 It returns an SQL DELETE statement and list of bind values.
1516 =head2 where(\%where, \@order)
1518 This is used to generate just the WHERE clause. For example,
1519 if you have an arbitrary data structure and know what the
1520 rest of your SQL is going to look like, but want an easy way
1521 to produce a WHERE clause, use this. It returns an SQL WHERE
1522 clause and list of bind values.
1525 =head2 values(\%data)
1527 This just returns the values from the hash C<%data>, in the same
1528 order that would be returned from any of the other above queries.
1529 Using this allows you to markedly speed up your queries if you
1530 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1532 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1534 Warning: This is an experimental method and subject to change.
1536 This returns arbitrarily generated SQL. It's a really basic shortcut.
1537 It will return two different things, depending on return context:
1539 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1540 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1542 These would return the following:
1544 # First calling form
1545 $stmt = "CREATE TABLE test (?, ?)";
1546 @bind = (field1, field2);
1548 # Second calling form
1549 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1551 Depending on what you're trying to do, it's up to you to choose the correct
1552 format. In this example, the second form is what you would want.
1556 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1560 ALTER SESSION SET nls_date_format = 'MM/YY'
1562 You get the idea. Strings get their case twiddled, but everything
1563 else remains verbatim.
1565 =head1 WHERE CLAUSES
1569 This module uses a variation on the idea from L<DBIx::Abstract>. It
1570 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1571 module is that things in arrays are OR'ed, and things in hashes
1574 The easiest way to explain is to show lots of examples. After
1575 each C<%where> hash shown, it is assumed you used:
1577 my($stmt, @bind) = $sql->where(\%where);
1579 However, note that the C<%where> hash can be used directly in any
1580 of the other functions as well, as described above.
1582 =head2 Key-value pairs
1584 So, let's get started. To begin, a simple hash:
1588 status => 'completed'
1591 Is converted to SQL C<key = val> statements:
1593 $stmt = "WHERE user = ? AND status = ?";
1594 @bind = ('nwiger', 'completed');
1596 One common thing I end up doing is having a list of values that
1597 a field can be in. To do this, simply specify a list inside of
1602 status => ['assigned', 'in-progress', 'pending'];
1605 This simple code will create the following:
1607 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1608 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1610 A field associated to an empty arrayref will be considered a
1611 logical false and will generate 0=1.
1613 =head2 Tests for NULL values
1615 If the value part is C<undef> then this is converted to SQL <IS NULL>
1624 $stmt = "WHERE user = ? AND status IS NULL";
1627 To test if a column IS NOT NULL:
1631 status => { '!=', undef },
1634 =head2 Specific comparison operators
1636 If you want to specify a different type of operator for your comparison,
1637 you can use a hashref for a given column:
1641 status => { '!=', 'completed' }
1644 Which would generate:
1646 $stmt = "WHERE user = ? AND status != ?";
1647 @bind = ('nwiger', 'completed');
1649 To test against multiple values, just enclose the values in an arrayref:
1651 status => { '=', ['assigned', 'in-progress', 'pending'] };
1653 Which would give you:
1655 "WHERE status = ? OR status = ? OR status = ?"
1658 The hashref can also contain multiple pairs, in which case it is expanded
1659 into an C<AND> of its elements:
1663 status => { '!=', 'completed', -not_like => 'pending%' }
1666 # Or more dynamically, like from a form
1667 $where{user} = 'nwiger';
1668 $where{status}{'!='} = 'completed';
1669 $where{status}{'-not_like'} = 'pending%';
1671 # Both generate this
1672 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1673 @bind = ('nwiger', 'completed', 'pending%');
1676 To get an OR instead, you can combine it with the arrayref idea:
1680 priority => [ { '=', 2 }, { '>', 5 } ]
1683 Which would generate:
1685 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1686 @bind = ('2', '5', 'nwiger');
1688 If you want to include literal SQL (with or without bind values), just use a
1689 scalar reference or array reference as the value:
1692 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1693 date_expires => { '<' => \"now()" }
1696 Which would generate:
1698 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1699 @bind = ('11/26/2008');
1702 =head2 Logic and nesting operators
1704 In the example above,
1705 there is a subtle trap if you want to say something like
1706 this (notice the C<AND>):
1708 WHERE priority != ? AND priority != ?
1710 Because, in Perl you I<can't> do this:
1712 priority => { '!=', 2, '!=', 1 }
1714 As the second C<!=> key will obliterate the first. The solution
1715 is to use the special C<-modifier> form inside an arrayref:
1717 priority => [ -and => {'!=', 2},
1721 Normally, these would be joined by C<OR>, but the modifier tells it
1722 to use C<AND> instead. (Hint: You can use this in conjunction with the
1723 C<logic> option to C<new()> in order to change the way your queries
1724 work by default.) B<Important:> Note that the C<-modifier> goes
1725 B<INSIDE> the arrayref, as an extra first element. This will
1726 B<NOT> do what you think it might:
1728 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1730 Here is a quick list of equivalencies, since there is some overlap:
1733 status => {'!=', 'completed', 'not like', 'pending%' }
1734 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1737 status => {'=', ['assigned', 'in-progress']}
1738 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1739 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1743 =head2 Special operators : IN, BETWEEN, etc.
1745 You can also use the hashref format to compare a list of fields using the
1746 C<IN> comparison operator, by specifying the list as an arrayref:
1749 status => 'completed',
1750 reportid => { -in => [567, 2335, 2] }
1753 Which would generate:
1755 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1756 @bind = ('completed', '567', '2335', '2');
1758 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1761 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1762 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1763 'sqltrue' (by default : C<1=1>).
1765 In addition to the array you can supply a chunk of literal sql or
1766 literal sql with bind:
1769 customer => { -in => \[
1770 'SELECT cust_id FROM cust WHERE balance > ?',
1773 status => { -in => \'SELECT status_codes FROM states' },
1779 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1780 AND status IN ( SELECT status_codes FROM states )
1786 Another pair of operators is C<-between> and C<-not_between>,
1787 used with an arrayref of two values:
1791 completion_date => {
1792 -not_between => ['2002-10-01', '2003-02-06']
1798 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1800 Just like with C<-in> all plausible combinations of literal SQL
1804 start0 => { -between => [ 1, 2 ] },
1805 start1 => { -between => \["? AND ?", 1, 2] },
1806 start2 => { -between => \"lower(x) AND upper(y)" },
1807 start3 => { -between => [
1809 \["upper(?)", 'stuff' ],
1816 ( start0 BETWEEN ? AND ? )
1817 AND ( start1 BETWEEN ? AND ? )
1818 AND ( start2 BETWEEN lower(x) AND upper(y) )
1819 AND ( start3 BETWEEN lower(x) AND upper(?) )
1821 @bind = (1, 2, 1, 2, 'stuff');
1824 These are the two builtin "special operators"; but the
1825 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1827 =head2 Unary operators: bool
1829 If you wish to test against boolean columns or functions within your
1830 database you can use the C<-bool> and C<-not_bool> operators. For
1831 example to test the column C<is_user> being true and the column
1832 C<is_enabled> being false you would use:-
1836 -not_bool => 'is_enabled',
1841 WHERE is_user AND NOT is_enabled
1843 If a more complex combination is required, testing more conditions,
1844 then you should use the and/or operators:-
1851 -not_bool => 'four',
1857 WHERE one AND two AND three AND NOT four
1860 =head2 Nested conditions, -and/-or prefixes
1862 So far, we've seen how multiple conditions are joined with a top-level
1863 C<AND>. We can change this by putting the different conditions we want in
1864 hashes and then putting those hashes in an array. For example:
1869 status => { -like => ['pending%', 'dispatched'] },
1873 status => 'unassigned',
1877 This data structure would create the following:
1879 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1880 OR ( user = ? AND status = ? ) )";
1881 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1884 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
1885 to change the logic inside :
1891 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1892 -or => { workhrs => {'<', 50}, geo => 'EURO' },
1899 WHERE ( user = ? AND (
1900 ( workhrs > ? AND geo = ? )
1901 OR ( workhrs < ? OR geo = ? )
1904 =head3 Algebraic inconsistency, for historical reasons
1906 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
1907 operator goes C<outside> of the nested structure; whereas when connecting
1908 several constraints on one column, the C<-and> operator goes
1909 C<inside> the arrayref. Here is an example combining both features :
1912 -and => [a => 1, b => 2],
1913 -or => [c => 3, d => 4],
1914 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
1919 WHERE ( ( ( a = ? AND b = ? )
1920 OR ( c = ? OR d = ? )
1921 OR ( e LIKE ? AND e LIKE ? ) ) )
1923 This difference in syntax is unfortunate but must be preserved for
1924 historical reasons. So be careful : the two examples below would
1925 seem algebraically equivalent, but they are not
1927 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
1928 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
1930 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
1931 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
1934 =head2 Literal SQL and value type operators
1936 The basic premise of SQL::Abstract is that in WHERE specifications the "left
1937 side" is a column name and the "right side" is a value (normally rendered as
1938 a placeholder). This holds true for both hashrefs and arrayref pairs as you
1939 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
1940 alter this behavior. There are several ways of doing so.
1944 This is a virtual operator that signals the string to its right side is an
1945 identifier (a column name) and not a value. For example to compare two
1946 columns you would write:
1949 priority => { '<', 2 },
1950 requestor => { -ident => 'submitter' },
1955 $stmt = "WHERE priority < ? AND requestor = submitter";
1958 If you are maintaining legacy code you may see a different construct as
1959 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
1964 This is a virtual operator that signals that the construct to its right side
1965 is a value to be passed to DBI. This is for example necessary when you want
1966 to write a where clause against an array (for RDBMS that support such
1967 datatypes). For example:
1970 array => { -value => [1, 2, 3] }
1975 $stmt = 'WHERE array = ?';
1976 @bind = ([1, 2, 3]);
1978 Note that if you were to simply say:
1984 the result would porbably be not what you wanted:
1986 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
1991 Finally, sometimes only literal SQL will do. To include a random snippet
1992 of SQL verbatim, you specify it as a scalar reference. Consider this only
1993 as a last resort. Usually there is a better way. For example:
1996 priority => { '<', 2 },
1997 requestor => { -in => \'(SELECT name FROM hitmen)' },
2002 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2005 Note that in this example, you only get one bind parameter back, since
2006 the verbatim SQL is passed as part of the statement.
2010 Never use untrusted input as a literal SQL argument - this is a massive
2011 security risk (there is no way to check literal snippets for SQL
2012 injections and other nastyness). If you need to deal with untrusted input
2013 use literal SQL with placeholders as described next.
2015 =head3 Literal SQL with placeholders and bind values (subqueries)
2017 If the literal SQL to be inserted has placeholders and bind values,
2018 use a reference to an arrayref (yes this is a double reference --
2019 not so common, but perfectly legal Perl). For example, to find a date
2020 in Postgres you can use something like this:
2023 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2028 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2031 Note that you must pass the bind values in the same format as they are returned
2032 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2033 provide the bind values in the C<< [ column_meta => value ] >> format, where
2034 C<column_meta> is an opaque scalar value; most commonly the column name, but
2035 you can use any scalar value (including references and blessed references),
2036 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2037 to C<columns> the above example will look like:
2040 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2043 Literal SQL is especially useful for nesting parenthesized clauses in the
2044 main SQL query. Here is a first example :
2046 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2050 bar => \["IN ($sub_stmt)" => @sub_bind],
2055 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2056 WHERE c2 < ? AND c3 LIKE ?))";
2057 @bind = (1234, 100, "foo%");
2059 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2060 are expressed in the same way. Of course the C<$sub_stmt> and
2061 its associated bind values can be generated through a former call
2064 my ($sub_stmt, @sub_bind)
2065 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2066 c3 => {-like => "foo%"}});
2069 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2072 In the examples above, the subquery was used as an operator on a column;
2073 but the same principle also applies for a clause within the main C<%where>
2074 hash, like an EXISTS subquery :
2076 my ($sub_stmt, @sub_bind)
2077 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2078 my %where = ( -and => [
2080 \["EXISTS ($sub_stmt)" => @sub_bind],
2085 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2086 WHERE c1 = ? AND c2 > t0.c0))";
2090 Observe that the condition on C<c2> in the subquery refers to
2091 column C<t0.c0> of the main query : this is I<not> a bind
2092 value, so we have to express it through a scalar ref.
2093 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2094 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2095 what we wanted here.
2097 Finally, here is an example where a subquery is used
2098 for expressing unary negation:
2100 my ($sub_stmt, @sub_bind)
2101 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2102 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2104 lname => {like => '%son%'},
2105 \["NOT ($sub_stmt)" => @sub_bind],
2110 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2111 @bind = ('%son%', 10, 20)
2113 =head3 Deprecated usage of Literal SQL
2115 Below are some examples of archaic use of literal SQL. It is shown only as
2116 reference for those who deal with legacy code. Each example has a much
2117 better, cleaner and safer alternative that users should opt for in new code.
2123 my %where = ( requestor => \'IS NOT NULL' )
2125 $stmt = "WHERE requestor IS NOT NULL"
2127 This used to be the way of generating NULL comparisons, before the handling
2128 of C<undef> got formalized. For new code please use the superior syntax as
2129 described in L</Tests for NULL values>.
2133 my %where = ( requestor => \'= submitter' )
2135 $stmt = "WHERE requestor = submitter"
2137 This used to be the only way to compare columns. Use the superior L</-ident>
2138 method for all new code. For example an identifier declared in such a way
2139 will be properly quoted if L</quote_char> is properly set, while the legacy
2140 form will remain as supplied.
2144 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2146 $stmt = "WHERE completed > ? AND is_ready"
2147 @bind = ('2012-12-21')
2149 Using an empty string literal used to be the only way to express a boolean.
2150 For all new code please use the much more readable
2151 L<-bool|/Unary operators: bool> operator.
2157 These pages could go on for a while, since the nesting of the data
2158 structures this module can handle are pretty much unlimited (the
2159 module implements the C<WHERE> expansion as a recursive function
2160 internally). Your best bet is to "play around" with the module a
2161 little to see how the data structures behave, and choose the best
2162 format for your data based on that.
2164 And of course, all the values above will probably be replaced with
2165 variables gotten from forms or the command line. After all, if you
2166 knew everything ahead of time, you wouldn't have to worry about
2167 dynamically-generating SQL and could just hardwire it into your
2170 =head1 ORDER BY CLAUSES
2172 Some functions take an order by clause. This can either be a scalar (just a
2173 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2174 or an array of either of the two previous forms. Examples:
2176 Given | Will Generate
2177 ----------------------------------------------------------
2179 \'colA DESC' | ORDER BY colA DESC
2181 'colA' | ORDER BY colA
2183 [qw/colA colB/] | ORDER BY colA, colB
2185 {-asc => 'colA'} | ORDER BY colA ASC
2187 {-desc => 'colB'} | ORDER BY colB DESC
2189 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2191 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2194 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2195 { -desc => [qw/colB/], | colC ASC, colD ASC
2196 { -asc => [qw/colC colD/],|
2198 ===========================================================
2202 =head1 SPECIAL OPERATORS
2204 my $sqlmaker = SQL::Abstract->new(special_ops => [
2208 my ($self, $field, $op, $arg) = @_;
2214 handler => 'method_name',
2218 A "special operator" is a SQL syntactic clause that can be
2219 applied to a field, instead of a usual binary operator.
2222 WHERE field IN (?, ?, ?)
2223 WHERE field BETWEEN ? AND ?
2224 WHERE MATCH(field) AGAINST (?, ?)
2226 Special operators IN and BETWEEN are fairly standard and therefore
2227 are builtin within C<SQL::Abstract> (as the overridable methods
2228 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2229 like the MATCH .. AGAINST example above which is specific to MySQL,
2230 you can write your own operator handlers - supply a C<special_ops>
2231 argument to the C<new> method. That argument takes an arrayref of
2232 operator definitions; each operator definition is a hashref with two
2239 the regular expression to match the operator
2243 Either a coderef or a plain scalar method name. In both cases
2244 the expected return is C<< ($sql, @bind) >>.
2246 When supplied with a method name, it is simply called on the
2247 L<SQL::Abstract/> object as:
2249 $self->$method_name ($field, $op, $arg)
2253 $op is the part that matched the handler regex
2254 $field is the LHS of the operator
2257 When supplied with a coderef, it is called as:
2259 $coderef->($self, $field, $op, $arg)
2264 For example, here is an implementation
2265 of the MATCH .. AGAINST syntax for MySQL
2267 my $sqlmaker = SQL::Abstract->new(special_ops => [
2269 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2270 {regex => qr/^match$/i,
2272 my ($self, $field, $op, $arg) = @_;
2273 $arg = [$arg] if not ref $arg;
2274 my $label = $self->_quote($field);
2275 my ($placeholder) = $self->_convert('?');
2276 my $placeholders = join ", ", (($placeholder) x @$arg);
2277 my $sql = $self->_sqlcase('match') . " ($label) "
2278 . $self->_sqlcase('against') . " ($placeholders) ";
2279 my @bind = $self->_bindtype($field, @$arg);
2280 return ($sql, @bind);
2287 =head1 UNARY OPERATORS
2289 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2293 my ($self, $op, $arg) = @_;
2299 handler => 'method_name',
2303 A "unary operator" is a SQL syntactic clause that can be
2304 applied to a field - the operator goes before the field
2306 You can write your own operator handlers - supply a C<unary_ops>
2307 argument to the C<new> method. That argument takes an arrayref of
2308 operator definitions; each operator definition is a hashref with two
2315 the regular expression to match the operator
2319 Either a coderef or a plain scalar method name. In both cases
2320 the expected return is C<< $sql >>.
2322 When supplied with a method name, it is simply called on the
2323 L<SQL::Abstract/> object as:
2325 $self->$method_name ($op, $arg)
2329 $op is the part that matched the handler regex
2330 $arg is the RHS or argument of the operator
2332 When supplied with a coderef, it is called as:
2334 $coderef->($self, $op, $arg)
2342 Thanks to some benchmarking by Mark Stosberg, it turns out that
2343 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2344 I must admit this wasn't an intentional design issue, but it's a
2345 byproduct of the fact that you get to control your C<DBI> handles
2348 To maximize performance, use a code snippet like the following:
2350 # prepare a statement handle using the first row
2351 # and then reuse it for the rest of the rows
2353 for my $href (@array_of_hashrefs) {
2354 $stmt ||= $sql->insert('table', $href);
2355 $sth ||= $dbh->prepare($stmt);
2356 $sth->execute($sql->values($href));
2359 The reason this works is because the keys in your C<$href> are sorted
2360 internally by B<SQL::Abstract>. Thus, as long as your data retains
2361 the same structure, you only have to generate the SQL the first time
2362 around. On subsequent queries, simply use the C<values> function provided
2363 by this module to return your values in the correct order.
2365 However this depends on the values having the same type - if, for
2366 example, the values of a where clause may either have values
2367 (resulting in sql of the form C<column = ?> with a single bind
2368 value), or alternatively the values might be C<undef> (resulting in
2369 sql of the form C<column IS NULL> with no bind value) then the
2370 caching technique suggested will not work.
2374 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2375 really like this part (I do, at least). Building up a complex query
2376 can be as simple as the following:
2380 use CGI::FormBuilder;
2383 my $form = CGI::FormBuilder->new(...);
2384 my $sql = SQL::Abstract->new;
2386 if ($form->submitted) {
2387 my $field = $form->field;
2388 my $id = delete $field->{id};
2389 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2392 Of course, you would still have to connect using C<DBI> to run the
2393 query, but the point is that if you make your form look like your
2394 table, the actual query script can be extremely simplistic.
2396 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2397 a fast interface to returning and formatting data. I frequently
2398 use these three modules together to write complex database query
2399 apps in under 50 lines.
2405 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2407 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2413 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2414 Great care has been taken to preserve the I<published> behavior
2415 documented in previous versions in the 1.* family; however,
2416 some features that were previously undocumented, or behaved
2417 differently from the documentation, had to be changed in order
2418 to clarify the semantics. Hence, client code that was relying
2419 on some dark areas of C<SQL::Abstract> v1.*
2420 B<might behave differently> in v1.50.
2422 The main changes are :
2428 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2432 support for the { operator => \"..." } construct (to embed literal SQL)
2436 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2440 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2444 defensive programming : check arguments
2448 fixed bug with global logic, which was previously implemented
2449 through global variables yielding side-effects. Prior versions would
2450 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2451 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2452 Now this is interpreted
2453 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2458 fixed semantics of _bindtype on array args
2462 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2463 we just avoid shifting arrays within that tree.
2467 dropped the C<_modlogic> function
2471 =head1 ACKNOWLEDGEMENTS
2473 There are a number of individuals that have really helped out with
2474 this module. Unfortunately, most of them submitted bugs via CPAN
2475 so I have no idea who they are! But the people I do know are:
2477 Ash Berlin (order_by hash term support)
2478 Matt Trout (DBIx::Class support)
2479 Mark Stosberg (benchmarking)
2480 Chas Owens (initial "IN" operator support)
2481 Philip Collins (per-field SQL functions)
2482 Eric Kolve (hashref "AND" support)
2483 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2484 Dan Kubb (support for "quote_char" and "name_sep")
2485 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2486 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2487 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2488 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2489 Oliver Charles (support for "RETURNING" after "INSERT")
2495 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2499 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2501 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2503 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2504 While not an official support venue, C<DBIx::Class> makes heavy use of
2505 C<SQL::Abstract>, and as such list members there are very familiar with
2506 how to create queries.
2510 This module is free software; you may copy this under the same
2511 terms as perl itself (either the GNU General Public License or
2512 the Artistic License)