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)
13 use Data::Query::Constants qw(
14 DQ_IDENTIFIER DQ_OPERATOR DQ_VALUE DQ_LITERAL DQ_JOIN DQ_SELECT DQ_ORDER
16 use Data::Query::ExprHelpers qw(perl_scalar_value);
18 #======================================================================
20 #======================================================================
22 our $VERSION = '1.72';
24 # This would confuse some packagers
25 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
29 # special operators (-in, -between). May be extended/overridden by user.
30 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
31 my @BUILTIN_SPECIAL_OPS = (
32 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
33 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
34 {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
35 {regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
38 # unaryish operators - key maps to handler
39 my @BUILTIN_UNARY_OPS = (
40 # the digits are backcompat stuff
41 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
42 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
43 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
44 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
45 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
46 { regex => qr/^ value $/ix, handler => '_where_op_VALUE' },
49 #======================================================================
50 # DEBUGGING AND ERROR REPORTING
51 #======================================================================
54 return unless $_[0]->{debug}; shift; # a little faster
55 my $func = (caller(1))[3];
56 warn "[$func] ", @_, "\n";
60 my($func) = (caller(1))[3];
61 Carp::carp "[$func] Warning: ", @_;
65 my($func) = (caller(1))[3];
66 Carp::croak "[$func] Fatal: ", @_;
70 #======================================================================
72 #======================================================================
76 my $class = ref($self) || $self;
77 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
79 # choose our case by keeping an option around
80 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
82 # default logic for interpreting arrayrefs
83 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
85 # how to return bind vars
86 # LDNOTE: changed nwiger code : why this 'delete' ??
87 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
88 $opt{bindtype} ||= 'normal';
90 # default comparison is "=", but can be overridden
93 # try to recognize which are the 'equality' and 'unequality' ops
94 # (temporary quickfix, should go through a more seasoned API)
95 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
96 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
99 $opt{sqltrue} ||= '1=1';
100 $opt{sqlfalse} ||= '0=1';
103 $opt{special_ops} ||= [];
104 # regexes are applied in order, thus push after user-defines
105 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
108 $opt{unary_ops} ||= [];
109 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
111 # rudimentary saniy-check for user supplied bits treated as functions/operators
112 # If a purported function matches this regular expression, an exception is thrown.
113 # Literal SQL is *NOT* subject to this check, only functions (and column names
114 # when quoting is not in effect)
117 # need to guard against ()'s in column names too, but this will break tons of
118 # hacks... ideas anyone?
119 $opt{injection_guard} ||= qr/
125 $opt{name_sep} ||= '.';
127 $opt{renderer} ||= do {
128 require Data::Query::Renderer::SQL::Naive;
129 my ($always, $chars);
130 for ($opt{quote_char}) {
131 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
134 Data::Query::Renderer::SQL::Naive->new({
135 quote_chars => $chars, always_quote => $always,
139 return bless \%opt, $class;
143 my ($self, $dq) = @_;
144 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
146 ($self->{bindtype} eq 'normal'
147 ? ($sql, map $_->{value}, @bind)
148 : ($sql, map [ $_->{meta}, $_->{value} ], @bind)
154 my ($self, @bind) = @_;
155 $self->{bindtype} eq 'normal'
156 ? map perl_scalar_value($_), @bind
157 : map perl_scalar_value(reverse @$_), @bind
161 my ($self, $ident) = @_;
163 type => DQ_IDENTIFIER,
164 elements => [ split /\Q$self->{name_sep}/, $ident ],
168 sub _assert_pass_injection_guard {
169 if ($_[1] =~ $_[0]->{injection_guard}) {
170 my $class = ref $_[0];
171 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
172 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
173 . "{injection_guard} attribute to ${class}->new()"
178 #======================================================================
180 #======================================================================
184 my $table = $self->_table(shift);
185 my $data = shift || return;
188 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
189 my ($sql, @bind) = $self->$method($data);
190 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
192 if ($options->{returning}) {
193 my ($s, @b) = $self->_insert_returning ($options);
198 return wantarray ? ($sql, @bind) : $sql;
201 sub _insert_returning {
202 my ($self, $options) = @_;
204 my $f = $options->{returning};
206 my $fieldlist = $self->_SWITCH_refkind($f, {
207 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
208 SCALAR => sub {$self->_quote($f)},
209 SCALARREF => sub {$$f},
211 return $self->_sqlcase(' returning ') . $fieldlist;
214 sub _insert_HASHREF { # explicit list of fields and then values
215 my ($self, $data) = @_;
217 my @fields = sort keys %$data;
219 my ($sql, @bind) = $self->_insert_values($data);
222 $_ = $self->_quote($_) foreach @fields;
223 $sql = "( ".join(", ", @fields).") ".$sql;
225 return ($sql, @bind);
228 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
229 my ($self, $data) = @_;
231 # no names (arrayref) so can't generate bindtype
232 $self->{bindtype} ne 'columns'
233 or belch "can't do 'columns' bindtype when called with arrayref";
235 # fold the list of values into a hash of column name - value pairs
236 # (where the column names are artificially generated, and their
237 # lexicographical ordering keep the ordering of the original list)
238 my $i = "a"; # incremented values will be in lexicographical order
239 my $data_in_hash = { map { ($i++ => $_) } @$data };
241 return $self->_insert_values($data_in_hash);
244 sub _insert_ARRAYREFREF { # literal SQL with bind
245 my ($self, $data) = @_;
247 my ($sql, @bind) = @${$data};
248 $self->_assert_bindval_matches_bindtype(@bind);
250 return ($sql, @bind);
254 sub _insert_SCALARREF { # literal SQL without bind
255 my ($self, $data) = @_;
261 my ($self, $data) = @_;
263 my (@values, @all_bind);
264 foreach my $column (sort keys %$data) {
265 my $v = $data->{$column};
267 $self->_SWITCH_refkind($v, {
270 if ($self->{array_datatypes}) { # if array datatype are activated
272 push @all_bind, $self->_bindtype($column, $v);
274 else { # else literal SQL with bind
275 my ($sql, @bind) = @$v;
276 $self->_assert_bindval_matches_bindtype(@bind);
278 push @all_bind, @bind;
282 ARRAYREFREF => sub { # literal SQL with bind
283 my ($sql, @bind) = @${$v};
284 $self->_assert_bindval_matches_bindtype(@bind);
286 push @all_bind, @bind;
289 # THINK : anything useful to do with a HASHREF ?
290 HASHREF => sub { # (nothing, but old SQLA passed it through)
291 #TODO in SQLA >= 2.0 it will die instead
292 belch "HASH ref as bind value in insert is not supported";
294 push @all_bind, $self->_bindtype($column, $v);
297 SCALARREF => sub { # literal SQL without bind
301 SCALAR_or_UNDEF => sub {
303 push @all_bind, $self->_bindtype($column, $v);
310 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
311 return ($sql, @all_bind);
316 #======================================================================
318 #======================================================================
323 my $table = $self->_table(shift);
324 my $data = shift || return;
327 # first build the 'SET' part of the sql statement
328 my (@set, @all_bind);
329 puke "Unsupported data type specified to \$sql->update"
330 unless ref $data eq 'HASH';
332 for my $k (sort keys %$data) {
335 my $label = $self->_quote($k);
337 $self->_SWITCH_refkind($v, {
339 if ($self->{array_datatypes}) { # array datatype
340 push @set, "$label = ?";
341 push @all_bind, $self->_bindtype($k, $v);
343 else { # literal SQL with bind
344 my ($sql, @bind) = @$v;
345 $self->_assert_bindval_matches_bindtype(@bind);
346 push @set, "$label = $sql";
347 push @all_bind, @bind;
350 ARRAYREFREF => sub { # literal SQL with bind
351 my ($sql, @bind) = @${$v};
352 $self->_assert_bindval_matches_bindtype(@bind);
353 push @set, "$label = $sql";
354 push @all_bind, @bind;
356 SCALARREF => sub { # literal SQL without bind
357 push @set, "$label = $$v";
360 my ($op, $arg, @rest) = %$v;
362 puke 'Operator calls in update must be in the form { -op => $arg }'
363 if (@rest or not $op =~ /^\-(.+)/);
365 local $self->{_nested_func_lhs} = $k;
366 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
368 push @set, "$label = $sql";
369 push @all_bind, @bind;
371 SCALAR_or_UNDEF => sub {
372 push @set, "$label = ?";
373 push @all_bind, $self->_bindtype($k, $v);
379 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
383 my($where_sql, @where_bind) = $self->where($where);
385 push @all_bind, @where_bind;
388 return wantarray ? ($sql, @all_bind) : $sql;
394 #======================================================================
396 #======================================================================
402 my $fields = shift || '*';
406 my($where_sql, @bind) = $self->where($where, $order);
408 my $sql = $self->_render_dq({
411 map $self->_ident_to_dq($_),
412 ref($fields) eq 'ARRAY' ? @$fields : $fields
414 from => $self->_table_to_dq($table),
419 return wantarray ? ($sql, @bind) : $sql;
422 #======================================================================
424 #======================================================================
429 my $table = $self->_table(shift);
433 my($where_sql, @bind) = $self->where($where);
434 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
436 return wantarray ? ($sql, @bind) : $sql;
440 #======================================================================
442 #======================================================================
446 # Finally, a separate routine just to handle WHERE clauses
448 my ($self, $where, $order) = @_;
451 my ($sql, @bind) = $self->_recurse_where($where);
452 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
456 $sql .= $self->_order_by($order);
459 return wantarray ? ($sql, @bind) : $sql;
464 my ($self, $where, $logic) = @_;
466 # dispatch on appropriate method according to refkind of $where
467 my $method = $self->_METHOD_FOR_refkind("_where", $where);
469 my ($sql, @bind) = $self->$method($where, $logic);
471 # DBIx::Class directly calls _recurse_where in scalar context, so
472 # we must implement it, even if not in the official API
473 return wantarray ? ($sql, @bind) : $sql;
478 #======================================================================
479 # WHERE: top-level ARRAYREF
480 #======================================================================
483 sub _where_ARRAYREF {
484 my ($self, $where, $logic) = @_;
486 $logic = uc($logic || $self->{logic});
487 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
489 my @clauses = @$where;
491 my (@sql_clauses, @all_bind);
492 # need to use while() so can shift() for pairs
493 while (my $el = shift @clauses) {
495 # switch according to kind of $el and get corresponding ($sql, @bind)
496 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
498 # skip empty elements, otherwise get invalid trailing AND stuff
499 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
503 $self->_assert_bindval_matches_bindtype(@b);
507 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
508 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
509 # side-effect: the first hashref within an array would change
510 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
511 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
512 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
514 SCALARREF => sub { ($$el); },
516 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
517 $self->_recurse_where({$el => shift(@clauses)})},
519 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
523 push @sql_clauses, $sql;
524 push @all_bind, @bind;
528 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
531 #======================================================================
532 # WHERE: top-level ARRAYREFREF
533 #======================================================================
535 sub _where_ARRAYREFREF {
536 my ($self, $where) = @_;
537 my ($sql, @bind) = @$$where;
538 $self->_assert_bindval_matches_bindtype(@bind);
539 return ($sql, @bind);
542 #======================================================================
543 # WHERE: top-level HASHREF
544 #======================================================================
547 my ($self, $where) = @_;
548 my (@sql_clauses, @all_bind);
550 for my $k (sort keys %$where) {
551 my $v = $where->{$k};
553 # ($k => $v) is either a special unary op or a regular hashpair
554 my ($sql, @bind) = do {
556 # put the operator in canonical form
558 $op = substr $op, 1; # remove initial dash
559 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
560 $op =~ s/\s+/ /g; # compress whitespace
562 # so that -not_foo works correctly
563 $op =~ s/^not_/NOT /i;
565 $self->_debug("Unary OP(-$op) within hashref, recursing...");
566 my ($s, @b) = $self->_where_unary_op ($op, $v);
568 # top level vs nested
569 # we assume that handled unary ops will take care of their ()s
571 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
573 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
578 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
579 $self->$method($k, $v);
583 push @sql_clauses, $sql;
584 push @all_bind, @bind;
587 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
590 sub _where_unary_op {
591 my ($self, $op, $rhs) = @_;
593 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
594 my $handler = $op_entry->{handler};
596 if (not ref $handler) {
597 if ($op =~ s/ [_\s]? \d+ $//x ) {
598 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
599 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
601 return $self->$handler ($op, $rhs);
603 elsif (ref $handler eq 'CODE') {
604 return $handler->($self, $op, $rhs);
607 puke "Illegal handler for operator $op - expecting a method name or a coderef";
611 $self->_debug("Generic unary OP: $op - recursing as function");
613 $self->_assert_pass_injection_guard($op);
615 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
617 puke "Illegal use of top-level '$op'"
618 unless $self->{_nested_func_lhs};
621 $self->_convert('?'),
622 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
626 $self->_recurse_where ($rhs)
630 $sql = sprintf ('%s %s',
631 $self->_sqlcase($op),
635 return ($sql, @bind);
638 sub _where_op_ANDOR {
639 my ($self, $op, $v) = @_;
641 $self->_SWITCH_refkind($v, {
643 return $self->_where_ARRAYREF($v, $op);
647 return ( $op =~ /^or/i )
648 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
649 : $self->_where_HASHREF($v);
653 puke "-$op => \\\$scalar makes little sense, use " .
655 ? '[ \$scalar, \%rest_of_conditions ] instead'
656 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
661 puke "-$op => \\[...] makes little sense, use " .
663 ? '[ \[...], \%rest_of_conditions ] instead'
664 : '-and => [ \[...], \%rest_of_conditions ] instead'
668 SCALAR => sub { # permissively interpreted as SQL
669 puke "-$op => \$value makes little sense, use -bool => \$value instead";
673 puke "-$op => undef not supported";
679 my ($self, $op, $v) = @_;
681 $self->_SWITCH_refkind($v, {
683 SCALAR => sub { # permissively interpreted as SQL
684 belch "literal SQL should be -nest => \\'scalar' "
685 . "instead of -nest => 'scalar' ";
690 puke "-$op => undef not supported";
694 $self->_recurse_where ($v);
702 my ($self, $op, $v) = @_;
704 my ($s, @b) = $self->_SWITCH_refkind($v, {
705 SCALAR => sub { # interpreted as SQL column
706 $self->_convert($self->_quote($v));
710 puke "-$op => undef not supported";
714 $self->_recurse_where ($v);
718 $s = "(NOT $s)" if $op =~ /^not/i;
723 sub _where_op_IDENT {
725 my ($op, $rhs) = splice @_, -2;
727 puke "-$op takes a single scalar argument (a quotable identifier)";
730 # in case we are called as a top level special op (no '=')
733 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
741 sub _where_op_VALUE {
743 my ($op, $rhs) = splice @_, -2;
745 # in case we are called as a top level special op (no '=')
750 ($lhs || $self->{_nested_func_lhs}),
757 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
761 $self->_convert('?'),
767 sub _where_hashpair_ARRAYREF {
768 my ($self, $k, $v) = @_;
771 my @v = @$v; # need copy because of shift below
772 $self->_debug("ARRAY($k) means distribute over elements");
774 # put apart first element if it is an operator (-and, -or)
776 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
780 my @distributed = map { {$k => $_} } @v;
783 $self->_debug("OP($op) reinjected into the distributed array");
784 unshift @distributed, $op;
787 my $logic = $op ? substr($op, 1) : '';
789 return $self->_recurse_where(\@distributed, $logic);
792 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
793 $self->_debug("empty ARRAY($k) means 0=1");
794 return ($self->{sqlfalse});
798 sub _where_hashpair_HASHREF {
799 my ($self, $k, $v, $logic) = @_;
802 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
804 my ($all_sql, @all_bind);
806 for my $orig_op (sort keys %$v) {
807 my $val = $v->{$orig_op};
809 # put the operator in canonical form
812 # FIXME - we need to phase out dash-less ops
813 $op =~ s/^-//; # remove possible initial dash
814 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
815 $op =~ s/\s+/ /g; # compress whitespace
817 $self->_assert_pass_injection_guard($op);
819 # so that -not_foo works correctly
820 $op =~ s/^not_/NOT /i;
824 # CASE: col-value logic modifiers
825 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
826 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
828 # CASE: special operators like -in or -between
829 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
830 my $handler = $special_op->{handler};
832 puke "No handler supplied for special operator $orig_op";
834 elsif (not ref $handler) {
835 ($sql, @bind) = $self->$handler ($k, $op, $val);
837 elsif (ref $handler eq 'CODE') {
838 ($sql, @bind) = $handler->($self, $k, $op, $val);
841 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
845 $self->_SWITCH_refkind($val, {
847 ARRAYREF => sub { # CASE: col => {op => \@vals}
848 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
851 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
852 my ($sub_sql, @sub_bind) = @$$val;
853 $self->_assert_bindval_matches_bindtype(@sub_bind);
854 $sql = join ' ', $self->_convert($self->_quote($k)),
855 $self->_sqlcase($op),
860 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
861 my $is = ($op =~ $self->{equality_op}) ? 'is' :
862 ($op =~ $self->{inequality_op}) ? 'is not' :
863 puke "unexpected operator '$orig_op' with undef operand";
864 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
867 FALLBACK => sub { # CASE: col => {op/func => $stuff}
869 # retain for proper column type bind
870 $self->{_nested_func_lhs} ||= $k;
872 ($sql, @bind) = $self->_where_unary_op ($op, $val);
875 $self->_convert($self->_quote($k)),
876 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
882 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
883 push @all_bind, @bind;
885 return ($all_sql, @all_bind);
890 sub _where_field_op_ARRAYREF {
891 my ($self, $k, $op, $vals) = @_;
893 my @vals = @$vals; #always work on a copy
896 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
898 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
901 # see if the first element is an -and/-or op
903 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
908 # distribute $op over each remaining member of @vals, append logic if exists
909 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
911 # LDNOTE : had planned to change the distribution logic when
912 # $op =~ $self->{inequality_op}, because of Morgan laws :
913 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
914 # WHERE field != 22 OR field != 33 : the user probably means
915 # WHERE field != 22 AND field != 33.
916 # To do this, replace the above to roughly :
917 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
918 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
922 # try to DWIM on equality operators
923 # LDNOTE : not 100% sure this is the correct thing to do ...
924 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
925 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
928 puke "operator '$op' applied on an empty array (field '$k')";
933 sub _where_hashpair_SCALARREF {
934 my ($self, $k, $v) = @_;
935 $self->_debug("SCALAR($k) means literal SQL: $$v");
936 my $sql = $self->_quote($k) . " " . $$v;
940 # literal SQL with bind
941 sub _where_hashpair_ARRAYREFREF {
942 my ($self, $k, $v) = @_;
943 $self->_debug("REF($k) means literal SQL: @${$v}");
944 my ($sql, @bind) = @$$v;
945 $self->_assert_bindval_matches_bindtype(@bind);
946 $sql = $self->_quote($k) . " " . $sql;
947 return ($sql, @bind );
950 # literal SQL without bind
951 sub _where_hashpair_SCALAR {
952 my ($self, $k, $v) = @_;
953 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
954 my $sql = join ' ', $self->_convert($self->_quote($k)),
955 $self->_sqlcase($self->{cmp}),
956 $self->_convert('?');
957 my @bind = $self->_bindtype($k, $v);
958 return ( $sql, @bind);
962 sub _where_hashpair_UNDEF {
963 my ($self, $k, $v) = @_;
964 $self->_debug("UNDEF($k) means IS NULL");
965 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
969 #======================================================================
970 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
971 #======================================================================
974 sub _where_SCALARREF {
975 my ($self, $where) = @_;
978 $self->_debug("SCALAR(*top) means literal SQL: $$where");
984 my ($self, $where) = @_;
987 $self->_debug("NOREF(*top) means literal SQL: $where");
998 #======================================================================
999 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
1000 #======================================================================
1003 sub _where_field_BETWEEN {
1004 my ($self, $k, $op, $vals) = @_;
1006 my ($label, $and, $placeholder);
1007 $label = $self->_convert($self->_quote($k));
1008 $and = ' ' . $self->_sqlcase('and') . ' ';
1009 $placeholder = $self->_convert('?');
1010 $op = $self->_sqlcase($op);
1012 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
1013 ARRAYREFREF => sub {
1014 my ($s, @b) = @$$vals;
1015 $self->_assert_bindval_matches_bindtype(@b);
1022 puke "special op 'between' accepts an arrayref with exactly two values"
1025 my (@all_sql, @all_bind);
1026 foreach my $val (@$vals) {
1027 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1029 return ($placeholder, $self->_bindtype($k, $val) );
1034 ARRAYREFREF => sub {
1035 my ($sql, @bind) = @$$val;
1036 $self->_assert_bindval_matches_bindtype(@bind);
1037 return ($sql, @bind);
1040 my ($func, $arg, @rest) = %$val;
1041 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
1042 if (@rest or $func !~ /^ \- (.+)/x);
1043 local $self->{_nested_func_lhs} = $k;
1044 $self->_where_unary_op ($1 => $arg);
1047 push @all_sql, $sql;
1048 push @all_bind, @bind;
1052 (join $and, @all_sql),
1057 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
1061 my $sql = "( $label $op $clause )";
1062 return ($sql, @bind)
1066 sub _where_field_IN {
1067 my ($self, $k, $op, $vals) = @_;
1069 # backwards compatibility : if scalar, force into an arrayref
1070 $vals = [$vals] if defined $vals && ! ref $vals;
1072 my ($label) = $self->_convert($self->_quote($k));
1073 my ($placeholder) = $self->_convert('?');
1074 $op = $self->_sqlcase($op);
1076 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1077 ARRAYREF => sub { # list of choices
1078 if (@$vals) { # nonempty list
1079 my (@all_sql, @all_bind);
1081 for my $val (@$vals) {
1082 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1084 return ($placeholder, $val);
1089 ARRAYREFREF => sub {
1090 my ($sql, @bind) = @$$val;
1091 $self->_assert_bindval_matches_bindtype(@bind);
1092 return ($sql, @bind);
1095 my ($func, $arg, @rest) = %$val;
1096 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1097 if (@rest or $func !~ /^ \- (.+)/x);
1098 local $self->{_nested_func_lhs} = $k;
1099 $self->_where_unary_op ($1 => $arg);
1102 return $self->_sqlcase('null');
1105 push @all_sql, $sql;
1106 push @all_bind, @bind;
1110 sprintf ('%s %s ( %s )',
1113 join (', ', @all_sql)
1115 $self->_bindtype($k, @all_bind),
1118 else { # empty list : some databases won't understand "IN ()", so DWIM
1119 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1124 SCALARREF => sub { # literal SQL
1125 my $sql = $self->_open_outer_paren ($$vals);
1126 return ("$label $op ( $sql )");
1128 ARRAYREFREF => sub { # literal SQL with bind
1129 my ($sql, @bind) = @$$vals;
1130 $self->_assert_bindval_matches_bindtype(@bind);
1131 $sql = $self->_open_outer_paren ($sql);
1132 return ("$label $op ( $sql )", @bind);
1136 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1140 return ($sql, @bind);
1143 # Some databases (SQLite) treat col IN (1, 2) different from
1144 # col IN ( (1, 2) ). Use this to strip all outer parens while
1145 # adding them back in the corresponding method
1146 sub _open_outer_paren {
1147 my ($self, $sql) = @_;
1148 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1153 #======================================================================
1155 #======================================================================
1158 my ($self, $arg) = @_;
1159 if (my $dq = $self->_order_by_to_dq($arg)) {
1160 # SQLA generates ' ORDER BY foo'. The hilarity.
1162 ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
1163 : ' '.$self->_render_dq($dq);
1169 sub _order_by_to_dq {
1170 my ($self, $arg, $dir) = @_;
1176 ($dir ? (direction => $dir) : ()),
1180 $dq->{by} = $self->_ident_to_dq($arg);
1181 } elsif (ref($arg) eq 'ARRAY') {
1182 return unless @$arg;
1183 local our $Order_Inner unless our $Order_Recursing;
1184 local $Order_Recursing = 1;
1185 my ($outer, $inner);
1186 foreach my $member (@$arg) {
1188 my $next = $self->_order_by_to_dq($member, $dir);
1190 $inner->{from} = $next if $inner;
1191 $inner = $Order_Inner || $next;
1193 $Order_Inner = $inner;
1195 } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
1196 my ($sql, @bind) = @{$$arg};
1201 values => [ $self->_bind_to_dq(@bind) ],
1203 } elsif (ref($arg) eq 'SCALAR') {
1209 } elsif (ref($arg) eq 'HASH') {
1210 my ($key, $val, @rest) = %$arg;
1214 if (@rest or not $key =~ /^-(desc|asc)/i) {
1215 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1218 return $self->_order_by_to_dq($val, $dir);
1220 die "Can't handle $arg in _order_by_to_dq";
1225 #======================================================================
1226 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1227 #======================================================================
1230 my ($self, $from) = @_;
1231 $self->_render_dq($self->_table_to_dq($from));
1235 my ($self, $from) = @_;
1236 $self->_SWITCH_refkind($from, {
1238 die "Empty FROM list" unless my @f = @$from;
1239 my $dq = $self->_ident_to_dq(shift @f);
1240 while (my $x = shift @f) {
1243 join => [ $dq, $self->_ident_to_dq($x) ]
1248 SCALAR => sub { $self->_ident_to_dq($from) },
1260 #======================================================================
1262 #======================================================================
1264 # highly optimized, as it's called way too often
1266 # my ($self, $label) = @_;
1268 return '' unless defined $_[1];
1269 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1271 unless ($_[0]->{quote_char}) {
1272 $_[0]->_assert_pass_injection_guard($_[1]);
1276 my $qref = ref $_[0]->{quote_char};
1279 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1281 elsif ($qref eq 'ARRAY') {
1282 ($l, $r) = @{$_[0]->{quote_char}};
1285 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1288 # parts containing * are naturally unquoted
1289 return join( $_[0]->{name_sep}||'', map
1290 { $_ eq '*' ? $_ : $l . $_ . $r }
1291 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1296 # Conversion, if applicable
1298 #my ($self, $arg) = @_;
1300 # LDNOTE : modified the previous implementation below because
1301 # it was not consistent : the first "return" is always an array,
1302 # the second "return" is context-dependent. Anyway, _convert
1303 # seems always used with just a single argument, so make it a
1305 # return @_ unless $self->{convert};
1306 # my $conv = $self->_sqlcase($self->{convert});
1307 # my @ret = map { $conv.'('.$_.')' } @_;
1308 # return wantarray ? @ret : $ret[0];
1309 if ($_[0]->{convert}) {
1310 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1317 #my ($self, $col, @vals) = @_;
1319 #LDNOTE : changed original implementation below because it did not make
1320 # sense when bindtype eq 'columns' and @vals > 1.
1321 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1323 # called often - tighten code
1324 return $_[0]->{bindtype} eq 'columns'
1325 ? map {[$_[1], $_]} @_[2 .. $#_]
1330 # Dies if any element of @bind is not in [colname => value] format
1331 # if bindtype is 'columns'.
1332 sub _assert_bindval_matches_bindtype {
1333 # my ($self, @bind) = @_;
1335 if ($self->{bindtype} eq 'columns') {
1337 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1338 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1344 sub _join_sql_clauses {
1345 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1347 if (@$clauses_aref > 1) {
1348 my $join = " " . $self->_sqlcase($logic) . " ";
1349 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1350 return ($sql, @$bind_aref);
1352 elsif (@$clauses_aref) {
1353 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1356 return (); # if no SQL, ignore @$bind_aref
1361 # Fix SQL case, if so requested
1363 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1364 # don't touch the argument ... crooked logic, but let's not change it!
1365 return $_[0]->{case} ? $_[1] : uc($_[1]);
1369 #======================================================================
1370 # DISPATCHING FROM REFKIND
1371 #======================================================================
1374 my ($self, $data) = @_;
1376 return 'UNDEF' unless defined $data;
1378 # blessed objects are treated like scalars
1379 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1381 return 'SCALAR' unless $ref;
1384 while ($ref eq 'REF') {
1386 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1390 return ($ref||'SCALAR') . ('REF' x $n_steps);
1394 my ($self, $data) = @_;
1395 my @try = ($self->_refkind($data));
1396 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1397 push @try, 'FALLBACK';
1401 sub _METHOD_FOR_refkind {
1402 my ($self, $meth_prefix, $data) = @_;
1405 for (@{$self->_try_refkind($data)}) {
1406 $method = $self->can($meth_prefix."_".$_)
1410 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1414 sub _SWITCH_refkind {
1415 my ($self, $data, $dispatch_table) = @_;
1418 for (@{$self->_try_refkind($data)}) {
1419 $coderef = $dispatch_table->{$_}
1423 puke "no dispatch entry for ".$self->_refkind($data)
1432 #======================================================================
1433 # VALUES, GENERATE, AUTOLOAD
1434 #======================================================================
1436 # LDNOTE: original code from nwiger, didn't touch code in that section
1437 # I feel the AUTOLOAD stuff should not be the default, it should
1438 # only be activated on explicit demand by user.
1442 my $data = shift || return;
1443 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1444 unless ref $data eq 'HASH';
1447 foreach my $k ( sort keys %$data ) {
1448 my $v = $data->{$k};
1449 $self->_SWITCH_refkind($v, {
1451 if ($self->{array_datatypes}) { # array datatype
1452 push @all_bind, $self->_bindtype($k, $v);
1454 else { # literal SQL with bind
1455 my ($sql, @bind) = @$v;
1456 $self->_assert_bindval_matches_bindtype(@bind);
1457 push @all_bind, @bind;
1460 ARRAYREFREF => sub { # literal SQL with bind
1461 my ($sql, @bind) = @${$v};
1462 $self->_assert_bindval_matches_bindtype(@bind);
1463 push @all_bind, @bind;
1465 SCALARREF => sub { # literal SQL without bind
1467 SCALAR_or_UNDEF => sub {
1468 push @all_bind, $self->_bindtype($k, $v);
1479 my(@sql, @sqlq, @sqlv);
1483 if ($ref eq 'HASH') {
1484 for my $k (sort keys %$_) {
1487 my $label = $self->_quote($k);
1488 if ($r eq 'ARRAY') {
1489 # literal SQL with bind
1490 my ($sql, @bind) = @$v;
1491 $self->_assert_bindval_matches_bindtype(@bind);
1492 push @sqlq, "$label = $sql";
1494 } elsif ($r eq 'SCALAR') {
1495 # literal SQL without bind
1496 push @sqlq, "$label = $$v";
1498 push @sqlq, "$label = ?";
1499 push @sqlv, $self->_bindtype($k, $v);
1502 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1503 } elsif ($ref eq 'ARRAY') {
1504 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1507 if ($r eq 'ARRAY') { # literal SQL with bind
1508 my ($sql, @bind) = @$v;
1509 $self->_assert_bindval_matches_bindtype(@bind);
1512 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1513 # embedded literal SQL
1520 push @sql, '(' . join(', ', @sqlq) . ')';
1521 } elsif ($ref eq 'SCALAR') {
1525 # strings get case twiddled
1526 push @sql, $self->_sqlcase($_);
1530 my $sql = join ' ', @sql;
1532 # this is pretty tricky
1533 # if ask for an array, return ($stmt, @bind)
1534 # otherwise, s/?/shift @sqlv/ to put it inline
1536 return ($sql, @sqlv);
1538 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1539 ref $d ? $d->[1] : $d/e;
1548 # This allows us to check for a local, then _form, attr
1550 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1551 return $self->generate($name, @_);
1562 SQL::Abstract - Generate SQL from Perl data structures
1568 my $sql = SQL::Abstract->new;
1570 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1572 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1574 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1576 my($stmt, @bind) = $sql->delete($table, \%where);
1578 # Then, use these in your DBI statements
1579 my $sth = $dbh->prepare($stmt);
1580 $sth->execute(@bind);
1582 # Just generate the WHERE clause
1583 my($stmt, @bind) = $sql->where(\%where, \@order);
1585 # Return values in the same order, for hashed queries
1586 # See PERFORMANCE section for more details
1587 my @bind = $sql->values(\%fieldvals);
1591 This module was inspired by the excellent L<DBIx::Abstract>.
1592 However, in using that module I found that what I really wanted
1593 to do was generate SQL, but still retain complete control over my
1594 statement handles and use the DBI interface. So, I set out to
1595 create an abstract SQL generation module.
1597 While based on the concepts used by L<DBIx::Abstract>, there are
1598 several important differences, especially when it comes to WHERE
1599 clauses. I have modified the concepts used to make the SQL easier
1600 to generate from Perl data structures and, IMO, more intuitive.
1601 The underlying idea is for this module to do what you mean, based
1602 on the data structures you provide it. The big advantage is that
1603 you don't have to modify your code every time your data changes,
1604 as this module figures it out.
1606 To begin with, an SQL INSERT is as easy as just specifying a hash
1607 of C<key=value> pairs:
1610 name => 'Jimbo Bobson',
1611 phone => '123-456-7890',
1612 address => '42 Sister Lane',
1613 city => 'St. Louis',
1614 state => 'Louisiana',
1617 The SQL can then be generated with this:
1619 my($stmt, @bind) = $sql->insert('people', \%data);
1621 Which would give you something like this:
1623 $stmt = "INSERT INTO people
1624 (address, city, name, phone, state)
1625 VALUES (?, ?, ?, ?, ?)";
1626 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1627 '123-456-7890', 'Louisiana');
1629 These are then used directly in your DBI code:
1631 my $sth = $dbh->prepare($stmt);
1632 $sth->execute(@bind);
1634 =head2 Inserting and Updating Arrays
1636 If your database has array types (like for example Postgres),
1637 activate the special option C<< array_datatypes => 1 >>
1638 when creating the C<SQL::Abstract> object.
1639 Then you may use an arrayref to insert and update database array types:
1641 my $sql = SQL::Abstract->new(array_datatypes => 1);
1643 planets => [qw/Mercury Venus Earth Mars/]
1646 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1650 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1652 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1655 =head2 Inserting and Updating SQL
1657 In order to apply SQL functions to elements of your C<%data> you may
1658 specify a reference to an arrayref for the given hash value. For example,
1659 if you need to execute the Oracle C<to_date> function on a value, you can
1660 say something like this:
1664 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1667 The first value in the array is the actual SQL. Any other values are
1668 optional and would be included in the bind values array. This gives
1671 my($stmt, @bind) = $sql->insert('people', \%data);
1673 $stmt = "INSERT INTO people (name, date_entered)
1674 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1675 @bind = ('Bill', '03/02/2003');
1677 An UPDATE is just as easy, all you change is the name of the function:
1679 my($stmt, @bind) = $sql->update('people', \%data);
1681 Notice that your C<%data> isn't touched; the module will generate
1682 the appropriately quirky SQL for you automatically. Usually you'll
1683 want to specify a WHERE clause for your UPDATE, though, which is
1684 where handling C<%where> hashes comes in handy...
1686 =head2 Complex where statements
1688 This module can generate pretty complicated WHERE statements
1689 easily. For example, simple C<key=value> pairs are taken to mean
1690 equality, and if you want to see if a field is within a set
1691 of values, you can use an arrayref. Let's say we wanted to
1692 SELECT some data based on this criteria:
1695 requestor => 'inna',
1696 worker => ['nwiger', 'rcwe', 'sfz'],
1697 status => { '!=', 'completed' }
1700 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1702 The above would give you something like this:
1704 $stmt = "SELECT * FROM tickets WHERE
1705 ( requestor = ? ) AND ( status != ? )
1706 AND ( worker = ? OR worker = ? OR worker = ? )";
1707 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1709 Which you could then use in DBI code like so:
1711 my $sth = $dbh->prepare($stmt);
1712 $sth->execute(@bind);
1718 The functions are simple. There's one for each major SQL operation,
1719 and a constructor you use first. The arguments are specified in a
1720 similar order to each function (table, then fields, then a where
1721 clause) to try and simplify things.
1726 =head2 new(option => 'value')
1728 The C<new()> function takes a list of options and values, and returns
1729 a new B<SQL::Abstract> object which can then be used to generate SQL
1730 through the methods below. The options accepted are:
1736 If set to 'lower', then SQL will be generated in all lowercase. By
1737 default SQL is generated in "textbook" case meaning something like:
1739 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1741 Any setting other than 'lower' is ignored.
1745 This determines what the default comparison operator is. By default
1746 it is C<=>, meaning that a hash like this:
1748 %where = (name => 'nwiger', email => 'nate@wiger.org');
1750 Will generate SQL like this:
1752 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1754 However, you may want loose comparisons by default, so if you set
1755 C<cmp> to C<like> you would get SQL such as:
1757 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1759 You can also override the comparsion on an individual basis - see
1760 the huge section on L</"WHERE CLAUSES"> at the bottom.
1762 =item sqltrue, sqlfalse
1764 Expressions for inserting boolean values within SQL statements.
1765 By default these are C<1=1> and C<1=0>. They are used
1766 by the special operators C<-in> and C<-not_in> for generating
1767 correct SQL even when the argument is an empty array (see below).
1771 This determines the default logical operator for multiple WHERE
1772 statements in arrays or hashes. If absent, the default logic is "or"
1773 for arrays, and "and" for hashes. This means that a WHERE
1777 event_date => {'>=', '2/13/99'},
1778 event_date => {'<=', '4/24/03'},
1781 will generate SQL like this:
1783 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1785 This is probably not what you want given this query, though (look
1786 at the dates). To change the "OR" to an "AND", simply specify:
1788 my $sql = SQL::Abstract->new(logic => 'and');
1790 Which will change the above C<WHERE> to:
1792 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1794 The logic can also be changed locally by inserting
1795 a modifier in front of an arrayref :
1797 @where = (-and => [event_date => {'>=', '2/13/99'},
1798 event_date => {'<=', '4/24/03'} ]);
1800 See the L</"WHERE CLAUSES"> section for explanations.
1804 This will automatically convert comparisons using the specified SQL
1805 function for both column and value. This is mostly used with an argument
1806 of C<upper> or C<lower>, so that the SQL will have the effect of
1807 case-insensitive "searches". For example, this:
1809 $sql = SQL::Abstract->new(convert => 'upper');
1810 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1812 Will turn out the following SQL:
1814 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1816 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1817 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1818 not validate this option; it will just pass through what you specify verbatim).
1822 This is a kludge because many databases suck. For example, you can't
1823 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1824 Instead, you have to use C<bind_param()>:
1826 $sth->bind_param(1, 'reg data');
1827 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1829 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1830 which loses track of which field each slot refers to. Fear not.
1832 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1833 Currently, you can specify either C<normal> (default) or C<columns>. If you
1834 specify C<columns>, you will get an array that looks like this:
1836 my $sql = SQL::Abstract->new(bindtype => 'columns');
1837 my($stmt, @bind) = $sql->insert(...);
1840 [ 'column1', 'value1' ],
1841 [ 'column2', 'value2' ],
1842 [ 'column3', 'value3' ],
1845 You can then iterate through this manually, using DBI's C<bind_param()>.
1847 $sth->prepare($stmt);
1850 my($col, $data) = @$_;
1851 if ($col eq 'details' || $col eq 'comments') {
1852 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1853 } elsif ($col eq 'image') {
1854 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1856 $sth->bind_param($i, $data);
1860 $sth->execute; # execute without @bind now
1862 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1863 Basically, the advantage is still that you don't have to care which fields
1864 are or are not included. You could wrap that above C<for> loop in a simple
1865 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1866 get a layer of abstraction over manual SQL specification.
1868 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1869 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1870 will expect the bind values in this format.
1874 This is the character that a table or column name will be quoted
1875 with. By default this is an empty string, but you could set it to
1876 the character C<`>, to generate SQL like this:
1878 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1880 Alternatively, you can supply an array ref of two items, the first being the left
1881 hand quote character, and the second the right hand quote character. For
1882 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1883 that generates SQL like this:
1885 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1887 Quoting is useful if you have tables or columns names that are reserved
1888 words in your database's SQL dialect.
1892 This is the character that separates a table and column name. It is
1893 necessary to specify this when the C<quote_char> option is selected,
1894 so that tables and column names can be individually quoted like this:
1896 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1898 =item injection_guard
1900 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1901 column name specified in a query structure. This is a safety mechanism to avoid
1902 injection attacks when mishandling user input e.g.:
1904 my %condition_as_column_value_pairs = get_values_from_user();
1905 $sqla->select( ... , \%condition_as_column_value_pairs );
1907 If the expression matches an exception is thrown. Note that literal SQL
1908 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1910 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1912 =item array_datatypes
1914 When this option is true, arrayrefs in INSERT or UPDATE are
1915 interpreted as array datatypes and are passed directly
1917 When this option is false, arrayrefs are interpreted
1918 as literal SQL, just like refs to arrayrefs
1919 (but this behavior is for backwards compatibility; when writing
1920 new queries, use the "reference to arrayref" syntax
1926 Takes a reference to a list of "special operators"
1927 to extend the syntax understood by L<SQL::Abstract>.
1928 See section L</"SPECIAL OPERATORS"> for details.
1932 Takes a reference to a list of "unary operators"
1933 to extend the syntax understood by L<SQL::Abstract>.
1934 See section L</"UNARY OPERATORS"> for details.
1940 =head2 insert($table, \@values || \%fieldvals, \%options)
1942 This is the simplest function. You simply give it a table name
1943 and either an arrayref of values or hashref of field/value pairs.
1944 It returns an SQL INSERT statement and a list of bind values.
1945 See the sections on L</"Inserting and Updating Arrays"> and
1946 L</"Inserting and Updating SQL"> for information on how to insert
1947 with those data types.
1949 The optional C<\%options> hash reference may contain additional
1950 options to generate the insert SQL. Currently supported options
1957 Takes either a scalar of raw SQL fields, or an array reference of
1958 field names, and adds on an SQL C<RETURNING> statement at the end.
1959 This allows you to return data generated by the insert statement
1960 (such as row IDs) without performing another C<SELECT> statement.
1961 Note, however, this is not part of the SQL standard and may not
1962 be supported by all database engines.
1966 =head2 update($table, \%fieldvals, \%where)
1968 This takes a table, hashref of field/value pairs, and an optional
1969 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1971 See the sections on L</"Inserting and Updating Arrays"> and
1972 L</"Inserting and Updating SQL"> for information on how to insert
1973 with those data types.
1975 =head2 select($source, $fields, $where, $order)
1977 This returns a SQL SELECT statement and associated list of bind values, as
1978 specified by the arguments :
1984 Specification of the 'FROM' part of the statement.
1985 The argument can be either a plain scalar (interpreted as a table
1986 name, will be quoted), or an arrayref (interpreted as a list
1987 of table names, joined by commas, quoted), or a scalarref
1988 (literal table name, not quoted), or a ref to an arrayref
1989 (list of literal table names, joined by commas, not quoted).
1993 Specification of the list of fields to retrieve from
1995 The argument can be either an arrayref (interpreted as a list
1996 of field names, will be joined by commas and quoted), or a
1997 plain scalar (literal SQL, not quoted).
1998 Please observe that this API is not as flexible as for
1999 the first argument C<$table>, for backwards compatibility reasons.
2003 Optional argument to specify the WHERE part of the query.
2004 The argument is most often a hashref, but can also be
2005 an arrayref or plain scalar --
2006 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2010 Optional argument to specify the ORDER BY part of the query.
2011 The argument can be a scalar, a hashref or an arrayref
2012 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2018 =head2 delete($table, \%where)
2020 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2021 It returns an SQL DELETE statement and list of bind values.
2023 =head2 where(\%where, \@order)
2025 This is used to generate just the WHERE clause. For example,
2026 if you have an arbitrary data structure and know what the
2027 rest of your SQL is going to look like, but want an easy way
2028 to produce a WHERE clause, use this. It returns an SQL WHERE
2029 clause and list of bind values.
2032 =head2 values(\%data)
2034 This just returns the values from the hash C<%data>, in the same
2035 order that would be returned from any of the other above queries.
2036 Using this allows you to markedly speed up your queries if you
2037 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2039 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2041 Warning: This is an experimental method and subject to change.
2043 This returns arbitrarily generated SQL. It's a really basic shortcut.
2044 It will return two different things, depending on return context:
2046 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2047 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2049 These would return the following:
2051 # First calling form
2052 $stmt = "CREATE TABLE test (?, ?)";
2053 @bind = (field1, field2);
2055 # Second calling form
2056 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2058 Depending on what you're trying to do, it's up to you to choose the correct
2059 format. In this example, the second form is what you would want.
2063 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2067 ALTER SESSION SET nls_date_format = 'MM/YY'
2069 You get the idea. Strings get their case twiddled, but everything
2070 else remains verbatim.
2072 =head1 WHERE CLAUSES
2076 This module uses a variation on the idea from L<DBIx::Abstract>. It
2077 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2078 module is that things in arrays are OR'ed, and things in hashes
2081 The easiest way to explain is to show lots of examples. After
2082 each C<%where> hash shown, it is assumed you used:
2084 my($stmt, @bind) = $sql->where(\%where);
2086 However, note that the C<%where> hash can be used directly in any
2087 of the other functions as well, as described above.
2089 =head2 Key-value pairs
2091 So, let's get started. To begin, a simple hash:
2095 status => 'completed'
2098 Is converted to SQL C<key = val> statements:
2100 $stmt = "WHERE user = ? AND status = ?";
2101 @bind = ('nwiger', 'completed');
2103 One common thing I end up doing is having a list of values that
2104 a field can be in. To do this, simply specify a list inside of
2109 status => ['assigned', 'in-progress', 'pending'];
2112 This simple code will create the following:
2114 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2115 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2117 A field associated to an empty arrayref will be considered a
2118 logical false and will generate 0=1.
2120 =head2 Tests for NULL values
2122 If the value part is C<undef> then this is converted to SQL <IS NULL>
2131 $stmt = "WHERE user = ? AND status IS NULL";
2134 To test if a column IS NOT NULL:
2138 status => { '!=', undef },
2141 =head2 Specific comparison operators
2143 If you want to specify a different type of operator for your comparison,
2144 you can use a hashref for a given column:
2148 status => { '!=', 'completed' }
2151 Which would generate:
2153 $stmt = "WHERE user = ? AND status != ?";
2154 @bind = ('nwiger', 'completed');
2156 To test against multiple values, just enclose the values in an arrayref:
2158 status => { '=', ['assigned', 'in-progress', 'pending'] };
2160 Which would give you:
2162 "WHERE status = ? OR status = ? OR status = ?"
2165 The hashref can also contain multiple pairs, in which case it is expanded
2166 into an C<AND> of its elements:
2170 status => { '!=', 'completed', -not_like => 'pending%' }
2173 # Or more dynamically, like from a form
2174 $where{user} = 'nwiger';
2175 $where{status}{'!='} = 'completed';
2176 $where{status}{'-not_like'} = 'pending%';
2178 # Both generate this
2179 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2180 @bind = ('nwiger', 'completed', 'pending%');
2183 To get an OR instead, you can combine it with the arrayref idea:
2187 priority => [ { '=', 2 }, { '>', 5 } ]
2190 Which would generate:
2192 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2193 @bind = ('2', '5', 'nwiger');
2195 If you want to include literal SQL (with or without bind values), just use a
2196 scalar reference or array reference as the value:
2199 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2200 date_expires => { '<' => \"now()" }
2203 Which would generate:
2205 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2206 @bind = ('11/26/2008');
2209 =head2 Logic and nesting operators
2211 In the example above,
2212 there is a subtle trap if you want to say something like
2213 this (notice the C<AND>):
2215 WHERE priority != ? AND priority != ?
2217 Because, in Perl you I<can't> do this:
2219 priority => { '!=', 2, '!=', 1 }
2221 As the second C<!=> key will obliterate the first. The solution
2222 is to use the special C<-modifier> form inside an arrayref:
2224 priority => [ -and => {'!=', 2},
2228 Normally, these would be joined by C<OR>, but the modifier tells it
2229 to use C<AND> instead. (Hint: You can use this in conjunction with the
2230 C<logic> option to C<new()> in order to change the way your queries
2231 work by default.) B<Important:> Note that the C<-modifier> goes
2232 B<INSIDE> the arrayref, as an extra first element. This will
2233 B<NOT> do what you think it might:
2235 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2237 Here is a quick list of equivalencies, since there is some overlap:
2240 status => {'!=', 'completed', 'not like', 'pending%' }
2241 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2244 status => {'=', ['assigned', 'in-progress']}
2245 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2246 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2250 =head2 Special operators : IN, BETWEEN, etc.
2252 You can also use the hashref format to compare a list of fields using the
2253 C<IN> comparison operator, by specifying the list as an arrayref:
2256 status => 'completed',
2257 reportid => { -in => [567, 2335, 2] }
2260 Which would generate:
2262 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2263 @bind = ('completed', '567', '2335', '2');
2265 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2268 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2269 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2270 'sqltrue' (by default : C<1=1>).
2272 In addition to the array you can supply a chunk of literal sql or
2273 literal sql with bind:
2276 customer => { -in => \[
2277 'SELECT cust_id FROM cust WHERE balance > ?',
2280 status => { -in => \'SELECT status_codes FROM states' },
2286 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2287 AND status IN ( SELECT status_codes FROM states )
2293 Another pair of operators is C<-between> and C<-not_between>,
2294 used with an arrayref of two values:
2298 completion_date => {
2299 -not_between => ['2002-10-01', '2003-02-06']
2305 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2307 Just like with C<-in> all plausible combinations of literal SQL
2311 start0 => { -between => [ 1, 2 ] },
2312 start1 => { -between => \["? AND ?", 1, 2] },
2313 start2 => { -between => \"lower(x) AND upper(y)" },
2314 start3 => { -between => [
2316 \["upper(?)", 'stuff' ],
2323 ( start0 BETWEEN ? AND ? )
2324 AND ( start1 BETWEEN ? AND ? )
2325 AND ( start2 BETWEEN lower(x) AND upper(y) )
2326 AND ( start3 BETWEEN lower(x) AND upper(?) )
2328 @bind = (1, 2, 1, 2, 'stuff');
2331 These are the two builtin "special operators"; but the
2332 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2334 =head2 Unary operators: bool
2336 If you wish to test against boolean columns or functions within your
2337 database you can use the C<-bool> and C<-not_bool> operators. For
2338 example to test the column C<is_user> being true and the column
2339 C<is_enabled> being false you would use:-
2343 -not_bool => 'is_enabled',
2348 WHERE is_user AND NOT is_enabled
2350 If a more complex combination is required, testing more conditions,
2351 then you should use the and/or operators:-
2358 -not_bool => 'four',
2364 WHERE one AND two AND three AND NOT four
2367 =head2 Nested conditions, -and/-or prefixes
2369 So far, we've seen how multiple conditions are joined with a top-level
2370 C<AND>. We can change this by putting the different conditions we want in
2371 hashes and then putting those hashes in an array. For example:
2376 status => { -like => ['pending%', 'dispatched'] },
2380 status => 'unassigned',
2384 This data structure would create the following:
2386 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2387 OR ( user = ? AND status = ? ) )";
2388 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2391 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2392 to change the logic inside :
2398 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2399 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2406 WHERE ( user = ? AND (
2407 ( workhrs > ? AND geo = ? )
2408 OR ( workhrs < ? OR geo = ? )
2411 =head3 Algebraic inconsistency, for historical reasons
2413 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2414 operator goes C<outside> of the nested structure; whereas when connecting
2415 several constraints on one column, the C<-and> operator goes
2416 C<inside> the arrayref. Here is an example combining both features :
2419 -and => [a => 1, b => 2],
2420 -or => [c => 3, d => 4],
2421 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2426 WHERE ( ( ( a = ? AND b = ? )
2427 OR ( c = ? OR d = ? )
2428 OR ( e LIKE ? AND e LIKE ? ) ) )
2430 This difference in syntax is unfortunate but must be preserved for
2431 historical reasons. So be careful : the two examples below would
2432 seem algebraically equivalent, but they are not
2434 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2435 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2437 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2438 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2441 =head2 Literal SQL and value type operators
2443 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2444 side" is a column name and the "right side" is a value (normally rendered as
2445 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2446 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2447 alter this behavior. There are several ways of doing so.
2451 This is a virtual operator that signals the string to its right side is an
2452 identifier (a column name) and not a value. For example to compare two
2453 columns you would write:
2456 priority => { '<', 2 },
2457 requestor => { -ident => 'submitter' },
2462 $stmt = "WHERE priority < ? AND requestor = submitter";
2465 If you are maintaining legacy code you may see a different construct as
2466 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2471 This is a virtual operator that signals that the construct to its right side
2472 is a value to be passed to DBI. This is for example necessary when you want
2473 to write a where clause against an array (for RDBMS that support such
2474 datatypes). For example:
2477 array => { -value => [1, 2, 3] }
2482 $stmt = 'WHERE array = ?';
2483 @bind = ([1, 2, 3]);
2485 Note that if you were to simply say:
2491 the result would porbably be not what you wanted:
2493 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2498 Finally, sometimes only literal SQL will do. To include a random snippet
2499 of SQL verbatim, you specify it as a scalar reference. Consider this only
2500 as a last resort. Usually there is a better way. For example:
2503 priority => { '<', 2 },
2504 requestor => { -in => \'(SELECT name FROM hitmen)' },
2509 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2512 Note that in this example, you only get one bind parameter back, since
2513 the verbatim SQL is passed as part of the statement.
2517 Never use untrusted input as a literal SQL argument - this is a massive
2518 security risk (there is no way to check literal snippets for SQL
2519 injections and other nastyness). If you need to deal with untrusted input
2520 use literal SQL with placeholders as described next.
2522 =head3 Literal SQL with placeholders and bind values (subqueries)
2524 If the literal SQL to be inserted has placeholders and bind values,
2525 use a reference to an arrayref (yes this is a double reference --
2526 not so common, but perfectly legal Perl). For example, to find a date
2527 in Postgres you can use something like this:
2530 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2535 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2538 Note that you must pass the bind values in the same format as they are returned
2539 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2540 provide the bind values in the C<< [ column_meta => value ] >> format, where
2541 C<column_meta> is an opaque scalar value; most commonly the column name, but
2542 you can use any scalar value (including references and blessed references),
2543 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2544 to C<columns> the above example will look like:
2547 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2550 Literal SQL is especially useful for nesting parenthesized clauses in the
2551 main SQL query. Here is a first example :
2553 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2557 bar => \["IN ($sub_stmt)" => @sub_bind],
2562 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2563 WHERE c2 < ? AND c3 LIKE ?))";
2564 @bind = (1234, 100, "foo%");
2566 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2567 are expressed in the same way. Of course the C<$sub_stmt> and
2568 its associated bind values can be generated through a former call
2571 my ($sub_stmt, @sub_bind)
2572 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2573 c3 => {-like => "foo%"}});
2576 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2579 In the examples above, the subquery was used as an operator on a column;
2580 but the same principle also applies for a clause within the main C<%where>
2581 hash, like an EXISTS subquery :
2583 my ($sub_stmt, @sub_bind)
2584 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2585 my %where = ( -and => [
2587 \["EXISTS ($sub_stmt)" => @sub_bind],
2592 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2593 WHERE c1 = ? AND c2 > t0.c0))";
2597 Observe that the condition on C<c2> in the subquery refers to
2598 column C<t0.c0> of the main query : this is I<not> a bind
2599 value, so we have to express it through a scalar ref.
2600 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2601 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2602 what we wanted here.
2604 Finally, here is an example where a subquery is used
2605 for expressing unary negation:
2607 my ($sub_stmt, @sub_bind)
2608 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2609 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2611 lname => {like => '%son%'},
2612 \["NOT ($sub_stmt)" => @sub_bind],
2617 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2618 @bind = ('%son%', 10, 20)
2620 =head3 Deprecated usage of Literal SQL
2622 Below are some examples of archaic use of literal SQL. It is shown only as
2623 reference for those who deal with legacy code. Each example has a much
2624 better, cleaner and safer alternative that users should opt for in new code.
2630 my %where = ( requestor => \'IS NOT NULL' )
2632 $stmt = "WHERE requestor IS NOT NULL"
2634 This used to be the way of generating NULL comparisons, before the handling
2635 of C<undef> got formalized. For new code please use the superior syntax as
2636 described in L</Tests for NULL values>.
2640 my %where = ( requestor => \'= submitter' )
2642 $stmt = "WHERE requestor = submitter"
2644 This used to be the only way to compare columns. Use the superior L</-ident>
2645 method for all new code. For example an identifier declared in such a way
2646 will be properly quoted if L</quote_char> is properly set, while the legacy
2647 form will remain as supplied.
2651 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2653 $stmt = "WHERE completed > ? AND is_ready"
2654 @bind = ('2012-12-21')
2656 Using an empty string literal used to be the only way to express a boolean.
2657 For all new code please use the much more readable
2658 L<-bool|/Unary operators: bool> operator.
2664 These pages could go on for a while, since the nesting of the data
2665 structures this module can handle are pretty much unlimited (the
2666 module implements the C<WHERE> expansion as a recursive function
2667 internally). Your best bet is to "play around" with the module a
2668 little to see how the data structures behave, and choose the best
2669 format for your data based on that.
2671 And of course, all the values above will probably be replaced with
2672 variables gotten from forms or the command line. After all, if you
2673 knew everything ahead of time, you wouldn't have to worry about
2674 dynamically-generating SQL and could just hardwire it into your
2677 =head1 ORDER BY CLAUSES
2679 Some functions take an order by clause. This can either be a scalar (just a
2680 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2681 or an array of either of the two previous forms. Examples:
2683 Given | Will Generate
2684 ----------------------------------------------------------
2686 \'colA DESC' | ORDER BY colA DESC
2688 'colA' | ORDER BY colA
2690 [qw/colA colB/] | ORDER BY colA, colB
2692 {-asc => 'colA'} | ORDER BY colA ASC
2694 {-desc => 'colB'} | ORDER BY colB DESC
2696 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2698 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2701 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2702 { -desc => [qw/colB/], | colC ASC, colD ASC
2703 { -asc => [qw/colC colD/],|
2705 ===========================================================
2709 =head1 SPECIAL OPERATORS
2711 my $sqlmaker = SQL::Abstract->new(special_ops => [
2715 my ($self, $field, $op, $arg) = @_;
2721 handler => 'method_name',
2725 A "special operator" is a SQL syntactic clause that can be
2726 applied to a field, instead of a usual binary operator.
2729 WHERE field IN (?, ?, ?)
2730 WHERE field BETWEEN ? AND ?
2731 WHERE MATCH(field) AGAINST (?, ?)
2733 Special operators IN and BETWEEN are fairly standard and therefore
2734 are builtin within C<SQL::Abstract> (as the overridable methods
2735 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2736 like the MATCH .. AGAINST example above which is specific to MySQL,
2737 you can write your own operator handlers - supply a C<special_ops>
2738 argument to the C<new> method. That argument takes an arrayref of
2739 operator definitions; each operator definition is a hashref with two
2746 the regular expression to match the operator
2750 Either a coderef or a plain scalar method name. In both cases
2751 the expected return is C<< ($sql, @bind) >>.
2753 When supplied with a method name, it is simply called on the
2754 L<SQL::Abstract/> object as:
2756 $self->$method_name ($field, $op, $arg)
2760 $op is the part that matched the handler regex
2761 $field is the LHS of the operator
2764 When supplied with a coderef, it is called as:
2766 $coderef->($self, $field, $op, $arg)
2771 For example, here is an implementation
2772 of the MATCH .. AGAINST syntax for MySQL
2774 my $sqlmaker = SQL::Abstract->new(special_ops => [
2776 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2777 {regex => qr/^match$/i,
2779 my ($self, $field, $op, $arg) = @_;
2780 $arg = [$arg] if not ref $arg;
2781 my $label = $self->_quote($field);
2782 my ($placeholder) = $self->_convert('?');
2783 my $placeholders = join ", ", (($placeholder) x @$arg);
2784 my $sql = $self->_sqlcase('match') . " ($label) "
2785 . $self->_sqlcase('against') . " ($placeholders) ";
2786 my @bind = $self->_bindtype($field, @$arg);
2787 return ($sql, @bind);
2794 =head1 UNARY OPERATORS
2796 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2800 my ($self, $op, $arg) = @_;
2806 handler => 'method_name',
2810 A "unary operator" is a SQL syntactic clause that can be
2811 applied to a field - the operator goes before the field
2813 You can write your own operator handlers - supply a C<unary_ops>
2814 argument to the C<new> method. That argument takes an arrayref of
2815 operator definitions; each operator definition is a hashref with two
2822 the regular expression to match the operator
2826 Either a coderef or a plain scalar method name. In both cases
2827 the expected return is C<< $sql >>.
2829 When supplied with a method name, it is simply called on the
2830 L<SQL::Abstract/> object as:
2832 $self->$method_name ($op, $arg)
2836 $op is the part that matched the handler regex
2837 $arg is the RHS or argument of the operator
2839 When supplied with a coderef, it is called as:
2841 $coderef->($self, $op, $arg)
2849 Thanks to some benchmarking by Mark Stosberg, it turns out that
2850 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2851 I must admit this wasn't an intentional design issue, but it's a
2852 byproduct of the fact that you get to control your C<DBI> handles
2855 To maximize performance, use a code snippet like the following:
2857 # prepare a statement handle using the first row
2858 # and then reuse it for the rest of the rows
2860 for my $href (@array_of_hashrefs) {
2861 $stmt ||= $sql->insert('table', $href);
2862 $sth ||= $dbh->prepare($stmt);
2863 $sth->execute($sql->values($href));
2866 The reason this works is because the keys in your C<$href> are sorted
2867 internally by B<SQL::Abstract>. Thus, as long as your data retains
2868 the same structure, you only have to generate the SQL the first time
2869 around. On subsequent queries, simply use the C<values> function provided
2870 by this module to return your values in the correct order.
2872 However this depends on the values having the same type - if, for
2873 example, the values of a where clause may either have values
2874 (resulting in sql of the form C<column = ?> with a single bind
2875 value), or alternatively the values might be C<undef> (resulting in
2876 sql of the form C<column IS NULL> with no bind value) then the
2877 caching technique suggested will not work.
2881 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2882 really like this part (I do, at least). Building up a complex query
2883 can be as simple as the following:
2887 use CGI::FormBuilder;
2890 my $form = CGI::FormBuilder->new(...);
2891 my $sql = SQL::Abstract->new;
2893 if ($form->submitted) {
2894 my $field = $form->field;
2895 my $id = delete $field->{id};
2896 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2899 Of course, you would still have to connect using C<DBI> to run the
2900 query, but the point is that if you make your form look like your
2901 table, the actual query script can be extremely simplistic.
2903 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2904 a fast interface to returning and formatting data. I frequently
2905 use these three modules together to write complex database query
2906 apps in under 50 lines.
2912 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2914 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2920 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2921 Great care has been taken to preserve the I<published> behavior
2922 documented in previous versions in the 1.* family; however,
2923 some features that were previously undocumented, or behaved
2924 differently from the documentation, had to be changed in order
2925 to clarify the semantics. Hence, client code that was relying
2926 on some dark areas of C<SQL::Abstract> v1.*
2927 B<might behave differently> in v1.50.
2929 The main changes are :
2935 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2939 support for the { operator => \"..." } construct (to embed literal SQL)
2943 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2947 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2951 defensive programming : check arguments
2955 fixed bug with global logic, which was previously implemented
2956 through global variables yielding side-effects. Prior versions would
2957 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2958 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2959 Now this is interpreted
2960 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2965 fixed semantics of _bindtype on array args
2969 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2970 we just avoid shifting arrays within that tree.
2974 dropped the C<_modlogic> function
2978 =head1 ACKNOWLEDGEMENTS
2980 There are a number of individuals that have really helped out with
2981 this module. Unfortunately, most of them submitted bugs via CPAN
2982 so I have no idea who they are! But the people I do know are:
2984 Ash Berlin (order_by hash term support)
2985 Matt Trout (DBIx::Class support)
2986 Mark Stosberg (benchmarking)
2987 Chas Owens (initial "IN" operator support)
2988 Philip Collins (per-field SQL functions)
2989 Eric Kolve (hashref "AND" support)
2990 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2991 Dan Kubb (support for "quote_char" and "name_sep")
2992 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2993 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2994 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2995 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2996 Oliver Charles (support for "RETURNING" after "INSERT")
3002 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3006 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3008 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3010 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3011 While not an official support venue, C<DBIx::Class> makes heavy use of
3012 C<SQL::Abstract>, and as such list members there are very familiar with
3013 how to create queries.
3017 This module is free software; you may copy this under the same
3018 terms as perl itself (either the GNU General Public License or
3019 the Artistic License)