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.69';
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 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
99 $opt{unary_ops} ||= [];
100 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
102 return bless \%opt, $class;
107 #======================================================================
109 #======================================================================
113 my $table = $self->_table(shift);
114 my $data = shift || return;
117 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
118 my ($sql, @bind) = $self->$method($data);
119 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
121 if (my $ret = $options->{returning}) {
122 $sql .= $self->_insert_returning ($ret);
125 return wantarray ? ($sql, @bind) : $sql;
128 sub _insert_returning {
129 my ($self, $fields) = @_;
131 my $f = $self->_SWITCH_refkind($fields, {
132 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$fields;},
133 SCALAR => sub {$self->_quote($fields)},
134 SCALARREF => sub {$$fields},
136 return join (' ', $self->_sqlcase(' returning'), $f);
139 sub _insert_HASHREF { # explicit list of fields and then values
140 my ($self, $data) = @_;
142 my @fields = sort keys %$data;
144 my ($sql, @bind) = $self->_insert_values($data);
147 $_ = $self->_quote($_) foreach @fields;
148 $sql = "( ".join(", ", @fields).") ".$sql;
150 return ($sql, @bind);
153 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
154 my ($self, $data) = @_;
156 # no names (arrayref) so can't generate bindtype
157 $self->{bindtype} ne 'columns'
158 or belch "can't do 'columns' bindtype when called with arrayref";
160 # fold the list of values into a hash of column name - value pairs
161 # (where the column names are artificially generated, and their
162 # lexicographical ordering keep the ordering of the original list)
163 my $i = "a"; # incremented values will be in lexicographical order
164 my $data_in_hash = { map { ($i++ => $_) } @$data };
166 return $self->_insert_values($data_in_hash);
169 sub _insert_ARRAYREFREF { # literal SQL with bind
170 my ($self, $data) = @_;
172 my ($sql, @bind) = @${$data};
173 $self->_assert_bindval_matches_bindtype(@bind);
175 return ($sql, @bind);
179 sub _insert_SCALARREF { # literal SQL without bind
180 my ($self, $data) = @_;
186 my ($self, $data) = @_;
188 my (@values, @all_bind);
189 foreach my $column (sort keys %$data) {
190 my $v = $data->{$column};
192 $self->_SWITCH_refkind($v, {
195 if ($self->{array_datatypes}) { # if array datatype are activated
197 push @all_bind, $self->_bindtype($column, $v);
199 else { # else literal SQL with bind
200 my ($sql, @bind) = @$v;
201 $self->_assert_bindval_matches_bindtype(@bind);
203 push @all_bind, @bind;
207 ARRAYREFREF => sub { # literal SQL with bind
208 my ($sql, @bind) = @${$v};
209 $self->_assert_bindval_matches_bindtype(@bind);
211 push @all_bind, @bind;
214 # THINK : anything useful to do with a HASHREF ?
215 HASHREF => sub { # (nothing, but old SQLA passed it through)
216 #TODO in SQLA >= 2.0 it will die instead
217 belch "HASH ref as bind value in insert is not supported";
219 push @all_bind, $self->_bindtype($column, $v);
222 SCALARREF => sub { # literal SQL without bind
226 SCALAR_or_UNDEF => sub {
228 push @all_bind, $self->_bindtype($column, $v);
235 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
236 return ($sql, @all_bind);
241 #======================================================================
243 #======================================================================
248 my $table = $self->_table(shift);
249 my $data = shift || return;
252 # first build the 'SET' part of the sql statement
253 my (@set, @all_bind);
254 puke "Unsupported data type specified to \$sql->update"
255 unless ref $data eq 'HASH';
257 for my $k (sort keys %$data) {
260 my $label = $self->_quote($k);
262 $self->_SWITCH_refkind($v, {
264 if ($self->{array_datatypes}) { # array datatype
265 push @set, "$label = ?";
266 push @all_bind, $self->_bindtype($k, $v);
268 else { # literal SQL with bind
269 my ($sql, @bind) = @$v;
270 $self->_assert_bindval_matches_bindtype(@bind);
271 push @set, "$label = $sql";
272 push @all_bind, @bind;
275 ARRAYREFREF => sub { # literal SQL with bind
276 my ($sql, @bind) = @${$v};
277 $self->_assert_bindval_matches_bindtype(@bind);
278 push @set, "$label = $sql";
279 push @all_bind, @bind;
281 SCALARREF => sub { # literal SQL without bind
282 push @set, "$label = $$v";
285 my ($op, $arg, @rest) = %$v;
287 puke 'Operator calls in update must be in the form { -op => $arg }'
288 if (@rest or not $op =~ /^\-(.+)/);
290 local $self->{_nested_func_lhs} = $k;
291 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
293 push @set, "$label = $sql";
294 push @all_bind, @bind;
296 SCALAR_or_UNDEF => sub {
297 push @set, "$label = ?";
298 push @all_bind, $self->_bindtype($k, $v);
304 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
308 my($where_sql, @where_bind) = $self->where($where);
310 push @all_bind, @where_bind;
313 return wantarray ? ($sql, @all_bind) : $sql;
319 #======================================================================
321 #======================================================================
326 my $table = $self->_table(shift);
327 my $fields = shift || '*';
331 my($where_sql, @bind) = $self->where($where, $order);
333 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
335 my $sql = join(' ', $self->_sqlcase('select'), $f,
336 $self->_sqlcase('from'), $table)
339 return wantarray ? ($sql, @bind) : $sql;
342 #======================================================================
344 #======================================================================
349 my $table = $self->_table(shift);
353 my($where_sql, @bind) = $self->where($where);
354 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
356 return wantarray ? ($sql, @bind) : $sql;
360 #======================================================================
362 #======================================================================
366 # Finally, a separate routine just to handle WHERE clauses
368 my ($self, $where, $order) = @_;
371 my ($sql, @bind) = $self->_recurse_where($where);
372 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
376 $sql .= $self->_order_by($order);
379 return wantarray ? ($sql, @bind) : $sql;
384 my ($self, $where, $logic) = @_;
386 # dispatch on appropriate method according to refkind of $where
387 my $method = $self->_METHOD_FOR_refkind("_where", $where);
389 my ($sql, @bind) = $self->$method($where, $logic);
391 # DBIx::Class directly calls _recurse_where in scalar context, so
392 # we must implement it, even if not in the official API
393 return wantarray ? ($sql, @bind) : $sql;
398 #======================================================================
399 # WHERE: top-level ARRAYREF
400 #======================================================================
403 sub _where_ARRAYREF {
404 my ($self, $where, $logic) = @_;
406 $logic = uc($logic || $self->{logic});
407 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
409 my @clauses = @$where;
411 my (@sql_clauses, @all_bind);
412 # need to use while() so can shift() for pairs
413 while (my $el = shift @clauses) {
415 # switch according to kind of $el and get corresponding ($sql, @bind)
416 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
418 # skip empty elements, otherwise get invalid trailing AND stuff
419 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
423 $self->_assert_bindval_matches_bindtype(@b);
427 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
428 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
429 # side-effect: the first hashref within an array would change
430 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
431 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
432 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
434 SCALARREF => sub { ($$el); },
436 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
437 $self->_recurse_where({$el => shift(@clauses)})},
439 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
443 push @sql_clauses, $sql;
444 push @all_bind, @bind;
448 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
451 #======================================================================
452 # WHERE: top-level ARRAYREFREF
453 #======================================================================
455 sub _where_ARRAYREFREF {
456 my ($self, $where) = @_;
457 my ($sql, @bind) = @$$where;
458 $self->_assert_bindval_matches_bindtype(@bind);
459 return ($sql, @bind);
462 #======================================================================
463 # WHERE: top-level HASHREF
464 #======================================================================
467 my ($self, $where) = @_;
468 my (@sql_clauses, @all_bind);
470 for my $k (sort keys %$where) {
471 my $v = $where->{$k};
473 # ($k => $v) is either a special unary op or a regular hashpair
474 my ($sql, @bind) = do {
476 # put the operator in canonical form
478 $op = substr $op, 1; # remove initial dash
479 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
480 $op =~ s/\s+/ /g; # compress whitespace
482 # so that -not_foo works correctly
483 $op =~ s/^not_/NOT /i;
485 $self->_debug("Unary OP(-$op) within hashref, recursing...");
486 my ($s, @b) = $self->_where_unary_op ($op, $v);
488 # top level vs nested
489 # we assume that handled unary ops will take care of their ()s
491 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
493 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
498 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
499 $self->$method($k, $v);
503 push @sql_clauses, $sql;
504 push @all_bind, @bind;
507 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
510 sub _where_unary_op {
511 my ($self, $op, $rhs) = @_;
513 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
514 my $handler = $op_entry->{handler};
516 if (not ref $handler) {
517 if ($op =~ s/ [_\s]? \d+ $//x ) {
518 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
519 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
521 return $self->$handler ($op, $rhs);
523 elsif (ref $handler eq 'CODE') {
524 return $handler->($self, $op, $rhs);
527 puke "Illegal handler for operator $op - expecting a method name or a coderef";
531 $self->debug("Generic unary OP: $op - recursing as function");
533 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
535 puke "Illegal use of top-level '$op'"
536 unless $self->{_nested_func_lhs};
539 $self->_convert('?'),
540 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
544 $self->_recurse_where ($rhs)
548 $sql = sprintf ('%s %s',
549 $self->_sqlcase($op),
553 return ($sql, @bind);
556 sub _where_op_ANDOR {
557 my ($self, $op, $v) = @_;
559 $self->_SWITCH_refkind($v, {
561 return $self->_where_ARRAYREF($v, $op);
565 return ( $op =~ /^or/i )
566 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
567 : $self->_where_HASHREF($v);
571 puke "-$op => \\\$scalar not supported, use -nest => ...";
575 puke "-$op => \\[..] not supported, use -nest => ...";
578 SCALAR => sub { # permissively interpreted as SQL
579 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
583 puke "-$op => undef not supported";
589 my ($self, $op, $v) = @_;
591 $self->_SWITCH_refkind($v, {
593 SCALAR => sub { # permissively interpreted as SQL
594 belch "literal SQL should be -nest => \\'scalar' "
595 . "instead of -nest => 'scalar' ";
600 puke "-$op => undef not supported";
604 $self->_recurse_where ($v);
612 my ($self, $op, $v) = @_;
614 my ($s, @b) = $self->_SWITCH_refkind($v, {
615 SCALAR => sub { # interpreted as SQL column
616 $self->_convert($self->_quote($v));
620 puke "-$op => undef not supported";
624 $self->_recurse_where ($v);
628 $s = "(NOT $s)" if $op =~ /^not/i;
633 sub _where_hashpair_ARRAYREF {
634 my ($self, $k, $v) = @_;
637 my @v = @$v; # need copy because of shift below
638 $self->_debug("ARRAY($k) means distribute over elements");
640 # put apart first element if it is an operator (-and, -or)
642 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
646 my @distributed = map { {$k => $_} } @v;
649 $self->_debug("OP($op) reinjected into the distributed array");
650 unshift @distributed, $op;
653 my $logic = $op ? substr($op, 1) : '';
655 return $self->_recurse_where(\@distributed, $logic);
658 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
659 $self->_debug("empty ARRAY($k) means 0=1");
660 return ($self->{sqlfalse});
664 sub _where_hashpair_HASHREF {
665 my ($self, $k, $v, $logic) = @_;
668 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
670 my ($all_sql, @all_bind);
672 for my $orig_op (sort keys %$v) {
673 my $val = $v->{$orig_op};
675 # put the operator in canonical form
678 # FIXME - we need to phase out dash-less ops
679 $op =~ s/^-//; # remove possible initial dash
680 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
681 $op =~ s/\s+/ /g; # compress whitespace
683 # so that -not_foo works correctly
684 $op =~ s/^not_/NOT /i;
688 # CASE: col-value logic modifiers
689 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
690 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
692 # CASE: special operators like -in or -between
693 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
694 my $handler = $special_op->{handler};
696 puke "No handler supplied for special operator $orig_op";
698 elsif (not ref $handler) {
699 ($sql, @bind) = $self->$handler ($k, $op, $val);
701 elsif (ref $handler eq 'CODE') {
702 ($sql, @bind) = $handler->($self, $k, $op, $val);
705 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
709 $self->_SWITCH_refkind($val, {
711 ARRAYREF => sub { # CASE: col => {op => \@vals}
712 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
715 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
716 my ($sub_sql, @sub_bind) = @$$val;
717 $self->_assert_bindval_matches_bindtype(@sub_bind);
718 $sql = join ' ', $self->_convert($self->_quote($k)),
719 $self->_sqlcase($op),
724 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
725 my $is = ($op =~ $self->{equality_op}) ? 'is' :
726 ($op =~ $self->{inequality_op}) ? 'is not' :
727 puke "unexpected operator '$orig_op' with undef operand";
728 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
731 FALLBACK => sub { # CASE: col => {op/func => $stuff}
733 # retain for proper column type bind
734 $self->{_nested_func_lhs} ||= $k;
736 ($sql, @bind) = $self->_where_unary_op ($op, $val);
739 $self->_convert($self->_quote($k)),
740 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
746 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
747 push @all_bind, @bind;
749 return ($all_sql, @all_bind);
754 sub _where_field_op_ARRAYREF {
755 my ($self, $k, $op, $vals) = @_;
757 my @vals = @$vals; #always work on a copy
760 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
762 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
765 # see if the first element is an -and/-or op
767 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
772 # distribute $op over each remaining member of @vals, append logic if exists
773 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
775 # LDNOTE : had planned to change the distribution logic when
776 # $op =~ $self->{inequality_op}, because of Morgan laws :
777 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
778 # WHERE field != 22 OR field != 33 : the user probably means
779 # WHERE field != 22 AND field != 33.
780 # To do this, replace the above to roughly :
781 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
782 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
786 # try to DWIM on equality operators
787 # LDNOTE : not 100% sure this is the correct thing to do ...
788 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
789 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
792 puke "operator '$op' applied on an empty array (field '$k')";
797 sub _where_hashpair_SCALARREF {
798 my ($self, $k, $v) = @_;
799 $self->_debug("SCALAR($k) means literal SQL: $$v");
800 my $sql = $self->_quote($k) . " " . $$v;
804 # literal SQL with bind
805 sub _where_hashpair_ARRAYREFREF {
806 my ($self, $k, $v) = @_;
807 $self->_debug("REF($k) means literal SQL: @${$v}");
808 my ($sql, @bind) = @$$v;
809 $self->_assert_bindval_matches_bindtype(@bind);
810 $sql = $self->_quote($k) . " " . $sql;
811 return ($sql, @bind );
814 # literal SQL without bind
815 sub _where_hashpair_SCALAR {
816 my ($self, $k, $v) = @_;
817 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
818 my $sql = join ' ', $self->_convert($self->_quote($k)),
819 $self->_sqlcase($self->{cmp}),
820 $self->_convert('?');
821 my @bind = $self->_bindtype($k, $v);
822 return ( $sql, @bind);
826 sub _where_hashpair_UNDEF {
827 my ($self, $k, $v) = @_;
828 $self->_debug("UNDEF($k) means IS NULL");
829 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
833 #======================================================================
834 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
835 #======================================================================
838 sub _where_SCALARREF {
839 my ($self, $where) = @_;
842 $self->_debug("SCALAR(*top) means literal SQL: $$where");
848 my ($self, $where) = @_;
851 $self->_debug("NOREF(*top) means literal SQL: $where");
862 #======================================================================
863 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
864 #======================================================================
867 sub _where_field_BETWEEN {
868 my ($self, $k, $op, $vals) = @_;
870 my ($label, $and, $placeholder);
871 $label = $self->_convert($self->_quote($k));
872 $and = ' ' . $self->_sqlcase('and') . ' ';
873 $placeholder = $self->_convert('?');
874 $op = $self->_sqlcase($op);
876 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
878 my ($s, @b) = @$$vals;
879 $self->_assert_bindval_matches_bindtype(@b);
886 puke "special op 'between' accepts an arrayref with exactly two values"
889 my (@all_sql, @all_bind);
890 foreach my $val (@$vals) {
891 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
893 return ($placeholder, $val);
899 my ($sql, @bind) = @$$val;
900 $self->_assert_bindval_matches_bindtype(@bind);
901 return ($sql, @bind);
904 my ($func, $arg, @rest) = %$val;
905 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
906 if (@rest or $func !~ /^ \- (.+)/x);
907 local $self->{_nested_func_lhs} = $k;
908 $self->_where_unary_op ($1 => $arg);
912 push @all_bind, @bind;
916 (join $and, @all_sql),
917 $self->_bindtype($k, @all_bind),
921 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
925 my $sql = "( $label $op $clause )";
930 sub _where_field_IN {
931 my ($self, $k, $op, $vals) = @_;
933 # backwards compatibility : if scalar, force into an arrayref
934 $vals = [$vals] if defined $vals && ! ref $vals;
936 my ($label) = $self->_convert($self->_quote($k));
937 my ($placeholder) = $self->_convert('?');
938 $op = $self->_sqlcase($op);
940 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
941 ARRAYREF => sub { # list of choices
942 if (@$vals) { # nonempty list
943 my (@all_sql, @all_bind);
945 for my $val (@$vals) {
946 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
948 return ($placeholder, $val);
954 my ($sql, @bind) = @$$val;
955 $self->_assert_bindval_matches_bindtype(@bind);
956 return ($sql, @bind);
959 my ($func, $arg, @rest) = %$val;
960 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
961 if (@rest or $func !~ /^ \- (.+)/x);
962 local $self->{_nested_func_lhs} = $k;
963 $self->_where_unary_op ($1 => $arg);
967 push @all_bind, @bind;
971 sprintf ('%s %s ( %s )',
974 join (', ', @all_sql)
976 $self->_bindtype($k, @all_bind),
979 else { # empty list : some databases won't understand "IN ()", so DWIM
980 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
985 SCALARREF => sub { # literal SQL
986 my $sql = $self->_open_outer_paren ($$vals);
987 return ("$label $op ( $sql )");
989 ARRAYREFREF => sub { # literal SQL with bind
990 my ($sql, @bind) = @$$vals;
991 $self->_assert_bindval_matches_bindtype(@bind);
992 $sql = $self->_open_outer_paren ($sql);
993 return ("$label $op ( $sql )", @bind);
997 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1001 return ($sql, @bind);
1004 # Some databases (SQLite) treat col IN (1, 2) different from
1005 # col IN ( (1, 2) ). Use this to strip all outer parens while
1006 # adding them back in the corresponding method
1007 sub _open_outer_paren {
1008 my ($self, $sql) = @_;
1009 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1014 #======================================================================
1016 #======================================================================
1019 my ($self, $arg) = @_;
1022 for my $c ($self->_order_by_chunks ($arg) ) {
1023 $self->_SWITCH_refkind ($c, {
1024 SCALAR => sub { push @sql, $c },
1025 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1031 $self->_sqlcase(' order by'),
1037 return wantarray ? ($sql, @bind) : $sql;
1040 sub _order_by_chunks {
1041 my ($self, $arg) = @_;
1043 return $self->_SWITCH_refkind($arg, {
1046 map { $self->_order_by_chunks ($_ ) } @$arg;
1049 ARRAYREFREF => sub {
1050 my ($s, @b) = @$$arg;
1051 $self->_assert_bindval_matches_bindtype(@b);
1055 SCALAR => sub {$self->_quote($arg)},
1057 UNDEF => sub {return () },
1059 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1062 # get first pair in hash
1063 my ($key, $val, @rest) = %$arg;
1065 return () unless $key;
1067 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1068 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1074 for my $c ($self->_order_by_chunks ($val)) {
1077 $self->_SWITCH_refkind ($c, {
1082 ($sql, @bind) = @$c;
1086 $sql = $sql . ' ' . $self->_sqlcase($direction);
1088 push @ret, [ $sql, @bind];
1097 #======================================================================
1098 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1099 #======================================================================
1104 $self->_SWITCH_refkind($from, {
1105 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1106 SCALAR => sub {$self->_quote($from)},
1107 SCALARREF => sub {$$from},
1108 ARRAYREFREF => sub {join ', ', @$from;},
1113 #======================================================================
1115 #======================================================================
1117 # highly optimized, as it's called way too often
1119 # my ($self, $label) = @_;
1121 return '' unless defined $_[1];
1122 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1124 return $_[1] unless $_[0]->{quote_char};
1126 my $qref = ref $_[0]->{quote_char};
1129 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1131 elsif ($qref eq 'ARRAY') {
1132 ($l, $r) = @{$_[0]->{quote_char}};
1135 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1138 # parts containing * are naturally unquoted
1139 return join( $_[0]->{name_sep}||'', map
1140 { $_ eq '*' ? $_ : $l . $_ . $r }
1141 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1146 # Conversion, if applicable
1148 #my ($self, $arg) = @_;
1150 # LDNOTE : modified the previous implementation below because
1151 # it was not consistent : the first "return" is always an array,
1152 # the second "return" is context-dependent. Anyway, _convert
1153 # seems always used with just a single argument, so make it a
1155 # return @_ unless $self->{convert};
1156 # my $conv = $self->_sqlcase($self->{convert});
1157 # my @ret = map { $conv.'('.$_.')' } @_;
1158 # return wantarray ? @ret : $ret[0];
1159 if ($_[0]->{convert}) {
1160 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1167 #my ($self, $col, @vals) = @_;
1169 #LDNOTE : changed original implementation below because it did not make
1170 # sense when bindtype eq 'columns' and @vals > 1.
1171 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1173 # called often - tighten code
1174 return $_[0]->{bindtype} eq 'columns'
1175 ? map {[$_[1], $_]} @_[2 .. $#_]
1180 # Dies if any element of @bind is not in [colname => value] format
1181 # if bindtype is 'columns'.
1182 sub _assert_bindval_matches_bindtype {
1183 # my ($self, @bind) = @_;
1185 if ($self->{bindtype} eq 'columns') {
1187 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1188 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1194 sub _join_sql_clauses {
1195 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1197 if (@$clauses_aref > 1) {
1198 my $join = " " . $self->_sqlcase($logic) . " ";
1199 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1200 return ($sql, @$bind_aref);
1202 elsif (@$clauses_aref) {
1203 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1206 return (); # if no SQL, ignore @$bind_aref
1211 # Fix SQL case, if so requested
1213 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1214 # don't touch the argument ... crooked logic, but let's not change it!
1215 return $_[0]->{case} ? $_[1] : uc($_[1]);
1219 #======================================================================
1220 # DISPATCHING FROM REFKIND
1221 #======================================================================
1224 my ($self, $data) = @_;
1226 return 'UNDEF' unless defined $data;
1228 # blessed objects are treated like scalars
1229 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1231 return 'SCALAR' unless $ref;
1234 while ($ref eq 'REF') {
1236 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1240 return ($ref||'SCALAR') . ('REF' x $n_steps);
1244 my ($self, $data) = @_;
1245 my @try = ($self->_refkind($data));
1246 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1247 push @try, 'FALLBACK';
1251 sub _METHOD_FOR_refkind {
1252 my ($self, $meth_prefix, $data) = @_;
1255 for (@{$self->_try_refkind($data)}) {
1256 $method = $self->can($meth_prefix."_".$_)
1260 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1264 sub _SWITCH_refkind {
1265 my ($self, $data, $dispatch_table) = @_;
1268 for (@{$self->_try_refkind($data)}) {
1269 $coderef = $dispatch_table->{$_}
1273 puke "no dispatch entry for ".$self->_refkind($data)
1282 #======================================================================
1283 # VALUES, GENERATE, AUTOLOAD
1284 #======================================================================
1286 # LDNOTE: original code from nwiger, didn't touch code in that section
1287 # I feel the AUTOLOAD stuff should not be the default, it should
1288 # only be activated on explicit demand by user.
1292 my $data = shift || return;
1293 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1294 unless ref $data eq 'HASH';
1297 foreach my $k ( sort keys %$data ) {
1298 my $v = $data->{$k};
1299 $self->_SWITCH_refkind($v, {
1301 if ($self->{array_datatypes}) { # array datatype
1302 push @all_bind, $self->_bindtype($k, $v);
1304 else { # literal SQL with bind
1305 my ($sql, @bind) = @$v;
1306 $self->_assert_bindval_matches_bindtype(@bind);
1307 push @all_bind, @bind;
1310 ARRAYREFREF => sub { # literal SQL with bind
1311 my ($sql, @bind) = @${$v};
1312 $self->_assert_bindval_matches_bindtype(@bind);
1313 push @all_bind, @bind;
1315 SCALARREF => sub { # literal SQL without bind
1317 SCALAR_or_UNDEF => sub {
1318 push @all_bind, $self->_bindtype($k, $v);
1329 my(@sql, @sqlq, @sqlv);
1333 if ($ref eq 'HASH') {
1334 for my $k (sort keys %$_) {
1337 my $label = $self->_quote($k);
1338 if ($r eq 'ARRAY') {
1339 # literal SQL with bind
1340 my ($sql, @bind) = @$v;
1341 $self->_assert_bindval_matches_bindtype(@bind);
1342 push @sqlq, "$label = $sql";
1344 } elsif ($r eq 'SCALAR') {
1345 # literal SQL without bind
1346 push @sqlq, "$label = $$v";
1348 push @sqlq, "$label = ?";
1349 push @sqlv, $self->_bindtype($k, $v);
1352 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1353 } elsif ($ref eq 'ARRAY') {
1354 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1357 if ($r eq 'ARRAY') { # literal SQL with bind
1358 my ($sql, @bind) = @$v;
1359 $self->_assert_bindval_matches_bindtype(@bind);
1362 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1363 # embedded literal SQL
1370 push @sql, '(' . join(', ', @sqlq) . ')';
1371 } elsif ($ref eq 'SCALAR') {
1375 # strings get case twiddled
1376 push @sql, $self->_sqlcase($_);
1380 my $sql = join ' ', @sql;
1382 # this is pretty tricky
1383 # if ask for an array, return ($stmt, @bind)
1384 # otherwise, s/?/shift @sqlv/ to put it inline
1386 return ($sql, @sqlv);
1388 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1389 ref $d ? $d->[1] : $d/e;
1398 # This allows us to check for a local, then _form, attr
1400 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1401 return $self->generate($name, @_);
1412 SQL::Abstract - Generate SQL from Perl data structures
1418 my $sql = SQL::Abstract->new;
1420 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1422 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1424 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1426 my($stmt, @bind) = $sql->delete($table, \%where);
1428 # Then, use these in your DBI statements
1429 my $sth = $dbh->prepare($stmt);
1430 $sth->execute(@bind);
1432 # Just generate the WHERE clause
1433 my($stmt, @bind) = $sql->where(\%where, \@order);
1435 # Return values in the same order, for hashed queries
1436 # See PERFORMANCE section for more details
1437 my @bind = $sql->values(\%fieldvals);
1441 This module was inspired by the excellent L<DBIx::Abstract>.
1442 However, in using that module I found that what I really wanted
1443 to do was generate SQL, but still retain complete control over my
1444 statement handles and use the DBI interface. So, I set out to
1445 create an abstract SQL generation module.
1447 While based on the concepts used by L<DBIx::Abstract>, there are
1448 several important differences, especially when it comes to WHERE
1449 clauses. I have modified the concepts used to make the SQL easier
1450 to generate from Perl data structures and, IMO, more intuitive.
1451 The underlying idea is for this module to do what you mean, based
1452 on the data structures you provide it. The big advantage is that
1453 you don't have to modify your code every time your data changes,
1454 as this module figures it out.
1456 To begin with, an SQL INSERT is as easy as just specifying a hash
1457 of C<key=value> pairs:
1460 name => 'Jimbo Bobson',
1461 phone => '123-456-7890',
1462 address => '42 Sister Lane',
1463 city => 'St. Louis',
1464 state => 'Louisiana',
1467 The SQL can then be generated with this:
1469 my($stmt, @bind) = $sql->insert('people', \%data);
1471 Which would give you something like this:
1473 $stmt = "INSERT INTO people
1474 (address, city, name, phone, state)
1475 VALUES (?, ?, ?, ?, ?)";
1476 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1477 '123-456-7890', 'Louisiana');
1479 These are then used directly in your DBI code:
1481 my $sth = $dbh->prepare($stmt);
1482 $sth->execute(@bind);
1484 =head2 Inserting and Updating Arrays
1486 If your database has array types (like for example Postgres),
1487 activate the special option C<< array_datatypes => 1 >>
1488 when creating the C<SQL::Abstract> object.
1489 Then you may use an arrayref to insert and update database array types:
1491 my $sql = SQL::Abstract->new(array_datatypes => 1);
1493 planets => [qw/Mercury Venus Earth Mars/]
1496 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1500 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1502 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1505 =head2 Inserting and Updating SQL
1507 In order to apply SQL functions to elements of your C<%data> you may
1508 specify a reference to an arrayref for the given hash value. For example,
1509 if you need to execute the Oracle C<to_date> function on a value, you can
1510 say something like this:
1514 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1517 The first value in the array is the actual SQL. Any other values are
1518 optional and would be included in the bind values array. This gives
1521 my($stmt, @bind) = $sql->insert('people', \%data);
1523 $stmt = "INSERT INTO people (name, date_entered)
1524 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1525 @bind = ('Bill', '03/02/2003');
1527 An UPDATE is just as easy, all you change is the name of the function:
1529 my($stmt, @bind) = $sql->update('people', \%data);
1531 Notice that your C<%data> isn't touched; the module will generate
1532 the appropriately quirky SQL for you automatically. Usually you'll
1533 want to specify a WHERE clause for your UPDATE, though, which is
1534 where handling C<%where> hashes comes in handy...
1536 =head2 Complex where statements
1538 This module can generate pretty complicated WHERE statements
1539 easily. For example, simple C<key=value> pairs are taken to mean
1540 equality, and if you want to see if a field is within a set
1541 of values, you can use an arrayref. Let's say we wanted to
1542 SELECT some data based on this criteria:
1545 requestor => 'inna',
1546 worker => ['nwiger', 'rcwe', 'sfz'],
1547 status => { '!=', 'completed' }
1550 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1552 The above would give you something like this:
1554 $stmt = "SELECT * FROM tickets WHERE
1555 ( requestor = ? ) AND ( status != ? )
1556 AND ( worker = ? OR worker = ? OR worker = ? )";
1557 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1559 Which you could then use in DBI code like so:
1561 my $sth = $dbh->prepare($stmt);
1562 $sth->execute(@bind);
1568 The functions are simple. There's one for each major SQL operation,
1569 and a constructor you use first. The arguments are specified in a
1570 similar order to each function (table, then fields, then a where
1571 clause) to try and simplify things.
1576 =head2 new(option => 'value')
1578 The C<new()> function takes a list of options and values, and returns
1579 a new B<SQL::Abstract> object which can then be used to generate SQL
1580 through the methods below. The options accepted are:
1586 If set to 'lower', then SQL will be generated in all lowercase. By
1587 default SQL is generated in "textbook" case meaning something like:
1589 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1591 Any setting other than 'lower' is ignored.
1595 This determines what the default comparison operator is. By default
1596 it is C<=>, meaning that a hash like this:
1598 %where = (name => 'nwiger', email => 'nate@wiger.org');
1600 Will generate SQL like this:
1602 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1604 However, you may want loose comparisons by default, so if you set
1605 C<cmp> to C<like> you would get SQL such as:
1607 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1609 You can also override the comparsion on an individual basis - see
1610 the huge section on L</"WHERE CLAUSES"> at the bottom.
1612 =item sqltrue, sqlfalse
1614 Expressions for inserting boolean values within SQL statements.
1615 By default these are C<1=1> and C<1=0>. They are used
1616 by the special operators C<-in> and C<-not_in> for generating
1617 correct SQL even when the argument is an empty array (see below).
1621 This determines the default logical operator for multiple WHERE
1622 statements in arrays or hashes. If absent, the default logic is "or"
1623 for arrays, and "and" for hashes. This means that a WHERE
1627 event_date => {'>=', '2/13/99'},
1628 event_date => {'<=', '4/24/03'},
1631 will generate SQL like this:
1633 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1635 This is probably not what you want given this query, though (look
1636 at the dates). To change the "OR" to an "AND", simply specify:
1638 my $sql = SQL::Abstract->new(logic => 'and');
1640 Which will change the above C<WHERE> to:
1642 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1644 The logic can also be changed locally by inserting
1645 a modifier in front of an arrayref :
1647 @where = (-and => [event_date => {'>=', '2/13/99'},
1648 event_date => {'<=', '4/24/03'} ]);
1650 See the L</"WHERE CLAUSES"> section for explanations.
1654 This will automatically convert comparisons using the specified SQL
1655 function for both column and value. This is mostly used with an argument
1656 of C<upper> or C<lower>, so that the SQL will have the effect of
1657 case-insensitive "searches". For example, this:
1659 $sql = SQL::Abstract->new(convert => 'upper');
1660 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1662 Will turn out the following SQL:
1664 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1666 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1667 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1668 not validate this option; it will just pass through what you specify verbatim).
1672 This is a kludge because many databases suck. For example, you can't
1673 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1674 Instead, you have to use C<bind_param()>:
1676 $sth->bind_param(1, 'reg data');
1677 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1679 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1680 which loses track of which field each slot refers to. Fear not.
1682 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1683 Currently, you can specify either C<normal> (default) or C<columns>. If you
1684 specify C<columns>, you will get an array that looks like this:
1686 my $sql = SQL::Abstract->new(bindtype => 'columns');
1687 my($stmt, @bind) = $sql->insert(...);
1690 [ 'column1', 'value1' ],
1691 [ 'column2', 'value2' ],
1692 [ 'column3', 'value3' ],
1695 You can then iterate through this manually, using DBI's C<bind_param()>.
1697 $sth->prepare($stmt);
1700 my($col, $data) = @$_;
1701 if ($col eq 'details' || $col eq 'comments') {
1702 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1703 } elsif ($col eq 'image') {
1704 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1706 $sth->bind_param($i, $data);
1710 $sth->execute; # execute without @bind now
1712 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1713 Basically, the advantage is still that you don't have to care which fields
1714 are or are not included. You could wrap that above C<for> loop in a simple
1715 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1716 get a layer of abstraction over manual SQL specification.
1718 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1719 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1720 will expect the bind values in this format.
1724 This is the character that a table or column name will be quoted
1725 with. By default this is an empty string, but you could set it to
1726 the character C<`>, to generate SQL like this:
1728 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1730 Alternatively, you can supply an array ref of two items, the first being the left
1731 hand quote character, and the second the right hand quote character. For
1732 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1733 that generates SQL like this:
1735 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1737 Quoting is useful if you have tables or columns names that are reserved
1738 words in your database's SQL dialect.
1742 This is the character that separates a table and column name. It is
1743 necessary to specify this when the C<quote_char> option is selected,
1744 so that tables and column names can be individually quoted like this:
1746 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1748 =item array_datatypes
1750 When this option is true, arrayrefs in INSERT or UPDATE are
1751 interpreted as array datatypes and are passed directly
1753 When this option is false, arrayrefs are interpreted
1754 as literal SQL, just like refs to arrayrefs
1755 (but this behavior is for backwards compatibility; when writing
1756 new queries, use the "reference to arrayref" syntax
1762 Takes a reference to a list of "special operators"
1763 to extend the syntax understood by L<SQL::Abstract>.
1764 See section L</"SPECIAL OPERATORS"> for details.
1768 Takes a reference to a list of "unary operators"
1769 to extend the syntax understood by L<SQL::Abstract>.
1770 See section L</"UNARY OPERATORS"> for details.
1776 =head2 insert($table, \@values || \%fieldvals, \%options)
1778 This is the simplest function. You simply give it a table name
1779 and either an arrayref of values or hashref of field/value pairs.
1780 It returns an SQL INSERT statement and a list of bind values.
1781 See the sections on L</"Inserting and Updating Arrays"> and
1782 L</"Inserting and Updating SQL"> for information on how to insert
1783 with those data types.
1785 The optional C<\%options> hash reference may contain additional
1786 options to generate the insert SQL. Currently supported options
1793 Takes either a scalar of raw SQL fields, or an array reference of
1794 field names, and adds on an SQL C<RETURNING> statement at the end.
1795 This allows you to return data generated by the insert statement
1796 (such as row IDs) without performing another C<SELECT> statement.
1797 Note, however, this is not part of the SQL standard and may not
1798 be supported by all database engines.
1802 =head2 update($table, \%fieldvals, \%where)
1804 This takes a table, hashref of field/value pairs, and an optional
1805 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1807 See the sections on L</"Inserting and Updating Arrays"> and
1808 L</"Inserting and Updating SQL"> for information on how to insert
1809 with those data types.
1811 =head2 select($source, $fields, $where, $order)
1813 This returns a SQL SELECT statement and associated list of bind values, as
1814 specified by the arguments :
1820 Specification of the 'FROM' part of the statement.
1821 The argument can be either a plain scalar (interpreted as a table
1822 name, will be quoted), or an arrayref (interpreted as a list
1823 of table names, joined by commas, quoted), or a scalarref
1824 (literal table name, not quoted), or a ref to an arrayref
1825 (list of literal table names, joined by commas, not quoted).
1829 Specification of the list of fields to retrieve from
1831 The argument can be either an arrayref (interpreted as a list
1832 of field names, will be joined by commas and quoted), or a
1833 plain scalar (literal SQL, not quoted).
1834 Please observe that this API is not as flexible as for
1835 the first argument C<$table>, for backwards compatibility reasons.
1839 Optional argument to specify the WHERE part of the query.
1840 The argument is most often a hashref, but can also be
1841 an arrayref or plain scalar --
1842 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1846 Optional argument to specify the ORDER BY part of the query.
1847 The argument can be a scalar, a hashref or an arrayref
1848 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1854 =head2 delete($table, \%where)
1856 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1857 It returns an SQL DELETE statement and list of bind values.
1859 =head2 where(\%where, \@order)
1861 This is used to generate just the WHERE clause. For example,
1862 if you have an arbitrary data structure and know what the
1863 rest of your SQL is going to look like, but want an easy way
1864 to produce a WHERE clause, use this. It returns an SQL WHERE
1865 clause and list of bind values.
1868 =head2 values(\%data)
1870 This just returns the values from the hash C<%data>, in the same
1871 order that would be returned from any of the other above queries.
1872 Using this allows you to markedly speed up your queries if you
1873 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1875 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1877 Warning: This is an experimental method and subject to change.
1879 This returns arbitrarily generated SQL. It's a really basic shortcut.
1880 It will return two different things, depending on return context:
1882 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1883 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1885 These would return the following:
1887 # First calling form
1888 $stmt = "CREATE TABLE test (?, ?)";
1889 @bind = (field1, field2);
1891 # Second calling form
1892 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1894 Depending on what you're trying to do, it's up to you to choose the correct
1895 format. In this example, the second form is what you would want.
1899 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1903 ALTER SESSION SET nls_date_format = 'MM/YY'
1905 You get the idea. Strings get their case twiddled, but everything
1906 else remains verbatim.
1911 =head1 WHERE CLAUSES
1915 This module uses a variation on the idea from L<DBIx::Abstract>. It
1916 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1917 module is that things in arrays are OR'ed, and things in hashes
1920 The easiest way to explain is to show lots of examples. After
1921 each C<%where> hash shown, it is assumed you used:
1923 my($stmt, @bind) = $sql->where(\%where);
1925 However, note that the C<%where> hash can be used directly in any
1926 of the other functions as well, as described above.
1928 =head2 Key-value pairs
1930 So, let's get started. To begin, a simple hash:
1934 status => 'completed'
1937 Is converted to SQL C<key = val> statements:
1939 $stmt = "WHERE user = ? AND status = ?";
1940 @bind = ('nwiger', 'completed');
1942 One common thing I end up doing is having a list of values that
1943 a field can be in. To do this, simply specify a list inside of
1948 status => ['assigned', 'in-progress', 'pending'];
1951 This simple code will create the following:
1953 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1954 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1956 A field associated to an empty arrayref will be considered a
1957 logical false and will generate 0=1.
1959 =head2 Tests for NULL values
1961 If the value part is C<undef> then this is converted to SQL <IS NULL>
1970 $stmt = "WHERE user = ? AND status IS NULL";
1973 =head2 Specific comparison operators
1975 If you want to specify a different type of operator for your comparison,
1976 you can use a hashref for a given column:
1980 status => { '!=', 'completed' }
1983 Which would generate:
1985 $stmt = "WHERE user = ? AND status != ?";
1986 @bind = ('nwiger', 'completed');
1988 To test against multiple values, just enclose the values in an arrayref:
1990 status => { '=', ['assigned', 'in-progress', 'pending'] };
1992 Which would give you:
1994 "WHERE status = ? OR status = ? OR status = ?"
1997 The hashref can also contain multiple pairs, in which case it is expanded
1998 into an C<AND> of its elements:
2002 status => { '!=', 'completed', -not_like => 'pending%' }
2005 # Or more dynamically, like from a form
2006 $where{user} = 'nwiger';
2007 $where{status}{'!='} = 'completed';
2008 $where{status}{'-not_like'} = 'pending%';
2010 # Both generate this
2011 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2012 @bind = ('nwiger', 'completed', 'pending%');
2015 To get an OR instead, you can combine it with the arrayref idea:
2019 priority => [ {'=', 2}, {'!=', 1} ]
2022 Which would generate:
2024 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
2025 @bind = ('nwiger', '2', '1');
2027 If you want to include literal SQL (with or without bind values), just use a
2028 scalar reference or array reference as the value:
2031 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2032 date_expires => { '<' => \"now()" }
2035 Which would generate:
2037 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2038 @bind = ('11/26/2008');
2041 =head2 Logic and nesting operators
2043 In the example above,
2044 there is a subtle trap if you want to say something like
2045 this (notice the C<AND>):
2047 WHERE priority != ? AND priority != ?
2049 Because, in Perl you I<can't> do this:
2051 priority => { '!=', 2, '!=', 1 }
2053 As the second C<!=> key will obliterate the first. The solution
2054 is to use the special C<-modifier> form inside an arrayref:
2056 priority => [ -and => {'!=', 2},
2060 Normally, these would be joined by C<OR>, but the modifier tells it
2061 to use C<AND> instead. (Hint: You can use this in conjunction with the
2062 C<logic> option to C<new()> in order to change the way your queries
2063 work by default.) B<Important:> Note that the C<-modifier> goes
2064 B<INSIDE> the arrayref, as an extra first element. This will
2065 B<NOT> do what you think it might:
2067 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2069 Here is a quick list of equivalencies, since there is some overlap:
2072 status => {'!=', 'completed', 'not like', 'pending%' }
2073 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2076 status => {'=', ['assigned', 'in-progress']}
2077 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2078 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2082 =head2 Special operators : IN, BETWEEN, etc.
2084 You can also use the hashref format to compare a list of fields using the
2085 C<IN> comparison operator, by specifying the list as an arrayref:
2088 status => 'completed',
2089 reportid => { -in => [567, 2335, 2] }
2092 Which would generate:
2094 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2095 @bind = ('completed', '567', '2335', '2');
2097 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2100 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2101 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2102 'sqltrue' (by default : C<1=1>).
2104 In addition to the array you can supply a chunk of literal sql or
2105 literal sql with bind:
2108 customer => { -in => \[
2109 'SELECT cust_id FROM cust WHERE balance > ?',
2112 status => { -in => \'SELECT status_codes FROM states' },
2118 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2119 AND status IN ( SELECT status_codes FROM states )
2125 Another pair of operators is C<-between> and C<-not_between>,
2126 used with an arrayref of two values:
2130 completion_date => {
2131 -not_between => ['2002-10-01', '2003-02-06']
2137 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2139 Just like with C<-in> all plausible combinations of literal SQL
2143 start0 => { -between => [ 1, 2 ] },
2144 start1 => { -between => \["? AND ?", 1, 2] },
2145 start2 => { -between => \"lower(x) AND upper(y)" },
2146 start3 => { -between => [
2148 \["upper(?)", 'stuff' ],
2155 ( start0 BETWEEN ? AND ? )
2156 AND ( start1 BETWEEN ? AND ? )
2157 AND ( start2 BETWEEN lower(x) AND upper(y) )
2158 AND ( start3 BETWEEN lower(x) AND upper(?) )
2160 @bind = (1, 2, 1, 2, 'stuff');
2163 These are the two builtin "special operators"; but the
2164 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2166 =head2 Unary operators: bool
2168 If you wish to test against boolean columns or functions within your
2169 database you can use the C<-bool> and C<-not_bool> operators. For
2170 example to test the column C<is_user> being true and the column
2171 C<is_enabled> being false you would use:-
2175 -not_bool => 'is_enabled',
2180 WHERE is_user AND NOT is_enabled
2182 If a more complex combination is required, testing more conditions,
2183 then you should use the and/or operators:-
2190 -not_bool => 'four',
2196 WHERE one AND two AND three AND NOT four
2199 =head2 Nested conditions, -and/-or prefixes
2201 So far, we've seen how multiple conditions are joined with a top-level
2202 C<AND>. We can change this by putting the different conditions we want in
2203 hashes and then putting those hashes in an array. For example:
2208 status => { -like => ['pending%', 'dispatched'] },
2212 status => 'unassigned',
2216 This data structure would create the following:
2218 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2219 OR ( user = ? AND status = ? ) )";
2220 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2223 There is also a special C<-nest>
2224 operator which adds an additional set of parens, to create a subquery.
2225 For example, to get something like this:
2227 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2228 @bind = ('nwiger', '20', 'ASIA');
2234 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2238 Finally, clauses in hashrefs or arrayrefs can be
2239 prefixed with an C<-and> or C<-or> to change the logic
2246 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2247 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2254 WHERE ( user = ? AND
2255 ( ( workhrs > ? AND geo = ? )
2256 OR ( workhrs < ? AND geo = ? ) ) )
2259 =head2 Algebraic inconsistency, for historical reasons
2261 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2262 operator goes C<outside> of the nested structure; whereas when connecting
2263 several constraints on one column, the C<-and> operator goes
2264 C<inside> the arrayref. Here is an example combining both features :
2267 -and => [a => 1, b => 2],
2268 -or => [c => 3, d => 4],
2269 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2274 WHERE ( ( ( a = ? AND b = ? )
2275 OR ( c = ? OR d = ? )
2276 OR ( e LIKE ? AND e LIKE ? ) ) )
2278 This difference in syntax is unfortunate but must be preserved for
2279 historical reasons. So be careful : the two examples below would
2280 seem algebraically equivalent, but they are not
2282 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2283 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2285 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2286 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2291 Finally, sometimes only literal SQL will do. If you want to include
2292 literal SQL verbatim, you can specify it as a scalar reference, namely:
2294 my $inn = 'is Not Null';
2296 priority => { '<', 2 },
2302 $stmt = "WHERE priority < ? AND requestor is Not Null";
2305 Note that in this example, you only get one bind parameter back, since
2306 the verbatim SQL is passed as part of the statement.
2308 Of course, just to prove a point, the above can also be accomplished
2312 priority => { '<', 2 },
2313 requestor => { '!=', undef },
2319 Conditions on boolean columns can be expressed in the same way, passing
2320 a reference to an empty string, however using liternal SQL in this way
2321 is deprecated - the preferred method is to use the boolean operators -
2322 see L</"Unary operators: bool"> :
2325 priority => { '<', 2 },
2331 $stmt = "WHERE priority < ? AND is_ready";
2334 Literal SQL is also the only way to compare 2 columns to one another:
2337 priority => { '<', 2 },
2338 requestor => \'= submittor'
2343 $stmt = "WHERE priority < ? AND requestor = submitter";
2346 =head2 Literal SQL with placeholders and bind values (subqueries)
2348 If the literal SQL to be inserted has placeholders and bind values,
2349 use a reference to an arrayref (yes this is a double reference --
2350 not so common, but perfectly legal Perl). For example, to find a date
2351 in Postgres you can use something like this:
2354 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2359 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2362 Note that you must pass the bind values in the same format as they are returned
2363 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2364 provide the bind values in the C<< [ column_meta => value ] >> format, where
2365 C<column_meta> is an opaque scalar value; most commonly the column name, but
2366 you can use any scalar value (including references and blessed references),
2367 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2368 to C<columns> the above example will look like:
2371 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2374 Literal SQL is especially useful for nesting parenthesized clauses in the
2375 main SQL query. Here is a first example :
2377 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2381 bar => \["IN ($sub_stmt)" => @sub_bind],
2386 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2387 WHERE c2 < ? AND c3 LIKE ?))";
2388 @bind = (1234, 100, "foo%");
2390 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2391 are expressed in the same way. Of course the C<$sub_stmt> and
2392 its associated bind values can be generated through a former call
2395 my ($sub_stmt, @sub_bind)
2396 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2397 c3 => {-like => "foo%"}});
2400 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2403 In the examples above, the subquery was used as an operator on a column;
2404 but the same principle also applies for a clause within the main C<%where>
2405 hash, like an EXISTS subquery :
2407 my ($sub_stmt, @sub_bind)
2408 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2411 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2416 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2417 WHERE c1 = ? AND c2 > t0.c0))";
2421 Observe that the condition on C<c2> in the subquery refers to
2422 column C<t0.c0> of the main query : this is I<not> a bind
2423 value, so we have to express it through a scalar ref.
2424 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2425 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2426 what we wanted here.
2428 Another use of the subquery technique is when some SQL clauses need
2429 parentheses, as it often occurs with some proprietary SQL extensions
2430 like for example fulltext expressions, geospatial expressions,
2431 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2434 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2437 Finally, here is an example where a subquery is used
2438 for expressing unary negation:
2440 my ($sub_stmt, @sub_bind)
2441 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2442 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2444 lname => {like => '%son%'},
2445 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2450 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2451 @bind = ('%son%', 10, 20)
2457 These pages could go on for a while, since the nesting of the data
2458 structures this module can handle are pretty much unlimited (the
2459 module implements the C<WHERE> expansion as a recursive function
2460 internally). Your best bet is to "play around" with the module a
2461 little to see how the data structures behave, and choose the best
2462 format for your data based on that.
2464 And of course, all the values above will probably be replaced with
2465 variables gotten from forms or the command line. After all, if you
2466 knew everything ahead of time, you wouldn't have to worry about
2467 dynamically-generating SQL and could just hardwire it into your
2473 =head1 ORDER BY CLAUSES
2475 Some functions take an order by clause. This can either be a scalar (just a
2476 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2477 or an array of either of the two previous forms. Examples:
2479 Given | Will Generate
2480 ----------------------------------------------------------
2482 \'colA DESC' | ORDER BY colA DESC
2484 'colA' | ORDER BY colA
2486 [qw/colA colB/] | ORDER BY colA, colB
2488 {-asc => 'colA'} | ORDER BY colA ASC
2490 {-desc => 'colB'} | ORDER BY colB DESC
2492 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2494 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2497 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2498 { -desc => [qw/colB/], | colC ASC, colD ASC
2499 { -asc => [qw/colC colD/],|
2501 ===========================================================
2505 =head1 SPECIAL OPERATORS
2507 my $sqlmaker = SQL::Abstract->new(special_ops => [
2511 my ($self, $field, $op, $arg) = @_;
2517 handler => 'method_name',
2521 A "special operator" is a SQL syntactic clause that can be
2522 applied to a field, instead of a usual binary operator.
2525 WHERE field IN (?, ?, ?)
2526 WHERE field BETWEEN ? AND ?
2527 WHERE MATCH(field) AGAINST (?, ?)
2529 Special operators IN and BETWEEN are fairly standard and therefore
2530 are builtin within C<SQL::Abstract> (as the overridable methods
2531 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2532 like the MATCH .. AGAINST example above which is specific to MySQL,
2533 you can write your own operator handlers - supply a C<special_ops>
2534 argument to the C<new> method. That argument takes an arrayref of
2535 operator definitions; each operator definition is a hashref with two
2542 the regular expression to match the operator
2546 Either a coderef or a plain scalar method name. In both cases
2547 the expected return is C<< ($sql, @bind) >>.
2549 When supplied with a method name, it is simply called on the
2550 L<SQL::Abstract/> object as:
2552 $self->$method_name ($field, $op, $arg)
2556 $op is the part that matched the handler regex
2557 $field is the LHS of the operator
2560 When supplied with a coderef, it is called as:
2562 $coderef->($self, $field, $op, $arg)
2567 For example, here is an implementation
2568 of the MATCH .. AGAINST syntax for MySQL
2570 my $sqlmaker = SQL::Abstract->new(special_ops => [
2572 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2573 {regex => qr/^match$/i,
2575 my ($self, $field, $op, $arg) = @_;
2576 $arg = [$arg] if not ref $arg;
2577 my $label = $self->_quote($field);
2578 my ($placeholder) = $self->_convert('?');
2579 my $placeholders = join ", ", (($placeholder) x @$arg);
2580 my $sql = $self->_sqlcase('match') . " ($label) "
2581 . $self->_sqlcase('against') . " ($placeholders) ";
2582 my @bind = $self->_bindtype($field, @$arg);
2583 return ($sql, @bind);
2590 =head1 UNARY OPERATORS
2592 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2596 my ($self, $op, $arg) = @_;
2602 handler => 'method_name',
2606 A "unary operator" is a SQL syntactic clause that can be
2607 applied to a field - the operator goes before the field
2609 You can write your own operator handlers - supply a C<unary_ops>
2610 argument to the C<new> method. That argument takes an arrayref of
2611 operator definitions; each operator definition is a hashref with two
2618 the regular expression to match the operator
2622 Either a coderef or a plain scalar method name. In both cases
2623 the expected return is C<< $sql >>.
2625 When supplied with a method name, it is simply called on the
2626 L<SQL::Abstract/> object as:
2628 $self->$method_name ($op, $arg)
2632 $op is the part that matched the handler regex
2633 $arg is the RHS or argument of the operator
2635 When supplied with a coderef, it is called as:
2637 $coderef->($self, $op, $arg)
2645 Thanks to some benchmarking by Mark Stosberg, it turns out that
2646 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2647 I must admit this wasn't an intentional design issue, but it's a
2648 byproduct of the fact that you get to control your C<DBI> handles
2651 To maximize performance, use a code snippet like the following:
2653 # prepare a statement handle using the first row
2654 # and then reuse it for the rest of the rows
2656 for my $href (@array_of_hashrefs) {
2657 $stmt ||= $sql->insert('table', $href);
2658 $sth ||= $dbh->prepare($stmt);
2659 $sth->execute($sql->values($href));
2662 The reason this works is because the keys in your C<$href> are sorted
2663 internally by B<SQL::Abstract>. Thus, as long as your data retains
2664 the same structure, you only have to generate the SQL the first time
2665 around. On subsequent queries, simply use the C<values> function provided
2666 by this module to return your values in the correct order.
2668 However this depends on the values having the same type - if, for
2669 example, the values of a where clause may either have values
2670 (resulting in sql of the form C<column = ?> with a single bind
2671 value), or alternatively the values might be C<undef> (resulting in
2672 sql of the form C<column IS NULL> with no bind value) then the
2673 caching technique suggested will not work.
2677 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2678 really like this part (I do, at least). Building up a complex query
2679 can be as simple as the following:
2683 use CGI::FormBuilder;
2686 my $form = CGI::FormBuilder->new(...);
2687 my $sql = SQL::Abstract->new;
2689 if ($form->submitted) {
2690 my $field = $form->field;
2691 my $id = delete $field->{id};
2692 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2695 Of course, you would still have to connect using C<DBI> to run the
2696 query, but the point is that if you make your form look like your
2697 table, the actual query script can be extremely simplistic.
2699 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2700 a fast interface to returning and formatting data. I frequently
2701 use these three modules together to write complex database query
2702 apps in under 50 lines.
2708 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
2710 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
2716 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2717 Great care has been taken to preserve the I<published> behavior
2718 documented in previous versions in the 1.* family; however,
2719 some features that were previously undocumented, or behaved
2720 differently from the documentation, had to be changed in order
2721 to clarify the semantics. Hence, client code that was relying
2722 on some dark areas of C<SQL::Abstract> v1.*
2723 B<might behave differently> in v1.50.
2725 The main changes are :
2731 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2735 support for the { operator => \"..." } construct (to embed literal SQL)
2739 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2743 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2747 defensive programming : check arguments
2751 fixed bug with global logic, which was previously implemented
2752 through global variables yielding side-effects. Prior versions would
2753 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2754 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2755 Now this is interpreted
2756 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2761 fixed semantics of _bindtype on array args
2765 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2766 we just avoid shifting arrays within that tree.
2770 dropped the C<_modlogic> function
2776 =head1 ACKNOWLEDGEMENTS
2778 There are a number of individuals that have really helped out with
2779 this module. Unfortunately, most of them submitted bugs via CPAN
2780 so I have no idea who they are! But the people I do know are:
2782 Ash Berlin (order_by hash term support)
2783 Matt Trout (DBIx::Class support)
2784 Mark Stosberg (benchmarking)
2785 Chas Owens (initial "IN" operator support)
2786 Philip Collins (per-field SQL functions)
2787 Eric Kolve (hashref "AND" support)
2788 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2789 Dan Kubb (support for "quote_char" and "name_sep")
2790 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2791 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2792 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2793 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2794 Oliver Charles (support for "RETURNING" after "INSERT")
2800 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2804 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2806 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2808 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2809 While not an official support venue, C<DBIx::Class> makes heavy use of
2810 C<SQL::Abstract>, and as such list members there are very familiar with
2811 how to create queries.
2815 This module is free software; you may copy this under the same
2816 terms as perl itself (either the GNU General Public License or
2817 the Artistic License)