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.65_02';
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 )?between$/i, handler => '_where_field_BETWEEN'},
29 {regex => qr/^(not )?in$/i, 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";
284 SCALAR_or_UNDEF => sub {
285 push @set, "$label = ?";
286 push @all_bind, $self->_bindtype($k, $v);
292 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
296 my($where_sql, @where_bind) = $self->where($where);
298 push @all_bind, @where_bind;
301 return wantarray ? ($sql, @all_bind) : $sql;
307 #======================================================================
309 #======================================================================
314 my $table = $self->_table(shift);
315 my $fields = shift || '*';
319 my($where_sql, @bind) = $self->where($where, $order);
321 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
323 my $sql = join(' ', $self->_sqlcase('select'), $f,
324 $self->_sqlcase('from'), $table)
327 return wantarray ? ($sql, @bind) : $sql;
330 #======================================================================
332 #======================================================================
337 my $table = $self->_table(shift);
341 my($where_sql, @bind) = $self->where($where);
342 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
344 return wantarray ? ($sql, @bind) : $sql;
348 #======================================================================
350 #======================================================================
354 # Finally, a separate routine just to handle WHERE clauses
356 my ($self, $where, $order) = @_;
359 my ($sql, @bind) = $self->_recurse_where($where);
360 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
364 $sql .= $self->_order_by($order);
367 return wantarray ? ($sql, @bind) : $sql;
372 my ($self, $where, $logic) = @_;
374 # dispatch on appropriate method according to refkind of $where
375 my $method = $self->_METHOD_FOR_refkind("_where", $where);
377 my ($sql, @bind) = $self->$method($where, $logic);
379 # DBIx::Class directly calls _recurse_where in scalar context, so
380 # we must implement it, even if not in the official API
381 return wantarray ? ($sql, @bind) : $sql;
386 #======================================================================
387 # WHERE: top-level ARRAYREF
388 #======================================================================
391 sub _where_ARRAYREF {
392 my ($self, $where, $logic) = @_;
394 $logic = uc($logic || $self->{logic});
395 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
397 my @clauses = @$where;
399 my (@sql_clauses, @all_bind);
400 # need to use while() so can shift() for pairs
401 while (my $el = shift @clauses) {
403 # switch according to kind of $el and get corresponding ($sql, @bind)
404 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
406 # skip empty elements, otherwise get invalid trailing AND stuff
407 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
409 ARRAYREFREF => sub { @{${$el}} if @{${$el}}},
411 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
412 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
413 # side-effect: the first hashref within an array would change
414 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
415 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
416 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
418 SCALARREF => sub { ($$el); },
420 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
421 $self->_recurse_where({$el => shift(@clauses)})},
423 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
427 push @sql_clauses, $sql;
428 push @all_bind, @bind;
432 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
435 #======================================================================
436 # WHERE: top-level ARRAYREFREF
437 #======================================================================
439 sub _where_ARRAYREFREF {
440 my ($self, $where) = @_;
441 my ($sql, @bind) = @{${$where}};
443 return ($sql, @bind);
446 #======================================================================
447 # WHERE: top-level HASHREF
448 #======================================================================
451 my ($self, $where) = @_;
452 my (@sql_clauses, @all_bind);
454 for my $k (sort keys %$where) {
455 my $v = $where->{$k};
457 # ($k => $v) is either a special unary op or a regular hashpair
458 my ($sql, @bind) = do {
460 # put the operator in canonical form
462 $op =~ s/^-//; # remove initial dash
463 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
464 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
466 $self->_debug("Unary OP(-$op) within hashref, recursing...");
468 my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}};
469 if (my $handler = $op_entry->{handler}) {
470 if (not ref $handler) {
471 if ($op =~ s/\s?\d+$//) {
472 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
473 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
475 $self->$handler ($op, $v);
477 elsif (ref $handler eq 'CODE') {
478 $handler->($self, $op, $v);
481 puke "Illegal handler for operator $k - expecting a method name or a coderef";
485 $self->debug("Generic unary OP: $k - recursing as function");
486 my ($sql, @bind) = $self->_where_func_generic ($op, $v);
487 $sql = "($sql)" unless $self->{_nested_func_lhs} eq $k; # top level vs nested
492 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
493 $self->$method($k, $v);
497 push @sql_clauses, $sql;
498 push @all_bind, @bind;
501 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
504 sub _where_func_generic {
505 my ($self, $op, $rhs) = @_;
507 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
509 puke "Illegal use of top-level '$op'"
510 unless $self->{_nested_func_lhs};
513 $self->_convert('?'),
514 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
518 $self->_recurse_where ($rhs)
522 $sql = sprintf ('%s %s',
523 $self->_sqlcase($op),
527 return ($sql, @bind);
530 sub _where_op_ANDOR {
531 my ($self, $op, $v) = @_;
533 $self->_SWITCH_refkind($v, {
535 return $self->_where_ARRAYREF($v, $op);
539 return ( $op =~ /^or/i )
540 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
541 : $self->_where_HASHREF($v);
545 puke "-$op => \\\$scalar not supported, use -nest => ...";
549 puke "-$op => \\[..] not supported, use -nest => ...";
552 SCALAR => sub { # permissively interpreted as SQL
553 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
557 puke "-$op => undef not supported";
563 my ($self, $op, $v) = @_;
565 $self->_SWITCH_refkind($v, {
567 SCALAR => sub { # permissively interpreted as SQL
568 belch "literal SQL should be -nest => \\'scalar' "
569 . "instead of -nest => 'scalar' ";
574 puke "-$op => undef not supported";
578 $self->_recurse_where ($v);
586 my ($self, $op, $v) = @_;
588 my ( $prefix, $suffix ) = ( $op =~ /\bnot\b/i )
592 my ($sql, @bind) = do {
593 $self->_SWITCH_refkind($v, {
594 SCALAR => sub { # interpreted as SQL column
595 $self->_convert($self->_quote($v));
599 puke "-$op => undef not supported";
603 $self->_recurse_where ($v);
609 join ('', $prefix, $sql, $suffix),
615 sub _where_hashpair_ARRAYREF {
616 my ($self, $k, $v) = @_;
619 my @v = @$v; # need copy because of shift below
620 $self->_debug("ARRAY($k) means distribute over elements");
622 # put apart first element if it is an operator (-and, -or)
624 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
628 my @distributed = map { {$k => $_} } @v;
631 $self->_debug("OP($op) reinjected into the distributed array");
632 unshift @distributed, $op;
635 my $logic = $op ? substr($op, 1) : '';
637 return $self->_recurse_where(\@distributed, $logic);
640 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
641 $self->_debug("empty ARRAY($k) means 0=1");
642 return ($self->{sqlfalse});
646 sub _where_hashpair_HASHREF {
647 my ($self, $k, $v, $logic) = @_;
650 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
652 my ($all_sql, @all_bind);
654 for my $orig_op (sort keys %$v) {
655 my $val = $v->{$orig_op};
657 # put the operator in canonical form
659 $op =~ s/^-//; # remove initial dash
660 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
661 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
665 # CASE: col-value logic modifiers
666 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
667 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
669 # CASE: special operators like -in or -between
670 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
671 my $handler = $special_op->{handler};
673 puke "No handler supplied for special operator $orig_op";
675 elsif (not ref $handler) {
676 ($sql, @bind) = $self->$handler ($k, $op, $val);
678 elsif (ref $handler eq 'CODE') {
679 ($sql, @bind) = $handler->($self, $k, $op, $val);
682 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
686 $self->_SWITCH_refkind($val, {
688 ARRAYREF => sub { # CASE: col => {op => \@vals}
689 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
692 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
693 my ($sub_sql, @sub_bind) = @$$val;
694 $self->_assert_bindval_matches_bindtype(@sub_bind);
695 $sql = join ' ', $self->_convert($self->_quote($k)),
696 $self->_sqlcase($op),
701 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
702 my $is = ($op =~ $self->{equality_op}) ? 'is' :
703 ($op =~ $self->{inequality_op}) ? 'is not' :
704 puke "unexpected operator '$orig_op' with undef operand";
705 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
708 FALLBACK => sub { # CASE: col => {op/func => $stuff}
710 # retain for proper column type bind
711 $self->{_nested_func_lhs} ||= $k;
713 ($sql, @bind) = $self->_where_func_generic ($op, $val);
716 $self->_convert($self->_quote($k)),
717 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
723 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
724 push @all_bind, @bind;
726 return ($all_sql, @all_bind);
731 sub _where_field_op_ARRAYREF {
732 my ($self, $k, $op, $vals) = @_;
734 my @vals = @$vals; #always work on a copy
737 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
739 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
742 # see if the first element is an -and/-or op
744 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
749 # distribute $op over each remaining member of @vals, append logic if exists
750 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
752 # LDNOTE : had planned to change the distribution logic when
753 # $op =~ $self->{inequality_op}, because of Morgan laws :
754 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
755 # WHERE field != 22 OR field != 33 : the user probably means
756 # WHERE field != 22 AND field != 33.
757 # To do this, replace the above to roughly :
758 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
759 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
763 # try to DWIM on equality operators
764 # LDNOTE : not 100% sure this is the correct thing to do ...
765 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
766 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
769 puke "operator '$op' applied on an empty array (field '$k')";
774 sub _where_hashpair_SCALARREF {
775 my ($self, $k, $v) = @_;
776 $self->_debug("SCALAR($k) means literal SQL: $$v");
777 my $sql = $self->_quote($k) . " " . $$v;
781 # literal SQL with bind
782 sub _where_hashpair_ARRAYREFREF {
783 my ($self, $k, $v) = @_;
784 $self->_debug("REF($k) means literal SQL: @${$v}");
785 my ($sql, @bind) = @${$v};
786 $self->_assert_bindval_matches_bindtype(@bind);
787 $sql = $self->_quote($k) . " " . $sql;
788 return ($sql, @bind );
791 # literal SQL without bind
792 sub _where_hashpair_SCALAR {
793 my ($self, $k, $v) = @_;
794 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
795 my $sql = join ' ', $self->_convert($self->_quote($k)),
796 $self->_sqlcase($self->{cmp}),
797 $self->_convert('?');
798 my @bind = $self->_bindtype($k, $v);
799 return ( $sql, @bind);
803 sub _where_hashpair_UNDEF {
804 my ($self, $k, $v) = @_;
805 $self->_debug("UNDEF($k) means IS NULL");
806 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
810 #======================================================================
811 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
812 #======================================================================
815 sub _where_SCALARREF {
816 my ($self, $where) = @_;
819 $self->_debug("SCALAR(*top) means literal SQL: $$where");
825 my ($self, $where) = @_;
828 $self->_debug("NOREF(*top) means literal SQL: $where");
839 #======================================================================
840 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
841 #======================================================================
844 sub _where_field_BETWEEN {
845 my ($self, $k, $op, $vals) = @_;
847 my ($label, $and, $placeholder);
848 $label = $self->_convert($self->_quote($k));
849 $and = ' ' . $self->_sqlcase('and') . ' ';
850 $placeholder = $self->_convert('?');
851 $op = $self->_sqlcase($op);
853 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
861 puke "special op 'between' accepts an arrayref with exactly two values"
864 my (@all_sql, @all_bind);
865 foreach my $val (@$vals) {
866 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
868 return ($placeholder, ($val));
871 return ($self->_convert($$val), ());
874 my ($sql, @bind) = @$$val;
875 return ($self->_convert($sql), @bind);
879 push @all_bind, @bind;
883 (join $and, @all_sql),
884 $self->_bindtype($k, @all_bind),
888 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
892 my $sql = "( $label $op $clause )";
897 sub _where_field_IN {
898 my ($self, $k, $op, $vals) = @_;
900 # backwards compatibility : if scalar, force into an arrayref
901 $vals = [$vals] if defined $vals && ! ref $vals;
903 my ($label) = $self->_convert($self->_quote($k));
904 my ($placeholder) = $self->_convert('?');
905 $op = $self->_sqlcase($op);
907 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
908 ARRAYREF => sub { # list of choices
909 if (@$vals) { # nonempty list
910 my $placeholders = join ", ", (($placeholder) x @$vals);
911 my $sql = "$label $op ( $placeholders )";
912 my @bind = $self->_bindtype($k, @$vals);
914 return ($sql, @bind);
916 else { # empty list : some databases won't understand "IN ()", so DWIM
917 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
922 SCALARREF => sub { # literal SQL
923 my $sql = $self->_open_outer_paren ($$vals);
924 return ("$label $op ( $sql )");
926 ARRAYREFREF => sub { # literal SQL with bind
927 my ($sql, @bind) = @$$vals;
928 $self->_assert_bindval_matches_bindtype(@bind);
929 $sql = $self->_open_outer_paren ($sql);
930 return ("$label $op ( $sql )", @bind);
934 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
938 return ($sql, @bind);
941 # Some databases (SQLite) treat col IN (1, 2) different from
942 # col IN ( (1, 2) ). Use this to strip all outer parens while
943 # adding them back in the corresponding method
944 sub _open_outer_paren {
945 my ($self, $sql) = @_;
946 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
951 #======================================================================
953 #======================================================================
956 my ($self, $arg) = @_;
959 for my $c ($self->_order_by_chunks ($arg) ) {
960 $self->_SWITCH_refkind ($c, {
961 SCALAR => sub { push @sql, $c },
962 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
968 $self->_sqlcase(' order by'),
974 return wantarray ? ($sql, @bind) : $sql;
977 sub _order_by_chunks {
978 my ($self, $arg) = @_;
980 return $self->_SWITCH_refkind($arg, {
983 map { $self->_order_by_chunks ($_ ) } @$arg;
986 ARRAYREFREF => sub { [ @$$arg ] },
988 SCALAR => sub {$self->_quote($arg)},
990 UNDEF => sub {return () },
992 SCALARREF => sub {$$arg}, # literal SQL, no quoting
995 # get first pair in hash
996 my ($key, $val) = each %$arg;
998 return () unless $key;
1000 if ( (keys %$arg) > 1 or not $key =~ /^-(desc|asc)/i ) {
1001 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1007 for my $c ($self->_order_by_chunks ($val)) {
1010 $self->_SWITCH_refkind ($c, {
1015 ($sql, @bind) = @$c;
1019 $sql = $sql . ' ' . $self->_sqlcase($direction);
1021 push @ret, [ $sql, @bind];
1030 #======================================================================
1031 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1032 #======================================================================
1037 $self->_SWITCH_refkind($from, {
1038 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1039 SCALAR => sub {$self->_quote($from)},
1040 SCALARREF => sub {$$from},
1041 ARRAYREFREF => sub {join ', ', @$from;},
1046 #======================================================================
1048 #======================================================================
1050 # highly optimized, as it's called way too often
1052 # my ($self, $label) = @_;
1054 return '' unless defined $_[1];
1055 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1057 return $_[1] unless $_[0]->{quote_char};
1059 my $qref = ref $_[0]->{quote_char};
1062 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1064 elsif ($qref eq 'ARRAY') {
1065 ($l, $r) = @{$_[0]->{quote_char}};
1068 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1071 # parts containing * are naturally unquoted
1072 return join( $_[0]->{name_sep}||'', map
1073 { $_ eq '*' ? $_ : $l . $_ . $r }
1074 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1079 # Conversion, if applicable
1081 #my ($self, $arg) = @_;
1083 # LDNOTE : modified the previous implementation below because
1084 # it was not consistent : the first "return" is always an array,
1085 # the second "return" is context-dependent. Anyway, _convert
1086 # seems always used with just a single argument, so make it a
1088 # return @_ unless $self->{convert};
1089 # my $conv = $self->_sqlcase($self->{convert});
1090 # my @ret = map { $conv.'('.$_.')' } @_;
1091 # return wantarray ? @ret : $ret[0];
1092 if ($_[0]->{convert}) {
1093 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1100 #my ($self, $col, @vals) = @_;
1102 #LDNOTE : changed original implementation below because it did not make
1103 # sense when bindtype eq 'columns' and @vals > 1.
1104 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1106 # called often - tighten code
1107 return $_[0]->{bindtype} eq 'columns'
1108 ? map {[$_[1], $_]} @_[2 .. $#_]
1113 # Dies if any element of @bind is not in [colname => value] format
1114 # if bindtype is 'columns'.
1115 sub _assert_bindval_matches_bindtype {
1116 my ($self, @bind) = @_;
1118 if ($self->{bindtype} eq 'columns') {
1119 foreach my $val (@bind) {
1120 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1121 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1127 sub _join_sql_clauses {
1128 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1130 if (@$clauses_aref > 1) {
1131 my $join = " " . $self->_sqlcase($logic) . " ";
1132 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1133 return ($sql, @$bind_aref);
1135 elsif (@$clauses_aref) {
1136 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1139 return (); # if no SQL, ignore @$bind_aref
1144 # Fix SQL case, if so requested
1146 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1147 # don't touch the argument ... crooked logic, but let's not change it!
1148 return $_[0]->{case} ? $_[1] : uc($_[1]);
1152 #======================================================================
1153 # DISPATCHING FROM REFKIND
1154 #======================================================================
1157 my ($self, $data) = @_;
1159 return 'UNDEF' unless defined $data;
1161 # blessed objects are treated like scalars
1162 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1164 return 'SCALAR' unless $ref;
1167 while ($ref eq 'REF') {
1169 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1173 return $ref . ('REF' x $n_steps);
1177 my ($self, $data) = @_;
1178 my @try = ($self->_refkind($data));
1179 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1180 push @try, 'FALLBACK';
1184 sub _METHOD_FOR_refkind {
1185 my ($self, $meth_prefix, $data) = @_;
1188 for (@{$self->_try_refkind($data)}) {
1189 $method = $self->can($meth_prefix."_".$_)
1193 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1197 sub _SWITCH_refkind {
1198 my ($self, $data, $dispatch_table) = @_;
1201 for (@{$self->_try_refkind($data)}) {
1202 $coderef = $dispatch_table->{$_}
1206 puke "no dispatch entry for ".$self->_refkind($data)
1215 #======================================================================
1216 # VALUES, GENERATE, AUTOLOAD
1217 #======================================================================
1219 # LDNOTE: original code from nwiger, didn't touch code in that section
1220 # I feel the AUTOLOAD stuff should not be the default, it should
1221 # only be activated on explicit demand by user.
1225 my $data = shift || return;
1226 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1227 unless ref $data eq 'HASH';
1230 foreach my $k ( sort keys %$data ) {
1231 my $v = $data->{$k};
1232 $self->_SWITCH_refkind($v, {
1234 if ($self->{array_datatypes}) { # array datatype
1235 push @all_bind, $self->_bindtype($k, $v);
1237 else { # literal SQL with bind
1238 my ($sql, @bind) = @$v;
1239 $self->_assert_bindval_matches_bindtype(@bind);
1240 push @all_bind, @bind;
1243 ARRAYREFREF => sub { # literal SQL with bind
1244 my ($sql, @bind) = @${$v};
1245 $self->_assert_bindval_matches_bindtype(@bind);
1246 push @all_bind, @bind;
1248 SCALARREF => sub { # literal SQL without bind
1250 SCALAR_or_UNDEF => sub {
1251 push @all_bind, $self->_bindtype($k, $v);
1262 my(@sql, @sqlq, @sqlv);
1266 if ($ref eq 'HASH') {
1267 for my $k (sort keys %$_) {
1270 my $label = $self->_quote($k);
1271 if ($r eq 'ARRAY') {
1272 # literal SQL with bind
1273 my ($sql, @bind) = @$v;
1274 $self->_assert_bindval_matches_bindtype(@bind);
1275 push @sqlq, "$label = $sql";
1277 } elsif ($r eq 'SCALAR') {
1278 # literal SQL without bind
1279 push @sqlq, "$label = $$v";
1281 push @sqlq, "$label = ?";
1282 push @sqlv, $self->_bindtype($k, $v);
1285 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1286 } elsif ($ref eq 'ARRAY') {
1287 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1290 if ($r eq 'ARRAY') { # literal SQL with bind
1291 my ($sql, @bind) = @$v;
1292 $self->_assert_bindval_matches_bindtype(@bind);
1295 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1296 # embedded literal SQL
1303 push @sql, '(' . join(', ', @sqlq) . ')';
1304 } elsif ($ref eq 'SCALAR') {
1308 # strings get case twiddled
1309 push @sql, $self->_sqlcase($_);
1313 my $sql = join ' ', @sql;
1315 # this is pretty tricky
1316 # if ask for an array, return ($stmt, @bind)
1317 # otherwise, s/?/shift @sqlv/ to put it inline
1319 return ($sql, @sqlv);
1321 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1322 ref $d ? $d->[1] : $d/e;
1331 # This allows us to check for a local, then _form, attr
1333 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1334 return $self->generate($name, @_);
1345 SQL::Abstract - Generate SQL from Perl data structures
1351 my $sql = SQL::Abstract->new;
1353 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1355 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1357 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1359 my($stmt, @bind) = $sql->delete($table, \%where);
1361 # Then, use these in your DBI statements
1362 my $sth = $dbh->prepare($stmt);
1363 $sth->execute(@bind);
1365 # Just generate the WHERE clause
1366 my($stmt, @bind) = $sql->where(\%where, \@order);
1368 # Return values in the same order, for hashed queries
1369 # See PERFORMANCE section for more details
1370 my @bind = $sql->values(\%fieldvals);
1374 This module was inspired by the excellent L<DBIx::Abstract>.
1375 However, in using that module I found that what I really wanted
1376 to do was generate SQL, but still retain complete control over my
1377 statement handles and use the DBI interface. So, I set out to
1378 create an abstract SQL generation module.
1380 While based on the concepts used by L<DBIx::Abstract>, there are
1381 several important differences, especially when it comes to WHERE
1382 clauses. I have modified the concepts used to make the SQL easier
1383 to generate from Perl data structures and, IMO, more intuitive.
1384 The underlying idea is for this module to do what you mean, based
1385 on the data structures you provide it. The big advantage is that
1386 you don't have to modify your code every time your data changes,
1387 as this module figures it out.
1389 To begin with, an SQL INSERT is as easy as just specifying a hash
1390 of C<key=value> pairs:
1393 name => 'Jimbo Bobson',
1394 phone => '123-456-7890',
1395 address => '42 Sister Lane',
1396 city => 'St. Louis',
1397 state => 'Louisiana',
1400 The SQL can then be generated with this:
1402 my($stmt, @bind) = $sql->insert('people', \%data);
1404 Which would give you something like this:
1406 $stmt = "INSERT INTO people
1407 (address, city, name, phone, state)
1408 VALUES (?, ?, ?, ?, ?)";
1409 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1410 '123-456-7890', 'Louisiana');
1412 These are then used directly in your DBI code:
1414 my $sth = $dbh->prepare($stmt);
1415 $sth->execute(@bind);
1417 =head2 Inserting and Updating Arrays
1419 If your database has array types (like for example Postgres),
1420 activate the special option C<< array_datatypes => 1 >>
1421 when creating the C<SQL::Abstract> object.
1422 Then you may use an arrayref to insert and update database array types:
1424 my $sql = SQL::Abstract->new(array_datatypes => 1);
1426 planets => [qw/Mercury Venus Earth Mars/]
1429 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1433 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1435 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1438 =head2 Inserting and Updating SQL
1440 In order to apply SQL functions to elements of your C<%data> you may
1441 specify a reference to an arrayref for the given hash value. For example,
1442 if you need to execute the Oracle C<to_date> function on a value, you can
1443 say something like this:
1447 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1450 The first value in the array is the actual SQL. Any other values are
1451 optional and would be included in the bind values array. This gives
1454 my($stmt, @bind) = $sql->insert('people', \%data);
1456 $stmt = "INSERT INTO people (name, date_entered)
1457 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1458 @bind = ('Bill', '03/02/2003');
1460 An UPDATE is just as easy, all you change is the name of the function:
1462 my($stmt, @bind) = $sql->update('people', \%data);
1464 Notice that your C<%data> isn't touched; the module will generate
1465 the appropriately quirky SQL for you automatically. Usually you'll
1466 want to specify a WHERE clause for your UPDATE, though, which is
1467 where handling C<%where> hashes comes in handy...
1469 =head2 Complex where statements
1471 This module can generate pretty complicated WHERE statements
1472 easily. For example, simple C<key=value> pairs are taken to mean
1473 equality, and if you want to see if a field is within a set
1474 of values, you can use an arrayref. Let's say we wanted to
1475 SELECT some data based on this criteria:
1478 requestor => 'inna',
1479 worker => ['nwiger', 'rcwe', 'sfz'],
1480 status => { '!=', 'completed' }
1483 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1485 The above would give you something like this:
1487 $stmt = "SELECT * FROM tickets WHERE
1488 ( requestor = ? ) AND ( status != ? )
1489 AND ( worker = ? OR worker = ? OR worker = ? )";
1490 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1492 Which you could then use in DBI code like so:
1494 my $sth = $dbh->prepare($stmt);
1495 $sth->execute(@bind);
1501 The functions are simple. There's one for each major SQL operation,
1502 and a constructor you use first. The arguments are specified in a
1503 similar order to each function (table, then fields, then a where
1504 clause) to try and simplify things.
1509 =head2 new(option => 'value')
1511 The C<new()> function takes a list of options and values, and returns
1512 a new B<SQL::Abstract> object which can then be used to generate SQL
1513 through the methods below. The options accepted are:
1519 If set to 'lower', then SQL will be generated in all lowercase. By
1520 default SQL is generated in "textbook" case meaning something like:
1522 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1524 Any setting other than 'lower' is ignored.
1528 This determines what the default comparison operator is. By default
1529 it is C<=>, meaning that a hash like this:
1531 %where = (name => 'nwiger', email => 'nate@wiger.org');
1533 Will generate SQL like this:
1535 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1537 However, you may want loose comparisons by default, so if you set
1538 C<cmp> to C<like> you would get SQL such as:
1540 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1542 You can also override the comparsion on an individual basis - see
1543 the huge section on L</"WHERE CLAUSES"> at the bottom.
1545 =item sqltrue, sqlfalse
1547 Expressions for inserting boolean values within SQL statements.
1548 By default these are C<1=1> and C<1=0>. They are used
1549 by the special operators C<-in> and C<-not_in> for generating
1550 correct SQL even when the argument is an empty array (see below).
1554 This determines the default logical operator for multiple WHERE
1555 statements in arrays or hashes. If absent, the default logic is "or"
1556 for arrays, and "and" for hashes. This means that a WHERE
1560 event_date => {'>=', '2/13/99'},
1561 event_date => {'<=', '4/24/03'},
1564 will generate SQL like this:
1566 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1568 This is probably not what you want given this query, though (look
1569 at the dates). To change the "OR" to an "AND", simply specify:
1571 my $sql = SQL::Abstract->new(logic => 'and');
1573 Which will change the above C<WHERE> to:
1575 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1577 The logic can also be changed locally by inserting
1578 a modifier in front of an arrayref :
1580 @where = (-and => [event_date => {'>=', '2/13/99'},
1581 event_date => {'<=', '4/24/03'} ]);
1583 See the L</"WHERE CLAUSES"> section for explanations.
1587 This will automatically convert comparisons using the specified SQL
1588 function for both column and value. This is mostly used with an argument
1589 of C<upper> or C<lower>, so that the SQL will have the effect of
1590 case-insensitive "searches". For example, this:
1592 $sql = SQL::Abstract->new(convert => 'upper');
1593 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1595 Will turn out the following SQL:
1597 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1599 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1600 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1601 not validate this option; it will just pass through what you specify verbatim).
1605 This is a kludge because many databases suck. For example, you can't
1606 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1607 Instead, you have to use C<bind_param()>:
1609 $sth->bind_param(1, 'reg data');
1610 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1612 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1613 which loses track of which field each slot refers to. Fear not.
1615 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1616 Currently, you can specify either C<normal> (default) or C<columns>. If you
1617 specify C<columns>, you will get an array that looks like this:
1619 my $sql = SQL::Abstract->new(bindtype => 'columns');
1620 my($stmt, @bind) = $sql->insert(...);
1623 [ 'column1', 'value1' ],
1624 [ 'column2', 'value2' ],
1625 [ 'column3', 'value3' ],
1628 You can then iterate through this manually, using DBI's C<bind_param()>.
1630 $sth->prepare($stmt);
1633 my($col, $data) = @$_;
1634 if ($col eq 'details' || $col eq 'comments') {
1635 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1636 } elsif ($col eq 'image') {
1637 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1639 $sth->bind_param($i, $data);
1643 $sth->execute; # execute without @bind now
1645 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1646 Basically, the advantage is still that you don't have to care which fields
1647 are or are not included. You could wrap that above C<for> loop in a simple
1648 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1649 get a layer of abstraction over manual SQL specification.
1651 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1652 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1653 will expect the bind values in this format.
1657 This is the character that a table or column name will be quoted
1658 with. By default this is an empty string, but you could set it to
1659 the character C<`>, to generate SQL like this:
1661 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1663 Alternatively, you can supply an array ref of two items, the first being the left
1664 hand quote character, and the second the right hand quote character. For
1665 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1666 that generates SQL like this:
1668 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1670 Quoting is useful if you have tables or columns names that are reserved
1671 words in your database's SQL dialect.
1675 This is the character that separates a table and column name. It is
1676 necessary to specify this when the C<quote_char> option is selected,
1677 so that tables and column names can be individually quoted like this:
1679 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1681 =item array_datatypes
1683 When this option is true, arrayrefs in INSERT or UPDATE are
1684 interpreted as array datatypes and are passed directly
1686 When this option is false, arrayrefs are interpreted
1687 as literal SQL, just like refs to arrayrefs
1688 (but this behavior is for backwards compatibility; when writing
1689 new queries, use the "reference to arrayref" syntax
1695 Takes a reference to a list of "special operators"
1696 to extend the syntax understood by L<SQL::Abstract>.
1697 See section L</"SPECIAL OPERATORS"> for details.
1701 Takes a reference to a list of "unary operators"
1702 to extend the syntax understood by L<SQL::Abstract>.
1703 See section L</"UNARY OPERATORS"> for details.
1709 =head2 insert($table, \@values || \%fieldvals, \%options)
1711 This is the simplest function. You simply give it a table name
1712 and either an arrayref of values or hashref of field/value pairs.
1713 It returns an SQL INSERT statement and a list of bind values.
1714 See the sections on L</"Inserting and Updating Arrays"> and
1715 L</"Inserting and Updating SQL"> for information on how to insert
1716 with those data types.
1718 The optional C<\%options> hash reference may contain additional
1719 options to generate the insert SQL. Currently supported options
1726 Takes either a scalar of raw SQL fields, or an array reference of
1727 field names, and adds on an SQL C<RETURNING> statement at the end.
1728 This allows you to return data generated by the insert statement
1729 (such as row IDs) without performing another C<SELECT> statement.
1730 Note, however, this is not part of the SQL standard and may not
1731 be supported by all database engines.
1735 =head2 update($table, \%fieldvals, \%where)
1737 This takes a table, hashref of field/value pairs, and an optional
1738 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1740 See the sections on L</"Inserting and Updating Arrays"> and
1741 L</"Inserting and Updating SQL"> for information on how to insert
1742 with those data types.
1744 =head2 select($source, $fields, $where, $order)
1746 This returns a SQL SELECT statement and associated list of bind values, as
1747 specified by the arguments :
1753 Specification of the 'FROM' part of the statement.
1754 The argument can be either a plain scalar (interpreted as a table
1755 name, will be quoted), or an arrayref (interpreted as a list
1756 of table names, joined by commas, quoted), or a scalarref
1757 (literal table name, not quoted), or a ref to an arrayref
1758 (list of literal table names, joined by commas, not quoted).
1762 Specification of the list of fields to retrieve from
1764 The argument can be either an arrayref (interpreted as a list
1765 of field names, will be joined by commas and quoted), or a
1766 plain scalar (literal SQL, not quoted).
1767 Please observe that this API is not as flexible as for
1768 the first argument C<$table>, for backwards compatibility reasons.
1772 Optional argument to specify the WHERE part of the query.
1773 The argument is most often a hashref, but can also be
1774 an arrayref or plain scalar --
1775 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1779 Optional argument to specify the ORDER BY part of the query.
1780 The argument can be a scalar, a hashref or an arrayref
1781 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1787 =head2 delete($table, \%where)
1789 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1790 It returns an SQL DELETE statement and list of bind values.
1792 =head2 where(\%where, \@order)
1794 This is used to generate just the WHERE clause. For example,
1795 if you have an arbitrary data structure and know what the
1796 rest of your SQL is going to look like, but want an easy way
1797 to produce a WHERE clause, use this. It returns an SQL WHERE
1798 clause and list of bind values.
1801 =head2 values(\%data)
1803 This just returns the values from the hash C<%data>, in the same
1804 order that would be returned from any of the other above queries.
1805 Using this allows you to markedly speed up your queries if you
1806 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1808 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1810 Warning: This is an experimental method and subject to change.
1812 This returns arbitrarily generated SQL. It's a really basic shortcut.
1813 It will return two different things, depending on return context:
1815 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1816 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1818 These would return the following:
1820 # First calling form
1821 $stmt = "CREATE TABLE test (?, ?)";
1822 @bind = (field1, field2);
1824 # Second calling form
1825 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1827 Depending on what you're trying to do, it's up to you to choose the correct
1828 format. In this example, the second form is what you would want.
1832 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1836 ALTER SESSION SET nls_date_format = 'MM/YY'
1838 You get the idea. Strings get their case twiddled, but everything
1839 else remains verbatim.
1844 =head1 WHERE CLAUSES
1848 This module uses a variation on the idea from L<DBIx::Abstract>. It
1849 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1850 module is that things in arrays are OR'ed, and things in hashes
1853 The easiest way to explain is to show lots of examples. After
1854 each C<%where> hash shown, it is assumed you used:
1856 my($stmt, @bind) = $sql->where(\%where);
1858 However, note that the C<%where> hash can be used directly in any
1859 of the other functions as well, as described above.
1861 =head2 Key-value pairs
1863 So, let's get started. To begin, a simple hash:
1867 status => 'completed'
1870 Is converted to SQL C<key = val> statements:
1872 $stmt = "WHERE user = ? AND status = ?";
1873 @bind = ('nwiger', 'completed');
1875 One common thing I end up doing is having a list of values that
1876 a field can be in. To do this, simply specify a list inside of
1881 status => ['assigned', 'in-progress', 'pending'];
1884 This simple code will create the following:
1886 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1887 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1889 A field associated to an empty arrayref will be considered a
1890 logical false and will generate 0=1.
1892 =head2 Specific comparison operators
1894 If you want to specify a different type of operator for your comparison,
1895 you can use a hashref for a given column:
1899 status => { '!=', 'completed' }
1902 Which would generate:
1904 $stmt = "WHERE user = ? AND status != ?";
1905 @bind = ('nwiger', 'completed');
1907 To test against multiple values, just enclose the values in an arrayref:
1909 status => { '=', ['assigned', 'in-progress', 'pending'] };
1911 Which would give you:
1913 "WHERE status = ? OR status = ? OR status = ?"
1916 The hashref can also contain multiple pairs, in which case it is expanded
1917 into an C<AND> of its elements:
1921 status => { '!=', 'completed', -not_like => 'pending%' }
1924 # Or more dynamically, like from a form
1925 $where{user} = 'nwiger';
1926 $where{status}{'!='} = 'completed';
1927 $where{status}{'-not_like'} = 'pending%';
1929 # Both generate this
1930 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1931 @bind = ('nwiger', 'completed', 'pending%');
1934 To get an OR instead, you can combine it with the arrayref idea:
1938 priority => [ {'=', 2}, {'!=', 1} ]
1941 Which would generate:
1943 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1944 @bind = ('nwiger', '2', '1');
1946 If you want to include literal SQL (with or without bind values), just use a
1947 scalar reference or array reference as the value:
1950 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1951 date_expires => { '<' => \"now()" }
1954 Which would generate:
1956 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1957 @bind = ('11/26/2008');
1960 =head2 Logic and nesting operators
1962 In the example above,
1963 there is a subtle trap if you want to say something like
1964 this (notice the C<AND>):
1966 WHERE priority != ? AND priority != ?
1968 Because, in Perl you I<can't> do this:
1970 priority => { '!=', 2, '!=', 1 }
1972 As the second C<!=> key will obliterate the first. The solution
1973 is to use the special C<-modifier> form inside an arrayref:
1975 priority => [ -and => {'!=', 2},
1979 Normally, these would be joined by C<OR>, but the modifier tells it
1980 to use C<AND> instead. (Hint: You can use this in conjunction with the
1981 C<logic> option to C<new()> in order to change the way your queries
1982 work by default.) B<Important:> Note that the C<-modifier> goes
1983 B<INSIDE> the arrayref, as an extra first element. This will
1984 B<NOT> do what you think it might:
1986 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1988 Here is a quick list of equivalencies, since there is some overlap:
1991 status => {'!=', 'completed', 'not like', 'pending%' }
1992 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1995 status => {'=', ['assigned', 'in-progress']}
1996 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1997 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2001 =head2 Special operators : IN, BETWEEN, etc.
2003 You can also use the hashref format to compare a list of fields using the
2004 C<IN> comparison operator, by specifying the list as an arrayref:
2007 status => 'completed',
2008 reportid => { -in => [567, 2335, 2] }
2011 Which would generate:
2013 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2014 @bind = ('completed', '567', '2335', '2');
2016 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2019 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2020 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2021 'sqltrue' (by default : C<1=1>).
2023 In addition to the array you can supply a chunk of literal sql or
2024 literal sql with bind:
2027 customer => { -in => \[
2028 'SELECT cust_id FROM cust WHERE balance > ?',
2031 status => { -in => \'SELECT status_codes FROM states' },
2037 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2038 AND status IN ( SELECT status_codes FROM states )
2044 Another pair of operators is C<-between> and C<-not_between>,
2045 used with an arrayref of two values:
2049 completion_date => {
2050 -not_between => ['2002-10-01', '2003-02-06']
2056 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2058 Just like with C<-in> all plausible combinations of literal SQL
2062 start0 => { -between => [ 1, 2 ] },
2063 start1 => { -between => \["? AND ?", 1, 2] },
2064 start2 => { -between => \"lower(x) AND upper(y)" },
2065 start3 => { -between => [
2067 \["upper(?)", 'stuff' ],
2074 ( start0 BETWEEN ? AND ? )
2075 AND ( start1 BETWEEN ? AND ? )
2076 AND ( start2 BETWEEN lower(x) AND upper(y) )
2077 AND ( start3 BETWEEN lower(x) AND upper(?) )
2079 @bind = (1, 2, 1, 2, 'stuff');
2082 These are the two builtin "special operators"; but the
2083 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2085 =head2 Unary operators: bool
2087 If you wish to test against boolean columns or functions within your
2088 database you can use the C<-bool> and C<-not_bool> operators. For
2089 example to test the column C<is_user> being true and the column
2090 <is_enabled> being false you would use:-
2094 -not_bool => 'is_enabled',
2099 WHERE is_user AND NOT is_enabled
2101 If a more complex combination is required, testing more conditions,
2102 then you should use the and/or operators:-
2109 -not_bool => 'four',
2115 WHERE one AND two AND three AND NOT four
2118 =head2 Nested conditions, -and/-or prefixes
2120 So far, we've seen how multiple conditions are joined with a top-level
2121 C<AND>. We can change this by putting the different conditions we want in
2122 hashes and then putting those hashes in an array. For example:
2127 status => { -like => ['pending%', 'dispatched'] },
2131 status => 'unassigned',
2135 This data structure would create the following:
2137 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2138 OR ( user = ? AND status = ? ) )";
2139 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2142 There is also a special C<-nest>
2143 operator which adds an additional set of parens, to create a subquery.
2144 For example, to get something like this:
2146 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2147 @bind = ('nwiger', '20', 'ASIA');
2153 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2157 Finally, clauses in hashrefs or arrayrefs can be
2158 prefixed with an C<-and> or C<-or> to change the logic
2165 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2166 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2173 WHERE ( user = ? AND
2174 ( ( workhrs > ? AND geo = ? )
2175 OR ( workhrs < ? AND geo = ? ) ) )
2178 =head2 Algebraic inconsistency, for historical reasons
2180 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2181 operator goes C<outside> of the nested structure; whereas when connecting
2182 several constraints on one column, the C<-and> operator goes
2183 C<inside> the arrayref. Here is an example combining both features :
2186 -and => [a => 1, b => 2],
2187 -or => [c => 3, d => 4],
2188 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2193 WHERE ( ( ( a = ? AND b = ? )
2194 OR ( c = ? OR d = ? )
2195 OR ( e LIKE ? AND e LIKE ? ) ) )
2197 This difference in syntax is unfortunate but must be preserved for
2198 historical reasons. So be careful : the two examples below would
2199 seem algebraically equivalent, but they are not
2201 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2202 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2204 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2205 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2210 Finally, sometimes only literal SQL will do. If you want to include
2211 literal SQL verbatim, you can specify it as a scalar reference, namely:
2213 my $inn = 'is Not Null';
2215 priority => { '<', 2 },
2221 $stmt = "WHERE priority < ? AND requestor is Not Null";
2224 Note that in this example, you only get one bind parameter back, since
2225 the verbatim SQL is passed as part of the statement.
2227 Of course, just to prove a point, the above can also be accomplished
2231 priority => { '<', 2 },
2232 requestor => { '!=', undef },
2238 Conditions on boolean columns can be expressed in the same way, passing
2239 a reference to an empty string, however using liternal SQL in this way
2240 is deprecated - the preferred method is to use the boolean operators -
2241 see L</"Unary operators: bool"> :
2244 priority => { '<', 2 },
2250 $stmt = "WHERE priority < ? AND is_ready";
2254 =head2 Literal SQL with placeholders and bind values (subqueries)
2256 If the literal SQL to be inserted has placeholders and bind values,
2257 use a reference to an arrayref (yes this is a double reference --
2258 not so common, but perfectly legal Perl). For example, to find a date
2259 in Postgres you can use something like this:
2262 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2267 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2270 Note that you must pass the bind values in the same format as they are returned
2271 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2272 provide the bind values in the C<< [ column_meta => value ] >> format, where
2273 C<column_meta> is an opaque scalar value; most commonly the column name, but
2274 you can use any scalar value (including references and blessed references),
2275 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2276 to C<columns> the above example will look like:
2279 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2282 Literal SQL is especially useful for nesting parenthesized clauses in the
2283 main SQL query. Here is a first example :
2285 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2289 bar => \["IN ($sub_stmt)" => @sub_bind],
2294 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2295 WHERE c2 < ? AND c3 LIKE ?))";
2296 @bind = (1234, 100, "foo%");
2298 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2299 are expressed in the same way. Of course the C<$sub_stmt> and
2300 its associated bind values can be generated through a former call
2303 my ($sub_stmt, @sub_bind)
2304 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2305 c3 => {-like => "foo%"}});
2308 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2311 In the examples above, the subquery was used as an operator on a column;
2312 but the same principle also applies for a clause within the main C<%where>
2313 hash, like an EXISTS subquery :
2315 my ($sub_stmt, @sub_bind)
2316 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2319 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2324 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2325 WHERE c1 = ? AND c2 > t0.c0))";
2329 Observe that the condition on C<c2> in the subquery refers to
2330 column C<t0.c0> of the main query : this is I<not> a bind
2331 value, so we have to express it through a scalar ref.
2332 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2333 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2334 what we wanted here.
2336 Another use of the subquery technique is when some SQL clauses need
2337 parentheses, as it often occurs with some proprietary SQL extensions
2338 like for example fulltext expressions, geospatial expressions,
2339 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2342 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2345 Finally, here is an example where a subquery is used
2346 for expressing unary negation:
2348 my ($sub_stmt, @sub_bind)
2349 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2350 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2352 lname => {like => '%son%'},
2353 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2358 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2359 @bind = ('%son%', 10, 20)
2365 These pages could go on for a while, since the nesting of the data
2366 structures this module can handle are pretty much unlimited (the
2367 module implements the C<WHERE> expansion as a recursive function
2368 internally). Your best bet is to "play around" with the module a
2369 little to see how the data structures behave, and choose the best
2370 format for your data based on that.
2372 And of course, all the values above will probably be replaced with
2373 variables gotten from forms or the command line. After all, if you
2374 knew everything ahead of time, you wouldn't have to worry about
2375 dynamically-generating SQL and could just hardwire it into your
2381 =head1 ORDER BY CLAUSES
2383 Some functions take an order by clause. This can either be a scalar (just a
2384 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2385 or an array of either of the two previous forms. Examples:
2387 Given | Will Generate
2388 ----------------------------------------------------------
2390 \'colA DESC' | ORDER BY colA DESC
2392 'colA' | ORDER BY colA
2394 [qw/colA colB/] | ORDER BY colA, colB
2396 {-asc => 'colA'} | ORDER BY colA ASC
2398 {-desc => 'colB'} | ORDER BY colB DESC
2400 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2402 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2405 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2406 { -desc => [qw/colB/], | colC ASC, colD ASC
2407 { -asc => [qw/colC colD/],|
2409 ===========================================================
2413 =head1 SPECIAL OPERATORS
2415 my $sqlmaker = SQL::Abstract->new(special_ops => [
2419 my ($self, $field, $op, $arg) = @_;
2425 handler => 'method_name',
2429 A "special operator" is a SQL syntactic clause that can be
2430 applied to a field, instead of a usual binary operator.
2433 WHERE field IN (?, ?, ?)
2434 WHERE field BETWEEN ? AND ?
2435 WHERE MATCH(field) AGAINST (?, ?)
2437 Special operators IN and BETWEEN are fairly standard and therefore
2438 are builtin within C<SQL::Abstract> (as the overridable methods
2439 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2440 like the MATCH .. AGAINST example above which is specific to MySQL,
2441 you can write your own operator handlers - supply a C<special_ops>
2442 argument to the C<new> method. That argument takes an arrayref of
2443 operator definitions; each operator definition is a hashref with two
2450 the regular expression to match the operator
2454 Either a coderef or a plain scalar method name. In both cases
2455 the expected return is C<< ($sql, @bind) >>.
2457 When supplied with a method name, it is simply called on the
2458 L<SQL::Abstract/> object as:
2460 $self->$method_name ($field, $op, $arg)
2464 $op is the part that matched the handler regex
2465 $field is the LHS of the operator
2468 When supplied with a coderef, it is called as:
2470 $coderef->($self, $field, $op, $arg)
2475 For example, here is an implementation
2476 of the MATCH .. AGAINST syntax for MySQL
2478 my $sqlmaker = SQL::Abstract->new(special_ops => [
2480 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2481 {regex => qr/^match$/i,
2483 my ($self, $field, $op, $arg) = @_;
2484 $arg = [$arg] if not ref $arg;
2485 my $label = $self->_quote($field);
2486 my ($placeholder) = $self->_convert('?');
2487 my $placeholders = join ", ", (($placeholder) x @$arg);
2488 my $sql = $self->_sqlcase('match') . " ($label) "
2489 . $self->_sqlcase('against') . " ($placeholders) ";
2490 my @bind = $self->_bindtype($field, @$arg);
2491 return ($sql, @bind);
2498 =head1 UNARY OPERATORS
2500 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2504 my ($self, $op, $arg) = @_;
2510 handler => 'method_name',
2514 A "unary operator" is a SQL syntactic clause that can be
2515 applied to a field - the operator goes before the field
2517 You can write your own operator handlers - supply a C<unary_ops>
2518 argument to the C<new> method. That argument takes an arrayref of
2519 operator definitions; each operator definition is a hashref with two
2526 the regular expression to match the operator
2530 Either a coderef or a plain scalar method name. In both cases
2531 the expected return is C<< $sql >>.
2533 When supplied with a method name, it is simply called on the
2534 L<SQL::Abstract/> object as:
2536 $self->$method_name ($op, $arg)
2540 $op is the part that matched the handler regex
2541 $arg is the RHS or argument of the operator
2543 When supplied with a coderef, it is called as:
2545 $coderef->($self, $op, $arg)
2553 Thanks to some benchmarking by Mark Stosberg, it turns out that
2554 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2555 I must admit this wasn't an intentional design issue, but it's a
2556 byproduct of the fact that you get to control your C<DBI> handles
2559 To maximize performance, use a code snippet like the following:
2561 # prepare a statement handle using the first row
2562 # and then reuse it for the rest of the rows
2564 for my $href (@array_of_hashrefs) {
2565 $stmt ||= $sql->insert('table', $href);
2566 $sth ||= $dbh->prepare($stmt);
2567 $sth->execute($sql->values($href));
2570 The reason this works is because the keys in your C<$href> are sorted
2571 internally by B<SQL::Abstract>. Thus, as long as your data retains
2572 the same structure, you only have to generate the SQL the first time
2573 around. On subsequent queries, simply use the C<values> function provided
2574 by this module to return your values in the correct order.
2579 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2580 really like this part (I do, at least). Building up a complex query
2581 can be as simple as the following:
2585 use CGI::FormBuilder;
2588 my $form = CGI::FormBuilder->new(...);
2589 my $sql = SQL::Abstract->new;
2591 if ($form->submitted) {
2592 my $field = $form->field;
2593 my $id = delete $field->{id};
2594 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2597 Of course, you would still have to connect using C<DBI> to run the
2598 query, but the point is that if you make your form look like your
2599 table, the actual query script can be extremely simplistic.
2601 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2602 a fast interface to returning and formatting data. I frequently
2603 use these three modules together to write complex database query
2604 apps in under 50 lines.
2609 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2610 Great care has been taken to preserve the I<published> behavior
2611 documented in previous versions in the 1.* family; however,
2612 some features that were previously undocumented, or behaved
2613 differently from the documentation, had to be changed in order
2614 to clarify the semantics. Hence, client code that was relying
2615 on some dark areas of C<SQL::Abstract> v1.*
2616 B<might behave differently> in v1.50.
2618 The main changes are :
2624 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2628 support for the { operator => \"..." } construct (to embed literal SQL)
2632 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2636 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2640 defensive programming : check arguments
2644 fixed bug with global logic, which was previously implemented
2645 through global variables yielding side-effects. Prior versions would
2646 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2647 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2648 Now this is interpreted
2649 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2654 fixed semantics of _bindtype on array args
2658 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2659 we just avoid shifting arrays within that tree.
2663 dropped the C<_modlogic> function
2669 =head1 ACKNOWLEDGEMENTS
2671 There are a number of individuals that have really helped out with
2672 this module. Unfortunately, most of them submitted bugs via CPAN
2673 so I have no idea who they are! But the people I do know are:
2675 Ash Berlin (order_by hash term support)
2676 Matt Trout (DBIx::Class support)
2677 Mark Stosberg (benchmarking)
2678 Chas Owens (initial "IN" operator support)
2679 Philip Collins (per-field SQL functions)
2680 Eric Kolve (hashref "AND" support)
2681 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2682 Dan Kubb (support for "quote_char" and "name_sep")
2683 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2684 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2685 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2686 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2687 Oliver Charles (support for "RETURNING" after "INSERT")
2693 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2697 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2699 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2701 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2702 While not an official support venue, C<DBIx::Class> makes heavy use of
2703 C<SQL::Abstract>, and as such list members there are very familiar with
2704 how to create queries.
2708 This module is free software; you may copy this under the same
2709 terms as perl itself (either the GNU General Public License or
2710 the Artistic License)