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)
14 #======================================================================
16 #======================================================================
18 our $VERSION = '1.72';
20 # This would confuse some packagers
21 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
25 # special operators (-in, -between). May be extended/overridden by user.
26 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
27 my @BUILTIN_SPECIAL_OPS = (
28 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
29 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
32 # unaryish operators - key maps to handler
33 my @BUILTIN_UNARY_OPS = (
34 # the digits are backcompat stuff
35 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
36 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
37 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
38 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
41 #======================================================================
42 # DEBUGGING AND ERROR REPORTING
43 #======================================================================
46 return unless $_[0]->{debug}; shift; # a little faster
47 my $func = (caller(1))[3];
48 warn "[$func] ", @_, "\n";
52 my($func) = (caller(1))[3];
53 carp "[$func] Warning: ", @_;
57 my($func) = (caller(1))[3];
58 croak "[$func] Fatal: ", @_;
62 #======================================================================
64 #======================================================================
68 my $class = ref($self) || $self;
69 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
71 # choose our case by keeping an option around
72 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
74 # default logic for interpreting arrayrefs
75 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
77 # how to return bind vars
78 # LDNOTE: changed nwiger code : why this 'delete' ??
79 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
80 $opt{bindtype} ||= 'normal';
82 # default comparison is "=", but can be overridden
85 # try to recognize which are the 'equality' and 'unequality' ops
86 # (temporary quickfix, should go through a more seasoned API)
87 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
88 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
91 $opt{sqltrue} ||= '1=1';
92 $opt{sqlfalse} ||= '0=1';
95 $opt{special_ops} ||= [];
96 # regexes are applied in order, thus push after user-defines
97 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
100 $opt{unary_ops} ||= [];
101 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
103 # rudimentary saniy-check for user supplied bits treated as functions/operators
104 # If a purported function matches this regular expression, an exception is thrown.
105 # Literal SQL is *NOT* subject to this check, only functions (and column names
106 # when quoting is not in effect)
109 # need to guard against ()'s in column names too, but this will break tons of
110 # hacks... ideas anyone?
111 $opt{injection_guard} ||= qr/
117 return bless \%opt, $class;
121 sub _assert_pass_injection_guard {
122 if ($_[1] =~ $_[0]->{injection_guard}) {
123 my $class = ref $_[0];
124 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
125 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
126 . "{injection_guard} attribute to ${class}->new()"
131 #======================================================================
133 #======================================================================
137 my $table = $self->_table(shift);
138 my $data = shift || return;
141 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
142 my ($sql, @bind) = $self->$method($data);
143 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
145 if ($options->{returning}) {
146 my ($s, @b) = $self->_insert_returning ($options);
151 return wantarray ? ($sql, @bind) : $sql;
154 sub _insert_returning {
155 my ($self, $options) = @_;
157 my $f = $options->{returning};
159 my $fieldlist = $self->_SWITCH_refkind($f, {
160 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
161 SCALAR => sub {$self->_quote($f)},
162 SCALARREF => sub {$$f},
164 return $self->_sqlcase(' returning ') . $fieldlist;
167 sub _insert_HASHREF { # explicit list of fields and then values
168 my ($self, $data) = @_;
170 my @fields = sort keys %$data;
172 my ($sql, @bind) = $self->_insert_values($data);
175 $_ = $self->_quote($_) foreach @fields;
176 $sql = "( ".join(", ", @fields).") ".$sql;
178 return ($sql, @bind);
181 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
182 my ($self, $data) = @_;
184 # no names (arrayref) so can't generate bindtype
185 $self->{bindtype} ne 'columns'
186 or belch "can't do 'columns' bindtype when called with arrayref";
188 # fold the list of values into a hash of column name - value pairs
189 # (where the column names are artificially generated, and their
190 # lexicographical ordering keep the ordering of the original list)
191 my $i = "a"; # incremented values will be in lexicographical order
192 my $data_in_hash = { map { ($i++ => $_) } @$data };
194 return $self->_insert_values($data_in_hash);
197 sub _insert_ARRAYREFREF { # literal SQL with bind
198 my ($self, $data) = @_;
200 my ($sql, @bind) = @${$data};
201 $self->_assert_bindval_matches_bindtype(@bind);
203 return ($sql, @bind);
207 sub _insert_SCALARREF { # literal SQL without bind
208 my ($self, $data) = @_;
214 my ($self, $data) = @_;
216 my (@values, @all_bind);
217 foreach my $column (sort keys %$data) {
218 my $v = $data->{$column};
220 $self->_SWITCH_refkind($v, {
223 if ($self->{array_datatypes}) { # if array datatype are activated
225 push @all_bind, $self->_bindtype($column, $v);
227 else { # else literal SQL with bind
228 my ($sql, @bind) = @$v;
229 $self->_assert_bindval_matches_bindtype(@bind);
231 push @all_bind, @bind;
235 ARRAYREFREF => sub { # literal SQL with bind
236 my ($sql, @bind) = @${$v};
237 $self->_assert_bindval_matches_bindtype(@bind);
239 push @all_bind, @bind;
242 # THINK : anything useful to do with a HASHREF ?
243 HASHREF => sub { # (nothing, but old SQLA passed it through)
244 #TODO in SQLA >= 2.0 it will die instead
245 belch "HASH ref as bind value in insert is not supported";
247 push @all_bind, $self->_bindtype($column, $v);
250 SCALARREF => sub { # literal SQL without bind
254 SCALAR_or_UNDEF => sub {
256 push @all_bind, $self->_bindtype($column, $v);
263 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
264 return ($sql, @all_bind);
269 #======================================================================
271 #======================================================================
276 my $table = $self->_table(shift);
277 my $data = shift || return;
280 # first build the 'SET' part of the sql statement
281 my (@set, @all_bind);
282 puke "Unsupported data type specified to \$sql->update"
283 unless ref $data eq 'HASH';
285 for my $k (sort keys %$data) {
288 my $label = $self->_quote($k);
290 $self->_SWITCH_refkind($v, {
292 if ($self->{array_datatypes}) { # array datatype
293 push @set, "$label = ?";
294 push @all_bind, $self->_bindtype($k, $v);
296 else { # literal SQL with bind
297 my ($sql, @bind) = @$v;
298 $self->_assert_bindval_matches_bindtype(@bind);
299 push @set, "$label = $sql";
300 push @all_bind, @bind;
303 ARRAYREFREF => sub { # literal SQL with bind
304 my ($sql, @bind) = @${$v};
305 $self->_assert_bindval_matches_bindtype(@bind);
306 push @set, "$label = $sql";
307 push @all_bind, @bind;
309 SCALARREF => sub { # literal SQL without bind
310 push @set, "$label = $$v";
313 my ($op, $arg, @rest) = %$v;
315 puke 'Operator calls in update must be in the form { -op => $arg }'
316 if (@rest or not $op =~ /^\-(.+)/);
318 local $self->{_nested_func_lhs} = $k;
319 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
321 push @set, "$label = $sql";
322 push @all_bind, @bind;
324 SCALAR_or_UNDEF => sub {
325 push @set, "$label = ?";
326 push @all_bind, $self->_bindtype($k, $v);
332 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
336 my($where_sql, @where_bind) = $self->where($where);
338 push @all_bind, @where_bind;
341 return wantarray ? ($sql, @all_bind) : $sql;
347 #======================================================================
349 #======================================================================
354 my $table = $self->_table(shift);
355 my $fields = shift || '*';
359 my($where_sql, @bind) = $self->where($where, $order);
361 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
363 my $sql = join(' ', $self->_sqlcase('select'), $f,
364 $self->_sqlcase('from'), $table)
367 return wantarray ? ($sql, @bind) : $sql;
370 #======================================================================
372 #======================================================================
377 my $table = $self->_table(shift);
381 my($where_sql, @bind) = $self->where($where);
382 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
384 return wantarray ? ($sql, @bind) : $sql;
388 #======================================================================
390 #======================================================================
394 # Finally, a separate routine just to handle WHERE clauses
396 my ($self, $where, $order) = @_;
399 my ($sql, @bind) = $self->_recurse_where($where);
400 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
404 $sql .= $self->_order_by($order);
407 return wantarray ? ($sql, @bind) : $sql;
412 my ($self, $where, $logic) = @_;
414 # dispatch on appropriate method according to refkind of $where
415 my $method = $self->_METHOD_FOR_refkind("_where", $where);
417 my ($sql, @bind) = $self->$method($where, $logic);
419 # DBIx::Class directly calls _recurse_where in scalar context, so
420 # we must implement it, even if not in the official API
421 return wantarray ? ($sql, @bind) : $sql;
426 #======================================================================
427 # WHERE: top-level ARRAYREF
428 #======================================================================
431 sub _where_ARRAYREF {
432 my ($self, $where, $logic) = @_;
434 $logic = uc($logic || $self->{logic});
435 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
437 my @clauses = @$where;
439 my (@sql_clauses, @all_bind);
440 # need to use while() so can shift() for pairs
441 while (my $el = shift @clauses) {
443 # switch according to kind of $el and get corresponding ($sql, @bind)
444 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
446 # skip empty elements, otherwise get invalid trailing AND stuff
447 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
451 $self->_assert_bindval_matches_bindtype(@b);
455 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
456 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
457 # side-effect: the first hashref within an array would change
458 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
459 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
460 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
462 SCALARREF => sub { ($$el); },
464 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
465 $self->_recurse_where({$el => shift(@clauses)})},
467 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
471 push @sql_clauses, $sql;
472 push @all_bind, @bind;
476 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
479 #======================================================================
480 # WHERE: top-level ARRAYREFREF
481 #======================================================================
483 sub _where_ARRAYREFREF {
484 my ($self, $where) = @_;
485 my ($sql, @bind) = @$$where;
486 $self->_assert_bindval_matches_bindtype(@bind);
487 return ($sql, @bind);
490 #======================================================================
491 # WHERE: top-level HASHREF
492 #======================================================================
495 my ($self, $where) = @_;
496 my (@sql_clauses, @all_bind);
498 for my $k (sort keys %$where) {
499 my $v = $where->{$k};
501 # ($k => $v) is either a special unary op or a regular hashpair
502 my ($sql, @bind) = do {
504 # put the operator in canonical form
506 $op = substr $op, 1; # remove initial dash
507 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
508 $op =~ s/\s+/ /g; # compress whitespace
510 # so that -not_foo works correctly
511 $op =~ s/^not_/NOT /i;
513 $self->_debug("Unary OP(-$op) within hashref, recursing...");
514 my ($s, @b) = $self->_where_unary_op ($op, $v);
516 # top level vs nested
517 # we assume that handled unary ops will take care of their ()s
519 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
521 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
526 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
527 $self->$method($k, $v);
531 push @sql_clauses, $sql;
532 push @all_bind, @bind;
535 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
538 sub _where_unary_op {
539 my ($self, $op, $rhs) = @_;
541 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
542 my $handler = $op_entry->{handler};
544 if (not ref $handler) {
545 if ($op =~ s/ [_\s]? \d+ $//x ) {
546 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
547 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
549 return $self->$handler ($op, $rhs);
551 elsif (ref $handler eq 'CODE') {
552 return $handler->($self, $op, $rhs);
555 puke "Illegal handler for operator $op - expecting a method name or a coderef";
559 $self->_debug("Generic unary OP: $op - recursing as function");
561 $self->_assert_pass_injection_guard($op);
563 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
565 puke "Illegal use of top-level '$op'"
566 unless $self->{_nested_func_lhs};
569 $self->_convert('?'),
570 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
574 $self->_recurse_where ($rhs)
578 $sql = sprintf ('%s %s',
579 $self->_sqlcase($op),
583 return ($sql, @bind);
586 sub _where_op_ANDOR {
587 my ($self, $op, $v) = @_;
589 $self->_SWITCH_refkind($v, {
591 return $self->_where_ARRAYREF($v, $op);
595 return ( $op =~ /^or/i )
596 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
597 : $self->_where_HASHREF($v);
601 puke "-$op => \\\$scalar makes little sense, use " .
603 ? '[ \$scalar, \%rest_of_conditions ] instead'
604 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
609 puke "-$op => \\[...] makes little sense, use " .
611 ? '[ \[...], \%rest_of_conditions ] instead'
612 : '-and => [ \[...], \%rest_of_conditions ] instead'
616 SCALAR => sub { # permissively interpreted as SQL
617 puke "-$op => \$value makes little sense, use -bool => \$value instead";
621 puke "-$op => undef not supported";
627 my ($self, $op, $v) = @_;
629 $self->_SWITCH_refkind($v, {
631 SCALAR => sub { # permissively interpreted as SQL
632 belch "literal SQL should be -nest => \\'scalar' "
633 . "instead of -nest => 'scalar' ";
638 puke "-$op => undef not supported";
642 $self->_recurse_where ($v);
650 my ($self, $op, $v) = @_;
652 my ($s, @b) = $self->_SWITCH_refkind($v, {
653 SCALAR => sub { # interpreted as SQL column
654 $self->_convert($self->_quote($v));
658 puke "-$op => undef not supported";
662 $self->_recurse_where ($v);
666 $s = "(NOT $s)" if $op =~ /^not/i;
671 sub _where_hashpair_ARRAYREF {
672 my ($self, $k, $v) = @_;
675 my @v = @$v; # need copy because of shift below
676 $self->_debug("ARRAY($k) means distribute over elements");
678 # put apart first element if it is an operator (-and, -or)
680 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
684 my @distributed = map { {$k => $_} } @v;
687 $self->_debug("OP($op) reinjected into the distributed array");
688 unshift @distributed, $op;
691 my $logic = $op ? substr($op, 1) : '';
693 return $self->_recurse_where(\@distributed, $logic);
696 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
697 $self->_debug("empty ARRAY($k) means 0=1");
698 return ($self->{sqlfalse});
702 sub _where_hashpair_HASHREF {
703 my ($self, $k, $v, $logic) = @_;
706 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
708 my ($all_sql, @all_bind);
710 for my $orig_op (sort keys %$v) {
711 my $val = $v->{$orig_op};
713 # put the operator in canonical form
716 # FIXME - we need to phase out dash-less ops
717 $op =~ s/^-//; # remove possible initial dash
718 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
719 $op =~ s/\s+/ /g; # compress whitespace
721 $self->_assert_pass_injection_guard($op);
723 # so that -not_foo works correctly
724 $op =~ s/^not_/NOT /i;
728 # CASE: col-value logic modifiers
729 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
730 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
732 # CASE: special operators like -in or -between
733 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
734 my $handler = $special_op->{handler};
736 puke "No handler supplied for special operator $orig_op";
738 elsif (not ref $handler) {
739 ($sql, @bind) = $self->$handler ($k, $op, $val);
741 elsif (ref $handler eq 'CODE') {
742 ($sql, @bind) = $handler->($self, $k, $op, $val);
745 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
749 $self->_SWITCH_refkind($val, {
751 ARRAYREF => sub { # CASE: col => {op => \@vals}
752 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
755 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
756 my ($sub_sql, @sub_bind) = @$$val;
757 $self->_assert_bindval_matches_bindtype(@sub_bind);
758 $sql = join ' ', $self->_convert($self->_quote($k)),
759 $self->_sqlcase($op),
764 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
765 my $is = ($op =~ $self->{equality_op}) ? 'is' :
766 ($op =~ $self->{inequality_op}) ? 'is not' :
767 puke "unexpected operator '$orig_op' with undef operand";
768 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
771 FALLBACK => sub { # CASE: col => {op/func => $stuff}
773 # retain for proper column type bind
774 $self->{_nested_func_lhs} ||= $k;
776 ($sql, @bind) = $self->_where_unary_op ($op, $val);
779 $self->_convert($self->_quote($k)),
780 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
786 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
787 push @all_bind, @bind;
789 return ($all_sql, @all_bind);
794 sub _where_field_op_ARRAYREF {
795 my ($self, $k, $op, $vals) = @_;
797 my @vals = @$vals; #always work on a copy
800 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
802 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
805 # see if the first element is an -and/-or op
807 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
812 # distribute $op over each remaining member of @vals, append logic if exists
813 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
815 # LDNOTE : had planned to change the distribution logic when
816 # $op =~ $self->{inequality_op}, because of Morgan laws :
817 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
818 # WHERE field != 22 OR field != 33 : the user probably means
819 # WHERE field != 22 AND field != 33.
820 # To do this, replace the above to roughly :
821 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
822 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
826 # try to DWIM on equality operators
827 # LDNOTE : not 100% sure this is the correct thing to do ...
828 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
829 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
832 puke "operator '$op' applied on an empty array (field '$k')";
837 sub _where_hashpair_SCALARREF {
838 my ($self, $k, $v) = @_;
839 $self->_debug("SCALAR($k) means literal SQL: $$v");
840 my $sql = $self->_quote($k) . " " . $$v;
844 # literal SQL with bind
845 sub _where_hashpair_ARRAYREFREF {
846 my ($self, $k, $v) = @_;
847 $self->_debug("REF($k) means literal SQL: @${$v}");
848 my ($sql, @bind) = @$$v;
849 $self->_assert_bindval_matches_bindtype(@bind);
850 $sql = $self->_quote($k) . " " . $sql;
851 return ($sql, @bind );
854 # literal SQL without bind
855 sub _where_hashpair_SCALAR {
856 my ($self, $k, $v) = @_;
857 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
858 my $sql = join ' ', $self->_convert($self->_quote($k)),
859 $self->_sqlcase($self->{cmp}),
860 $self->_convert('?');
861 my @bind = $self->_bindtype($k, $v);
862 return ( $sql, @bind);
866 sub _where_hashpair_UNDEF {
867 my ($self, $k, $v) = @_;
868 $self->_debug("UNDEF($k) means IS NULL");
869 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
873 #======================================================================
874 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
875 #======================================================================
878 sub _where_SCALARREF {
879 my ($self, $where) = @_;
882 $self->_debug("SCALAR(*top) means literal SQL: $$where");
888 my ($self, $where) = @_;
891 $self->_debug("NOREF(*top) means literal SQL: $where");
902 #======================================================================
903 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
904 #======================================================================
907 sub _where_field_BETWEEN {
908 my ($self, $k, $op, $vals) = @_;
910 my ($label, $and, $placeholder);
911 $label = $self->_convert($self->_quote($k));
912 $and = ' ' . $self->_sqlcase('and') . ' ';
913 $placeholder = $self->_convert('?');
914 $op = $self->_sqlcase($op);
916 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
918 my ($s, @b) = @$$vals;
919 $self->_assert_bindval_matches_bindtype(@b);
926 puke "special op 'between' accepts an arrayref with exactly two values"
929 my (@all_sql, @all_bind);
930 foreach my $val (@$vals) {
931 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
933 return ($placeholder, $self->_bindtype($k, $val) );
939 my ($sql, @bind) = @$$val;
940 $self->_assert_bindval_matches_bindtype(@bind);
941 return ($sql, @bind);
944 my ($func, $arg, @rest) = %$val;
945 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
946 if (@rest or $func !~ /^ \- (.+)/x);
947 local $self->{_nested_func_lhs} = $k;
948 $self->_where_unary_op ($1 => $arg);
952 push @all_bind, @bind;
956 (join $and, @all_sql),
961 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
965 my $sql = "( $label $op $clause )";
970 sub _where_field_IN {
971 my ($self, $k, $op, $vals) = @_;
973 # backwards compatibility : if scalar, force into an arrayref
974 $vals = [$vals] if defined $vals && ! ref $vals;
976 my ($label) = $self->_convert($self->_quote($k));
977 my ($placeholder) = $self->_convert('?');
978 $op = $self->_sqlcase($op);
980 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
981 ARRAYREF => sub { # list of choices
982 if (@$vals) { # nonempty list
983 my (@all_sql, @all_bind);
985 for my $val (@$vals) {
986 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
988 return ($placeholder, $val);
994 my ($sql, @bind) = @$$val;
995 $self->_assert_bindval_matches_bindtype(@bind);
996 return ($sql, @bind);
999 my ($func, $arg, @rest) = %$val;
1000 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1001 if (@rest or $func !~ /^ \- (.+)/x);
1002 local $self->{_nested_func_lhs} = $k;
1003 $self->_where_unary_op ($1 => $arg);
1006 return $self->_sqlcase('null');
1009 push @all_sql, $sql;
1010 push @all_bind, @bind;
1014 sprintf ('%s %s ( %s )',
1017 join (', ', @all_sql)
1019 $self->_bindtype($k, @all_bind),
1022 else { # empty list : some databases won't understand "IN ()", so DWIM
1023 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1028 SCALARREF => sub { # literal SQL
1029 my $sql = $self->_open_outer_paren ($$vals);
1030 return ("$label $op ( $sql )");
1032 ARRAYREFREF => sub { # literal SQL with bind
1033 my ($sql, @bind) = @$$vals;
1034 $self->_assert_bindval_matches_bindtype(@bind);
1035 $sql = $self->_open_outer_paren ($sql);
1036 return ("$label $op ( $sql )", @bind);
1040 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1044 return ($sql, @bind);
1047 # Some databases (SQLite) treat col IN (1, 2) different from
1048 # col IN ( (1, 2) ). Use this to strip all outer parens while
1049 # adding them back in the corresponding method
1050 sub _open_outer_paren {
1051 my ($self, $sql) = @_;
1052 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1057 #======================================================================
1059 #======================================================================
1062 my ($self, $arg) = @_;
1065 for my $c ($self->_order_by_chunks ($arg) ) {
1066 $self->_SWITCH_refkind ($c, {
1067 SCALAR => sub { push @sql, $c },
1068 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1074 $self->_sqlcase(' order by'),
1080 return wantarray ? ($sql, @bind) : $sql;
1083 sub _order_by_chunks {
1084 my ($self, $arg) = @_;
1086 return $self->_SWITCH_refkind($arg, {
1089 map { $self->_order_by_chunks ($_ ) } @$arg;
1092 ARRAYREFREF => sub {
1093 my ($s, @b) = @$$arg;
1094 $self->_assert_bindval_matches_bindtype(@b);
1098 SCALAR => sub {$self->_quote($arg)},
1100 UNDEF => sub {return () },
1102 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1105 # get first pair in hash
1106 my ($key, $val, @rest) = %$arg;
1108 return () unless $key;
1110 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1111 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1117 for my $c ($self->_order_by_chunks ($val)) {
1120 $self->_SWITCH_refkind ($c, {
1125 ($sql, @bind) = @$c;
1129 $sql = $sql . ' ' . $self->_sqlcase($direction);
1131 push @ret, [ $sql, @bind];
1140 #======================================================================
1141 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1142 #======================================================================
1147 $self->_SWITCH_refkind($from, {
1148 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1149 SCALAR => sub {$self->_quote($from)},
1150 SCALARREF => sub {$$from},
1155 #======================================================================
1157 #======================================================================
1159 # highly optimized, as it's called way too often
1161 # my ($self, $label) = @_;
1163 return '' unless defined $_[1];
1164 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1166 unless ($_[0]->{quote_char}) {
1167 $_[0]->_assert_pass_injection_guard($_[1]);
1171 my $qref = ref $_[0]->{quote_char};
1174 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1176 elsif ($qref eq 'ARRAY') {
1177 ($l, $r) = @{$_[0]->{quote_char}};
1180 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1183 # parts containing * are naturally unquoted
1184 return join( $_[0]->{name_sep}||'', map
1185 { $_ eq '*' ? $_ : $l . $_ . $r }
1186 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1191 # Conversion, if applicable
1193 #my ($self, $arg) = @_;
1195 # LDNOTE : modified the previous implementation below because
1196 # it was not consistent : the first "return" is always an array,
1197 # the second "return" is context-dependent. Anyway, _convert
1198 # seems always used with just a single argument, so make it a
1200 # return @_ unless $self->{convert};
1201 # my $conv = $self->_sqlcase($self->{convert});
1202 # my @ret = map { $conv.'('.$_.')' } @_;
1203 # return wantarray ? @ret : $ret[0];
1204 if ($_[0]->{convert}) {
1205 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1212 #my ($self, $col, @vals) = @_;
1214 #LDNOTE : changed original implementation below because it did not make
1215 # sense when bindtype eq 'columns' and @vals > 1.
1216 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1218 # called often - tighten code
1219 return $_[0]->{bindtype} eq 'columns'
1220 ? map {[$_[1], $_]} @_[2 .. $#_]
1225 # Dies if any element of @bind is not in [colname => value] format
1226 # if bindtype is 'columns'.
1227 sub _assert_bindval_matches_bindtype {
1228 # my ($self, @bind) = @_;
1230 if ($self->{bindtype} eq 'columns') {
1232 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1233 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1239 sub _join_sql_clauses {
1240 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1242 if (@$clauses_aref > 1) {
1243 my $join = " " . $self->_sqlcase($logic) . " ";
1244 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1245 return ($sql, @$bind_aref);
1247 elsif (@$clauses_aref) {
1248 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1251 return (); # if no SQL, ignore @$bind_aref
1256 # Fix SQL case, if so requested
1258 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1259 # don't touch the argument ... crooked logic, but let's not change it!
1260 return $_[0]->{case} ? $_[1] : uc($_[1]);
1264 #======================================================================
1265 # DISPATCHING FROM REFKIND
1266 #======================================================================
1269 my ($self, $data) = @_;
1271 return 'UNDEF' unless defined $data;
1273 # blessed objects are treated like scalars
1274 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1276 return 'SCALAR' unless $ref;
1279 while ($ref eq 'REF') {
1281 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1285 return ($ref||'SCALAR') . ('REF' x $n_steps);
1289 my ($self, $data) = @_;
1290 my @try = ($self->_refkind($data));
1291 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1292 push @try, 'FALLBACK';
1296 sub _METHOD_FOR_refkind {
1297 my ($self, $meth_prefix, $data) = @_;
1300 for (@{$self->_try_refkind($data)}) {
1301 $method = $self->can($meth_prefix."_".$_)
1305 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1309 sub _SWITCH_refkind {
1310 my ($self, $data, $dispatch_table) = @_;
1313 for (@{$self->_try_refkind($data)}) {
1314 $coderef = $dispatch_table->{$_}
1318 puke "no dispatch entry for ".$self->_refkind($data)
1327 #======================================================================
1328 # VALUES, GENERATE, AUTOLOAD
1329 #======================================================================
1331 # LDNOTE: original code from nwiger, didn't touch code in that section
1332 # I feel the AUTOLOAD stuff should not be the default, it should
1333 # only be activated on explicit demand by user.
1337 my $data = shift || return;
1338 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1339 unless ref $data eq 'HASH';
1342 foreach my $k ( sort keys %$data ) {
1343 my $v = $data->{$k};
1344 $self->_SWITCH_refkind($v, {
1346 if ($self->{array_datatypes}) { # array datatype
1347 push @all_bind, $self->_bindtype($k, $v);
1349 else { # literal SQL with bind
1350 my ($sql, @bind) = @$v;
1351 $self->_assert_bindval_matches_bindtype(@bind);
1352 push @all_bind, @bind;
1355 ARRAYREFREF => sub { # literal SQL with bind
1356 my ($sql, @bind) = @${$v};
1357 $self->_assert_bindval_matches_bindtype(@bind);
1358 push @all_bind, @bind;
1360 SCALARREF => sub { # literal SQL without bind
1362 SCALAR_or_UNDEF => sub {
1363 push @all_bind, $self->_bindtype($k, $v);
1374 my(@sql, @sqlq, @sqlv);
1378 if ($ref eq 'HASH') {
1379 for my $k (sort keys %$_) {
1382 my $label = $self->_quote($k);
1383 if ($r eq 'ARRAY') {
1384 # literal SQL with bind
1385 my ($sql, @bind) = @$v;
1386 $self->_assert_bindval_matches_bindtype(@bind);
1387 push @sqlq, "$label = $sql";
1389 } elsif ($r eq 'SCALAR') {
1390 # literal SQL without bind
1391 push @sqlq, "$label = $$v";
1393 push @sqlq, "$label = ?";
1394 push @sqlv, $self->_bindtype($k, $v);
1397 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1398 } elsif ($ref eq 'ARRAY') {
1399 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1402 if ($r eq 'ARRAY') { # literal SQL with bind
1403 my ($sql, @bind) = @$v;
1404 $self->_assert_bindval_matches_bindtype(@bind);
1407 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1408 # embedded literal SQL
1415 push @sql, '(' . join(', ', @sqlq) . ')';
1416 } elsif ($ref eq 'SCALAR') {
1420 # strings get case twiddled
1421 push @sql, $self->_sqlcase($_);
1425 my $sql = join ' ', @sql;
1427 # this is pretty tricky
1428 # if ask for an array, return ($stmt, @bind)
1429 # otherwise, s/?/shift @sqlv/ to put it inline
1431 return ($sql, @sqlv);
1433 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1434 ref $d ? $d->[1] : $d/e;
1443 # This allows us to check for a local, then _form, attr
1445 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1446 return $self->generate($name, @_);
1457 SQL::Abstract - Generate SQL from Perl data structures
1463 my $sql = SQL::Abstract->new;
1465 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1467 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1469 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1471 my($stmt, @bind) = $sql->delete($table, \%where);
1473 # Then, use these in your DBI statements
1474 my $sth = $dbh->prepare($stmt);
1475 $sth->execute(@bind);
1477 # Just generate the WHERE clause
1478 my($stmt, @bind) = $sql->where(\%where, \@order);
1480 # Return values in the same order, for hashed queries
1481 # See PERFORMANCE section for more details
1482 my @bind = $sql->values(\%fieldvals);
1486 This module was inspired by the excellent L<DBIx::Abstract>.
1487 However, in using that module I found that what I really wanted
1488 to do was generate SQL, but still retain complete control over my
1489 statement handles and use the DBI interface. So, I set out to
1490 create an abstract SQL generation module.
1492 While based on the concepts used by L<DBIx::Abstract>, there are
1493 several important differences, especially when it comes to WHERE
1494 clauses. I have modified the concepts used to make the SQL easier
1495 to generate from Perl data structures and, IMO, more intuitive.
1496 The underlying idea is for this module to do what you mean, based
1497 on the data structures you provide it. The big advantage is that
1498 you don't have to modify your code every time your data changes,
1499 as this module figures it out.
1501 To begin with, an SQL INSERT is as easy as just specifying a hash
1502 of C<key=value> pairs:
1505 name => 'Jimbo Bobson',
1506 phone => '123-456-7890',
1507 address => '42 Sister Lane',
1508 city => 'St. Louis',
1509 state => 'Louisiana',
1512 The SQL can then be generated with this:
1514 my($stmt, @bind) = $sql->insert('people', \%data);
1516 Which would give you something like this:
1518 $stmt = "INSERT INTO people
1519 (address, city, name, phone, state)
1520 VALUES (?, ?, ?, ?, ?)";
1521 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1522 '123-456-7890', 'Louisiana');
1524 These are then used directly in your DBI code:
1526 my $sth = $dbh->prepare($stmt);
1527 $sth->execute(@bind);
1529 =head2 Inserting and Updating Arrays
1531 If your database has array types (like for example Postgres),
1532 activate the special option C<< array_datatypes => 1 >>
1533 when creating the C<SQL::Abstract> object.
1534 Then you may use an arrayref to insert and update database array types:
1536 my $sql = SQL::Abstract->new(array_datatypes => 1);
1538 planets => [qw/Mercury Venus Earth Mars/]
1541 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1545 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1547 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1550 =head2 Inserting and Updating SQL
1552 In order to apply SQL functions to elements of your C<%data> you may
1553 specify a reference to an arrayref for the given hash value. For example,
1554 if you need to execute the Oracle C<to_date> function on a value, you can
1555 say something like this:
1559 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1562 The first value in the array is the actual SQL. Any other values are
1563 optional and would be included in the bind values array. This gives
1566 my($stmt, @bind) = $sql->insert('people', \%data);
1568 $stmt = "INSERT INTO people (name, date_entered)
1569 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1570 @bind = ('Bill', '03/02/2003');
1572 An UPDATE is just as easy, all you change is the name of the function:
1574 my($stmt, @bind) = $sql->update('people', \%data);
1576 Notice that your C<%data> isn't touched; the module will generate
1577 the appropriately quirky SQL for you automatically. Usually you'll
1578 want to specify a WHERE clause for your UPDATE, though, which is
1579 where handling C<%where> hashes comes in handy...
1581 =head2 Complex where statements
1583 This module can generate pretty complicated WHERE statements
1584 easily. For example, simple C<key=value> pairs are taken to mean
1585 equality, and if you want to see if a field is within a set
1586 of values, you can use an arrayref. Let's say we wanted to
1587 SELECT some data based on this criteria:
1590 requestor => 'inna',
1591 worker => ['nwiger', 'rcwe', 'sfz'],
1592 status => { '!=', 'completed' }
1595 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1597 The above would give you something like this:
1599 $stmt = "SELECT * FROM tickets WHERE
1600 ( requestor = ? ) AND ( status != ? )
1601 AND ( worker = ? OR worker = ? OR worker = ? )";
1602 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1604 Which you could then use in DBI code like so:
1606 my $sth = $dbh->prepare($stmt);
1607 $sth->execute(@bind);
1613 The functions are simple. There's one for each major SQL operation,
1614 and a constructor you use first. The arguments are specified in a
1615 similar order to each function (table, then fields, then a where
1616 clause) to try and simplify things.
1621 =head2 new(option => 'value')
1623 The C<new()> function takes a list of options and values, and returns
1624 a new B<SQL::Abstract> object which can then be used to generate SQL
1625 through the methods below. The options accepted are:
1631 If set to 'lower', then SQL will be generated in all lowercase. By
1632 default SQL is generated in "textbook" case meaning something like:
1634 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1636 Any setting other than 'lower' is ignored.
1640 This determines what the default comparison operator is. By default
1641 it is C<=>, meaning that a hash like this:
1643 %where = (name => 'nwiger', email => 'nate@wiger.org');
1645 Will generate SQL like this:
1647 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1649 However, you may want loose comparisons by default, so if you set
1650 C<cmp> to C<like> you would get SQL such as:
1652 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1654 You can also override the comparsion on an individual basis - see
1655 the huge section on L</"WHERE CLAUSES"> at the bottom.
1657 =item sqltrue, sqlfalse
1659 Expressions for inserting boolean values within SQL statements.
1660 By default these are C<1=1> and C<1=0>. They are used
1661 by the special operators C<-in> and C<-not_in> for generating
1662 correct SQL even when the argument is an empty array (see below).
1666 This determines the default logical operator for multiple WHERE
1667 statements in arrays or hashes. If absent, the default logic is "or"
1668 for arrays, and "and" for hashes. This means that a WHERE
1672 event_date => {'>=', '2/13/99'},
1673 event_date => {'<=', '4/24/03'},
1676 will generate SQL like this:
1678 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1680 This is probably not what you want given this query, though (look
1681 at the dates). To change the "OR" to an "AND", simply specify:
1683 my $sql = SQL::Abstract->new(logic => 'and');
1685 Which will change the above C<WHERE> to:
1687 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1689 The logic can also be changed locally by inserting
1690 a modifier in front of an arrayref :
1692 @where = (-and => [event_date => {'>=', '2/13/99'},
1693 event_date => {'<=', '4/24/03'} ]);
1695 See the L</"WHERE CLAUSES"> section for explanations.
1699 This will automatically convert comparisons using the specified SQL
1700 function for both column and value. This is mostly used with an argument
1701 of C<upper> or C<lower>, so that the SQL will have the effect of
1702 case-insensitive "searches". For example, this:
1704 $sql = SQL::Abstract->new(convert => 'upper');
1705 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1707 Will turn out the following SQL:
1709 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1711 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1712 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1713 not validate this option; it will just pass through what you specify verbatim).
1717 This is a kludge because many databases suck. For example, you can't
1718 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1719 Instead, you have to use C<bind_param()>:
1721 $sth->bind_param(1, 'reg data');
1722 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1724 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1725 which loses track of which field each slot refers to. Fear not.
1727 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1728 Currently, you can specify either C<normal> (default) or C<columns>. If you
1729 specify C<columns>, you will get an array that looks like this:
1731 my $sql = SQL::Abstract->new(bindtype => 'columns');
1732 my($stmt, @bind) = $sql->insert(...);
1735 [ 'column1', 'value1' ],
1736 [ 'column2', 'value2' ],
1737 [ 'column3', 'value3' ],
1740 You can then iterate through this manually, using DBI's C<bind_param()>.
1742 $sth->prepare($stmt);
1745 my($col, $data) = @$_;
1746 if ($col eq 'details' || $col eq 'comments') {
1747 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1748 } elsif ($col eq 'image') {
1749 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1751 $sth->bind_param($i, $data);
1755 $sth->execute; # execute without @bind now
1757 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1758 Basically, the advantage is still that you don't have to care which fields
1759 are or are not included. You could wrap that above C<for> loop in a simple
1760 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1761 get a layer of abstraction over manual SQL specification.
1763 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1764 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1765 will expect the bind values in this format.
1769 This is the character that a table or column name will be quoted
1770 with. By default this is an empty string, but you could set it to
1771 the character C<`>, to generate SQL like this:
1773 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1775 Alternatively, you can supply an array ref of two items, the first being the left
1776 hand quote character, and the second the right hand quote character. For
1777 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1778 that generates SQL like this:
1780 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1782 Quoting is useful if you have tables or columns names that are reserved
1783 words in your database's SQL dialect.
1787 This is the character that separates a table and column name. It is
1788 necessary to specify this when the C<quote_char> option is selected,
1789 so that tables and column names can be individually quoted like this:
1791 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1793 =item injection_guard
1795 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1796 column name specified in a query structure. This is a safety mechanism to avoid
1797 injection attacks when mishandling user input e.g.:
1799 my %condition_as_column_value_pairs = get_values_from_user();
1800 $sqla->select( ... , \%condition_as_column_value_pairs );
1802 If the expression matches an exception is thrown. Note that literal SQL
1803 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1805 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1807 =item array_datatypes
1809 When this option is true, arrayrefs in INSERT or UPDATE are
1810 interpreted as array datatypes and are passed directly
1812 When this option is false, arrayrefs are interpreted
1813 as literal SQL, just like refs to arrayrefs
1814 (but this behavior is for backwards compatibility; when writing
1815 new queries, use the "reference to arrayref" syntax
1821 Takes a reference to a list of "special operators"
1822 to extend the syntax understood by L<SQL::Abstract>.
1823 See section L</"SPECIAL OPERATORS"> for details.
1827 Takes a reference to a list of "unary operators"
1828 to extend the syntax understood by L<SQL::Abstract>.
1829 See section L</"UNARY OPERATORS"> for details.
1835 =head2 insert($table, \@values || \%fieldvals, \%options)
1837 This is the simplest function. You simply give it a table name
1838 and either an arrayref of values or hashref of field/value pairs.
1839 It returns an SQL INSERT statement and a list of bind values.
1840 See the sections on L</"Inserting and Updating Arrays"> and
1841 L</"Inserting and Updating SQL"> for information on how to insert
1842 with those data types.
1844 The optional C<\%options> hash reference may contain additional
1845 options to generate the insert SQL. Currently supported options
1852 Takes either a scalar of raw SQL fields, or an array reference of
1853 field names, and adds on an SQL C<RETURNING> statement at the end.
1854 This allows you to return data generated by the insert statement
1855 (such as row IDs) without performing another C<SELECT> statement.
1856 Note, however, this is not part of the SQL standard and may not
1857 be supported by all database engines.
1861 =head2 update($table, \%fieldvals, \%where)
1863 This takes a table, hashref of field/value pairs, and an optional
1864 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1866 See the sections on L</"Inserting and Updating Arrays"> and
1867 L</"Inserting and Updating SQL"> for information on how to insert
1868 with those data types.
1870 =head2 select($source, $fields, $where, $order)
1872 This returns a SQL SELECT statement and associated list of bind values, as
1873 specified by the arguments :
1879 Specification of the 'FROM' part of the statement.
1880 The argument can be either a plain scalar (interpreted as a table
1881 name, will be quoted), or an arrayref (interpreted as a list
1882 of table names, joined by commas, quoted), or a scalarref
1883 (literal table name, not quoted), or a ref to an arrayref
1884 (list of literal table names, joined by commas, not quoted).
1888 Specification of the list of fields to retrieve from
1890 The argument can be either an arrayref (interpreted as a list
1891 of field names, will be joined by commas and quoted), or a
1892 plain scalar (literal SQL, not quoted).
1893 Please observe that this API is not as flexible as for
1894 the first argument C<$table>, for backwards compatibility reasons.
1898 Optional argument to specify the WHERE part of the query.
1899 The argument is most often a hashref, but can also be
1900 an arrayref or plain scalar --
1901 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1905 Optional argument to specify the ORDER BY part of the query.
1906 The argument can be a scalar, a hashref or an arrayref
1907 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1913 =head2 delete($table, \%where)
1915 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1916 It returns an SQL DELETE statement and list of bind values.
1918 =head2 where(\%where, \@order)
1920 This is used to generate just the WHERE clause. For example,
1921 if you have an arbitrary data structure and know what the
1922 rest of your SQL is going to look like, but want an easy way
1923 to produce a WHERE clause, use this. It returns an SQL WHERE
1924 clause and list of bind values.
1927 =head2 values(\%data)
1929 This just returns the values from the hash C<%data>, in the same
1930 order that would be returned from any of the other above queries.
1931 Using this allows you to markedly speed up your queries if you
1932 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1934 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1936 Warning: This is an experimental method and subject to change.
1938 This returns arbitrarily generated SQL. It's a really basic shortcut.
1939 It will return two different things, depending on return context:
1941 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1942 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1944 These would return the following:
1946 # First calling form
1947 $stmt = "CREATE TABLE test (?, ?)";
1948 @bind = (field1, field2);
1950 # Second calling form
1951 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1953 Depending on what you're trying to do, it's up to you to choose the correct
1954 format. In this example, the second form is what you would want.
1958 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1962 ALTER SESSION SET nls_date_format = 'MM/YY'
1964 You get the idea. Strings get their case twiddled, but everything
1965 else remains verbatim.
1970 =head1 WHERE CLAUSES
1974 This module uses a variation on the idea from L<DBIx::Abstract>. It
1975 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1976 module is that things in arrays are OR'ed, and things in hashes
1979 The easiest way to explain is to show lots of examples. After
1980 each C<%where> hash shown, it is assumed you used:
1982 my($stmt, @bind) = $sql->where(\%where);
1984 However, note that the C<%where> hash can be used directly in any
1985 of the other functions as well, as described above.
1987 =head2 Key-value pairs
1989 So, let's get started. To begin, a simple hash:
1993 status => 'completed'
1996 Is converted to SQL C<key = val> statements:
1998 $stmt = "WHERE user = ? AND status = ?";
1999 @bind = ('nwiger', 'completed');
2001 One common thing I end up doing is having a list of values that
2002 a field can be in. To do this, simply specify a list inside of
2007 status => ['assigned', 'in-progress', 'pending'];
2010 This simple code will create the following:
2012 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2013 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2015 A field associated to an empty arrayref will be considered a
2016 logical false and will generate 0=1.
2018 =head2 Tests for NULL values
2020 If the value part is C<undef> then this is converted to SQL <IS NULL>
2029 $stmt = "WHERE user = ? AND status IS NULL";
2032 =head2 Specific comparison operators
2034 If you want to specify a different type of operator for your comparison,
2035 you can use a hashref for a given column:
2039 status => { '!=', 'completed' }
2042 Which would generate:
2044 $stmt = "WHERE user = ? AND status != ?";
2045 @bind = ('nwiger', 'completed');
2047 To test against multiple values, just enclose the values in an arrayref:
2049 status => { '=', ['assigned', 'in-progress', 'pending'] };
2051 Which would give you:
2053 "WHERE status = ? OR status = ? OR status = ?"
2056 The hashref can also contain multiple pairs, in which case it is expanded
2057 into an C<AND> of its elements:
2061 status => { '!=', 'completed', -not_like => 'pending%' }
2064 # Or more dynamically, like from a form
2065 $where{user} = 'nwiger';
2066 $where{status}{'!='} = 'completed';
2067 $where{status}{'-not_like'} = 'pending%';
2069 # Both generate this
2070 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2071 @bind = ('nwiger', 'completed', 'pending%');
2074 To get an OR instead, you can combine it with the arrayref idea:
2078 priority => [ { '=', 2 }, { '>', 5 } ]
2081 Which would generate:
2083 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2084 @bind = ('2', '5', 'nwiger');
2086 If you want to include literal SQL (with or without bind values), just use a
2087 scalar reference or array reference as the value:
2090 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2091 date_expires => { '<' => \"now()" }
2094 Which would generate:
2096 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2097 @bind = ('11/26/2008');
2100 =head2 Logic and nesting operators
2102 In the example above,
2103 there is a subtle trap if you want to say something like
2104 this (notice the C<AND>):
2106 WHERE priority != ? AND priority != ?
2108 Because, in Perl you I<can't> do this:
2110 priority => { '!=', 2, '!=', 1 }
2112 As the second C<!=> key will obliterate the first. The solution
2113 is to use the special C<-modifier> form inside an arrayref:
2115 priority => [ -and => {'!=', 2},
2119 Normally, these would be joined by C<OR>, but the modifier tells it
2120 to use C<AND> instead. (Hint: You can use this in conjunction with the
2121 C<logic> option to C<new()> in order to change the way your queries
2122 work by default.) B<Important:> Note that the C<-modifier> goes
2123 B<INSIDE> the arrayref, as an extra first element. This will
2124 B<NOT> do what you think it might:
2126 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2128 Here is a quick list of equivalencies, since there is some overlap:
2131 status => {'!=', 'completed', 'not like', 'pending%' }
2132 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2135 status => {'=', ['assigned', 'in-progress']}
2136 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2137 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2141 =head2 Special operators : IN, BETWEEN, etc.
2143 You can also use the hashref format to compare a list of fields using the
2144 C<IN> comparison operator, by specifying the list as an arrayref:
2147 status => 'completed',
2148 reportid => { -in => [567, 2335, 2] }
2151 Which would generate:
2153 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2154 @bind = ('completed', '567', '2335', '2');
2156 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2159 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2160 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2161 'sqltrue' (by default : C<1=1>).
2163 In addition to the array you can supply a chunk of literal sql or
2164 literal sql with bind:
2167 customer => { -in => \[
2168 'SELECT cust_id FROM cust WHERE balance > ?',
2171 status => { -in => \'SELECT status_codes FROM states' },
2177 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2178 AND status IN ( SELECT status_codes FROM states )
2184 Another pair of operators is C<-between> and C<-not_between>,
2185 used with an arrayref of two values:
2189 completion_date => {
2190 -not_between => ['2002-10-01', '2003-02-06']
2196 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2198 Just like with C<-in> all plausible combinations of literal SQL
2202 start0 => { -between => [ 1, 2 ] },
2203 start1 => { -between => \["? AND ?", 1, 2] },
2204 start2 => { -between => \"lower(x) AND upper(y)" },
2205 start3 => { -between => [
2207 \["upper(?)", 'stuff' ],
2214 ( start0 BETWEEN ? AND ? )
2215 AND ( start1 BETWEEN ? AND ? )
2216 AND ( start2 BETWEEN lower(x) AND upper(y) )
2217 AND ( start3 BETWEEN lower(x) AND upper(?) )
2219 @bind = (1, 2, 1, 2, 'stuff');
2222 These are the two builtin "special operators"; but the
2223 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2225 =head2 Unary operators: bool
2227 If you wish to test against boolean columns or functions within your
2228 database you can use the C<-bool> and C<-not_bool> operators. For
2229 example to test the column C<is_user> being true and the column
2230 C<is_enabled> being false you would use:-
2234 -not_bool => 'is_enabled',
2239 WHERE is_user AND NOT is_enabled
2241 If a more complex combination is required, testing more conditions,
2242 then you should use the and/or operators:-
2249 -not_bool => 'four',
2255 WHERE one AND two AND three AND NOT four
2258 =head2 Nested conditions, -and/-or prefixes
2260 So far, we've seen how multiple conditions are joined with a top-level
2261 C<AND>. We can change this by putting the different conditions we want in
2262 hashes and then putting those hashes in an array. For example:
2267 status => { -like => ['pending%', 'dispatched'] },
2271 status => 'unassigned',
2275 This data structure would create the following:
2277 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2278 OR ( user = ? AND status = ? ) )";
2279 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2282 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2283 to change the logic inside :
2289 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2290 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2297 WHERE ( user = ? AND (
2298 ( workhrs > ? AND geo = ? )
2299 OR ( workhrs < ? OR geo = ? )
2302 =head2 Algebraic inconsistency, for historical reasons
2304 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2305 operator goes C<outside> of the nested structure; whereas when connecting
2306 several constraints on one column, the C<-and> operator goes
2307 C<inside> the arrayref. Here is an example combining both features :
2310 -and => [a => 1, b => 2],
2311 -or => [c => 3, d => 4],
2312 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2317 WHERE ( ( ( a = ? AND b = ? )
2318 OR ( c = ? OR d = ? )
2319 OR ( e LIKE ? AND e LIKE ? ) ) )
2321 This difference in syntax is unfortunate but must be preserved for
2322 historical reasons. So be careful : the two examples below would
2323 seem algebraically equivalent, but they are not
2325 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2326 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2328 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2329 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2334 Finally, sometimes only literal SQL will do. If you want to include
2335 literal SQL verbatim, you can specify it as a scalar reference, namely:
2337 my $inn = 'is Not Null';
2339 priority => { '<', 2 },
2345 $stmt = "WHERE priority < ? AND requestor is Not Null";
2348 Note that in this example, you only get one bind parameter back, since
2349 the verbatim SQL is passed as part of the statement.
2351 Of course, just to prove a point, the above can also be accomplished
2355 priority => { '<', 2 },
2356 requestor => { '!=', undef },
2362 Conditions on boolean columns can be expressed in the same way, passing
2363 a reference to an empty string, however using liternal SQL in this way
2364 is deprecated - the preferred method is to use the boolean operators -
2365 see L</"Unary operators: bool"> :
2368 priority => { '<', 2 },
2374 $stmt = "WHERE priority < ? AND is_ready";
2377 Literal SQL is also the only way to compare 2 columns to one another:
2380 priority => { '<', 2 },
2381 requestor => \'= submittor'
2386 $stmt = "WHERE priority < ? AND requestor = submitter";
2389 =head2 Literal SQL with placeholders and bind values (subqueries)
2391 If the literal SQL to be inserted has placeholders and bind values,
2392 use a reference to an arrayref (yes this is a double reference --
2393 not so common, but perfectly legal Perl). For example, to find a date
2394 in Postgres you can use something like this:
2397 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2402 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2405 Note that you must pass the bind values in the same format as they are returned
2406 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2407 provide the bind values in the C<< [ column_meta => value ] >> format, where
2408 C<column_meta> is an opaque scalar value; most commonly the column name, but
2409 you can use any scalar value (including references and blessed references),
2410 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2411 to C<columns> the above example will look like:
2414 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2417 Literal SQL is especially useful for nesting parenthesized clauses in the
2418 main SQL query. Here is a first example :
2420 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2424 bar => \["IN ($sub_stmt)" => @sub_bind],
2429 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2430 WHERE c2 < ? AND c3 LIKE ?))";
2431 @bind = (1234, 100, "foo%");
2433 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2434 are expressed in the same way. Of course the C<$sub_stmt> and
2435 its associated bind values can be generated through a former call
2438 my ($sub_stmt, @sub_bind)
2439 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2440 c3 => {-like => "foo%"}});
2443 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2446 In the examples above, the subquery was used as an operator on a column;
2447 but the same principle also applies for a clause within the main C<%where>
2448 hash, like an EXISTS subquery :
2450 my ($sub_stmt, @sub_bind)
2451 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2452 my %where = ( -and => [
2454 \["EXISTS ($sub_stmt)" => @sub_bind],
2459 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2460 WHERE c1 = ? AND c2 > t0.c0))";
2464 Observe that the condition on C<c2> in the subquery refers to
2465 column C<t0.c0> of the main query : this is I<not> a bind
2466 value, so we have to express it through a scalar ref.
2467 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2468 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2469 what we wanted here.
2471 Finally, here is an example where a subquery is used
2472 for expressing unary negation:
2474 my ($sub_stmt, @sub_bind)
2475 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2476 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2478 lname => {like => '%son%'},
2479 \["NOT ($sub_stmt)" => @sub_bind],
2484 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2485 @bind = ('%son%', 10, 20)
2491 These pages could go on for a while, since the nesting of the data
2492 structures this module can handle are pretty much unlimited (the
2493 module implements the C<WHERE> expansion as a recursive function
2494 internally). Your best bet is to "play around" with the module a
2495 little to see how the data structures behave, and choose the best
2496 format for your data based on that.
2498 And of course, all the values above will probably be replaced with
2499 variables gotten from forms or the command line. After all, if you
2500 knew everything ahead of time, you wouldn't have to worry about
2501 dynamically-generating SQL and could just hardwire it into your
2507 =head1 ORDER BY CLAUSES
2509 Some functions take an order by clause. This can either be a scalar (just a
2510 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2511 or an array of either of the two previous forms. Examples:
2513 Given | Will Generate
2514 ----------------------------------------------------------
2516 \'colA DESC' | ORDER BY colA DESC
2518 'colA' | ORDER BY colA
2520 [qw/colA colB/] | ORDER BY colA, colB
2522 {-asc => 'colA'} | ORDER BY colA ASC
2524 {-desc => 'colB'} | ORDER BY colB DESC
2526 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2528 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2531 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2532 { -desc => [qw/colB/], | colC ASC, colD ASC
2533 { -asc => [qw/colC colD/],|
2535 ===========================================================
2539 =head1 SPECIAL OPERATORS
2541 my $sqlmaker = SQL::Abstract->new(special_ops => [
2545 my ($self, $field, $op, $arg) = @_;
2551 handler => 'method_name',
2555 A "special operator" is a SQL syntactic clause that can be
2556 applied to a field, instead of a usual binary operator.
2559 WHERE field IN (?, ?, ?)
2560 WHERE field BETWEEN ? AND ?
2561 WHERE MATCH(field) AGAINST (?, ?)
2563 Special operators IN and BETWEEN are fairly standard and therefore
2564 are builtin within C<SQL::Abstract> (as the overridable methods
2565 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2566 like the MATCH .. AGAINST example above which is specific to MySQL,
2567 you can write your own operator handlers - supply a C<special_ops>
2568 argument to the C<new> method. That argument takes an arrayref of
2569 operator definitions; each operator definition is a hashref with two
2576 the regular expression to match the operator
2580 Either a coderef or a plain scalar method name. In both cases
2581 the expected return is C<< ($sql, @bind) >>.
2583 When supplied with a method name, it is simply called on the
2584 L<SQL::Abstract/> object as:
2586 $self->$method_name ($field, $op, $arg)
2590 $op is the part that matched the handler regex
2591 $field is the LHS of the operator
2594 When supplied with a coderef, it is called as:
2596 $coderef->($self, $field, $op, $arg)
2601 For example, here is an implementation
2602 of the MATCH .. AGAINST syntax for MySQL
2604 my $sqlmaker = SQL::Abstract->new(special_ops => [
2606 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2607 {regex => qr/^match$/i,
2609 my ($self, $field, $op, $arg) = @_;
2610 $arg = [$arg] if not ref $arg;
2611 my $label = $self->_quote($field);
2612 my ($placeholder) = $self->_convert('?');
2613 my $placeholders = join ", ", (($placeholder) x @$arg);
2614 my $sql = $self->_sqlcase('match') . " ($label) "
2615 . $self->_sqlcase('against') . " ($placeholders) ";
2616 my @bind = $self->_bindtype($field, @$arg);
2617 return ($sql, @bind);
2624 =head1 UNARY OPERATORS
2626 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2630 my ($self, $op, $arg) = @_;
2636 handler => 'method_name',
2640 A "unary operator" is a SQL syntactic clause that can be
2641 applied to a field - the operator goes before the field
2643 You can write your own operator handlers - supply a C<unary_ops>
2644 argument to the C<new> method. That argument takes an arrayref of
2645 operator definitions; each operator definition is a hashref with two
2652 the regular expression to match the operator
2656 Either a coderef or a plain scalar method name. In both cases
2657 the expected return is C<< $sql >>.
2659 When supplied with a method name, it is simply called on the
2660 L<SQL::Abstract/> object as:
2662 $self->$method_name ($op, $arg)
2666 $op is the part that matched the handler regex
2667 $arg is the RHS or argument of the operator
2669 When supplied with a coderef, it is called as:
2671 $coderef->($self, $op, $arg)
2679 Thanks to some benchmarking by Mark Stosberg, it turns out that
2680 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2681 I must admit this wasn't an intentional design issue, but it's a
2682 byproduct of the fact that you get to control your C<DBI> handles
2685 To maximize performance, use a code snippet like the following:
2687 # prepare a statement handle using the first row
2688 # and then reuse it for the rest of the rows
2690 for my $href (@array_of_hashrefs) {
2691 $stmt ||= $sql->insert('table', $href);
2692 $sth ||= $dbh->prepare($stmt);
2693 $sth->execute($sql->values($href));
2696 The reason this works is because the keys in your C<$href> are sorted
2697 internally by B<SQL::Abstract>. Thus, as long as your data retains
2698 the same structure, you only have to generate the SQL the first time
2699 around. On subsequent queries, simply use the C<values> function provided
2700 by this module to return your values in the correct order.
2702 However this depends on the values having the same type - if, for
2703 example, the values of a where clause may either have values
2704 (resulting in sql of the form C<column = ?> with a single bind
2705 value), or alternatively the values might be C<undef> (resulting in
2706 sql of the form C<column IS NULL> with no bind value) then the
2707 caching technique suggested will not work.
2711 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2712 really like this part (I do, at least). Building up a complex query
2713 can be as simple as the following:
2717 use CGI::FormBuilder;
2720 my $form = CGI::FormBuilder->new(...);
2721 my $sql = SQL::Abstract->new;
2723 if ($form->submitted) {
2724 my $field = $form->field;
2725 my $id = delete $field->{id};
2726 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2729 Of course, you would still have to connect using C<DBI> to run the
2730 query, but the point is that if you make your form look like your
2731 table, the actual query script can be extremely simplistic.
2733 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2734 a fast interface to returning and formatting data. I frequently
2735 use these three modules together to write complex database query
2736 apps in under 50 lines.
2742 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2744 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2750 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2751 Great care has been taken to preserve the I<published> behavior
2752 documented in previous versions in the 1.* family; however,
2753 some features that were previously undocumented, or behaved
2754 differently from the documentation, had to be changed in order
2755 to clarify the semantics. Hence, client code that was relying
2756 on some dark areas of C<SQL::Abstract> v1.*
2757 B<might behave differently> in v1.50.
2759 The main changes are :
2765 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2769 support for the { operator => \"..." } construct (to embed literal SQL)
2773 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2777 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2781 defensive programming : check arguments
2785 fixed bug with global logic, which was previously implemented
2786 through global variables yielding side-effects. Prior versions would
2787 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2788 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2789 Now this is interpreted
2790 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2795 fixed semantics of _bindtype on array args
2799 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2800 we just avoid shifting arrays within that tree.
2804 dropped the C<_modlogic> function
2810 =head1 ACKNOWLEDGEMENTS
2812 There are a number of individuals that have really helped out with
2813 this module. Unfortunately, most of them submitted bugs via CPAN
2814 so I have no idea who they are! But the people I do know are:
2816 Ash Berlin (order_by hash term support)
2817 Matt Trout (DBIx::Class support)
2818 Mark Stosberg (benchmarking)
2819 Chas Owens (initial "IN" operator support)
2820 Philip Collins (per-field SQL functions)
2821 Eric Kolve (hashref "AND" support)
2822 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2823 Dan Kubb (support for "quote_char" and "name_sep")
2824 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2825 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2826 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2827 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2828 Oliver Charles (support for "RETURNING" after "INSERT")
2834 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2838 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2840 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2842 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2843 While not an official support venue, C<DBIx::Class> makes heavy use of
2844 C<SQL::Abstract>, and as such list members there are very familiar with
2845 how to create queries.
2849 This module is free software; you may copy this under the same
2850 terms as perl itself (either the GNU General Public License or
2851 the Artistic License)