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
17 #======================================================================
19 #======================================================================
21 our $VERSION = '1.72';
23 # This would confuse some packagers
24 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
28 # special operators (-in, -between). May be extended/overridden by user.
29 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
30 my @BUILTIN_SPECIAL_OPS = (
31 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
32 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
33 {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
34 {regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
37 # unaryish operators - key maps to handler
38 my @BUILTIN_UNARY_OPS = (
39 # the digits are backcompat stuff
40 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
41 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
42 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
43 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
44 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
45 { regex => qr/^ value $/ix, handler => '_where_op_VALUE' },
48 #======================================================================
49 # DEBUGGING AND ERROR REPORTING
50 #======================================================================
53 return unless $_[0]->{debug}; shift; # a little faster
54 my $func = (caller(1))[3];
55 warn "[$func] ", @_, "\n";
59 my($func) = (caller(1))[3];
60 Carp::carp "[$func] Warning: ", @_;
64 my($func) = (caller(1))[3];
65 Carp::croak "[$func] Fatal: ", @_;
69 #======================================================================
71 #======================================================================
75 my $class = ref($self) || $self;
76 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
78 # choose our case by keeping an option around
79 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
81 # default logic for interpreting arrayrefs
82 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
84 # how to return bind vars
85 # LDNOTE: changed nwiger code : why this 'delete' ??
86 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
87 $opt{bindtype} ||= 'normal';
89 # default comparison is "=", but can be overridden
92 # try to recognize which are the 'equality' and 'unequality' ops
93 # (temporary quickfix, should go through a more seasoned API)
94 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
95 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
98 $opt{sqltrue} ||= '1=1';
99 $opt{sqlfalse} ||= '0=1';
102 $opt{special_ops} ||= [];
103 # regexes are applied in order, thus push after user-defines
104 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
107 $opt{unary_ops} ||= [];
108 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
110 # rudimentary saniy-check for user supplied bits treated as functions/operators
111 # If a purported function matches this regular expression, an exception is thrown.
112 # Literal SQL is *NOT* subject to this check, only functions (and column names
113 # when quoting is not in effect)
116 # need to guard against ()'s in column names too, but this will break tons of
117 # hacks... ideas anyone?
118 $opt{injection_guard} ||= qr/
124 $opt{name_sep} ||= '.';
126 $opt{renderer} ||= do {
127 require Data::Query::Renderer::SQL::Naive;
128 my ($always, $chars);
129 for ($opt{quote_char}) {
130 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
133 Data::Query::Renderer::SQL::Naive->new({
134 quote_chars => $chars, always_quote => $always,
138 return bless \%opt, $class;
142 my ($self, $dq) = @_;
143 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
144 wantarray ? ($sql, map $_->{value}, @bind) : $sql;
147 sub _assert_pass_injection_guard {
148 if ($_[1] =~ $_[0]->{injection_guard}) {
149 my $class = ref $_[0];
150 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
151 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
152 . "{injection_guard} attribute to ${class}->new()"
157 #======================================================================
159 #======================================================================
163 my $table = $self->_table(shift);
164 my $data = shift || return;
167 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
168 my ($sql, @bind) = $self->$method($data);
169 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
171 if ($options->{returning}) {
172 my ($s, @b) = $self->_insert_returning ($options);
177 return wantarray ? ($sql, @bind) : $sql;
180 sub _insert_returning {
181 my ($self, $options) = @_;
183 my $f = $options->{returning};
185 my $fieldlist = $self->_SWITCH_refkind($f, {
186 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
187 SCALAR => sub {$self->_quote($f)},
188 SCALARREF => sub {$$f},
190 return $self->_sqlcase(' returning ') . $fieldlist;
193 sub _insert_HASHREF { # explicit list of fields and then values
194 my ($self, $data) = @_;
196 my @fields = sort keys %$data;
198 my ($sql, @bind) = $self->_insert_values($data);
201 $_ = $self->_quote($_) foreach @fields;
202 $sql = "( ".join(", ", @fields).") ".$sql;
204 return ($sql, @bind);
207 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
208 my ($self, $data) = @_;
210 # no names (arrayref) so can't generate bindtype
211 $self->{bindtype} ne 'columns'
212 or belch "can't do 'columns' bindtype when called with arrayref";
214 # fold the list of values into a hash of column name - value pairs
215 # (where the column names are artificially generated, and their
216 # lexicographical ordering keep the ordering of the original list)
217 my $i = "a"; # incremented values will be in lexicographical order
218 my $data_in_hash = { map { ($i++ => $_) } @$data };
220 return $self->_insert_values($data_in_hash);
223 sub _insert_ARRAYREFREF { # literal SQL with bind
224 my ($self, $data) = @_;
226 my ($sql, @bind) = @${$data};
227 $self->_assert_bindval_matches_bindtype(@bind);
229 return ($sql, @bind);
233 sub _insert_SCALARREF { # literal SQL without bind
234 my ($self, $data) = @_;
240 my ($self, $data) = @_;
242 my (@values, @all_bind);
243 foreach my $column (sort keys %$data) {
244 my $v = $data->{$column};
246 $self->_SWITCH_refkind($v, {
249 if ($self->{array_datatypes}) { # if array datatype are activated
251 push @all_bind, $self->_bindtype($column, $v);
253 else { # else literal SQL with bind
254 my ($sql, @bind) = @$v;
255 $self->_assert_bindval_matches_bindtype(@bind);
257 push @all_bind, @bind;
261 ARRAYREFREF => sub { # literal SQL with bind
262 my ($sql, @bind) = @${$v};
263 $self->_assert_bindval_matches_bindtype(@bind);
265 push @all_bind, @bind;
268 # THINK : anything useful to do with a HASHREF ?
269 HASHREF => sub { # (nothing, but old SQLA passed it through)
270 #TODO in SQLA >= 2.0 it will die instead
271 belch "HASH ref as bind value in insert is not supported";
273 push @all_bind, $self->_bindtype($column, $v);
276 SCALARREF => sub { # literal SQL without bind
280 SCALAR_or_UNDEF => sub {
282 push @all_bind, $self->_bindtype($column, $v);
289 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
290 return ($sql, @all_bind);
295 #======================================================================
297 #======================================================================
302 my $table = $self->_table(shift);
303 my $data = shift || return;
306 # first build the 'SET' part of the sql statement
307 my (@set, @all_bind);
308 puke "Unsupported data type specified to \$sql->update"
309 unless ref $data eq 'HASH';
311 for my $k (sort keys %$data) {
314 my $label = $self->_quote($k);
316 $self->_SWITCH_refkind($v, {
318 if ($self->{array_datatypes}) { # array datatype
319 push @set, "$label = ?";
320 push @all_bind, $self->_bindtype($k, $v);
322 else { # literal SQL with bind
323 my ($sql, @bind) = @$v;
324 $self->_assert_bindval_matches_bindtype(@bind);
325 push @set, "$label = $sql";
326 push @all_bind, @bind;
329 ARRAYREFREF => sub { # literal SQL with bind
330 my ($sql, @bind) = @${$v};
331 $self->_assert_bindval_matches_bindtype(@bind);
332 push @set, "$label = $sql";
333 push @all_bind, @bind;
335 SCALARREF => sub { # literal SQL without bind
336 push @set, "$label = $$v";
339 my ($op, $arg, @rest) = %$v;
341 puke 'Operator calls in update must be in the form { -op => $arg }'
342 if (@rest or not $op =~ /^\-(.+)/);
344 local $self->{_nested_func_lhs} = $k;
345 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
347 push @set, "$label = $sql";
348 push @all_bind, @bind;
350 SCALAR_or_UNDEF => sub {
351 push @set, "$label = ?";
352 push @all_bind, $self->_bindtype($k, $v);
358 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
362 my($where_sql, @where_bind) = $self->where($where);
364 push @all_bind, @where_bind;
367 return wantarray ? ($sql, @all_bind) : $sql;
373 #======================================================================
375 #======================================================================
380 my $table = $self->_table(shift);
381 my $fields = shift || '*';
385 my($where_sql, @bind) = $self->where($where, $order);
387 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
389 my $sql = join(' ', $self->_sqlcase('select'), $f,
390 $self->_sqlcase('from'), $table)
393 return wantarray ? ($sql, @bind) : $sql;
396 #======================================================================
398 #======================================================================
403 my $table = $self->_table(shift);
407 my($where_sql, @bind) = $self->where($where);
408 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
410 return wantarray ? ($sql, @bind) : $sql;
414 #======================================================================
416 #======================================================================
420 # Finally, a separate routine just to handle WHERE clauses
422 my ($self, $where, $order) = @_;
425 my ($sql, @bind) = $self->_recurse_where($where);
426 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
430 $sql .= $self->_order_by($order);
433 return wantarray ? ($sql, @bind) : $sql;
438 my ($self, $where, $logic) = @_;
440 # dispatch on appropriate method according to refkind of $where
441 my $method = $self->_METHOD_FOR_refkind("_where", $where);
443 my ($sql, @bind) = $self->$method($where, $logic);
445 # DBIx::Class directly calls _recurse_where in scalar context, so
446 # we must implement it, even if not in the official API
447 return wantarray ? ($sql, @bind) : $sql;
452 #======================================================================
453 # WHERE: top-level ARRAYREF
454 #======================================================================
457 sub _where_ARRAYREF {
458 my ($self, $where, $logic) = @_;
460 $logic = uc($logic || $self->{logic});
461 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
463 my @clauses = @$where;
465 my (@sql_clauses, @all_bind);
466 # need to use while() so can shift() for pairs
467 while (my $el = shift @clauses) {
469 # switch according to kind of $el and get corresponding ($sql, @bind)
470 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
472 # skip empty elements, otherwise get invalid trailing AND stuff
473 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
477 $self->_assert_bindval_matches_bindtype(@b);
481 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
482 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
483 # side-effect: the first hashref within an array would change
484 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
485 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
486 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
488 SCALARREF => sub { ($$el); },
490 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
491 $self->_recurse_where({$el => shift(@clauses)})},
493 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
497 push @sql_clauses, $sql;
498 push @all_bind, @bind;
502 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
505 #======================================================================
506 # WHERE: top-level ARRAYREFREF
507 #======================================================================
509 sub _where_ARRAYREFREF {
510 my ($self, $where) = @_;
511 my ($sql, @bind) = @$$where;
512 $self->_assert_bindval_matches_bindtype(@bind);
513 return ($sql, @bind);
516 #======================================================================
517 # WHERE: top-level HASHREF
518 #======================================================================
521 my ($self, $where) = @_;
522 my (@sql_clauses, @all_bind);
524 for my $k (sort keys %$where) {
525 my $v = $where->{$k};
527 # ($k => $v) is either a special unary op or a regular hashpair
528 my ($sql, @bind) = do {
530 # put the operator in canonical form
532 $op = substr $op, 1; # remove initial dash
533 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
534 $op =~ s/\s+/ /g; # compress whitespace
536 # so that -not_foo works correctly
537 $op =~ s/^not_/NOT /i;
539 $self->_debug("Unary OP(-$op) within hashref, recursing...");
540 my ($s, @b) = $self->_where_unary_op ($op, $v);
542 # top level vs nested
543 # we assume that handled unary ops will take care of their ()s
545 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
547 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
552 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
553 $self->$method($k, $v);
557 push @sql_clauses, $sql;
558 push @all_bind, @bind;
561 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
564 sub _where_unary_op {
565 my ($self, $op, $rhs) = @_;
567 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
568 my $handler = $op_entry->{handler};
570 if (not ref $handler) {
571 if ($op =~ s/ [_\s]? \d+ $//x ) {
572 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
573 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
575 return $self->$handler ($op, $rhs);
577 elsif (ref $handler eq 'CODE') {
578 return $handler->($self, $op, $rhs);
581 puke "Illegal handler for operator $op - expecting a method name or a coderef";
585 $self->_debug("Generic unary OP: $op - recursing as function");
587 $self->_assert_pass_injection_guard($op);
589 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
591 puke "Illegal use of top-level '$op'"
592 unless $self->{_nested_func_lhs};
595 $self->_convert('?'),
596 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
600 $self->_recurse_where ($rhs)
604 $sql = sprintf ('%s %s',
605 $self->_sqlcase($op),
609 return ($sql, @bind);
612 sub _where_op_ANDOR {
613 my ($self, $op, $v) = @_;
615 $self->_SWITCH_refkind($v, {
617 return $self->_where_ARRAYREF($v, $op);
621 return ( $op =~ /^or/i )
622 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
623 : $self->_where_HASHREF($v);
627 puke "-$op => \\\$scalar makes little sense, use " .
629 ? '[ \$scalar, \%rest_of_conditions ] instead'
630 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
635 puke "-$op => \\[...] makes little sense, use " .
637 ? '[ \[...], \%rest_of_conditions ] instead'
638 : '-and => [ \[...], \%rest_of_conditions ] instead'
642 SCALAR => sub { # permissively interpreted as SQL
643 puke "-$op => \$value makes little sense, use -bool => \$value instead";
647 puke "-$op => undef not supported";
653 my ($self, $op, $v) = @_;
655 $self->_SWITCH_refkind($v, {
657 SCALAR => sub { # permissively interpreted as SQL
658 belch "literal SQL should be -nest => \\'scalar' "
659 . "instead of -nest => 'scalar' ";
664 puke "-$op => undef not supported";
668 $self->_recurse_where ($v);
676 my ($self, $op, $v) = @_;
678 my ($s, @b) = $self->_SWITCH_refkind($v, {
679 SCALAR => sub { # interpreted as SQL column
680 $self->_convert($self->_quote($v));
684 puke "-$op => undef not supported";
688 $self->_recurse_where ($v);
692 $s = "(NOT $s)" if $op =~ /^not/i;
697 sub _where_op_IDENT {
699 my ($op, $rhs) = splice @_, -2;
701 puke "-$op takes a single scalar argument (a quotable identifier)";
704 # in case we are called as a top level special op (no '=')
707 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
715 sub _where_op_VALUE {
717 my ($op, $rhs) = splice @_, -2;
719 # in case we are called as a top level special op (no '=')
724 ($lhs || $self->{_nested_func_lhs}),
731 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
735 $self->_convert('?'),
741 sub _where_hashpair_ARRAYREF {
742 my ($self, $k, $v) = @_;
745 my @v = @$v; # need copy because of shift below
746 $self->_debug("ARRAY($k) means distribute over elements");
748 # put apart first element if it is an operator (-and, -or)
750 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
754 my @distributed = map { {$k => $_} } @v;
757 $self->_debug("OP($op) reinjected into the distributed array");
758 unshift @distributed, $op;
761 my $logic = $op ? substr($op, 1) : '';
763 return $self->_recurse_where(\@distributed, $logic);
766 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
767 $self->_debug("empty ARRAY($k) means 0=1");
768 return ($self->{sqlfalse});
772 sub _where_hashpair_HASHREF {
773 my ($self, $k, $v, $logic) = @_;
776 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
778 my ($all_sql, @all_bind);
780 for my $orig_op (sort keys %$v) {
781 my $val = $v->{$orig_op};
783 # put the operator in canonical form
786 # FIXME - we need to phase out dash-less ops
787 $op =~ s/^-//; # remove possible initial dash
788 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
789 $op =~ s/\s+/ /g; # compress whitespace
791 $self->_assert_pass_injection_guard($op);
793 # so that -not_foo works correctly
794 $op =~ s/^not_/NOT /i;
798 # CASE: col-value logic modifiers
799 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
800 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
802 # CASE: special operators like -in or -between
803 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
804 my $handler = $special_op->{handler};
806 puke "No handler supplied for special operator $orig_op";
808 elsif (not ref $handler) {
809 ($sql, @bind) = $self->$handler ($k, $op, $val);
811 elsif (ref $handler eq 'CODE') {
812 ($sql, @bind) = $handler->($self, $k, $op, $val);
815 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
819 $self->_SWITCH_refkind($val, {
821 ARRAYREF => sub { # CASE: col => {op => \@vals}
822 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
825 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
826 my ($sub_sql, @sub_bind) = @$$val;
827 $self->_assert_bindval_matches_bindtype(@sub_bind);
828 $sql = join ' ', $self->_convert($self->_quote($k)),
829 $self->_sqlcase($op),
834 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
835 my $is = ($op =~ $self->{equality_op}) ? 'is' :
836 ($op =~ $self->{inequality_op}) ? 'is not' :
837 puke "unexpected operator '$orig_op' with undef operand";
838 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
841 FALLBACK => sub { # CASE: col => {op/func => $stuff}
843 # retain for proper column type bind
844 $self->{_nested_func_lhs} ||= $k;
846 ($sql, @bind) = $self->_where_unary_op ($op, $val);
849 $self->_convert($self->_quote($k)),
850 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
856 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
857 push @all_bind, @bind;
859 return ($all_sql, @all_bind);
864 sub _where_field_op_ARRAYREF {
865 my ($self, $k, $op, $vals) = @_;
867 my @vals = @$vals; #always work on a copy
870 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
872 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
875 # see if the first element is an -and/-or op
877 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
882 # distribute $op over each remaining member of @vals, append logic if exists
883 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
885 # LDNOTE : had planned to change the distribution logic when
886 # $op =~ $self->{inequality_op}, because of Morgan laws :
887 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
888 # WHERE field != 22 OR field != 33 : the user probably means
889 # WHERE field != 22 AND field != 33.
890 # To do this, replace the above to roughly :
891 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
892 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
896 # try to DWIM on equality operators
897 # LDNOTE : not 100% sure this is the correct thing to do ...
898 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
899 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
902 puke "operator '$op' applied on an empty array (field '$k')";
907 sub _where_hashpair_SCALARREF {
908 my ($self, $k, $v) = @_;
909 $self->_debug("SCALAR($k) means literal SQL: $$v");
910 my $sql = $self->_quote($k) . " " . $$v;
914 # literal SQL with bind
915 sub _where_hashpair_ARRAYREFREF {
916 my ($self, $k, $v) = @_;
917 $self->_debug("REF($k) means literal SQL: @${$v}");
918 my ($sql, @bind) = @$$v;
919 $self->_assert_bindval_matches_bindtype(@bind);
920 $sql = $self->_quote($k) . " " . $sql;
921 return ($sql, @bind );
924 # literal SQL without bind
925 sub _where_hashpair_SCALAR {
926 my ($self, $k, $v) = @_;
927 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
928 my $sql = join ' ', $self->_convert($self->_quote($k)),
929 $self->_sqlcase($self->{cmp}),
930 $self->_convert('?');
931 my @bind = $self->_bindtype($k, $v);
932 return ( $sql, @bind);
936 sub _where_hashpair_UNDEF {
937 my ($self, $k, $v) = @_;
938 $self->_debug("UNDEF($k) means IS NULL");
939 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
943 #======================================================================
944 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
945 #======================================================================
948 sub _where_SCALARREF {
949 my ($self, $where) = @_;
952 $self->_debug("SCALAR(*top) means literal SQL: $$where");
958 my ($self, $where) = @_;
961 $self->_debug("NOREF(*top) means literal SQL: $where");
972 #======================================================================
973 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
974 #======================================================================
977 sub _where_field_BETWEEN {
978 my ($self, $k, $op, $vals) = @_;
980 my ($label, $and, $placeholder);
981 $label = $self->_convert($self->_quote($k));
982 $and = ' ' . $self->_sqlcase('and') . ' ';
983 $placeholder = $self->_convert('?');
984 $op = $self->_sqlcase($op);
986 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
988 my ($s, @b) = @$$vals;
989 $self->_assert_bindval_matches_bindtype(@b);
996 puke "special op 'between' accepts an arrayref with exactly two values"
999 my (@all_sql, @all_bind);
1000 foreach my $val (@$vals) {
1001 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1003 return ($placeholder, $self->_bindtype($k, $val) );
1008 ARRAYREFREF => sub {
1009 my ($sql, @bind) = @$$val;
1010 $self->_assert_bindval_matches_bindtype(@bind);
1011 return ($sql, @bind);
1014 my ($func, $arg, @rest) = %$val;
1015 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
1016 if (@rest or $func !~ /^ \- (.+)/x);
1017 local $self->{_nested_func_lhs} = $k;
1018 $self->_where_unary_op ($1 => $arg);
1021 push @all_sql, $sql;
1022 push @all_bind, @bind;
1026 (join $and, @all_sql),
1031 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
1035 my $sql = "( $label $op $clause )";
1036 return ($sql, @bind)
1040 sub _where_field_IN {
1041 my ($self, $k, $op, $vals) = @_;
1043 # backwards compatibility : if scalar, force into an arrayref
1044 $vals = [$vals] if defined $vals && ! ref $vals;
1046 my ($label) = $self->_convert($self->_quote($k));
1047 my ($placeholder) = $self->_convert('?');
1048 $op = $self->_sqlcase($op);
1050 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1051 ARRAYREF => sub { # list of choices
1052 if (@$vals) { # nonempty list
1053 my (@all_sql, @all_bind);
1055 for my $val (@$vals) {
1056 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1058 return ($placeholder, $val);
1063 ARRAYREFREF => sub {
1064 my ($sql, @bind) = @$$val;
1065 $self->_assert_bindval_matches_bindtype(@bind);
1066 return ($sql, @bind);
1069 my ($func, $arg, @rest) = %$val;
1070 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1071 if (@rest or $func !~ /^ \- (.+)/x);
1072 local $self->{_nested_func_lhs} = $k;
1073 $self->_where_unary_op ($1 => $arg);
1076 return $self->_sqlcase('null');
1079 push @all_sql, $sql;
1080 push @all_bind, @bind;
1084 sprintf ('%s %s ( %s )',
1087 join (', ', @all_sql)
1089 $self->_bindtype($k, @all_bind),
1092 else { # empty list : some databases won't understand "IN ()", so DWIM
1093 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1098 SCALARREF => sub { # literal SQL
1099 my $sql = $self->_open_outer_paren ($$vals);
1100 return ("$label $op ( $sql )");
1102 ARRAYREFREF => sub { # literal SQL with bind
1103 my ($sql, @bind) = @$$vals;
1104 $self->_assert_bindval_matches_bindtype(@bind);
1105 $sql = $self->_open_outer_paren ($sql);
1106 return ("$label $op ( $sql )", @bind);
1110 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1114 return ($sql, @bind);
1117 # Some databases (SQLite) treat col IN (1, 2) different from
1118 # col IN ( (1, 2) ). Use this to strip all outer parens while
1119 # adding them back in the corresponding method
1120 sub _open_outer_paren {
1121 my ($self, $sql) = @_;
1122 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1127 #======================================================================
1129 #======================================================================
1132 my ($self, $arg) = @_;
1135 for my $c ($self->_order_by_chunks ($arg) ) {
1136 $self->_SWITCH_refkind ($c, {
1137 SCALAR => sub { push @sql, $c },
1138 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1144 $self->_sqlcase(' order by'),
1150 return wantarray ? ($sql, @bind) : $sql;
1153 sub _order_by_chunks {
1154 my ($self, $arg) = @_;
1156 return $self->_SWITCH_refkind($arg, {
1159 map { $self->_order_by_chunks ($_ ) } @$arg;
1162 ARRAYREFREF => sub {
1163 my ($s, @b) = @$$arg;
1164 $self->_assert_bindval_matches_bindtype(@b);
1168 SCALAR => sub {$self->_quote($arg)},
1170 UNDEF => sub {return () },
1172 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1175 # get first pair in hash
1176 my ($key, $val, @rest) = %$arg;
1178 return () unless $key;
1180 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1181 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1187 for my $c ($self->_order_by_chunks ($val)) {
1190 $self->_SWITCH_refkind ($c, {
1195 ($sql, @bind) = @$c;
1199 $sql = $sql . ' ' . $self->_sqlcase($direction);
1201 push @ret, [ $sql, @bind];
1210 #======================================================================
1211 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1212 #======================================================================
1217 $self->_SWITCH_refkind($from, {
1219 die "Empty FROM list" unless my @f = @$from;
1221 type => DQ_IDENTIFIER,
1222 elements => [ split /\Q$self->{name_sep}/, shift @f ],
1224 while (my $x = shift @f) {
1228 type => DQ_IDENTIFIER,
1229 elements => [ split /\Q$self->{name_sep}/, $x ],
1233 $self->_render_dq($dq);
1237 type => DQ_IDENTIFIER,
1238 elements => [ split /\Q$self->{name_sep}/, $from ],
1252 #======================================================================
1254 #======================================================================
1256 # highly optimized, as it's called way too often
1258 # my ($self, $label) = @_;
1260 return '' unless defined $_[1];
1261 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1263 unless ($_[0]->{quote_char}) {
1264 $_[0]->_assert_pass_injection_guard($_[1]);
1268 my $qref = ref $_[0]->{quote_char};
1271 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1273 elsif ($qref eq 'ARRAY') {
1274 ($l, $r) = @{$_[0]->{quote_char}};
1277 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1280 # parts containing * are naturally unquoted
1281 return join( $_[0]->{name_sep}||'', map
1282 { $_ eq '*' ? $_ : $l . $_ . $r }
1283 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1288 # Conversion, if applicable
1290 #my ($self, $arg) = @_;
1292 # LDNOTE : modified the previous implementation below because
1293 # it was not consistent : the first "return" is always an array,
1294 # the second "return" is context-dependent. Anyway, _convert
1295 # seems always used with just a single argument, so make it a
1297 # return @_ unless $self->{convert};
1298 # my $conv = $self->_sqlcase($self->{convert});
1299 # my @ret = map { $conv.'('.$_.')' } @_;
1300 # return wantarray ? @ret : $ret[0];
1301 if ($_[0]->{convert}) {
1302 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1309 #my ($self, $col, @vals) = @_;
1311 #LDNOTE : changed original implementation below because it did not make
1312 # sense when bindtype eq 'columns' and @vals > 1.
1313 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1315 # called often - tighten code
1316 return $_[0]->{bindtype} eq 'columns'
1317 ? map {[$_[1], $_]} @_[2 .. $#_]
1322 # Dies if any element of @bind is not in [colname => value] format
1323 # if bindtype is 'columns'.
1324 sub _assert_bindval_matches_bindtype {
1325 # my ($self, @bind) = @_;
1327 if ($self->{bindtype} eq 'columns') {
1329 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1330 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1336 sub _join_sql_clauses {
1337 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1339 if (@$clauses_aref > 1) {
1340 my $join = " " . $self->_sqlcase($logic) . " ";
1341 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1342 return ($sql, @$bind_aref);
1344 elsif (@$clauses_aref) {
1345 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1348 return (); # if no SQL, ignore @$bind_aref
1353 # Fix SQL case, if so requested
1355 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1356 # don't touch the argument ... crooked logic, but let's not change it!
1357 return $_[0]->{case} ? $_[1] : uc($_[1]);
1361 #======================================================================
1362 # DISPATCHING FROM REFKIND
1363 #======================================================================
1366 my ($self, $data) = @_;
1368 return 'UNDEF' unless defined $data;
1370 # blessed objects are treated like scalars
1371 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1373 return 'SCALAR' unless $ref;
1376 while ($ref eq 'REF') {
1378 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1382 return ($ref||'SCALAR') . ('REF' x $n_steps);
1386 my ($self, $data) = @_;
1387 my @try = ($self->_refkind($data));
1388 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1389 push @try, 'FALLBACK';
1393 sub _METHOD_FOR_refkind {
1394 my ($self, $meth_prefix, $data) = @_;
1397 for (@{$self->_try_refkind($data)}) {
1398 $method = $self->can($meth_prefix."_".$_)
1402 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1406 sub _SWITCH_refkind {
1407 my ($self, $data, $dispatch_table) = @_;
1410 for (@{$self->_try_refkind($data)}) {
1411 $coderef = $dispatch_table->{$_}
1415 puke "no dispatch entry for ".$self->_refkind($data)
1424 #======================================================================
1425 # VALUES, GENERATE, AUTOLOAD
1426 #======================================================================
1428 # LDNOTE: original code from nwiger, didn't touch code in that section
1429 # I feel the AUTOLOAD stuff should not be the default, it should
1430 # only be activated on explicit demand by user.
1434 my $data = shift || return;
1435 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1436 unless ref $data eq 'HASH';
1439 foreach my $k ( sort keys %$data ) {
1440 my $v = $data->{$k};
1441 $self->_SWITCH_refkind($v, {
1443 if ($self->{array_datatypes}) { # array datatype
1444 push @all_bind, $self->_bindtype($k, $v);
1446 else { # literal SQL with bind
1447 my ($sql, @bind) = @$v;
1448 $self->_assert_bindval_matches_bindtype(@bind);
1449 push @all_bind, @bind;
1452 ARRAYREFREF => sub { # literal SQL with bind
1453 my ($sql, @bind) = @${$v};
1454 $self->_assert_bindval_matches_bindtype(@bind);
1455 push @all_bind, @bind;
1457 SCALARREF => sub { # literal SQL without bind
1459 SCALAR_or_UNDEF => sub {
1460 push @all_bind, $self->_bindtype($k, $v);
1471 my(@sql, @sqlq, @sqlv);
1475 if ($ref eq 'HASH') {
1476 for my $k (sort keys %$_) {
1479 my $label = $self->_quote($k);
1480 if ($r eq 'ARRAY') {
1481 # literal SQL with bind
1482 my ($sql, @bind) = @$v;
1483 $self->_assert_bindval_matches_bindtype(@bind);
1484 push @sqlq, "$label = $sql";
1486 } elsif ($r eq 'SCALAR') {
1487 # literal SQL without bind
1488 push @sqlq, "$label = $$v";
1490 push @sqlq, "$label = ?";
1491 push @sqlv, $self->_bindtype($k, $v);
1494 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1495 } elsif ($ref eq 'ARRAY') {
1496 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1499 if ($r eq 'ARRAY') { # literal SQL with bind
1500 my ($sql, @bind) = @$v;
1501 $self->_assert_bindval_matches_bindtype(@bind);
1504 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1505 # embedded literal SQL
1512 push @sql, '(' . join(', ', @sqlq) . ')';
1513 } elsif ($ref eq 'SCALAR') {
1517 # strings get case twiddled
1518 push @sql, $self->_sqlcase($_);
1522 my $sql = join ' ', @sql;
1524 # this is pretty tricky
1525 # if ask for an array, return ($stmt, @bind)
1526 # otherwise, s/?/shift @sqlv/ to put it inline
1528 return ($sql, @sqlv);
1530 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1531 ref $d ? $d->[1] : $d/e;
1540 # This allows us to check for a local, then _form, attr
1542 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1543 return $self->generate($name, @_);
1554 SQL::Abstract - Generate SQL from Perl data structures
1560 my $sql = SQL::Abstract->new;
1562 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1564 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1566 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1568 my($stmt, @bind) = $sql->delete($table, \%where);
1570 # Then, use these in your DBI statements
1571 my $sth = $dbh->prepare($stmt);
1572 $sth->execute(@bind);
1574 # Just generate the WHERE clause
1575 my($stmt, @bind) = $sql->where(\%where, \@order);
1577 # Return values in the same order, for hashed queries
1578 # See PERFORMANCE section for more details
1579 my @bind = $sql->values(\%fieldvals);
1583 This module was inspired by the excellent L<DBIx::Abstract>.
1584 However, in using that module I found that what I really wanted
1585 to do was generate SQL, but still retain complete control over my
1586 statement handles and use the DBI interface. So, I set out to
1587 create an abstract SQL generation module.
1589 While based on the concepts used by L<DBIx::Abstract>, there are
1590 several important differences, especially when it comes to WHERE
1591 clauses. I have modified the concepts used to make the SQL easier
1592 to generate from Perl data structures and, IMO, more intuitive.
1593 The underlying idea is for this module to do what you mean, based
1594 on the data structures you provide it. The big advantage is that
1595 you don't have to modify your code every time your data changes,
1596 as this module figures it out.
1598 To begin with, an SQL INSERT is as easy as just specifying a hash
1599 of C<key=value> pairs:
1602 name => 'Jimbo Bobson',
1603 phone => '123-456-7890',
1604 address => '42 Sister Lane',
1605 city => 'St. Louis',
1606 state => 'Louisiana',
1609 The SQL can then be generated with this:
1611 my($stmt, @bind) = $sql->insert('people', \%data);
1613 Which would give you something like this:
1615 $stmt = "INSERT INTO people
1616 (address, city, name, phone, state)
1617 VALUES (?, ?, ?, ?, ?)";
1618 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1619 '123-456-7890', 'Louisiana');
1621 These are then used directly in your DBI code:
1623 my $sth = $dbh->prepare($stmt);
1624 $sth->execute(@bind);
1626 =head2 Inserting and Updating Arrays
1628 If your database has array types (like for example Postgres),
1629 activate the special option C<< array_datatypes => 1 >>
1630 when creating the C<SQL::Abstract> object.
1631 Then you may use an arrayref to insert and update database array types:
1633 my $sql = SQL::Abstract->new(array_datatypes => 1);
1635 planets => [qw/Mercury Venus Earth Mars/]
1638 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1642 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1644 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1647 =head2 Inserting and Updating SQL
1649 In order to apply SQL functions to elements of your C<%data> you may
1650 specify a reference to an arrayref for the given hash value. For example,
1651 if you need to execute the Oracle C<to_date> function on a value, you can
1652 say something like this:
1656 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1659 The first value in the array is the actual SQL. Any other values are
1660 optional and would be included in the bind values array. This gives
1663 my($stmt, @bind) = $sql->insert('people', \%data);
1665 $stmt = "INSERT INTO people (name, date_entered)
1666 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1667 @bind = ('Bill', '03/02/2003');
1669 An UPDATE is just as easy, all you change is the name of the function:
1671 my($stmt, @bind) = $sql->update('people', \%data);
1673 Notice that your C<%data> isn't touched; the module will generate
1674 the appropriately quirky SQL for you automatically. Usually you'll
1675 want to specify a WHERE clause for your UPDATE, though, which is
1676 where handling C<%where> hashes comes in handy...
1678 =head2 Complex where statements
1680 This module can generate pretty complicated WHERE statements
1681 easily. For example, simple C<key=value> pairs are taken to mean
1682 equality, and if you want to see if a field is within a set
1683 of values, you can use an arrayref. Let's say we wanted to
1684 SELECT some data based on this criteria:
1687 requestor => 'inna',
1688 worker => ['nwiger', 'rcwe', 'sfz'],
1689 status => { '!=', 'completed' }
1692 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1694 The above would give you something like this:
1696 $stmt = "SELECT * FROM tickets WHERE
1697 ( requestor = ? ) AND ( status != ? )
1698 AND ( worker = ? OR worker = ? OR worker = ? )";
1699 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1701 Which you could then use in DBI code like so:
1703 my $sth = $dbh->prepare($stmt);
1704 $sth->execute(@bind);
1710 The functions are simple. There's one for each major SQL operation,
1711 and a constructor you use first. The arguments are specified in a
1712 similar order to each function (table, then fields, then a where
1713 clause) to try and simplify things.
1718 =head2 new(option => 'value')
1720 The C<new()> function takes a list of options and values, and returns
1721 a new B<SQL::Abstract> object which can then be used to generate SQL
1722 through the methods below. The options accepted are:
1728 If set to 'lower', then SQL will be generated in all lowercase. By
1729 default SQL is generated in "textbook" case meaning something like:
1731 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1733 Any setting other than 'lower' is ignored.
1737 This determines what the default comparison operator is. By default
1738 it is C<=>, meaning that a hash like this:
1740 %where = (name => 'nwiger', email => 'nate@wiger.org');
1742 Will generate SQL like this:
1744 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1746 However, you may want loose comparisons by default, so if you set
1747 C<cmp> to C<like> you would get SQL such as:
1749 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1751 You can also override the comparsion on an individual basis - see
1752 the huge section on L</"WHERE CLAUSES"> at the bottom.
1754 =item sqltrue, sqlfalse
1756 Expressions for inserting boolean values within SQL statements.
1757 By default these are C<1=1> and C<1=0>. They are used
1758 by the special operators C<-in> and C<-not_in> for generating
1759 correct SQL even when the argument is an empty array (see below).
1763 This determines the default logical operator for multiple WHERE
1764 statements in arrays or hashes. If absent, the default logic is "or"
1765 for arrays, and "and" for hashes. This means that a WHERE
1769 event_date => {'>=', '2/13/99'},
1770 event_date => {'<=', '4/24/03'},
1773 will generate SQL like this:
1775 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1777 This is probably not what you want given this query, though (look
1778 at the dates). To change the "OR" to an "AND", simply specify:
1780 my $sql = SQL::Abstract->new(logic => 'and');
1782 Which will change the above C<WHERE> to:
1784 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1786 The logic can also be changed locally by inserting
1787 a modifier in front of an arrayref :
1789 @where = (-and => [event_date => {'>=', '2/13/99'},
1790 event_date => {'<=', '4/24/03'} ]);
1792 See the L</"WHERE CLAUSES"> section for explanations.
1796 This will automatically convert comparisons using the specified SQL
1797 function for both column and value. This is mostly used with an argument
1798 of C<upper> or C<lower>, so that the SQL will have the effect of
1799 case-insensitive "searches". For example, this:
1801 $sql = SQL::Abstract->new(convert => 'upper');
1802 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1804 Will turn out the following SQL:
1806 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1808 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1809 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1810 not validate this option; it will just pass through what you specify verbatim).
1814 This is a kludge because many databases suck. For example, you can't
1815 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1816 Instead, you have to use C<bind_param()>:
1818 $sth->bind_param(1, 'reg data');
1819 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1821 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1822 which loses track of which field each slot refers to. Fear not.
1824 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1825 Currently, you can specify either C<normal> (default) or C<columns>. If you
1826 specify C<columns>, you will get an array that looks like this:
1828 my $sql = SQL::Abstract->new(bindtype => 'columns');
1829 my($stmt, @bind) = $sql->insert(...);
1832 [ 'column1', 'value1' ],
1833 [ 'column2', 'value2' ],
1834 [ 'column3', 'value3' ],
1837 You can then iterate through this manually, using DBI's C<bind_param()>.
1839 $sth->prepare($stmt);
1842 my($col, $data) = @$_;
1843 if ($col eq 'details' || $col eq 'comments') {
1844 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1845 } elsif ($col eq 'image') {
1846 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1848 $sth->bind_param($i, $data);
1852 $sth->execute; # execute without @bind now
1854 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1855 Basically, the advantage is still that you don't have to care which fields
1856 are or are not included. You could wrap that above C<for> loop in a simple
1857 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1858 get a layer of abstraction over manual SQL specification.
1860 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1861 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1862 will expect the bind values in this format.
1866 This is the character that a table or column name will be quoted
1867 with. By default this is an empty string, but you could set it to
1868 the character C<`>, to generate SQL like this:
1870 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1872 Alternatively, you can supply an array ref of two items, the first being the left
1873 hand quote character, and the second the right hand quote character. For
1874 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1875 that generates SQL like this:
1877 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1879 Quoting is useful if you have tables or columns names that are reserved
1880 words in your database's SQL dialect.
1884 This is the character that separates a table and column name. It is
1885 necessary to specify this when the C<quote_char> option is selected,
1886 so that tables and column names can be individually quoted like this:
1888 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1890 =item injection_guard
1892 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1893 column name specified in a query structure. This is a safety mechanism to avoid
1894 injection attacks when mishandling user input e.g.:
1896 my %condition_as_column_value_pairs = get_values_from_user();
1897 $sqla->select( ... , \%condition_as_column_value_pairs );
1899 If the expression matches an exception is thrown. Note that literal SQL
1900 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1902 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1904 =item array_datatypes
1906 When this option is true, arrayrefs in INSERT or UPDATE are
1907 interpreted as array datatypes and are passed directly
1909 When this option is false, arrayrefs are interpreted
1910 as literal SQL, just like refs to arrayrefs
1911 (but this behavior is for backwards compatibility; when writing
1912 new queries, use the "reference to arrayref" syntax
1918 Takes a reference to a list of "special operators"
1919 to extend the syntax understood by L<SQL::Abstract>.
1920 See section L</"SPECIAL OPERATORS"> for details.
1924 Takes a reference to a list of "unary operators"
1925 to extend the syntax understood by L<SQL::Abstract>.
1926 See section L</"UNARY OPERATORS"> for details.
1932 =head2 insert($table, \@values || \%fieldvals, \%options)
1934 This is the simplest function. You simply give it a table name
1935 and either an arrayref of values or hashref of field/value pairs.
1936 It returns an SQL INSERT statement and a list of bind values.
1937 See the sections on L</"Inserting and Updating Arrays"> and
1938 L</"Inserting and Updating SQL"> for information on how to insert
1939 with those data types.
1941 The optional C<\%options> hash reference may contain additional
1942 options to generate the insert SQL. Currently supported options
1949 Takes either a scalar of raw SQL fields, or an array reference of
1950 field names, and adds on an SQL C<RETURNING> statement at the end.
1951 This allows you to return data generated by the insert statement
1952 (such as row IDs) without performing another C<SELECT> statement.
1953 Note, however, this is not part of the SQL standard and may not
1954 be supported by all database engines.
1958 =head2 update($table, \%fieldvals, \%where)
1960 This takes a table, hashref of field/value pairs, and an optional
1961 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1963 See the sections on L</"Inserting and Updating Arrays"> and
1964 L</"Inserting and Updating SQL"> for information on how to insert
1965 with those data types.
1967 =head2 select($source, $fields, $where, $order)
1969 This returns a SQL SELECT statement and associated list of bind values, as
1970 specified by the arguments :
1976 Specification of the 'FROM' part of the statement.
1977 The argument can be either a plain scalar (interpreted as a table
1978 name, will be quoted), or an arrayref (interpreted as a list
1979 of table names, joined by commas, quoted), or a scalarref
1980 (literal table name, not quoted), or a ref to an arrayref
1981 (list of literal table names, joined by commas, not quoted).
1985 Specification of the list of fields to retrieve from
1987 The argument can be either an arrayref (interpreted as a list
1988 of field names, will be joined by commas and quoted), or a
1989 plain scalar (literal SQL, not quoted).
1990 Please observe that this API is not as flexible as for
1991 the first argument C<$table>, for backwards compatibility reasons.
1995 Optional argument to specify the WHERE part of the query.
1996 The argument is most often a hashref, but can also be
1997 an arrayref or plain scalar --
1998 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2002 Optional argument to specify the ORDER BY part of the query.
2003 The argument can be a scalar, a hashref or an arrayref
2004 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2010 =head2 delete($table, \%where)
2012 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2013 It returns an SQL DELETE statement and list of bind values.
2015 =head2 where(\%where, \@order)
2017 This is used to generate just the WHERE clause. For example,
2018 if you have an arbitrary data structure and know what the
2019 rest of your SQL is going to look like, but want an easy way
2020 to produce a WHERE clause, use this. It returns an SQL WHERE
2021 clause and list of bind values.
2024 =head2 values(\%data)
2026 This just returns the values from the hash C<%data>, in the same
2027 order that would be returned from any of the other above queries.
2028 Using this allows you to markedly speed up your queries if you
2029 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2031 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2033 Warning: This is an experimental method and subject to change.
2035 This returns arbitrarily generated SQL. It's a really basic shortcut.
2036 It will return two different things, depending on return context:
2038 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2039 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2041 These would return the following:
2043 # First calling form
2044 $stmt = "CREATE TABLE test (?, ?)";
2045 @bind = (field1, field2);
2047 # Second calling form
2048 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2050 Depending on what you're trying to do, it's up to you to choose the correct
2051 format. In this example, the second form is what you would want.
2055 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2059 ALTER SESSION SET nls_date_format = 'MM/YY'
2061 You get the idea. Strings get their case twiddled, but everything
2062 else remains verbatim.
2064 =head1 WHERE CLAUSES
2068 This module uses a variation on the idea from L<DBIx::Abstract>. It
2069 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2070 module is that things in arrays are OR'ed, and things in hashes
2073 The easiest way to explain is to show lots of examples. After
2074 each C<%where> hash shown, it is assumed you used:
2076 my($stmt, @bind) = $sql->where(\%where);
2078 However, note that the C<%where> hash can be used directly in any
2079 of the other functions as well, as described above.
2081 =head2 Key-value pairs
2083 So, let's get started. To begin, a simple hash:
2087 status => 'completed'
2090 Is converted to SQL C<key = val> statements:
2092 $stmt = "WHERE user = ? AND status = ?";
2093 @bind = ('nwiger', 'completed');
2095 One common thing I end up doing is having a list of values that
2096 a field can be in. To do this, simply specify a list inside of
2101 status => ['assigned', 'in-progress', 'pending'];
2104 This simple code will create the following:
2106 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2107 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2109 A field associated to an empty arrayref will be considered a
2110 logical false and will generate 0=1.
2112 =head2 Tests for NULL values
2114 If the value part is C<undef> then this is converted to SQL <IS NULL>
2123 $stmt = "WHERE user = ? AND status IS NULL";
2126 To test if a column IS NOT NULL:
2130 status => { '!=', undef },
2133 =head2 Specific comparison operators
2135 If you want to specify a different type of operator for your comparison,
2136 you can use a hashref for a given column:
2140 status => { '!=', 'completed' }
2143 Which would generate:
2145 $stmt = "WHERE user = ? AND status != ?";
2146 @bind = ('nwiger', 'completed');
2148 To test against multiple values, just enclose the values in an arrayref:
2150 status => { '=', ['assigned', 'in-progress', 'pending'] };
2152 Which would give you:
2154 "WHERE status = ? OR status = ? OR status = ?"
2157 The hashref can also contain multiple pairs, in which case it is expanded
2158 into an C<AND> of its elements:
2162 status => { '!=', 'completed', -not_like => 'pending%' }
2165 # Or more dynamically, like from a form
2166 $where{user} = 'nwiger';
2167 $where{status}{'!='} = 'completed';
2168 $where{status}{'-not_like'} = 'pending%';
2170 # Both generate this
2171 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2172 @bind = ('nwiger', 'completed', 'pending%');
2175 To get an OR instead, you can combine it with the arrayref idea:
2179 priority => [ { '=', 2 }, { '>', 5 } ]
2182 Which would generate:
2184 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2185 @bind = ('2', '5', 'nwiger');
2187 If you want to include literal SQL (with or without bind values), just use a
2188 scalar reference or array reference as the value:
2191 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2192 date_expires => { '<' => \"now()" }
2195 Which would generate:
2197 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2198 @bind = ('11/26/2008');
2201 =head2 Logic and nesting operators
2203 In the example above,
2204 there is a subtle trap if you want to say something like
2205 this (notice the C<AND>):
2207 WHERE priority != ? AND priority != ?
2209 Because, in Perl you I<can't> do this:
2211 priority => { '!=', 2, '!=', 1 }
2213 As the second C<!=> key will obliterate the first. The solution
2214 is to use the special C<-modifier> form inside an arrayref:
2216 priority => [ -and => {'!=', 2},
2220 Normally, these would be joined by C<OR>, but the modifier tells it
2221 to use C<AND> instead. (Hint: You can use this in conjunction with the
2222 C<logic> option to C<new()> in order to change the way your queries
2223 work by default.) B<Important:> Note that the C<-modifier> goes
2224 B<INSIDE> the arrayref, as an extra first element. This will
2225 B<NOT> do what you think it might:
2227 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2229 Here is a quick list of equivalencies, since there is some overlap:
2232 status => {'!=', 'completed', 'not like', 'pending%' }
2233 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2236 status => {'=', ['assigned', 'in-progress']}
2237 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2238 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2242 =head2 Special operators : IN, BETWEEN, etc.
2244 You can also use the hashref format to compare a list of fields using the
2245 C<IN> comparison operator, by specifying the list as an arrayref:
2248 status => 'completed',
2249 reportid => { -in => [567, 2335, 2] }
2252 Which would generate:
2254 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2255 @bind = ('completed', '567', '2335', '2');
2257 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2260 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2261 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2262 'sqltrue' (by default : C<1=1>).
2264 In addition to the array you can supply a chunk of literal sql or
2265 literal sql with bind:
2268 customer => { -in => \[
2269 'SELECT cust_id FROM cust WHERE balance > ?',
2272 status => { -in => \'SELECT status_codes FROM states' },
2278 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2279 AND status IN ( SELECT status_codes FROM states )
2285 Another pair of operators is C<-between> and C<-not_between>,
2286 used with an arrayref of two values:
2290 completion_date => {
2291 -not_between => ['2002-10-01', '2003-02-06']
2297 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2299 Just like with C<-in> all plausible combinations of literal SQL
2303 start0 => { -between => [ 1, 2 ] },
2304 start1 => { -between => \["? AND ?", 1, 2] },
2305 start2 => { -between => \"lower(x) AND upper(y)" },
2306 start3 => { -between => [
2308 \["upper(?)", 'stuff' ],
2315 ( start0 BETWEEN ? AND ? )
2316 AND ( start1 BETWEEN ? AND ? )
2317 AND ( start2 BETWEEN lower(x) AND upper(y) )
2318 AND ( start3 BETWEEN lower(x) AND upper(?) )
2320 @bind = (1, 2, 1, 2, 'stuff');
2323 These are the two builtin "special operators"; but the
2324 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2326 =head2 Unary operators: bool
2328 If you wish to test against boolean columns or functions within your
2329 database you can use the C<-bool> and C<-not_bool> operators. For
2330 example to test the column C<is_user> being true and the column
2331 C<is_enabled> being false you would use:-
2335 -not_bool => 'is_enabled',
2340 WHERE is_user AND NOT is_enabled
2342 If a more complex combination is required, testing more conditions,
2343 then you should use the and/or operators:-
2350 -not_bool => 'four',
2356 WHERE one AND two AND three AND NOT four
2359 =head2 Nested conditions, -and/-or prefixes
2361 So far, we've seen how multiple conditions are joined with a top-level
2362 C<AND>. We can change this by putting the different conditions we want in
2363 hashes and then putting those hashes in an array. For example:
2368 status => { -like => ['pending%', 'dispatched'] },
2372 status => 'unassigned',
2376 This data structure would create the following:
2378 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2379 OR ( user = ? AND status = ? ) )";
2380 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2383 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2384 to change the logic inside :
2390 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2391 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2398 WHERE ( user = ? AND (
2399 ( workhrs > ? AND geo = ? )
2400 OR ( workhrs < ? OR geo = ? )
2403 =head3 Algebraic inconsistency, for historical reasons
2405 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2406 operator goes C<outside> of the nested structure; whereas when connecting
2407 several constraints on one column, the C<-and> operator goes
2408 C<inside> the arrayref. Here is an example combining both features :
2411 -and => [a => 1, b => 2],
2412 -or => [c => 3, d => 4],
2413 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2418 WHERE ( ( ( a = ? AND b = ? )
2419 OR ( c = ? OR d = ? )
2420 OR ( e LIKE ? AND e LIKE ? ) ) )
2422 This difference in syntax is unfortunate but must be preserved for
2423 historical reasons. So be careful : the two examples below would
2424 seem algebraically equivalent, but they are not
2426 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2427 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2429 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2430 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2433 =head2 Literal SQL and value type operators
2435 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2436 side" is a column name and the "right side" is a value (normally rendered as
2437 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2438 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2439 alter this behavior. There are several ways of doing so.
2443 This is a virtual operator that signals the string to its right side is an
2444 identifier (a column name) and not a value. For example to compare two
2445 columns you would write:
2448 priority => { '<', 2 },
2449 requestor => { -ident => 'submitter' },
2454 $stmt = "WHERE priority < ? AND requestor = submitter";
2457 If you are maintaining legacy code you may see a different construct as
2458 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2463 This is a virtual operator that signals that the construct to its right side
2464 is a value to be passed to DBI. This is for example necessary when you want
2465 to write a where clause against an array (for RDBMS that support such
2466 datatypes). For example:
2469 array => { -value => [1, 2, 3] }
2474 $stmt = 'WHERE array = ?';
2475 @bind = ([1, 2, 3]);
2477 Note that if you were to simply say:
2483 the result would porbably be not what you wanted:
2485 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2490 Finally, sometimes only literal SQL will do. To include a random snippet
2491 of SQL verbatim, you specify it as a scalar reference. Consider this only
2492 as a last resort. Usually there is a better way. For example:
2495 priority => { '<', 2 },
2496 requestor => { -in => \'(SELECT name FROM hitmen)' },
2501 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2504 Note that in this example, you only get one bind parameter back, since
2505 the verbatim SQL is passed as part of the statement.
2509 Never use untrusted input as a literal SQL argument - this is a massive
2510 security risk (there is no way to check literal snippets for SQL
2511 injections and other nastyness). If you need to deal with untrusted input
2512 use literal SQL with placeholders as described next.
2514 =head3 Literal SQL with placeholders and bind values (subqueries)
2516 If the literal SQL to be inserted has placeholders and bind values,
2517 use a reference to an arrayref (yes this is a double reference --
2518 not so common, but perfectly legal Perl). For example, to find a date
2519 in Postgres you can use something like this:
2522 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2527 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2530 Note that you must pass the bind values in the same format as they are returned
2531 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2532 provide the bind values in the C<< [ column_meta => value ] >> format, where
2533 C<column_meta> is an opaque scalar value; most commonly the column name, but
2534 you can use any scalar value (including references and blessed references),
2535 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2536 to C<columns> the above example will look like:
2539 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2542 Literal SQL is especially useful for nesting parenthesized clauses in the
2543 main SQL query. Here is a first example :
2545 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2549 bar => \["IN ($sub_stmt)" => @sub_bind],
2554 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2555 WHERE c2 < ? AND c3 LIKE ?))";
2556 @bind = (1234, 100, "foo%");
2558 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2559 are expressed in the same way. Of course the C<$sub_stmt> and
2560 its associated bind values can be generated through a former call
2563 my ($sub_stmt, @sub_bind)
2564 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2565 c3 => {-like => "foo%"}});
2568 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2571 In the examples above, the subquery was used as an operator on a column;
2572 but the same principle also applies for a clause within the main C<%where>
2573 hash, like an EXISTS subquery :
2575 my ($sub_stmt, @sub_bind)
2576 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2577 my %where = ( -and => [
2579 \["EXISTS ($sub_stmt)" => @sub_bind],
2584 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2585 WHERE c1 = ? AND c2 > t0.c0))";
2589 Observe that the condition on C<c2> in the subquery refers to
2590 column C<t0.c0> of the main query : this is I<not> a bind
2591 value, so we have to express it through a scalar ref.
2592 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2593 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2594 what we wanted here.
2596 Finally, here is an example where a subquery is used
2597 for expressing unary negation:
2599 my ($sub_stmt, @sub_bind)
2600 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2601 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2603 lname => {like => '%son%'},
2604 \["NOT ($sub_stmt)" => @sub_bind],
2609 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2610 @bind = ('%son%', 10, 20)
2612 =head3 Deprecated usage of Literal SQL
2614 Below are some examples of archaic use of literal SQL. It is shown only as
2615 reference for those who deal with legacy code. Each example has a much
2616 better, cleaner and safer alternative that users should opt for in new code.
2622 my %where = ( requestor => \'IS NOT NULL' )
2624 $stmt = "WHERE requestor IS NOT NULL"
2626 This used to be the way of generating NULL comparisons, before the handling
2627 of C<undef> got formalized. For new code please use the superior syntax as
2628 described in L</Tests for NULL values>.
2632 my %where = ( requestor => \'= submitter' )
2634 $stmt = "WHERE requestor = submitter"
2636 This used to be the only way to compare columns. Use the superior L</-ident>
2637 method for all new code. For example an identifier declared in such a way
2638 will be properly quoted if L</quote_char> is properly set, while the legacy
2639 form will remain as supplied.
2643 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2645 $stmt = "WHERE completed > ? AND is_ready"
2646 @bind = ('2012-12-21')
2648 Using an empty string literal used to be the only way to express a boolean.
2649 For all new code please use the much more readable
2650 L<-bool|/Unary operators: bool> operator.
2656 These pages could go on for a while, since the nesting of the data
2657 structures this module can handle are pretty much unlimited (the
2658 module implements the C<WHERE> expansion as a recursive function
2659 internally). Your best bet is to "play around" with the module a
2660 little to see how the data structures behave, and choose the best
2661 format for your data based on that.
2663 And of course, all the values above will probably be replaced with
2664 variables gotten from forms or the command line. After all, if you
2665 knew everything ahead of time, you wouldn't have to worry about
2666 dynamically-generating SQL and could just hardwire it into your
2669 =head1 ORDER BY CLAUSES
2671 Some functions take an order by clause. This can either be a scalar (just a
2672 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2673 or an array of either of the two previous forms. Examples:
2675 Given | Will Generate
2676 ----------------------------------------------------------
2678 \'colA DESC' | ORDER BY colA DESC
2680 'colA' | ORDER BY colA
2682 [qw/colA colB/] | ORDER BY colA, colB
2684 {-asc => 'colA'} | ORDER BY colA ASC
2686 {-desc => 'colB'} | ORDER BY colB DESC
2688 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2690 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2693 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2694 { -desc => [qw/colB/], | colC ASC, colD ASC
2695 { -asc => [qw/colC colD/],|
2697 ===========================================================
2701 =head1 SPECIAL OPERATORS
2703 my $sqlmaker = SQL::Abstract->new(special_ops => [
2707 my ($self, $field, $op, $arg) = @_;
2713 handler => 'method_name',
2717 A "special operator" is a SQL syntactic clause that can be
2718 applied to a field, instead of a usual binary operator.
2721 WHERE field IN (?, ?, ?)
2722 WHERE field BETWEEN ? AND ?
2723 WHERE MATCH(field) AGAINST (?, ?)
2725 Special operators IN and BETWEEN are fairly standard and therefore
2726 are builtin within C<SQL::Abstract> (as the overridable methods
2727 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2728 like the MATCH .. AGAINST example above which is specific to MySQL,
2729 you can write your own operator handlers - supply a C<special_ops>
2730 argument to the C<new> method. That argument takes an arrayref of
2731 operator definitions; each operator definition is a hashref with two
2738 the regular expression to match the operator
2742 Either a coderef or a plain scalar method name. In both cases
2743 the expected return is C<< ($sql, @bind) >>.
2745 When supplied with a method name, it is simply called on the
2746 L<SQL::Abstract/> object as:
2748 $self->$method_name ($field, $op, $arg)
2752 $op is the part that matched the handler regex
2753 $field is the LHS of the operator
2756 When supplied with a coderef, it is called as:
2758 $coderef->($self, $field, $op, $arg)
2763 For example, here is an implementation
2764 of the MATCH .. AGAINST syntax for MySQL
2766 my $sqlmaker = SQL::Abstract->new(special_ops => [
2768 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2769 {regex => qr/^match$/i,
2771 my ($self, $field, $op, $arg) = @_;
2772 $arg = [$arg] if not ref $arg;
2773 my $label = $self->_quote($field);
2774 my ($placeholder) = $self->_convert('?');
2775 my $placeholders = join ", ", (($placeholder) x @$arg);
2776 my $sql = $self->_sqlcase('match') . " ($label) "
2777 . $self->_sqlcase('against') . " ($placeholders) ";
2778 my @bind = $self->_bindtype($field, @$arg);
2779 return ($sql, @bind);
2786 =head1 UNARY OPERATORS
2788 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2792 my ($self, $op, $arg) = @_;
2798 handler => 'method_name',
2802 A "unary operator" is a SQL syntactic clause that can be
2803 applied to a field - the operator goes before the field
2805 You can write your own operator handlers - supply a C<unary_ops>
2806 argument to the C<new> method. That argument takes an arrayref of
2807 operator definitions; each operator definition is a hashref with two
2814 the regular expression to match the operator
2818 Either a coderef or a plain scalar method name. In both cases
2819 the expected return is C<< $sql >>.
2821 When supplied with a method name, it is simply called on the
2822 L<SQL::Abstract/> object as:
2824 $self->$method_name ($op, $arg)
2828 $op is the part that matched the handler regex
2829 $arg is the RHS or argument of the operator
2831 When supplied with a coderef, it is called as:
2833 $coderef->($self, $op, $arg)
2841 Thanks to some benchmarking by Mark Stosberg, it turns out that
2842 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2843 I must admit this wasn't an intentional design issue, but it's a
2844 byproduct of the fact that you get to control your C<DBI> handles
2847 To maximize performance, use a code snippet like the following:
2849 # prepare a statement handle using the first row
2850 # and then reuse it for the rest of the rows
2852 for my $href (@array_of_hashrefs) {
2853 $stmt ||= $sql->insert('table', $href);
2854 $sth ||= $dbh->prepare($stmt);
2855 $sth->execute($sql->values($href));
2858 The reason this works is because the keys in your C<$href> are sorted
2859 internally by B<SQL::Abstract>. Thus, as long as your data retains
2860 the same structure, you only have to generate the SQL the first time
2861 around. On subsequent queries, simply use the C<values> function provided
2862 by this module to return your values in the correct order.
2864 However this depends on the values having the same type - if, for
2865 example, the values of a where clause may either have values
2866 (resulting in sql of the form C<column = ?> with a single bind
2867 value), or alternatively the values might be C<undef> (resulting in
2868 sql of the form C<column IS NULL> with no bind value) then the
2869 caching technique suggested will not work.
2873 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2874 really like this part (I do, at least). Building up a complex query
2875 can be as simple as the following:
2879 use CGI::FormBuilder;
2882 my $form = CGI::FormBuilder->new(...);
2883 my $sql = SQL::Abstract->new;
2885 if ($form->submitted) {
2886 my $field = $form->field;
2887 my $id = delete $field->{id};
2888 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2891 Of course, you would still have to connect using C<DBI> to run the
2892 query, but the point is that if you make your form look like your
2893 table, the actual query script can be extremely simplistic.
2895 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2896 a fast interface to returning and formatting data. I frequently
2897 use these three modules together to write complex database query
2898 apps in under 50 lines.
2904 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2906 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2912 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2913 Great care has been taken to preserve the I<published> behavior
2914 documented in previous versions in the 1.* family; however,
2915 some features that were previously undocumented, or behaved
2916 differently from the documentation, had to be changed in order
2917 to clarify the semantics. Hence, client code that was relying
2918 on some dark areas of C<SQL::Abstract> v1.*
2919 B<might behave differently> in v1.50.
2921 The main changes are :
2927 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2931 support for the { operator => \"..." } construct (to embed literal SQL)
2935 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2939 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2943 defensive programming : check arguments
2947 fixed bug with global logic, which was previously implemented
2948 through global variables yielding side-effects. Prior versions would
2949 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2950 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2951 Now this is interpreted
2952 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2957 fixed semantics of _bindtype on array args
2961 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2962 we just avoid shifting arrays within that tree.
2966 dropped the C<_modlogic> function
2970 =head1 ACKNOWLEDGEMENTS
2972 There are a number of individuals that have really helped out with
2973 this module. Unfortunately, most of them submitted bugs via CPAN
2974 so I have no idea who they are! But the people I do know are:
2976 Ash Berlin (order_by hash term support)
2977 Matt Trout (DBIx::Class support)
2978 Mark Stosberg (benchmarking)
2979 Chas Owens (initial "IN" operator support)
2980 Philip Collins (per-field SQL functions)
2981 Eric Kolve (hashref "AND" support)
2982 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2983 Dan Kubb (support for "quote_char" and "name_sep")
2984 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2985 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2986 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2987 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2988 Oliver Charles (support for "RETURNING" after "INSERT")
2994 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2998 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3000 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3002 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3003 While not an official support venue, C<DBIx::Class> makes heavy use of
3004 C<SQL::Abstract>, and as such list members there are very familiar with
3005 how to create queries.
3009 This module is free software; you may copy this under the same
3010 terms as perl itself (either the GNU General Public License or
3011 the Artistic License)