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.71';
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, $self->_bindtype($k, $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),
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);
966 return $self->_sqlcase('null');
970 push @all_bind, @bind;
974 sprintf ('%s %s ( %s )',
977 join (', ', @all_sql)
979 $self->_bindtype($k, @all_bind),
982 else { # empty list : some databases won't understand "IN ()", so DWIM
983 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
988 SCALARREF => sub { # literal SQL
989 my $sql = $self->_open_outer_paren ($$vals);
990 return ("$label $op ( $sql )");
992 ARRAYREFREF => sub { # literal SQL with bind
993 my ($sql, @bind) = @$$vals;
994 $self->_assert_bindval_matches_bindtype(@bind);
995 $sql = $self->_open_outer_paren ($sql);
996 return ("$label $op ( $sql )", @bind);
1000 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1004 return ($sql, @bind);
1007 # Some databases (SQLite) treat col IN (1, 2) different from
1008 # col IN ( (1, 2) ). Use this to strip all outer parens while
1009 # adding them back in the corresponding method
1010 sub _open_outer_paren {
1011 my ($self, $sql) = @_;
1012 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1017 #======================================================================
1019 #======================================================================
1022 my ($self, $arg) = @_;
1025 for my $c ($self->_order_by_chunks ($arg) ) {
1026 $self->_SWITCH_refkind ($c, {
1027 SCALAR => sub { push @sql, $c },
1028 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1034 $self->_sqlcase(' order by'),
1040 return wantarray ? ($sql, @bind) : $sql;
1043 sub _order_by_chunks {
1044 my ($self, $arg) = @_;
1046 return $self->_SWITCH_refkind($arg, {
1049 map { $self->_order_by_chunks ($_ ) } @$arg;
1052 ARRAYREFREF => sub {
1053 my ($s, @b) = @$$arg;
1054 $self->_assert_bindval_matches_bindtype(@b);
1058 SCALAR => sub {$self->_quote($arg)},
1060 UNDEF => sub {return () },
1062 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1065 # get first pair in hash
1066 my ($key, $val, @rest) = %$arg;
1068 return () unless $key;
1070 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1071 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1077 for my $c ($self->_order_by_chunks ($val)) {
1080 $self->_SWITCH_refkind ($c, {
1085 ($sql, @bind) = @$c;
1089 $sql = $sql . ' ' . $self->_sqlcase($direction);
1091 push @ret, [ $sql, @bind];
1100 #======================================================================
1101 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1102 #======================================================================
1107 $self->_SWITCH_refkind($from, {
1108 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1109 SCALAR => sub {$self->_quote($from)},
1110 SCALARREF => sub {$$from},
1111 ARRAYREFREF => sub {join ', ', @$from;},
1116 #======================================================================
1118 #======================================================================
1120 # highly optimized, as it's called way too often
1122 # my ($self, $label) = @_;
1124 return '' unless defined $_[1];
1125 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1127 return $_[1] unless $_[0]->{quote_char};
1129 my $qref = ref $_[0]->{quote_char};
1132 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1134 elsif ($qref eq 'ARRAY') {
1135 ($l, $r) = @{$_[0]->{quote_char}};
1138 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1141 # parts containing * are naturally unquoted
1142 return join( $_[0]->{name_sep}||'', map
1143 { $_ eq '*' ? $_ : $l . $_ . $r }
1144 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1149 # Conversion, if applicable
1151 #my ($self, $arg) = @_;
1153 # LDNOTE : modified the previous implementation below because
1154 # it was not consistent : the first "return" is always an array,
1155 # the second "return" is context-dependent. Anyway, _convert
1156 # seems always used with just a single argument, so make it a
1158 # return @_ unless $self->{convert};
1159 # my $conv = $self->_sqlcase($self->{convert});
1160 # my @ret = map { $conv.'('.$_.')' } @_;
1161 # return wantarray ? @ret : $ret[0];
1162 if ($_[0]->{convert}) {
1163 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1170 #my ($self, $col, @vals) = @_;
1172 #LDNOTE : changed original implementation below because it did not make
1173 # sense when bindtype eq 'columns' and @vals > 1.
1174 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1176 # called often - tighten code
1177 return $_[0]->{bindtype} eq 'columns'
1178 ? map {[$_[1], $_]} @_[2 .. $#_]
1183 # Dies if any element of @bind is not in [colname => value] format
1184 # if bindtype is 'columns'.
1185 sub _assert_bindval_matches_bindtype {
1186 # my ($self, @bind) = @_;
1188 if ($self->{bindtype} eq 'columns') {
1190 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1191 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1197 sub _join_sql_clauses {
1198 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1200 if (@$clauses_aref > 1) {
1201 my $join = " " . $self->_sqlcase($logic) . " ";
1202 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1203 return ($sql, @$bind_aref);
1205 elsif (@$clauses_aref) {
1206 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1209 return (); # if no SQL, ignore @$bind_aref
1214 # Fix SQL case, if so requested
1216 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1217 # don't touch the argument ... crooked logic, but let's not change it!
1218 return $_[0]->{case} ? $_[1] : uc($_[1]);
1222 #======================================================================
1223 # DISPATCHING FROM REFKIND
1224 #======================================================================
1227 my ($self, $data) = @_;
1229 return 'UNDEF' unless defined $data;
1231 # blessed objects are treated like scalars
1232 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1234 return 'SCALAR' unless $ref;
1237 while ($ref eq 'REF') {
1239 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1243 return ($ref||'SCALAR') . ('REF' x $n_steps);
1247 my ($self, $data) = @_;
1248 my @try = ($self->_refkind($data));
1249 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1250 push @try, 'FALLBACK';
1254 sub _METHOD_FOR_refkind {
1255 my ($self, $meth_prefix, $data) = @_;
1258 for (@{$self->_try_refkind($data)}) {
1259 $method = $self->can($meth_prefix."_".$_)
1263 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1267 sub _SWITCH_refkind {
1268 my ($self, $data, $dispatch_table) = @_;
1271 for (@{$self->_try_refkind($data)}) {
1272 $coderef = $dispatch_table->{$_}
1276 puke "no dispatch entry for ".$self->_refkind($data)
1285 #======================================================================
1286 # VALUES, GENERATE, AUTOLOAD
1287 #======================================================================
1289 # LDNOTE: original code from nwiger, didn't touch code in that section
1290 # I feel the AUTOLOAD stuff should not be the default, it should
1291 # only be activated on explicit demand by user.
1295 my $data = shift || return;
1296 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1297 unless ref $data eq 'HASH';
1300 foreach my $k ( sort keys %$data ) {
1301 my $v = $data->{$k};
1302 $self->_SWITCH_refkind($v, {
1304 if ($self->{array_datatypes}) { # array datatype
1305 push @all_bind, $self->_bindtype($k, $v);
1307 else { # literal SQL with bind
1308 my ($sql, @bind) = @$v;
1309 $self->_assert_bindval_matches_bindtype(@bind);
1310 push @all_bind, @bind;
1313 ARRAYREFREF => sub { # literal SQL with bind
1314 my ($sql, @bind) = @${$v};
1315 $self->_assert_bindval_matches_bindtype(@bind);
1316 push @all_bind, @bind;
1318 SCALARREF => sub { # literal SQL without bind
1320 SCALAR_or_UNDEF => sub {
1321 push @all_bind, $self->_bindtype($k, $v);
1332 my(@sql, @sqlq, @sqlv);
1336 if ($ref eq 'HASH') {
1337 for my $k (sort keys %$_) {
1340 my $label = $self->_quote($k);
1341 if ($r eq 'ARRAY') {
1342 # literal SQL with bind
1343 my ($sql, @bind) = @$v;
1344 $self->_assert_bindval_matches_bindtype(@bind);
1345 push @sqlq, "$label = $sql";
1347 } elsif ($r eq 'SCALAR') {
1348 # literal SQL without bind
1349 push @sqlq, "$label = $$v";
1351 push @sqlq, "$label = ?";
1352 push @sqlv, $self->_bindtype($k, $v);
1355 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1356 } elsif ($ref eq 'ARRAY') {
1357 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1360 if ($r eq 'ARRAY') { # literal SQL with bind
1361 my ($sql, @bind) = @$v;
1362 $self->_assert_bindval_matches_bindtype(@bind);
1365 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1366 # embedded literal SQL
1373 push @sql, '(' . join(', ', @sqlq) . ')';
1374 } elsif ($ref eq 'SCALAR') {
1378 # strings get case twiddled
1379 push @sql, $self->_sqlcase($_);
1383 my $sql = join ' ', @sql;
1385 # this is pretty tricky
1386 # if ask for an array, return ($stmt, @bind)
1387 # otherwise, s/?/shift @sqlv/ to put it inline
1389 return ($sql, @sqlv);
1391 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1392 ref $d ? $d->[1] : $d/e;
1401 # This allows us to check for a local, then _form, attr
1403 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1404 return $self->generate($name, @_);
1415 SQL::Abstract - Generate SQL from Perl data structures
1421 my $sql = SQL::Abstract->new;
1423 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1425 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1427 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1429 my($stmt, @bind) = $sql->delete($table, \%where);
1431 # Then, use these in your DBI statements
1432 my $sth = $dbh->prepare($stmt);
1433 $sth->execute(@bind);
1435 # Just generate the WHERE clause
1436 my($stmt, @bind) = $sql->where(\%where, \@order);
1438 # Return values in the same order, for hashed queries
1439 # See PERFORMANCE section for more details
1440 my @bind = $sql->values(\%fieldvals);
1444 This module was inspired by the excellent L<DBIx::Abstract>.
1445 However, in using that module I found that what I really wanted
1446 to do was generate SQL, but still retain complete control over my
1447 statement handles and use the DBI interface. So, I set out to
1448 create an abstract SQL generation module.
1450 While based on the concepts used by L<DBIx::Abstract>, there are
1451 several important differences, especially when it comes to WHERE
1452 clauses. I have modified the concepts used to make the SQL easier
1453 to generate from Perl data structures and, IMO, more intuitive.
1454 The underlying idea is for this module to do what you mean, based
1455 on the data structures you provide it. The big advantage is that
1456 you don't have to modify your code every time your data changes,
1457 as this module figures it out.
1459 To begin with, an SQL INSERT is as easy as just specifying a hash
1460 of C<key=value> pairs:
1463 name => 'Jimbo Bobson',
1464 phone => '123-456-7890',
1465 address => '42 Sister Lane',
1466 city => 'St. Louis',
1467 state => 'Louisiana',
1470 The SQL can then be generated with this:
1472 my($stmt, @bind) = $sql->insert('people', \%data);
1474 Which would give you something like this:
1476 $stmt = "INSERT INTO people
1477 (address, city, name, phone, state)
1478 VALUES (?, ?, ?, ?, ?)";
1479 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1480 '123-456-7890', 'Louisiana');
1482 These are then used directly in your DBI code:
1484 my $sth = $dbh->prepare($stmt);
1485 $sth->execute(@bind);
1487 =head2 Inserting and Updating Arrays
1489 If your database has array types (like for example Postgres),
1490 activate the special option C<< array_datatypes => 1 >>
1491 when creating the C<SQL::Abstract> object.
1492 Then you may use an arrayref to insert and update database array types:
1494 my $sql = SQL::Abstract->new(array_datatypes => 1);
1496 planets => [qw/Mercury Venus Earth Mars/]
1499 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1503 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1505 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1508 =head2 Inserting and Updating SQL
1510 In order to apply SQL functions to elements of your C<%data> you may
1511 specify a reference to an arrayref for the given hash value. For example,
1512 if you need to execute the Oracle C<to_date> function on a value, you can
1513 say something like this:
1517 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1520 The first value in the array is the actual SQL. Any other values are
1521 optional and would be included in the bind values array. This gives
1524 my($stmt, @bind) = $sql->insert('people', \%data);
1526 $stmt = "INSERT INTO people (name, date_entered)
1527 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1528 @bind = ('Bill', '03/02/2003');
1530 An UPDATE is just as easy, all you change is the name of the function:
1532 my($stmt, @bind) = $sql->update('people', \%data);
1534 Notice that your C<%data> isn't touched; the module will generate
1535 the appropriately quirky SQL for you automatically. Usually you'll
1536 want to specify a WHERE clause for your UPDATE, though, which is
1537 where handling C<%where> hashes comes in handy...
1539 =head2 Complex where statements
1541 This module can generate pretty complicated WHERE statements
1542 easily. For example, simple C<key=value> pairs are taken to mean
1543 equality, and if you want to see if a field is within a set
1544 of values, you can use an arrayref. Let's say we wanted to
1545 SELECT some data based on this criteria:
1548 requestor => 'inna',
1549 worker => ['nwiger', 'rcwe', 'sfz'],
1550 status => { '!=', 'completed' }
1553 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1555 The above would give you something like this:
1557 $stmt = "SELECT * FROM tickets WHERE
1558 ( requestor = ? ) AND ( status != ? )
1559 AND ( worker = ? OR worker = ? OR worker = ? )";
1560 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1562 Which you could then use in DBI code like so:
1564 my $sth = $dbh->prepare($stmt);
1565 $sth->execute(@bind);
1571 The functions are simple. There's one for each major SQL operation,
1572 and a constructor you use first. The arguments are specified in a
1573 similar order to each function (table, then fields, then a where
1574 clause) to try and simplify things.
1579 =head2 new(option => 'value')
1581 The C<new()> function takes a list of options and values, and returns
1582 a new B<SQL::Abstract> object which can then be used to generate SQL
1583 through the methods below. The options accepted are:
1589 If set to 'lower', then SQL will be generated in all lowercase. By
1590 default SQL is generated in "textbook" case meaning something like:
1592 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1594 Any setting other than 'lower' is ignored.
1598 This determines what the default comparison operator is. By default
1599 it is C<=>, meaning that a hash like this:
1601 %where = (name => 'nwiger', email => 'nate@wiger.org');
1603 Will generate SQL like this:
1605 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1607 However, you may want loose comparisons by default, so if you set
1608 C<cmp> to C<like> you would get SQL such as:
1610 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1612 You can also override the comparsion on an individual basis - see
1613 the huge section on L</"WHERE CLAUSES"> at the bottom.
1615 =item sqltrue, sqlfalse
1617 Expressions for inserting boolean values within SQL statements.
1618 By default these are C<1=1> and C<1=0>. They are used
1619 by the special operators C<-in> and C<-not_in> for generating
1620 correct SQL even when the argument is an empty array (see below).
1624 This determines the default logical operator for multiple WHERE
1625 statements in arrays or hashes. If absent, the default logic is "or"
1626 for arrays, and "and" for hashes. This means that a WHERE
1630 event_date => {'>=', '2/13/99'},
1631 event_date => {'<=', '4/24/03'},
1634 will generate SQL like this:
1636 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1638 This is probably not what you want given this query, though (look
1639 at the dates). To change the "OR" to an "AND", simply specify:
1641 my $sql = SQL::Abstract->new(logic => 'and');
1643 Which will change the above C<WHERE> to:
1645 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1647 The logic can also be changed locally by inserting
1648 a modifier in front of an arrayref :
1650 @where = (-and => [event_date => {'>=', '2/13/99'},
1651 event_date => {'<=', '4/24/03'} ]);
1653 See the L</"WHERE CLAUSES"> section for explanations.
1657 This will automatically convert comparisons using the specified SQL
1658 function for both column and value. This is mostly used with an argument
1659 of C<upper> or C<lower>, so that the SQL will have the effect of
1660 case-insensitive "searches". For example, this:
1662 $sql = SQL::Abstract->new(convert => 'upper');
1663 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1665 Will turn out the following SQL:
1667 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1669 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1670 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1671 not validate this option; it will just pass through what you specify verbatim).
1675 This is a kludge because many databases suck. For example, you can't
1676 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1677 Instead, you have to use C<bind_param()>:
1679 $sth->bind_param(1, 'reg data');
1680 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1682 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1683 which loses track of which field each slot refers to. Fear not.
1685 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1686 Currently, you can specify either C<normal> (default) or C<columns>. If you
1687 specify C<columns>, you will get an array that looks like this:
1689 my $sql = SQL::Abstract->new(bindtype => 'columns');
1690 my($stmt, @bind) = $sql->insert(...);
1693 [ 'column1', 'value1' ],
1694 [ 'column2', 'value2' ],
1695 [ 'column3', 'value3' ],
1698 You can then iterate through this manually, using DBI's C<bind_param()>.
1700 $sth->prepare($stmt);
1703 my($col, $data) = @$_;
1704 if ($col eq 'details' || $col eq 'comments') {
1705 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1706 } elsif ($col eq 'image') {
1707 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1709 $sth->bind_param($i, $data);
1713 $sth->execute; # execute without @bind now
1715 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1716 Basically, the advantage is still that you don't have to care which fields
1717 are or are not included. You could wrap that above C<for> loop in a simple
1718 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1719 get a layer of abstraction over manual SQL specification.
1721 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1722 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1723 will expect the bind values in this format.
1727 This is the character that a table or column name will be quoted
1728 with. By default this is an empty string, but you could set it to
1729 the character C<`>, to generate SQL like this:
1731 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1733 Alternatively, you can supply an array ref of two items, the first being the left
1734 hand quote character, and the second the right hand quote character. For
1735 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1736 that generates SQL like this:
1738 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1740 Quoting is useful if you have tables or columns names that are reserved
1741 words in your database's SQL dialect.
1745 This is the character that separates a table and column name. It is
1746 necessary to specify this when the C<quote_char> option is selected,
1747 so that tables and column names can be individually quoted like this:
1749 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1751 =item array_datatypes
1753 When this option is true, arrayrefs in INSERT or UPDATE are
1754 interpreted as array datatypes and are passed directly
1756 When this option is false, arrayrefs are interpreted
1757 as literal SQL, just like refs to arrayrefs
1758 (but this behavior is for backwards compatibility; when writing
1759 new queries, use the "reference to arrayref" syntax
1765 Takes a reference to a list of "special operators"
1766 to extend the syntax understood by L<SQL::Abstract>.
1767 See section L</"SPECIAL OPERATORS"> for details.
1771 Takes a reference to a list of "unary operators"
1772 to extend the syntax understood by L<SQL::Abstract>.
1773 See section L</"UNARY OPERATORS"> for details.
1779 =head2 insert($table, \@values || \%fieldvals, \%options)
1781 This is the simplest function. You simply give it a table name
1782 and either an arrayref of values or hashref of field/value pairs.
1783 It returns an SQL INSERT statement and a list of bind values.
1784 See the sections on L</"Inserting and Updating Arrays"> and
1785 L</"Inserting and Updating SQL"> for information on how to insert
1786 with those data types.
1788 The optional C<\%options> hash reference may contain additional
1789 options to generate the insert SQL. Currently supported options
1796 Takes either a scalar of raw SQL fields, or an array reference of
1797 field names, and adds on an SQL C<RETURNING> statement at the end.
1798 This allows you to return data generated by the insert statement
1799 (such as row IDs) without performing another C<SELECT> statement.
1800 Note, however, this is not part of the SQL standard and may not
1801 be supported by all database engines.
1805 =head2 update($table, \%fieldvals, \%where)
1807 This takes a table, hashref of field/value pairs, and an optional
1808 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1810 See the sections on L</"Inserting and Updating Arrays"> and
1811 L</"Inserting and Updating SQL"> for information on how to insert
1812 with those data types.
1814 =head2 select($source, $fields, $where, $order)
1816 This returns a SQL SELECT statement and associated list of bind values, as
1817 specified by the arguments :
1823 Specification of the 'FROM' part of the statement.
1824 The argument can be either a plain scalar (interpreted as a table
1825 name, will be quoted), or an arrayref (interpreted as a list
1826 of table names, joined by commas, quoted), or a scalarref
1827 (literal table name, not quoted), or a ref to an arrayref
1828 (list of literal table names, joined by commas, not quoted).
1832 Specification of the list of fields to retrieve from
1834 The argument can be either an arrayref (interpreted as a list
1835 of field names, will be joined by commas and quoted), or a
1836 plain scalar (literal SQL, not quoted).
1837 Please observe that this API is not as flexible as for
1838 the first argument C<$table>, for backwards compatibility reasons.
1842 Optional argument to specify the WHERE part of the query.
1843 The argument is most often a hashref, but can also be
1844 an arrayref or plain scalar --
1845 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1849 Optional argument to specify the ORDER BY part of the query.
1850 The argument can be a scalar, a hashref or an arrayref
1851 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1857 =head2 delete($table, \%where)
1859 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1860 It returns an SQL DELETE statement and list of bind values.
1862 =head2 where(\%where, \@order)
1864 This is used to generate just the WHERE clause. For example,
1865 if you have an arbitrary data structure and know what the
1866 rest of your SQL is going to look like, but want an easy way
1867 to produce a WHERE clause, use this. It returns an SQL WHERE
1868 clause and list of bind values.
1871 =head2 values(\%data)
1873 This just returns the values from the hash C<%data>, in the same
1874 order that would be returned from any of the other above queries.
1875 Using this allows you to markedly speed up your queries if you
1876 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1878 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1880 Warning: This is an experimental method and subject to change.
1882 This returns arbitrarily generated SQL. It's a really basic shortcut.
1883 It will return two different things, depending on return context:
1885 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1886 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1888 These would return the following:
1890 # First calling form
1891 $stmt = "CREATE TABLE test (?, ?)";
1892 @bind = (field1, field2);
1894 # Second calling form
1895 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1897 Depending on what you're trying to do, it's up to you to choose the correct
1898 format. In this example, the second form is what you would want.
1902 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1906 ALTER SESSION SET nls_date_format = 'MM/YY'
1908 You get the idea. Strings get their case twiddled, but everything
1909 else remains verbatim.
1914 =head1 WHERE CLAUSES
1918 This module uses a variation on the idea from L<DBIx::Abstract>. It
1919 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1920 module is that things in arrays are OR'ed, and things in hashes
1923 The easiest way to explain is to show lots of examples. After
1924 each C<%where> hash shown, it is assumed you used:
1926 my($stmt, @bind) = $sql->where(\%where);
1928 However, note that the C<%where> hash can be used directly in any
1929 of the other functions as well, as described above.
1931 =head2 Key-value pairs
1933 So, let's get started. To begin, a simple hash:
1937 status => 'completed'
1940 Is converted to SQL C<key = val> statements:
1942 $stmt = "WHERE user = ? AND status = ?";
1943 @bind = ('nwiger', 'completed');
1945 One common thing I end up doing is having a list of values that
1946 a field can be in. To do this, simply specify a list inside of
1951 status => ['assigned', 'in-progress', 'pending'];
1954 This simple code will create the following:
1956 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1957 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1959 A field associated to an empty arrayref will be considered a
1960 logical false and will generate 0=1.
1962 =head2 Tests for NULL values
1964 If the value part is C<undef> then this is converted to SQL <IS NULL>
1973 $stmt = "WHERE user = ? AND status IS NULL";
1976 =head2 Specific comparison operators
1978 If you want to specify a different type of operator for your comparison,
1979 you can use a hashref for a given column:
1983 status => { '!=', 'completed' }
1986 Which would generate:
1988 $stmt = "WHERE user = ? AND status != ?";
1989 @bind = ('nwiger', 'completed');
1991 To test against multiple values, just enclose the values in an arrayref:
1993 status => { '=', ['assigned', 'in-progress', 'pending'] };
1995 Which would give you:
1997 "WHERE status = ? OR status = ? OR status = ?"
2000 The hashref can also contain multiple pairs, in which case it is expanded
2001 into an C<AND> of its elements:
2005 status => { '!=', 'completed', -not_like => 'pending%' }
2008 # Or more dynamically, like from a form
2009 $where{user} = 'nwiger';
2010 $where{status}{'!='} = 'completed';
2011 $where{status}{'-not_like'} = 'pending%';
2013 # Both generate this
2014 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2015 @bind = ('nwiger', 'completed', 'pending%');
2018 To get an OR instead, you can combine it with the arrayref idea:
2022 priority => [ {'=', 2}, {'!=', 1} ]
2025 Which would generate:
2027 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
2028 @bind = ('nwiger', '2', '1');
2030 If you want to include literal SQL (with or without bind values), just use a
2031 scalar reference or array reference as the value:
2034 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2035 date_expires => { '<' => \"now()" }
2038 Which would generate:
2040 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2041 @bind = ('11/26/2008');
2044 =head2 Logic and nesting operators
2046 In the example above,
2047 there is a subtle trap if you want to say something like
2048 this (notice the C<AND>):
2050 WHERE priority != ? AND priority != ?
2052 Because, in Perl you I<can't> do this:
2054 priority => { '!=', 2, '!=', 1 }
2056 As the second C<!=> key will obliterate the first. The solution
2057 is to use the special C<-modifier> form inside an arrayref:
2059 priority => [ -and => {'!=', 2},
2063 Normally, these would be joined by C<OR>, but the modifier tells it
2064 to use C<AND> instead. (Hint: You can use this in conjunction with the
2065 C<logic> option to C<new()> in order to change the way your queries
2066 work by default.) B<Important:> Note that the C<-modifier> goes
2067 B<INSIDE> the arrayref, as an extra first element. This will
2068 B<NOT> do what you think it might:
2070 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2072 Here is a quick list of equivalencies, since there is some overlap:
2075 status => {'!=', 'completed', 'not like', 'pending%' }
2076 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2079 status => {'=', ['assigned', 'in-progress']}
2080 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2081 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2085 =head2 Special operators : IN, BETWEEN, etc.
2087 You can also use the hashref format to compare a list of fields using the
2088 C<IN> comparison operator, by specifying the list as an arrayref:
2091 status => 'completed',
2092 reportid => { -in => [567, 2335, 2] }
2095 Which would generate:
2097 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2098 @bind = ('completed', '567', '2335', '2');
2100 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2103 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2104 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2105 'sqltrue' (by default : C<1=1>).
2107 In addition to the array you can supply a chunk of literal sql or
2108 literal sql with bind:
2111 customer => { -in => \[
2112 'SELECT cust_id FROM cust WHERE balance > ?',
2115 status => { -in => \'SELECT status_codes FROM states' },
2121 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2122 AND status IN ( SELECT status_codes FROM states )
2128 Another pair of operators is C<-between> and C<-not_between>,
2129 used with an arrayref of two values:
2133 completion_date => {
2134 -not_between => ['2002-10-01', '2003-02-06']
2140 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2142 Just like with C<-in> all plausible combinations of literal SQL
2146 start0 => { -between => [ 1, 2 ] },
2147 start1 => { -between => \["? AND ?", 1, 2] },
2148 start2 => { -between => \"lower(x) AND upper(y)" },
2149 start3 => { -between => [
2151 \["upper(?)", 'stuff' ],
2158 ( start0 BETWEEN ? AND ? )
2159 AND ( start1 BETWEEN ? AND ? )
2160 AND ( start2 BETWEEN lower(x) AND upper(y) )
2161 AND ( start3 BETWEEN lower(x) AND upper(?) )
2163 @bind = (1, 2, 1, 2, 'stuff');
2166 These are the two builtin "special operators"; but the
2167 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2169 =head2 Unary operators: bool
2171 If you wish to test against boolean columns or functions within your
2172 database you can use the C<-bool> and C<-not_bool> operators. For
2173 example to test the column C<is_user> being true and the column
2174 C<is_enabled> being false you would use:-
2178 -not_bool => 'is_enabled',
2183 WHERE is_user AND NOT is_enabled
2185 If a more complex combination is required, testing more conditions,
2186 then you should use the and/or operators:-
2193 -not_bool => 'four',
2199 WHERE one AND two AND three AND NOT four
2202 =head2 Nested conditions, -and/-or prefixes
2204 So far, we've seen how multiple conditions are joined with a top-level
2205 C<AND>. We can change this by putting the different conditions we want in
2206 hashes and then putting those hashes in an array. For example:
2211 status => { -like => ['pending%', 'dispatched'] },
2215 status => 'unassigned',
2219 This data structure would create the following:
2221 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2222 OR ( user = ? AND status = ? ) )";
2223 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2226 There is also a special C<-nest>
2227 operator which adds an additional set of parens, to create a subquery.
2228 For example, to get something like this:
2230 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2231 @bind = ('nwiger', '20', 'ASIA');
2237 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2241 Finally, clauses in hashrefs or arrayrefs can be
2242 prefixed with an C<-and> or C<-or> to change the logic
2249 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2250 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2257 WHERE ( user = ? AND
2258 ( ( workhrs > ? AND geo = ? )
2259 OR ( workhrs < ? AND geo = ? ) ) )
2262 =head2 Algebraic inconsistency, for historical reasons
2264 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2265 operator goes C<outside> of the nested structure; whereas when connecting
2266 several constraints on one column, the C<-and> operator goes
2267 C<inside> the arrayref. Here is an example combining both features :
2270 -and => [a => 1, b => 2],
2271 -or => [c => 3, d => 4],
2272 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2277 WHERE ( ( ( a = ? AND b = ? )
2278 OR ( c = ? OR d = ? )
2279 OR ( e LIKE ? AND e LIKE ? ) ) )
2281 This difference in syntax is unfortunate but must be preserved for
2282 historical reasons. So be careful : the two examples below would
2283 seem algebraically equivalent, but they are not
2285 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2286 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2288 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2289 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2294 Finally, sometimes only literal SQL will do. If you want to include
2295 literal SQL verbatim, you can specify it as a scalar reference, namely:
2297 my $inn = 'is Not Null';
2299 priority => { '<', 2 },
2305 $stmt = "WHERE priority < ? AND requestor is Not Null";
2308 Note that in this example, you only get one bind parameter back, since
2309 the verbatim SQL is passed as part of the statement.
2311 Of course, just to prove a point, the above can also be accomplished
2315 priority => { '<', 2 },
2316 requestor => { '!=', undef },
2322 Conditions on boolean columns can be expressed in the same way, passing
2323 a reference to an empty string, however using liternal SQL in this way
2324 is deprecated - the preferred method is to use the boolean operators -
2325 see L</"Unary operators: bool"> :
2328 priority => { '<', 2 },
2334 $stmt = "WHERE priority < ? AND is_ready";
2337 Literal SQL is also the only way to compare 2 columns to one another:
2340 priority => { '<', 2 },
2341 requestor => \'= submittor'
2346 $stmt = "WHERE priority < ? AND requestor = submitter";
2349 =head2 Literal SQL with placeholders and bind values (subqueries)
2351 If the literal SQL to be inserted has placeholders and bind values,
2352 use a reference to an arrayref (yes this is a double reference --
2353 not so common, but perfectly legal Perl). For example, to find a date
2354 in Postgres you can use something like this:
2357 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2362 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2365 Note that you must pass the bind values in the same format as they are returned
2366 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2367 provide the bind values in the C<< [ column_meta => value ] >> format, where
2368 C<column_meta> is an opaque scalar value; most commonly the column name, but
2369 you can use any scalar value (including references and blessed references),
2370 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2371 to C<columns> the above example will look like:
2374 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2377 Literal SQL is especially useful for nesting parenthesized clauses in the
2378 main SQL query. Here is a first example :
2380 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2384 bar => \["IN ($sub_stmt)" => @sub_bind],
2389 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2390 WHERE c2 < ? AND c3 LIKE ?))";
2391 @bind = (1234, 100, "foo%");
2393 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2394 are expressed in the same way. Of course the C<$sub_stmt> and
2395 its associated bind values can be generated through a former call
2398 my ($sub_stmt, @sub_bind)
2399 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2400 c3 => {-like => "foo%"}});
2403 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2406 In the examples above, the subquery was used as an operator on a column;
2407 but the same principle also applies for a clause within the main C<%where>
2408 hash, like an EXISTS subquery :
2410 my ($sub_stmt, @sub_bind)
2411 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2414 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2419 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2420 WHERE c1 = ? AND c2 > t0.c0))";
2424 Observe that the condition on C<c2> in the subquery refers to
2425 column C<t0.c0> of the main query : this is I<not> a bind
2426 value, so we have to express it through a scalar ref.
2427 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2428 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2429 what we wanted here.
2431 Another use of the subquery technique is when some SQL clauses need
2432 parentheses, as it often occurs with some proprietary SQL extensions
2433 like for example fulltext expressions, geospatial expressions,
2434 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2437 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2440 Finally, here is an example where a subquery is used
2441 for expressing unary negation:
2443 my ($sub_stmt, @sub_bind)
2444 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2445 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2447 lname => {like => '%son%'},
2448 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2453 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2454 @bind = ('%son%', 10, 20)
2460 These pages could go on for a while, since the nesting of the data
2461 structures this module can handle are pretty much unlimited (the
2462 module implements the C<WHERE> expansion as a recursive function
2463 internally). Your best bet is to "play around" with the module a
2464 little to see how the data structures behave, and choose the best
2465 format for your data based on that.
2467 And of course, all the values above will probably be replaced with
2468 variables gotten from forms or the command line. After all, if you
2469 knew everything ahead of time, you wouldn't have to worry about
2470 dynamically-generating SQL and could just hardwire it into your
2476 =head1 ORDER BY CLAUSES
2478 Some functions take an order by clause. This can either be a scalar (just a
2479 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2480 or an array of either of the two previous forms. Examples:
2482 Given | Will Generate
2483 ----------------------------------------------------------
2485 \'colA DESC' | ORDER BY colA DESC
2487 'colA' | ORDER BY colA
2489 [qw/colA colB/] | ORDER BY colA, colB
2491 {-asc => 'colA'} | ORDER BY colA ASC
2493 {-desc => 'colB'} | ORDER BY colB DESC
2495 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2497 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2500 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2501 { -desc => [qw/colB/], | colC ASC, colD ASC
2502 { -asc => [qw/colC colD/],|
2504 ===========================================================
2508 =head1 SPECIAL OPERATORS
2510 my $sqlmaker = SQL::Abstract->new(special_ops => [
2514 my ($self, $field, $op, $arg) = @_;
2520 handler => 'method_name',
2524 A "special operator" is a SQL syntactic clause that can be
2525 applied to a field, instead of a usual binary operator.
2528 WHERE field IN (?, ?, ?)
2529 WHERE field BETWEEN ? AND ?
2530 WHERE MATCH(field) AGAINST (?, ?)
2532 Special operators IN and BETWEEN are fairly standard and therefore
2533 are builtin within C<SQL::Abstract> (as the overridable methods
2534 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2535 like the MATCH .. AGAINST example above which is specific to MySQL,
2536 you can write your own operator handlers - supply a C<special_ops>
2537 argument to the C<new> method. That argument takes an arrayref of
2538 operator definitions; each operator definition is a hashref with two
2545 the regular expression to match the operator
2549 Either a coderef or a plain scalar method name. In both cases
2550 the expected return is C<< ($sql, @bind) >>.
2552 When supplied with a method name, it is simply called on the
2553 L<SQL::Abstract/> object as:
2555 $self->$method_name ($field, $op, $arg)
2559 $op is the part that matched the handler regex
2560 $field is the LHS of the operator
2563 When supplied with a coderef, it is called as:
2565 $coderef->($self, $field, $op, $arg)
2570 For example, here is an implementation
2571 of the MATCH .. AGAINST syntax for MySQL
2573 my $sqlmaker = SQL::Abstract->new(special_ops => [
2575 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2576 {regex => qr/^match$/i,
2578 my ($self, $field, $op, $arg) = @_;
2579 $arg = [$arg] if not ref $arg;
2580 my $label = $self->_quote($field);
2581 my ($placeholder) = $self->_convert('?');
2582 my $placeholders = join ", ", (($placeholder) x @$arg);
2583 my $sql = $self->_sqlcase('match') . " ($label) "
2584 . $self->_sqlcase('against') . " ($placeholders) ";
2585 my @bind = $self->_bindtype($field, @$arg);
2586 return ($sql, @bind);
2593 =head1 UNARY OPERATORS
2595 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2599 my ($self, $op, $arg) = @_;
2605 handler => 'method_name',
2609 A "unary operator" is a SQL syntactic clause that can be
2610 applied to a field - the operator goes before the field
2612 You can write your own operator handlers - supply a C<unary_ops>
2613 argument to the C<new> method. That argument takes an arrayref of
2614 operator definitions; each operator definition is a hashref with two
2621 the regular expression to match the operator
2625 Either a coderef or a plain scalar method name. In both cases
2626 the expected return is C<< $sql >>.
2628 When supplied with a method name, it is simply called on the
2629 L<SQL::Abstract/> object as:
2631 $self->$method_name ($op, $arg)
2635 $op is the part that matched the handler regex
2636 $arg is the RHS or argument of the operator
2638 When supplied with a coderef, it is called as:
2640 $coderef->($self, $op, $arg)
2648 Thanks to some benchmarking by Mark Stosberg, it turns out that
2649 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2650 I must admit this wasn't an intentional design issue, but it's a
2651 byproduct of the fact that you get to control your C<DBI> handles
2654 To maximize performance, use a code snippet like the following:
2656 # prepare a statement handle using the first row
2657 # and then reuse it for the rest of the rows
2659 for my $href (@array_of_hashrefs) {
2660 $stmt ||= $sql->insert('table', $href);
2661 $sth ||= $dbh->prepare($stmt);
2662 $sth->execute($sql->values($href));
2665 The reason this works is because the keys in your C<$href> are sorted
2666 internally by B<SQL::Abstract>. Thus, as long as your data retains
2667 the same structure, you only have to generate the SQL the first time
2668 around. On subsequent queries, simply use the C<values> function provided
2669 by this module to return your values in the correct order.
2671 However this depends on the values having the same type - if, for
2672 example, the values of a where clause may either have values
2673 (resulting in sql of the form C<column = ?> with a single bind
2674 value), or alternatively the values might be C<undef> (resulting in
2675 sql of the form C<column IS NULL> with no bind value) then the
2676 caching technique suggested will not work.
2680 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2681 really like this part (I do, at least). Building up a complex query
2682 can be as simple as the following:
2686 use CGI::FormBuilder;
2689 my $form = CGI::FormBuilder->new(...);
2690 my $sql = SQL::Abstract->new;
2692 if ($form->submitted) {
2693 my $field = $form->field;
2694 my $id = delete $field->{id};
2695 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2698 Of course, you would still have to connect using C<DBI> to run the
2699 query, but the point is that if you make your form look like your
2700 table, the actual query script can be extremely simplistic.
2702 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2703 a fast interface to returning and formatting data. I frequently
2704 use these three modules together to write complex database query
2705 apps in under 50 lines.
2711 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
2713 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
2719 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2720 Great care has been taken to preserve the I<published> behavior
2721 documented in previous versions in the 1.* family; however,
2722 some features that were previously undocumented, or behaved
2723 differently from the documentation, had to be changed in order
2724 to clarify the semantics. Hence, client code that was relying
2725 on some dark areas of C<SQL::Abstract> v1.*
2726 B<might behave differently> in v1.50.
2728 The main changes are :
2734 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2738 support for the { operator => \"..." } construct (to embed literal SQL)
2742 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2746 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2750 defensive programming : check arguments
2754 fixed bug with global logic, which was previously implemented
2755 through global variables yielding side-effects. Prior versions would
2756 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2757 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2758 Now this is interpreted
2759 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2764 fixed semantics of _bindtype on array args
2768 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2769 we just avoid shifting arrays within that tree.
2773 dropped the C<_modlogic> function
2779 =head1 ACKNOWLEDGEMENTS
2781 There are a number of individuals that have really helped out with
2782 this module. Unfortunately, most of them submitted bugs via CPAN
2783 so I have no idea who they are! But the people I do know are:
2785 Ash Berlin (order_by hash term support)
2786 Matt Trout (DBIx::Class support)
2787 Mark Stosberg (benchmarking)
2788 Chas Owens (initial "IN" operator support)
2789 Philip Collins (per-field SQL functions)
2790 Eric Kolve (hashref "AND" support)
2791 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2792 Dan Kubb (support for "quote_char" and "name_sep")
2793 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2794 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2795 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2796 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2797 Oliver Charles (support for "RETURNING" after "INSERT")
2803 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2807 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2809 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2811 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2812 While not an official support venue, C<DBIx::Class> makes heavy use of
2813 C<SQL::Abstract>, and as such list members there are very familiar with
2814 how to create queries.
2818 This module is free software; you may copy this under the same
2819 terms as perl itself (either the GNU General Public License or
2820 the Artistic License)