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 #======================================================================
446 my ($self, $table, $where) = @_;
448 my $source_dq = $self->_table_to_dq($table);
450 if (defined($where) and my $where_dq = $self->_where_to_dq($where)) {
464 my $fields = shift || '*';
468 my $source_dq = $self->_source_to_dq($table, $where);
473 map $self->_ident_to_dq($_),
474 ref($fields) eq 'ARRAY' ? @$fields : $fields
480 $final_dq = $self->_order_by_to_dq($order, undef, $final_dq);
483 return $self->_render_dq($final_dq);
486 #======================================================================
488 #======================================================================
493 $self->_render_dq($self->_delete_to_dq(@_));
500 from => $self->_source_to_dq(@_)
505 #======================================================================
507 #======================================================================
511 # Finally, a separate routine just to handle WHERE clauses
513 my ($self, $where, $order) = @_;
519 ($sql, @bind) = $self->_recurse_where($where) if defined($where);
520 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
524 $sql .= $self->_order_by($order);
527 return wantarray ? ($sql, @bind) : $sql;
531 my ($self, $where, $logic) = @_;
533 return $self->_render_dq($self->_where_to_dq($where, $logic));
537 my ($self, $where, $logic) = @_;
539 # turn the convert misfeature on - only used in WHERE clauses
540 local $self->{where_convert} = $self->{convert};
542 return $self->_expr_to_dq($where, $logic);
546 my ($self, $where, $logic) = @_;
548 if (ref($where) eq 'ARRAY') {
549 return $self->_expr_to_dq_ARRAYREF($where, $logic);
550 } elsif (ref($where) eq 'HASH') {
551 return $self->_expr_to_dq_HASHREF($where, $logic);
553 ref($where) eq 'SCALAR'
554 or (ref($where) eq 'REF' and ref($$where) eq 'ARRAY')
556 return $self->_literal_to_dq($$where);
557 } elsif (!ref($where) or Scalar::Util::blessed($where)) {
558 return $self->_value_to_dq($where);
560 die "Can't handle $where";
563 sub _expr_to_dq_ARRAYREF {
564 my ($self, $where, $logic) = @_;
566 $logic = uc($logic || $self->{logic} || 'OR');
567 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
569 return unless @$where;
571 my ($first, @rest) = @$where;
573 return $self->_expr_to_dq($first) unless @rest;
577 $self->_where_hashpair_to_dq($first => shift(@rest));
579 $self->_expr_to_dq($first);
583 return $self->_expr_to_dq_ARRAYREF(\@rest, $logic) unless $first_dq;
586 $logic, $first_dq, $self->_expr_to_dq_ARRAYREF(\@rest, $logic)
590 sub _expr_to_dq_HASHREF {
591 my ($self, $where, $logic) = @_;
593 $logic = uc($logic) if $logic;
596 $self->_where_hashpair_to_dq($_ => $where->{$_}, $logic)
599 return $dq[0] unless @dq > 1;
601 my $final = pop(@dq);
603 foreach my $dq (reverse @dq) {
604 $final = $self->_op_to_dq($logic||'AND', $dq, $final);
610 sub _where_to_dq_SCALAR {
611 shift->_value_to_dq(@_);
614 sub _where_op_IDENT {
616 my ($op, $rhs) = splice @_, -2;
618 puke "-$op takes a single scalar argument (a quotable identifier)";
621 # in case we are called as a top level special op (no '=')
624 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
632 sub _where_op_VALUE {
634 my ($op, $rhs) = splice @_, -2;
636 # in case we are called as a top level special op (no '=')
641 ($lhs || $self->{_nested_func_lhs}),
648 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
652 $self->_convert('?'),
658 sub _where_hashpair_to_dq {
659 my ($self, $k, $v, $logic) = @_;
661 if ($k =~ /^-(.*)/s) {
663 if ($op eq 'AND' or $op eq 'OR') {
664 return $self->_expr_to_dq($v, $op);
665 } elsif ($op eq 'NEST') {
666 return $self->_expr_to_dq($v);
667 } elsif ($op eq 'NOT') {
668 return $self->_op_to_dq(NOT => $self->_expr_to_dq($v));
669 } elsif ($op eq 'BOOL') {
670 return ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v);
671 } elsif ($op eq 'NOT_BOOL') {
672 return $self->_op_to_dq(
673 NOT => ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v)
675 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+/) {
676 die "Use of [and|or|nest]_N modifiers is no longer supported";
679 if (ref($v) eq 'HASH' and keys(%$v) == 1 and (keys %$v)[0] =~ /^-(.*)/s) {
681 my ($inner) = values %$v;
684 (map $self->_expr_to_dq($_),
685 (ref($inner) eq 'ARRAY' ? @$inner : $inner))
688 (map $self->_expr_to_dq($_), (ref($v) eq 'ARRAY' ? @$v : $v))
691 $self->_assert_pass_injection_guard($op);
692 return $self->_op_to_dq(
693 apply => $self->_ident_to_dq($op), @args
697 local our $Cur_Col_Meta = $k;
698 if (ref($v) eq 'ARRAY') {
700 return $self->_literal_to_dq($self->{sqlfalse});
701 } elsif (defined($v->[0]) && $v->[0] =~ /-(and|or)/i) {
702 return $self->_expr_to_dq_ARRAYREF([
703 map +{ $k => $_ }, @{$v}[1..$#$v]
706 return $self->_expr_to_dq_ARRAYREF([
707 map +{ $k => $_ }, @$v
709 } elsif (ref($v) eq 'SCALAR' or (ref($v) eq 'REF' and ref($$v) eq 'ARRAY')) {
713 parts => [ $self->_ident_to_dq($k), $self->_literal_to_dq($$v) ]
716 my ($op, $rhs) = do {
717 if (ref($v) eq 'HASH') {
719 return $self->_expr_to_dq_ARRAYREF([
720 map +{ $k => { $_ => $v->{$_} } }, sort keys %$v
723 my ($op, $value) = %$v;
724 s/^-//, s/_/ /g for $op;
725 if ($op =~ /^(and|or)$/i) {
726 return $self->_expr_to_dq({ $k => $value }, $op);
728 my $special_op = List::Util::first {$op =~ $_->{regex}}
729 @{$self->{special_ops}}
731 return $self->_literal_to_dq(
732 [ $self->${\$special_op->{handler}}($k, $op, $value) ]
734 } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+$/i) {
735 die "Use of [and|or|nest]_N modifiers is no longer supported";
742 if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
743 if (ref($rhs) ne 'ARRAY') {
745 # have to add parens if none present because -in => \"SELECT ..."
746 # got documented. mst hates everything.
747 if (ref($rhs) eq 'SCALAR') {
749 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
752 my ($x, @rest) = @{$$rhs};
753 1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
754 $rhs = \[ $x, @rest ];
757 return $self->_op_to_dq(
758 $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
761 return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
762 return $self->_op_to_dq(
763 $op, $self->_ident_to_dq($k), map $self->_expr_to_dq($_), @$rhs
765 } elsif ($op =~ s/^NOT (?!LIKE)//) {
766 return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
767 } elsif (!defined($rhs)) {
769 if ($op eq '=' or $op eq 'LIKE') {
771 } elsif ($op eq '!=') {
774 die "Can't do undef -> NULL transform for operator ${op}";
777 return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
779 if (ref($rhs) eq 'ARRAY') {
781 return $self->_literal_to_dq(
782 $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
784 } elsif (defined($rhs->[0]) and $rhs->[0] =~ /^-(and|or)$/i) {
785 return $self->_expr_to_dq_ARRAYREF([
786 map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
788 } elsif ($op =~ /^-(?:AND|OR|NEST)_?\d+/) {
789 die "Use of [and|or|nest]_N modifiers is no longer supported";
791 return $self->_expr_to_dq_ARRAYREF([
792 map +{ $k => { $op => $_ } }, @$rhs
795 return $self->_op_to_dq(
796 $op, $self->_ident_to_dq($k), $self->_expr_to_dq($rhs)
801 #======================================================================
803 #======================================================================
806 my ($self, $arg) = @_;
807 if (my $dq = $self->_order_by_to_dq($arg)) {
808 # SQLA generates ' ORDER BY foo'. The hilarity.
810 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
811 : ' '.$self->_render_dq($dq);
817 sub _order_by_to_dq {
818 my ($self, $arg, $dir, $from) = @_;
824 ($dir ? (direction => $dir) : ()),
825 ($from ? (from => $from) : ()),
829 $dq->{by} = $self->_ident_to_dq($arg);
830 } elsif (ref($arg) eq 'ARRAY') {
832 local our $Order_Inner unless our $Order_Recursing;
833 local $Order_Recursing = 1;
835 foreach my $member (@$arg) {
837 my $next = $self->_order_by_to_dq($member, $dir, $from);
839 $inner->{from} = $next if $inner;
840 $inner = $Order_Inner || $next;
842 $Order_Inner = $inner;
844 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
845 $dq->{by} = $self->_literal_to_dq($$arg);
846 } elsif (ref($arg) eq 'SCALAR') {
847 $dq->{by} = $self->_literal_to_dq($$arg);
848 } elsif (ref($arg) eq 'HASH') {
849 my ($key, $val, @rest) = %$arg;
853 if (@rest or not $key =~ /^-(desc|asc)/i) {
854 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
857 return $self->_order_by_to_dq($val, $dir, $from);
859 die "Can't handle $arg in _order_by_to_dq";
864 #======================================================================
865 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
866 #======================================================================
869 my ($self, $from) = @_;
870 $self->_render_dq($self->_table_to_dq($from));
874 my ($self, $from) = @_;
875 $self->_SWITCH_refkind($from, {
877 die "Empty FROM list" unless my @f = @$from;
878 my $dq = $self->_ident_to_dq(shift @f);
879 while (my $x = shift @f) {
882 join => [ $dq, $self->_ident_to_dq($x) ]
887 SCALAR => sub { $self->_ident_to_dq($from) },
899 #======================================================================
901 #======================================================================
903 # highly optimized, as it's called way too often
905 # my ($self, $label) = @_;
907 return '' unless defined $_[1];
908 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
910 unless ($_[0]->{quote_char}) {
911 $_[0]->_assert_pass_injection_guard($_[1]);
915 my $qref = ref $_[0]->{quote_char};
918 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
920 elsif ($qref eq 'ARRAY') {
921 ($l, $r) = @{$_[0]->{quote_char}};
924 puke "Unsupported quote_char format: $_[0]->{quote_char}";
927 # parts containing * are naturally unquoted
928 return join( $_[0]->{name_sep}||'', map
929 { $_ eq '*' ? $_ : $l . $_ . $r }
930 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
935 # Conversion, if applicable
937 #my ($self, $arg) = @_;
939 # LDNOTE : modified the previous implementation below because
940 # it was not consistent : the first "return" is always an array,
941 # the second "return" is context-dependent. Anyway, _convert
942 # seems always used with just a single argument, so make it a
944 # return @_ unless $self->{convert};
945 # my $conv = $self->_sqlcase($self->{convert});
946 # my @ret = map { $conv.'('.$_.')' } @_;
947 # return wantarray ? @ret : $ret[0];
948 if ($_[0]->{convert}) {
949 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
956 #my ($self, $col, @vals) = @_;
958 #LDNOTE : changed original implementation below because it did not make
959 # sense when bindtype eq 'columns' and @vals > 1.
960 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
962 # called often - tighten code
963 return $_[0]->{bindtype} eq 'columns'
964 ? map {[$_[1], $_]} @_[2 .. $#_]
969 # Dies if any element of @bind is not in [colname => value] format
970 # if bindtype is 'columns'.
971 sub _assert_bindval_matches_bindtype {
972 # my ($self, @bind) = @_;
974 if ($self->{bindtype} eq 'columns') {
976 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
977 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
983 sub _join_sql_clauses {
984 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
986 if (@$clauses_aref > 1) {
987 my $join = " " . $self->_sqlcase($logic) . " ";
988 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
989 return ($sql, @$bind_aref);
991 elsif (@$clauses_aref) {
992 return ($clauses_aref->[0], @$bind_aref); # no parentheses
995 return (); # if no SQL, ignore @$bind_aref
1000 # Fix SQL case, if so requested
1002 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1003 # don't touch the argument ... crooked logic, but let's not change it!
1004 return $_[0]->{case} ? $_[1] : uc($_[1]);
1008 #======================================================================
1009 # DISPATCHING FROM REFKIND
1010 #======================================================================
1013 my ($self, $data) = @_;
1015 return 'UNDEF' unless defined $data;
1017 # blessed objects are treated like scalars
1018 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1020 return 'SCALAR' unless $ref;
1023 while ($ref eq 'REF') {
1025 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1029 return ($ref||'SCALAR') . ('REF' x $n_steps);
1033 my ($self, $data) = @_;
1034 my @try = ($self->_refkind($data));
1035 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1036 push @try, 'FALLBACK';
1040 sub _METHOD_FOR_refkind {
1041 my ($self, $meth_prefix, $data) = @_;
1044 for (@{$self->_try_refkind($data)}) {
1045 $method = $self->can($meth_prefix."_".$_)
1049 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1053 sub _SWITCH_refkind {
1054 my ($self, $data, $dispatch_table) = @_;
1057 for (@{$self->_try_refkind($data)}) {
1058 $coderef = $dispatch_table->{$_}
1062 puke "no dispatch entry for ".$self->_refkind($data)
1071 #======================================================================
1072 # VALUES, GENERATE, AUTOLOAD
1073 #======================================================================
1075 # LDNOTE: original code from nwiger, didn't touch code in that section
1076 # I feel the AUTOLOAD stuff should not be the default, it should
1077 # only be activated on explicit demand by user.
1081 my $data = shift || return;
1082 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1083 unless ref $data eq 'HASH';
1086 foreach my $k ( sort keys %$data ) {
1087 my $v = $data->{$k};
1088 $self->_SWITCH_refkind($v, {
1090 if ($self->{array_datatypes}) { # array datatype
1091 push @all_bind, $self->_bindtype($k, $v);
1093 else { # literal SQL with bind
1094 my ($sql, @bind) = @$v;
1095 $self->_assert_bindval_matches_bindtype(@bind);
1096 push @all_bind, @bind;
1099 ARRAYREFREF => sub { # literal SQL with bind
1100 my ($sql, @bind) = @${$v};
1101 $self->_assert_bindval_matches_bindtype(@bind);
1102 push @all_bind, @bind;
1104 SCALARREF => sub { # literal SQL without bind
1106 SCALAR_or_UNDEF => sub {
1107 push @all_bind, $self->_bindtype($k, $v);
1118 my(@sql, @sqlq, @sqlv);
1122 if ($ref eq 'HASH') {
1123 for my $k (sort keys %$_) {
1126 my $label = $self->_quote($k);
1127 if ($r eq 'ARRAY') {
1128 # literal SQL with bind
1129 my ($sql, @bind) = @$v;
1130 $self->_assert_bindval_matches_bindtype(@bind);
1131 push @sqlq, "$label = $sql";
1133 } elsif ($r eq 'SCALAR') {
1134 # literal SQL without bind
1135 push @sqlq, "$label = $$v";
1137 push @sqlq, "$label = ?";
1138 push @sqlv, $self->_bindtype($k, $v);
1141 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1142 } elsif ($ref eq 'ARRAY') {
1143 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1146 if ($r eq 'ARRAY') { # literal SQL with bind
1147 my ($sql, @bind) = @$v;
1148 $self->_assert_bindval_matches_bindtype(@bind);
1151 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1152 # embedded literal SQL
1159 push @sql, '(' . join(', ', @sqlq) . ')';
1160 } elsif ($ref eq 'SCALAR') {
1164 # strings get case twiddled
1165 push @sql, $self->_sqlcase($_);
1169 my $sql = join ' ', @sql;
1171 # this is pretty tricky
1172 # if ask for an array, return ($stmt, @bind)
1173 # otherwise, s/?/shift @sqlv/ to put it inline
1175 return ($sql, @sqlv);
1177 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1178 ref $d ? $d->[1] : $d/e;
1187 # This allows us to check for a local, then _form, attr
1189 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1190 return $self->generate($name, @_);
1201 SQL::Abstract - Generate SQL from Perl data structures
1207 my $sql = SQL::Abstract->new;
1209 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1211 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1213 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1215 my($stmt, @bind) = $sql->delete($table, \%where);
1217 # Then, use these in your DBI statements
1218 my $sth = $dbh->prepare($stmt);
1219 $sth->execute(@bind);
1221 # Just generate the WHERE clause
1222 my($stmt, @bind) = $sql->where(\%where, \@order);
1224 # Return values in the same order, for hashed queries
1225 # See PERFORMANCE section for more details
1226 my @bind = $sql->values(\%fieldvals);
1230 This module was inspired by the excellent L<DBIx::Abstract>.
1231 However, in using that module I found that what I really wanted
1232 to do was generate SQL, but still retain complete control over my
1233 statement handles and use the DBI interface. So, I set out to
1234 create an abstract SQL generation module.
1236 While based on the concepts used by L<DBIx::Abstract>, there are
1237 several important differences, especially when it comes to WHERE
1238 clauses. I have modified the concepts used to make the SQL easier
1239 to generate from Perl data structures and, IMO, more intuitive.
1240 The underlying idea is for this module to do what you mean, based
1241 on the data structures you provide it. The big advantage is that
1242 you don't have to modify your code every time your data changes,
1243 as this module figures it out.
1245 To begin with, an SQL INSERT is as easy as just specifying a hash
1246 of C<key=value> pairs:
1249 name => 'Jimbo Bobson',
1250 phone => '123-456-7890',
1251 address => '42 Sister Lane',
1252 city => 'St. Louis',
1253 state => 'Louisiana',
1256 The SQL can then be generated with this:
1258 my($stmt, @bind) = $sql->insert('people', \%data);
1260 Which would give you something like this:
1262 $stmt = "INSERT INTO people
1263 (address, city, name, phone, state)
1264 VALUES (?, ?, ?, ?, ?)";
1265 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1266 '123-456-7890', 'Louisiana');
1268 These are then used directly in your DBI code:
1270 my $sth = $dbh->prepare($stmt);
1271 $sth->execute(@bind);
1273 =head2 Inserting and Updating Arrays
1275 If your database has array types (like for example Postgres),
1276 activate the special option C<< array_datatypes => 1 >>
1277 when creating the C<SQL::Abstract> object.
1278 Then you may use an arrayref to insert and update database array types:
1280 my $sql = SQL::Abstract->new(array_datatypes => 1);
1282 planets => [qw/Mercury Venus Earth Mars/]
1285 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1289 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1291 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1294 =head2 Inserting and Updating SQL
1296 In order to apply SQL functions to elements of your C<%data> you may
1297 specify a reference to an arrayref for the given hash value. For example,
1298 if you need to execute the Oracle C<to_date> function on a value, you can
1299 say something like this:
1303 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1306 The first value in the array is the actual SQL. Any other values are
1307 optional and would be included in the bind values array. This gives
1310 my($stmt, @bind) = $sql->insert('people', \%data);
1312 $stmt = "INSERT INTO people (name, date_entered)
1313 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1314 @bind = ('Bill', '03/02/2003');
1316 An UPDATE is just as easy, all you change is the name of the function:
1318 my($stmt, @bind) = $sql->update('people', \%data);
1320 Notice that your C<%data> isn't touched; the module will generate
1321 the appropriately quirky SQL for you automatically. Usually you'll
1322 want to specify a WHERE clause for your UPDATE, though, which is
1323 where handling C<%where> hashes comes in handy...
1325 =head2 Complex where statements
1327 This module can generate pretty complicated WHERE statements
1328 easily. For example, simple C<key=value> pairs are taken to mean
1329 equality, and if you want to see if a field is within a set
1330 of values, you can use an arrayref. Let's say we wanted to
1331 SELECT some data based on this criteria:
1334 requestor => 'inna',
1335 worker => ['nwiger', 'rcwe', 'sfz'],
1336 status => { '!=', 'completed' }
1339 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1341 The above would give you something like this:
1343 $stmt = "SELECT * FROM tickets WHERE
1344 ( requestor = ? ) AND ( status != ? )
1345 AND ( worker = ? OR worker = ? OR worker = ? )";
1346 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1348 Which you could then use in DBI code like so:
1350 my $sth = $dbh->prepare($stmt);
1351 $sth->execute(@bind);
1357 The functions are simple. There's one for each major SQL operation,
1358 and a constructor you use first. The arguments are specified in a
1359 similar order to each function (table, then fields, then a where
1360 clause) to try and simplify things.
1365 =head2 new(option => 'value')
1367 The C<new()> function takes a list of options and values, and returns
1368 a new B<SQL::Abstract> object which can then be used to generate SQL
1369 through the methods below. The options accepted are:
1375 If set to 'lower', then SQL will be generated in all lowercase. By
1376 default SQL is generated in "textbook" case meaning something like:
1378 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1380 Any setting other than 'lower' is ignored.
1384 This determines what the default comparison operator is. By default
1385 it is C<=>, meaning that a hash like this:
1387 %where = (name => 'nwiger', email => 'nate@wiger.org');
1389 Will generate SQL like this:
1391 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1393 However, you may want loose comparisons by default, so if you set
1394 C<cmp> to C<like> you would get SQL such as:
1396 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1398 You can also override the comparsion on an individual basis - see
1399 the huge section on L</"WHERE CLAUSES"> at the bottom.
1401 =item sqltrue, sqlfalse
1403 Expressions for inserting boolean values within SQL statements.
1404 By default these are C<1=1> and C<1=0>. They are used
1405 by the special operators C<-in> and C<-not_in> for generating
1406 correct SQL even when the argument is an empty array (see below).
1410 This determines the default logical operator for multiple WHERE
1411 statements in arrays or hashes. If absent, the default logic is "or"
1412 for arrays, and "and" for hashes. This means that a WHERE
1416 event_date => {'>=', '2/13/99'},
1417 event_date => {'<=', '4/24/03'},
1420 will generate SQL like this:
1422 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1424 This is probably not what you want given this query, though (look
1425 at the dates). To change the "OR" to an "AND", simply specify:
1427 my $sql = SQL::Abstract->new(logic => 'and');
1429 Which will change the above C<WHERE> to:
1431 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1433 The logic can also be changed locally by inserting
1434 a modifier in front of an arrayref :
1436 @where = (-and => [event_date => {'>=', '2/13/99'},
1437 event_date => {'<=', '4/24/03'} ]);
1439 See the L</"WHERE CLAUSES"> section for explanations.
1443 This will automatically convert comparisons using the specified SQL
1444 function for both column and value. This is mostly used with an argument
1445 of C<upper> or C<lower>, so that the SQL will have the effect of
1446 case-insensitive "searches". For example, this:
1448 $sql = SQL::Abstract->new(convert => 'upper');
1449 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1451 Will turn out the following SQL:
1453 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1455 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1456 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1457 not validate this option; it will just pass through what you specify verbatim).
1461 This is a kludge because many databases suck. For example, you can't
1462 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1463 Instead, you have to use C<bind_param()>:
1465 $sth->bind_param(1, 'reg data');
1466 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1468 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1469 which loses track of which field each slot refers to. Fear not.
1471 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1472 Currently, you can specify either C<normal> (default) or C<columns>. If you
1473 specify C<columns>, you will get an array that looks like this:
1475 my $sql = SQL::Abstract->new(bindtype => 'columns');
1476 my($stmt, @bind) = $sql->insert(...);
1479 [ 'column1', 'value1' ],
1480 [ 'column2', 'value2' ],
1481 [ 'column3', 'value3' ],
1484 You can then iterate through this manually, using DBI's C<bind_param()>.
1486 $sth->prepare($stmt);
1489 my($col, $data) = @$_;
1490 if ($col eq 'details' || $col eq 'comments') {
1491 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1492 } elsif ($col eq 'image') {
1493 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1495 $sth->bind_param($i, $data);
1499 $sth->execute; # execute without @bind now
1501 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1502 Basically, the advantage is still that you don't have to care which fields
1503 are or are not included. You could wrap that above C<for> loop in a simple
1504 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1505 get a layer of abstraction over manual SQL specification.
1507 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1508 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1509 will expect the bind values in this format.
1513 This is the character that a table or column name will be quoted
1514 with. By default this is an empty string, but you could set it to
1515 the character C<`>, to generate SQL like this:
1517 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1519 Alternatively, you can supply an array ref of two items, the first being the left
1520 hand quote character, and the second the right hand quote character. For
1521 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1522 that generates SQL like this:
1524 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1526 Quoting is useful if you have tables or columns names that are reserved
1527 words in your database's SQL dialect.
1531 This is the character that separates a table and column name. It is
1532 necessary to specify this when the C<quote_char> option is selected,
1533 so that tables and column names can be individually quoted like this:
1535 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1537 =item injection_guard
1539 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1540 column name specified in a query structure. This is a safety mechanism to avoid
1541 injection attacks when mishandling user input e.g.:
1543 my %condition_as_column_value_pairs = get_values_from_user();
1544 $sqla->select( ... , \%condition_as_column_value_pairs );
1546 If the expression matches an exception is thrown. Note that literal SQL
1547 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1549 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1551 =item array_datatypes
1553 When this option is true, arrayrefs in INSERT or UPDATE are
1554 interpreted as array datatypes and are passed directly
1556 When this option is false, arrayrefs are interpreted
1557 as literal SQL, just like refs to arrayrefs
1558 (but this behavior is for backwards compatibility; when writing
1559 new queries, use the "reference to arrayref" syntax
1565 Takes a reference to a list of "special operators"
1566 to extend the syntax understood by L<SQL::Abstract>.
1567 See section L</"SPECIAL OPERATORS"> for details.
1571 Takes a reference to a list of "unary operators"
1572 to extend the syntax understood by L<SQL::Abstract>.
1573 See section L</"UNARY OPERATORS"> for details.
1579 =head2 insert($table, \@values || \%fieldvals, \%options)
1581 This is the simplest function. You simply give it a table name
1582 and either an arrayref of values or hashref of field/value pairs.
1583 It returns an SQL INSERT statement and a list of bind values.
1584 See the sections on L</"Inserting and Updating Arrays"> and
1585 L</"Inserting and Updating SQL"> for information on how to insert
1586 with those data types.
1588 The optional C<\%options> hash reference may contain additional
1589 options to generate the insert SQL. Currently supported options
1596 Takes either a scalar of raw SQL fields, or an array reference of
1597 field names, and adds on an SQL C<RETURNING> statement at the end.
1598 This allows you to return data generated by the insert statement
1599 (such as row IDs) without performing another C<SELECT> statement.
1600 Note, however, this is not part of the SQL standard and may not
1601 be supported by all database engines.
1605 =head2 update($table, \%fieldvals, \%where)
1607 This takes a table, hashref of field/value pairs, and an optional
1608 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1610 See the sections on L</"Inserting and Updating Arrays"> and
1611 L</"Inserting and Updating SQL"> for information on how to insert
1612 with those data types.
1614 =head2 select($source, $fields, $where, $order)
1616 This returns a SQL SELECT statement and associated list of bind values, as
1617 specified by the arguments :
1623 Specification of the 'FROM' part of the statement.
1624 The argument can be either a plain scalar (interpreted as a table
1625 name, will be quoted), or an arrayref (interpreted as a list
1626 of table names, joined by commas, quoted), or a scalarref
1627 (literal table name, not quoted), or a ref to an arrayref
1628 (list of literal table names, joined by commas, not quoted).
1632 Specification of the list of fields to retrieve from
1634 The argument can be either an arrayref (interpreted as a list
1635 of field names, will be joined by commas and quoted), or a
1636 plain scalar (literal SQL, not quoted).
1637 Please observe that this API is not as flexible as for
1638 the first argument C<$table>, for backwards compatibility reasons.
1642 Optional argument to specify the WHERE part of the query.
1643 The argument is most often a hashref, but can also be
1644 an arrayref or plain scalar --
1645 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1649 Optional argument to specify the ORDER BY part of the query.
1650 The argument can be a scalar, a hashref or an arrayref
1651 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1657 =head2 delete($table, \%where)
1659 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1660 It returns an SQL DELETE statement and list of bind values.
1662 =head2 where(\%where, \@order)
1664 This is used to generate just the WHERE clause. For example,
1665 if you have an arbitrary data structure and know what the
1666 rest of your SQL is going to look like, but want an easy way
1667 to produce a WHERE clause, use this. It returns an SQL WHERE
1668 clause and list of bind values.
1671 =head2 values(\%data)
1673 This just returns the values from the hash C<%data>, in the same
1674 order that would be returned from any of the other above queries.
1675 Using this allows you to markedly speed up your queries if you
1676 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1678 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1680 Warning: This is an experimental method and subject to change.
1682 This returns arbitrarily generated SQL. It's a really basic shortcut.
1683 It will return two different things, depending on return context:
1685 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1686 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1688 These would return the following:
1690 # First calling form
1691 $stmt = "CREATE TABLE test (?, ?)";
1692 @bind = (field1, field2);
1694 # Second calling form
1695 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1697 Depending on what you're trying to do, it's up to you to choose the correct
1698 format. In this example, the second form is what you would want.
1702 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1706 ALTER SESSION SET nls_date_format = 'MM/YY'
1708 You get the idea. Strings get their case twiddled, but everything
1709 else remains verbatim.
1711 =head1 WHERE CLAUSES
1715 This module uses a variation on the idea from L<DBIx::Abstract>. It
1716 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1717 module is that things in arrays are OR'ed, and things in hashes
1720 The easiest way to explain is to show lots of examples. After
1721 each C<%where> hash shown, it is assumed you used:
1723 my($stmt, @bind) = $sql->where(\%where);
1725 However, note that the C<%where> hash can be used directly in any
1726 of the other functions as well, as described above.
1728 =head2 Key-value pairs
1730 So, let's get started. To begin, a simple hash:
1734 status => 'completed'
1737 Is converted to SQL C<key = val> statements:
1739 $stmt = "WHERE user = ? AND status = ?";
1740 @bind = ('nwiger', 'completed');
1742 One common thing I end up doing is having a list of values that
1743 a field can be in. To do this, simply specify a list inside of
1748 status => ['assigned', 'in-progress', 'pending'];
1751 This simple code will create the following:
1753 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1754 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1756 A field associated to an empty arrayref will be considered a
1757 logical false and will generate 0=1.
1759 =head2 Tests for NULL values
1761 If the value part is C<undef> then this is converted to SQL <IS NULL>
1770 $stmt = "WHERE user = ? AND status IS NULL";
1773 To test if a column IS NOT NULL:
1777 status => { '!=', undef },
1780 =head2 Specific comparison operators
1782 If you want to specify a different type of operator for your comparison,
1783 you can use a hashref for a given column:
1787 status => { '!=', 'completed' }
1790 Which would generate:
1792 $stmt = "WHERE user = ? AND status != ?";
1793 @bind = ('nwiger', 'completed');
1795 To test against multiple values, just enclose the values in an arrayref:
1797 status => { '=', ['assigned', 'in-progress', 'pending'] };
1799 Which would give you:
1801 "WHERE status = ? OR status = ? OR status = ?"
1804 The hashref can also contain multiple pairs, in which case it is expanded
1805 into an C<AND> of its elements:
1809 status => { '!=', 'completed', -not_like => 'pending%' }
1812 # Or more dynamically, like from a form
1813 $where{user} = 'nwiger';
1814 $where{status}{'!='} = 'completed';
1815 $where{status}{'-not_like'} = 'pending%';
1817 # Both generate this
1818 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1819 @bind = ('nwiger', 'completed', 'pending%');
1822 To get an OR instead, you can combine it with the arrayref idea:
1826 priority => [ { '=', 2 }, { '>', 5 } ]
1829 Which would generate:
1831 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1832 @bind = ('2', '5', 'nwiger');
1834 If you want to include literal SQL (with or without bind values), just use a
1835 scalar reference or array reference as the value:
1838 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1839 date_expires => { '<' => \"now()" }
1842 Which would generate:
1844 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1845 @bind = ('11/26/2008');
1848 =head2 Logic and nesting operators
1850 In the example above,
1851 there is a subtle trap if you want to say something like
1852 this (notice the C<AND>):
1854 WHERE priority != ? AND priority != ?
1856 Because, in Perl you I<can't> do this:
1858 priority => { '!=', 2, '!=', 1 }
1860 As the second C<!=> key will obliterate the first. The solution
1861 is to use the special C<-modifier> form inside an arrayref:
1863 priority => [ -and => {'!=', 2},
1867 Normally, these would be joined by C<OR>, but the modifier tells it
1868 to use C<AND> instead. (Hint: You can use this in conjunction with the
1869 C<logic> option to C<new()> in order to change the way your queries
1870 work by default.) B<Important:> Note that the C<-modifier> goes
1871 B<INSIDE> the arrayref, as an extra first element. This will
1872 B<NOT> do what you think it might:
1874 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1876 Here is a quick list of equivalencies, since there is some overlap:
1879 status => {'!=', 'completed', 'not like', 'pending%' }
1880 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1883 status => {'=', ['assigned', 'in-progress']}
1884 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1885 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1889 =head2 Special operators : IN, BETWEEN, etc.
1891 You can also use the hashref format to compare a list of fields using the
1892 C<IN> comparison operator, by specifying the list as an arrayref:
1895 status => 'completed',
1896 reportid => { -in => [567, 2335, 2] }
1899 Which would generate:
1901 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1902 @bind = ('completed', '567', '2335', '2');
1904 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1907 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1908 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1909 'sqltrue' (by default : C<1=1>).
1911 In addition to the array you can supply a chunk of literal sql or
1912 literal sql with bind:
1915 customer => { -in => \[
1916 'SELECT cust_id FROM cust WHERE balance > ?',
1919 status => { -in => \'SELECT status_codes FROM states' },
1925 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1926 AND status IN ( SELECT status_codes FROM states )
1932 Another pair of operators is C<-between> and C<-not_between>,
1933 used with an arrayref of two values:
1937 completion_date => {
1938 -not_between => ['2002-10-01', '2003-02-06']
1944 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1946 Just like with C<-in> all plausible combinations of literal SQL
1950 start0 => { -between => [ 1, 2 ] },
1951 start1 => { -between => \["? AND ?", 1, 2] },
1952 start2 => { -between => \"lower(x) AND upper(y)" },
1953 start3 => { -between => [
1955 \["upper(?)", 'stuff' ],
1962 ( start0 BETWEEN ? AND ? )
1963 AND ( start1 BETWEEN ? AND ? )
1964 AND ( start2 BETWEEN lower(x) AND upper(y) )
1965 AND ( start3 BETWEEN lower(x) AND upper(?) )
1967 @bind = (1, 2, 1, 2, 'stuff');
1970 These are the two builtin "special operators"; but the
1971 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1973 =head2 Unary operators: bool
1975 If you wish to test against boolean columns or functions within your
1976 database you can use the C<-bool> and C<-not_bool> operators. For
1977 example to test the column C<is_user> being true and the column
1978 C<is_enabled> being false you would use:-
1982 -not_bool => 'is_enabled',
1987 WHERE is_user AND NOT is_enabled
1989 If a more complex combination is required, testing more conditions,
1990 then you should use the and/or operators:-
1997 -not_bool => 'four',
2003 WHERE one AND two AND three AND NOT four
2006 =head2 Nested conditions, -and/-or prefixes
2008 So far, we've seen how multiple conditions are joined with a top-level
2009 C<AND>. We can change this by putting the different conditions we want in
2010 hashes and then putting those hashes in an array. For example:
2015 status => { -like => ['pending%', 'dispatched'] },
2019 status => 'unassigned',
2023 This data structure would create the following:
2025 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2026 OR ( user = ? AND status = ? ) )";
2027 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2030 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2031 to change the logic inside :
2037 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2038 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2045 WHERE ( user = ? AND (
2046 ( workhrs > ? AND geo = ? )
2047 OR ( workhrs < ? OR geo = ? )
2050 =head3 Algebraic inconsistency, for historical reasons
2052 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2053 operator goes C<outside> of the nested structure; whereas when connecting
2054 several constraints on one column, the C<-and> operator goes
2055 C<inside> the arrayref. Here is an example combining both features :
2058 -and => [a => 1, b => 2],
2059 -or => [c => 3, d => 4],
2060 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2065 WHERE ( ( ( a = ? AND b = ? )
2066 OR ( c = ? OR d = ? )
2067 OR ( e LIKE ? AND e LIKE ? ) ) )
2069 This difference in syntax is unfortunate but must be preserved for
2070 historical reasons. So be careful : the two examples below would
2071 seem algebraically equivalent, but they are not
2073 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2074 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2076 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2077 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2080 =head2 Literal SQL and value type operators
2082 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2083 side" is a column name and the "right side" is a value (normally rendered as
2084 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2085 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2086 alter this behavior. There are several ways of doing so.
2090 This is a virtual operator that signals the string to its right side is an
2091 identifier (a column name) and not a value. For example to compare two
2092 columns you would write:
2095 priority => { '<', 2 },
2096 requestor => { -ident => 'submitter' },
2101 $stmt = "WHERE priority < ? AND requestor = submitter";
2104 If you are maintaining legacy code you may see a different construct as
2105 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2110 This is a virtual operator that signals that the construct to its right side
2111 is a value to be passed to DBI. This is for example necessary when you want
2112 to write a where clause against an array (for RDBMS that support such
2113 datatypes). For example:
2116 array => { -value => [1, 2, 3] }
2121 $stmt = 'WHERE array = ?';
2122 @bind = ([1, 2, 3]);
2124 Note that if you were to simply say:
2130 the result would porbably be not what you wanted:
2132 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2137 Finally, sometimes only literal SQL will do. To include a random snippet
2138 of SQL verbatim, you specify it as a scalar reference. Consider this only
2139 as a last resort. Usually there is a better way. For example:
2142 priority => { '<', 2 },
2143 requestor => { -in => \'(SELECT name FROM hitmen)' },
2148 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2151 Note that in this example, you only get one bind parameter back, since
2152 the verbatim SQL is passed as part of the statement.
2156 Never use untrusted input as a literal SQL argument - this is a massive
2157 security risk (there is no way to check literal snippets for SQL
2158 injections and other nastyness). If you need to deal with untrusted input
2159 use literal SQL with placeholders as described next.
2161 =head3 Literal SQL with placeholders and bind values (subqueries)
2163 If the literal SQL to be inserted has placeholders and bind values,
2164 use a reference to an arrayref (yes this is a double reference --
2165 not so common, but perfectly legal Perl). For example, to find a date
2166 in Postgres you can use something like this:
2169 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2174 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2177 Note that you must pass the bind values in the same format as they are returned
2178 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2179 provide the bind values in the C<< [ column_meta => value ] >> format, where
2180 C<column_meta> is an opaque scalar value; most commonly the column name, but
2181 you can use any scalar value (including references and blessed references),
2182 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2183 to C<columns> the above example will look like:
2186 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2189 Literal SQL is especially useful for nesting parenthesized clauses in the
2190 main SQL query. Here is a first example :
2192 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2196 bar => \["IN ($sub_stmt)" => @sub_bind],
2201 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2202 WHERE c2 < ? AND c3 LIKE ?))";
2203 @bind = (1234, 100, "foo%");
2205 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2206 are expressed in the same way. Of course the C<$sub_stmt> and
2207 its associated bind values can be generated through a former call
2210 my ($sub_stmt, @sub_bind)
2211 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2212 c3 => {-like => "foo%"}});
2215 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2218 In the examples above, the subquery was used as an operator on a column;
2219 but the same principle also applies for a clause within the main C<%where>
2220 hash, like an EXISTS subquery :
2222 my ($sub_stmt, @sub_bind)
2223 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2224 my %where = ( -and => [
2226 \["EXISTS ($sub_stmt)" => @sub_bind],
2231 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2232 WHERE c1 = ? AND c2 > t0.c0))";
2236 Observe that the condition on C<c2> in the subquery refers to
2237 column C<t0.c0> of the main query : this is I<not> a bind
2238 value, so we have to express it through a scalar ref.
2239 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2240 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2241 what we wanted here.
2243 Finally, here is an example where a subquery is used
2244 for expressing unary negation:
2246 my ($sub_stmt, @sub_bind)
2247 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2248 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2250 lname => {like => '%son%'},
2251 \["NOT ($sub_stmt)" => @sub_bind],
2256 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2257 @bind = ('%son%', 10, 20)
2259 =head3 Deprecated usage of Literal SQL
2261 Below are some examples of archaic use of literal SQL. It is shown only as
2262 reference for those who deal with legacy code. Each example has a much
2263 better, cleaner and safer alternative that users should opt for in new code.
2269 my %where = ( requestor => \'IS NOT NULL' )
2271 $stmt = "WHERE requestor IS NOT NULL"
2273 This used to be the way of generating NULL comparisons, before the handling
2274 of C<undef> got formalized. For new code please use the superior syntax as
2275 described in L</Tests for NULL values>.
2279 my %where = ( requestor => \'= submitter' )
2281 $stmt = "WHERE requestor = submitter"
2283 This used to be the only way to compare columns. Use the superior L</-ident>
2284 method for all new code. For example an identifier declared in such a way
2285 will be properly quoted if L</quote_char> is properly set, while the legacy
2286 form will remain as supplied.
2290 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2292 $stmt = "WHERE completed > ? AND is_ready"
2293 @bind = ('2012-12-21')
2295 Using an empty string literal used to be the only way to express a boolean.
2296 For all new code please use the much more readable
2297 L<-bool|/Unary operators: bool> operator.
2303 These pages could go on for a while, since the nesting of the data
2304 structures this module can handle are pretty much unlimited (the
2305 module implements the C<WHERE> expansion as a recursive function
2306 internally). Your best bet is to "play around" with the module a
2307 little to see how the data structures behave, and choose the best
2308 format for your data based on that.
2310 And of course, all the values above will probably be replaced with
2311 variables gotten from forms or the command line. After all, if you
2312 knew everything ahead of time, you wouldn't have to worry about
2313 dynamically-generating SQL and could just hardwire it into your
2316 =head1 ORDER BY CLAUSES
2318 Some functions take an order by clause. This can either be a scalar (just a
2319 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2320 or an array of either of the two previous forms. Examples:
2322 Given | Will Generate
2323 ----------------------------------------------------------
2325 \'colA DESC' | ORDER BY colA DESC
2327 'colA' | ORDER BY colA
2329 [qw/colA colB/] | ORDER BY colA, colB
2331 {-asc => 'colA'} | ORDER BY colA ASC
2333 {-desc => 'colB'} | ORDER BY colB DESC
2335 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2337 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2340 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2341 { -desc => [qw/colB/], | colC ASC, colD ASC
2342 { -asc => [qw/colC colD/],|
2344 ===========================================================
2348 =head1 SPECIAL OPERATORS
2350 my $sqlmaker = SQL::Abstract->new(special_ops => [
2354 my ($self, $field, $op, $arg) = @_;
2360 handler => 'method_name',
2364 A "special operator" is a SQL syntactic clause that can be
2365 applied to a field, instead of a usual binary operator.
2368 WHERE field IN (?, ?, ?)
2369 WHERE field BETWEEN ? AND ?
2370 WHERE MATCH(field) AGAINST (?, ?)
2372 Special operators IN and BETWEEN are fairly standard and therefore
2373 are builtin within C<SQL::Abstract> (as the overridable methods
2374 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2375 like the MATCH .. AGAINST example above which is specific to MySQL,
2376 you can write your own operator handlers - supply a C<special_ops>
2377 argument to the C<new> method. That argument takes an arrayref of
2378 operator definitions; each operator definition is a hashref with two
2385 the regular expression to match the operator
2389 Either a coderef or a plain scalar method name. In both cases
2390 the expected return is C<< ($sql, @bind) >>.
2392 When supplied with a method name, it is simply called on the
2393 L<SQL::Abstract/> object as:
2395 $self->$method_name ($field, $op, $arg)
2399 $op is the part that matched the handler regex
2400 $field is the LHS of the operator
2403 When supplied with a coderef, it is called as:
2405 $coderef->($self, $field, $op, $arg)
2410 For example, here is an implementation
2411 of the MATCH .. AGAINST syntax for MySQL
2413 my $sqlmaker = SQL::Abstract->new(special_ops => [
2415 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2416 {regex => qr/^match$/i,
2418 my ($self, $field, $op, $arg) = @_;
2419 $arg = [$arg] if not ref $arg;
2420 my $label = $self->_quote($field);
2421 my ($placeholder) = $self->_convert('?');
2422 my $placeholders = join ", ", (($placeholder) x @$arg);
2423 my $sql = $self->_sqlcase('match') . " ($label) "
2424 . $self->_sqlcase('against') . " ($placeholders) ";
2425 my @bind = $self->_bindtype($field, @$arg);
2426 return ($sql, @bind);
2433 =head1 UNARY OPERATORS
2435 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2439 my ($self, $op, $arg) = @_;
2445 handler => 'method_name',
2449 A "unary operator" is a SQL syntactic clause that can be
2450 applied to a field - the operator goes before the field
2452 You can write your own operator handlers - supply a C<unary_ops>
2453 argument to the C<new> method. That argument takes an arrayref of
2454 operator definitions; each operator definition is a hashref with two
2461 the regular expression to match the operator
2465 Either a coderef or a plain scalar method name. In both cases
2466 the expected return is C<< $sql >>.
2468 When supplied with a method name, it is simply called on the
2469 L<SQL::Abstract/> object as:
2471 $self->$method_name ($op, $arg)
2475 $op is the part that matched the handler regex
2476 $arg is the RHS or argument of the operator
2478 When supplied with a coderef, it is called as:
2480 $coderef->($self, $op, $arg)
2488 Thanks to some benchmarking by Mark Stosberg, it turns out that
2489 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2490 I must admit this wasn't an intentional design issue, but it's a
2491 byproduct of the fact that you get to control your C<DBI> handles
2494 To maximize performance, use a code snippet like the following:
2496 # prepare a statement handle using the first row
2497 # and then reuse it for the rest of the rows
2499 for my $href (@array_of_hashrefs) {
2500 $stmt ||= $sql->insert('table', $href);
2501 $sth ||= $dbh->prepare($stmt);
2502 $sth->execute($sql->values($href));
2505 The reason this works is because the keys in your C<$href> are sorted
2506 internally by B<SQL::Abstract>. Thus, as long as your data retains
2507 the same structure, you only have to generate the SQL the first time
2508 around. On subsequent queries, simply use the C<values> function provided
2509 by this module to return your values in the correct order.
2511 However this depends on the values having the same type - if, for
2512 example, the values of a where clause may either have values
2513 (resulting in sql of the form C<column = ?> with a single bind
2514 value), or alternatively the values might be C<undef> (resulting in
2515 sql of the form C<column IS NULL> with no bind value) then the
2516 caching technique suggested will not work.
2520 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2521 really like this part (I do, at least). Building up a complex query
2522 can be as simple as the following:
2526 use CGI::FormBuilder;
2529 my $form = CGI::FormBuilder->new(...);
2530 my $sql = SQL::Abstract->new;
2532 if ($form->submitted) {
2533 my $field = $form->field;
2534 my $id = delete $field->{id};
2535 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2538 Of course, you would still have to connect using C<DBI> to run the
2539 query, but the point is that if you make your form look like your
2540 table, the actual query script can be extremely simplistic.
2542 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2543 a fast interface to returning and formatting data. I frequently
2544 use these three modules together to write complex database query
2545 apps in under 50 lines.
2551 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2553 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2559 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2560 Great care has been taken to preserve the I<published> behavior
2561 documented in previous versions in the 1.* family; however,
2562 some features that were previously undocumented, or behaved
2563 differently from the documentation, had to be changed in order
2564 to clarify the semantics. Hence, client code that was relying
2565 on some dark areas of C<SQL::Abstract> v1.*
2566 B<might behave differently> in v1.50.
2568 The main changes are :
2574 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2578 support for the { operator => \"..." } construct (to embed literal SQL)
2582 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2586 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2590 defensive programming : check arguments
2594 fixed bug with global logic, which was previously implemented
2595 through global variables yielding side-effects. Prior versions would
2596 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2597 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2598 Now this is interpreted
2599 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2604 fixed semantics of _bindtype on array args
2608 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2609 we just avoid shifting arrays within that tree.
2613 dropped the C<_modlogic> function
2617 =head1 ACKNOWLEDGEMENTS
2619 There are a number of individuals that have really helped out with
2620 this module. Unfortunately, most of them submitted bugs via CPAN
2621 so I have no idea who they are! But the people I do know are:
2623 Ash Berlin (order_by hash term support)
2624 Matt Trout (DBIx::Class support)
2625 Mark Stosberg (benchmarking)
2626 Chas Owens (initial "IN" operator support)
2627 Philip Collins (per-field SQL functions)
2628 Eric Kolve (hashref "AND" support)
2629 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2630 Dan Kubb (support for "quote_char" and "name_sep")
2631 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2632 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2633 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2634 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2635 Oliver Charles (support for "RETURNING" after "INSERT")
2641 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2645 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2647 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2649 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2650 While not an official support venue, C<DBIx::Class> makes heavy use of
2651 C<SQL::Abstract>, and as such list members there are very familiar with
2652 how to create queries.
2656 This module is free software; you may copy this under the same
2657 terms as perl itself (either the GNU General Public License or
2658 the Artistic License)