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},
411 $self->_assert_bindval_matches_bindtype(@b);
415 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
416 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
417 # side-effect: the first hashref within an array would change
418 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
419 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
420 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
422 SCALARREF => sub { ($$el); },
424 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
425 $self->_recurse_where({$el => shift(@clauses)})},
427 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
431 push @sql_clauses, $sql;
432 push @all_bind, @bind;
436 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
439 #======================================================================
440 # WHERE: top-level ARRAYREFREF
441 #======================================================================
443 sub _where_ARRAYREFREF {
444 my ($self, $where) = @_;
445 my ($sql, @bind) = @$$where;
446 $self->_assert_bindval_matches_bindtype(@bind);
447 return ($sql, @bind);
450 #======================================================================
451 # WHERE: top-level HASHREF
452 #======================================================================
455 my ($self, $where) = @_;
456 my (@sql_clauses, @all_bind);
458 for my $k (sort keys %$where) {
459 my $v = $where->{$k};
461 # ($k => $v) is either a special unary op or a regular hashpair
462 my ($sql, @bind) = do {
464 # put the operator in canonical form
466 $op =~ s/^-//; # remove initial dash
467 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
468 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
470 $self->_debug("Unary OP(-$op) within hashref, recursing...");
472 my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}};
473 if (my $handler = $op_entry->{handler}) {
474 if (not ref $handler) {
475 if ($op =~ s/\s?\d+$//) {
476 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
477 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
479 $self->$handler ($op, $v);
481 elsif (ref $handler eq 'CODE') {
482 $handler->($self, $op, $v);
485 puke "Illegal handler for operator $k - expecting a method name or a coderef";
489 $self->debug("Generic unary OP: $k - recursing as function");
490 my ($sql, @bind) = $self->_where_func_generic ($op, $v);
491 $sql = "($sql)" unless (defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)); # top level vs nested
496 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
497 $self->$method($k, $v);
501 push @sql_clauses, $sql;
502 push @all_bind, @bind;
505 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
508 sub _where_func_generic {
509 my ($self, $op, $rhs) = @_;
511 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
513 puke "Illegal use of top-level '$op'"
514 unless $self->{_nested_func_lhs};
517 $self->_convert('?'),
518 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
522 $self->_recurse_where ($rhs)
526 $sql = sprintf ('%s %s',
527 $self->_sqlcase($op),
531 return ($sql, @bind);
534 sub _where_op_ANDOR {
535 my ($self, $op, $v) = @_;
537 $self->_SWITCH_refkind($v, {
539 return $self->_where_ARRAYREF($v, $op);
543 return ( $op =~ /^or/i )
544 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
545 : $self->_where_HASHREF($v);
549 puke "-$op => \\\$scalar not supported, use -nest => ...";
553 puke "-$op => \\[..] not supported, use -nest => ...";
556 SCALAR => sub { # permissively interpreted as SQL
557 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
561 puke "-$op => undef not supported";
567 my ($self, $op, $v) = @_;
569 $self->_SWITCH_refkind($v, {
571 SCALAR => sub { # permissively interpreted as SQL
572 belch "literal SQL should be -nest => \\'scalar' "
573 . "instead of -nest => 'scalar' ";
578 puke "-$op => undef not supported";
582 $self->_recurse_where ($v);
590 my ($self, $op, $v) = @_;
592 my ( $prefix, $suffix ) = ( $op =~ /\bnot\b/i )
596 my ($sql, @bind) = do {
597 $self->_SWITCH_refkind($v, {
598 SCALAR => sub { # interpreted as SQL column
599 $self->_convert($self->_quote($v));
603 puke "-$op => undef not supported";
607 $self->_recurse_where ($v);
613 join ('', $prefix, $sql, $suffix),
619 sub _where_hashpair_ARRAYREF {
620 my ($self, $k, $v) = @_;
623 my @v = @$v; # need copy because of shift below
624 $self->_debug("ARRAY($k) means distribute over elements");
626 # put apart first element if it is an operator (-and, -or)
628 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
632 my @distributed = map { {$k => $_} } @v;
635 $self->_debug("OP($op) reinjected into the distributed array");
636 unshift @distributed, $op;
639 my $logic = $op ? substr($op, 1) : '';
641 return $self->_recurse_where(\@distributed, $logic);
644 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
645 $self->_debug("empty ARRAY($k) means 0=1");
646 return ($self->{sqlfalse});
650 sub _where_hashpair_HASHREF {
651 my ($self, $k, $v, $logic) = @_;
654 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
656 my ($all_sql, @all_bind);
658 for my $orig_op (sort keys %$v) {
659 my $val = $v->{$orig_op};
661 # put the operator in canonical form
663 $op =~ s/^-//; # remove initial dash
664 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
665 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
669 # CASE: col-value logic modifiers
670 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
671 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
673 # CASE: special operators like -in or -between
674 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
675 my $handler = $special_op->{handler};
677 puke "No handler supplied for special operator $orig_op";
679 elsif (not ref $handler) {
680 ($sql, @bind) = $self->$handler ($k, $op, $val);
682 elsif (ref $handler eq 'CODE') {
683 ($sql, @bind) = $handler->($self, $k, $op, $val);
686 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
690 $self->_SWITCH_refkind($val, {
692 ARRAYREF => sub { # CASE: col => {op => \@vals}
693 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
696 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
697 my ($sub_sql, @sub_bind) = @$$val;
698 $self->_assert_bindval_matches_bindtype(@sub_bind);
699 $sql = join ' ', $self->_convert($self->_quote($k)),
700 $self->_sqlcase($op),
705 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
706 my $is = ($op =~ $self->{equality_op}) ? 'is' :
707 ($op =~ $self->{inequality_op}) ? 'is not' :
708 puke "unexpected operator '$orig_op' with undef operand";
709 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
712 FALLBACK => sub { # CASE: col => {op/func => $stuff}
714 # retain for proper column type bind
715 $self->{_nested_func_lhs} ||= $k;
717 ($sql, @bind) = $self->_where_func_generic ($op, $val);
720 $self->_convert($self->_quote($k)),
721 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
727 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
728 push @all_bind, @bind;
730 return ($all_sql, @all_bind);
735 sub _where_field_op_ARRAYREF {
736 my ($self, $k, $op, $vals) = @_;
738 my @vals = @$vals; #always work on a copy
741 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
743 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
746 # see if the first element is an -and/-or op
748 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
753 # distribute $op over each remaining member of @vals, append logic if exists
754 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
756 # LDNOTE : had planned to change the distribution logic when
757 # $op =~ $self->{inequality_op}, because of Morgan laws :
758 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
759 # WHERE field != 22 OR field != 33 : the user probably means
760 # WHERE field != 22 AND field != 33.
761 # To do this, replace the above to roughly :
762 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
763 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
767 # try to DWIM on equality operators
768 # LDNOTE : not 100% sure this is the correct thing to do ...
769 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
770 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
773 puke "operator '$op' applied on an empty array (field '$k')";
778 sub _where_hashpair_SCALARREF {
779 my ($self, $k, $v) = @_;
780 $self->_debug("SCALAR($k) means literal SQL: $$v");
781 my $sql = $self->_quote($k) . " " . $$v;
785 # literal SQL with bind
786 sub _where_hashpair_ARRAYREFREF {
787 my ($self, $k, $v) = @_;
788 $self->_debug("REF($k) means literal SQL: @${$v}");
789 my ($sql, @bind) = @$$v;
790 $self->_assert_bindval_matches_bindtype(@bind);
791 $sql = $self->_quote($k) . " " . $sql;
792 return ($sql, @bind );
795 # literal SQL without bind
796 sub _where_hashpair_SCALAR {
797 my ($self, $k, $v) = @_;
798 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
799 my $sql = join ' ', $self->_convert($self->_quote($k)),
800 $self->_sqlcase($self->{cmp}),
801 $self->_convert('?');
802 my @bind = $self->_bindtype($k, $v);
803 return ( $sql, @bind);
807 sub _where_hashpair_UNDEF {
808 my ($self, $k, $v) = @_;
809 $self->_debug("UNDEF($k) means IS NULL");
810 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
814 #======================================================================
815 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
816 #======================================================================
819 sub _where_SCALARREF {
820 my ($self, $where) = @_;
823 $self->_debug("SCALAR(*top) means literal SQL: $$where");
829 my ($self, $where) = @_;
832 $self->_debug("NOREF(*top) means literal SQL: $where");
843 #======================================================================
844 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
845 #======================================================================
848 sub _where_field_BETWEEN {
849 my ($self, $k, $op, $vals) = @_;
851 my ($label, $and, $placeholder);
852 $label = $self->_convert($self->_quote($k));
853 $and = ' ' . $self->_sqlcase('and') . ' ';
854 $placeholder = $self->_convert('?');
855 $op = $self->_sqlcase($op);
857 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
859 my ($s, @b) = @$$vals;
860 $self->_assert_bindval_matches_bindtype(@b);
867 puke "special op 'between' accepts an arrayref with exactly two values"
870 my (@all_sql, @all_bind);
871 foreach my $val (@$vals) {
872 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
874 return ($placeholder, ($val));
877 return ($self->_convert($$val), ());
880 my ($sql, @bind) = @$$val;
881 $self->_assert_bindval_matches_bindtype(@bind);
882 return ($self->_convert($sql), @bind);
886 push @all_bind, @bind;
890 (join $and, @all_sql),
891 $self->_bindtype($k, @all_bind),
895 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
899 my $sql = "( $label $op $clause )";
904 sub _where_field_IN {
905 my ($self, $k, $op, $vals) = @_;
907 # backwards compatibility : if scalar, force into an arrayref
908 $vals = [$vals] if defined $vals && ! ref $vals;
910 my ($label) = $self->_convert($self->_quote($k));
911 my ($placeholder) = $self->_convert('?');
912 $op = $self->_sqlcase($op);
914 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
915 ARRAYREF => sub { # list of choices
916 if (@$vals) { # nonempty list
917 my $placeholders = join ", ", (($placeholder) x @$vals);
918 my $sql = "$label $op ( $placeholders )";
919 my @bind = $self->_bindtype($k, @$vals);
921 return ($sql, @bind);
923 else { # empty list : some databases won't understand "IN ()", so DWIM
924 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
929 SCALARREF => sub { # literal SQL
930 my $sql = $self->_open_outer_paren ($$vals);
931 return ("$label $op ( $sql )");
933 ARRAYREFREF => sub { # literal SQL with bind
934 my ($sql, @bind) = @$$vals;
935 $self->_assert_bindval_matches_bindtype(@bind);
936 $sql = $self->_open_outer_paren ($sql);
937 return ("$label $op ( $sql )", @bind);
941 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
945 return ($sql, @bind);
948 # Some databases (SQLite) treat col IN (1, 2) different from
949 # col IN ( (1, 2) ). Use this to strip all outer parens while
950 # adding them back in the corresponding method
951 sub _open_outer_paren {
952 my ($self, $sql) = @_;
953 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
958 #======================================================================
960 #======================================================================
963 my ($self, $arg) = @_;
966 for my $c ($self->_order_by_chunks ($arg) ) {
967 $self->_SWITCH_refkind ($c, {
968 SCALAR => sub { push @sql, $c },
969 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
975 $self->_sqlcase(' order by'),
981 return wantarray ? ($sql, @bind) : $sql;
984 sub _order_by_chunks {
985 my ($self, $arg) = @_;
987 return $self->_SWITCH_refkind($arg, {
990 map { $self->_order_by_chunks ($_ ) } @$arg;
994 my ($s, @b) = @$$arg;
995 $self->_assert_bindval_matches_bindtype(@b);
999 SCALAR => sub {$self->_quote($arg)},
1001 UNDEF => sub {return () },
1003 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1006 # get first pair in hash
1007 my ($key, $val, @rest) = %$arg;
1009 return () unless $key;
1011 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1012 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1018 for my $c ($self->_order_by_chunks ($val)) {
1021 $self->_SWITCH_refkind ($c, {
1026 ($sql, @bind) = @$c;
1030 $sql = $sql . ' ' . $self->_sqlcase($direction);
1032 push @ret, [ $sql, @bind];
1041 #======================================================================
1042 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1043 #======================================================================
1048 $self->_SWITCH_refkind($from, {
1049 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1050 SCALAR => sub {$self->_quote($from)},
1051 SCALARREF => sub {$$from},
1052 ARRAYREFREF => sub {join ', ', @$from;},
1057 #======================================================================
1059 #======================================================================
1061 # highly optimized, as it's called way too often
1063 # my ($self, $label) = @_;
1065 return '' unless defined $_[1];
1066 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1068 return $_[1] unless $_[0]->{quote_char};
1070 my $qref = ref $_[0]->{quote_char};
1073 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1075 elsif ($qref eq 'ARRAY') {
1076 ($l, $r) = @{$_[0]->{quote_char}};
1079 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1082 # parts containing * are naturally unquoted
1083 return join( $_[0]->{name_sep}||'', map
1084 { $_ eq '*' ? $_ : $l . $_ . $r }
1085 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1090 # Conversion, if applicable
1092 #my ($self, $arg) = @_;
1094 # LDNOTE : modified the previous implementation below because
1095 # it was not consistent : the first "return" is always an array,
1096 # the second "return" is context-dependent. Anyway, _convert
1097 # seems always used with just a single argument, so make it a
1099 # return @_ unless $self->{convert};
1100 # my $conv = $self->_sqlcase($self->{convert});
1101 # my @ret = map { $conv.'('.$_.')' } @_;
1102 # return wantarray ? @ret : $ret[0];
1103 if ($_[0]->{convert}) {
1104 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1111 #my ($self, $col, @vals) = @_;
1113 #LDNOTE : changed original implementation below because it did not make
1114 # sense when bindtype eq 'columns' and @vals > 1.
1115 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1117 # called often - tighten code
1118 return $_[0]->{bindtype} eq 'columns'
1119 ? map {[$_[1], $_]} @_[2 .. $#_]
1124 # Dies if any element of @bind is not in [colname => value] format
1125 # if bindtype is 'columns'.
1126 sub _assert_bindval_matches_bindtype {
1127 # my ($self, @bind) = @_;
1129 if ($self->{bindtype} eq 'columns') {
1131 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1132 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1138 sub _join_sql_clauses {
1139 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1141 if (@$clauses_aref > 1) {
1142 my $join = " " . $self->_sqlcase($logic) . " ";
1143 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1144 return ($sql, @$bind_aref);
1146 elsif (@$clauses_aref) {
1147 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1150 return (); # if no SQL, ignore @$bind_aref
1155 # Fix SQL case, if so requested
1157 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1158 # don't touch the argument ... crooked logic, but let's not change it!
1159 return $_[0]->{case} ? $_[1] : uc($_[1]);
1163 #======================================================================
1164 # DISPATCHING FROM REFKIND
1165 #======================================================================
1168 my ($self, $data) = @_;
1170 return 'UNDEF' unless defined $data;
1172 # blessed objects are treated like scalars
1173 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1175 return 'SCALAR' unless $ref;
1178 while ($ref eq 'REF') {
1180 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1184 return ($ref||'SCALAR') . ('REF' x $n_steps);
1188 my ($self, $data) = @_;
1189 my @try = ($self->_refkind($data));
1190 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1191 push @try, 'FALLBACK';
1195 sub _METHOD_FOR_refkind {
1196 my ($self, $meth_prefix, $data) = @_;
1199 for (@{$self->_try_refkind($data)}) {
1200 $method = $self->can($meth_prefix."_".$_)
1204 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1208 sub _SWITCH_refkind {
1209 my ($self, $data, $dispatch_table) = @_;
1212 for (@{$self->_try_refkind($data)}) {
1213 $coderef = $dispatch_table->{$_}
1217 puke "no dispatch entry for ".$self->_refkind($data)
1226 #======================================================================
1227 # VALUES, GENERATE, AUTOLOAD
1228 #======================================================================
1230 # LDNOTE: original code from nwiger, didn't touch code in that section
1231 # I feel the AUTOLOAD stuff should not be the default, it should
1232 # only be activated on explicit demand by user.
1236 my $data = shift || return;
1237 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1238 unless ref $data eq 'HASH';
1241 foreach my $k ( sort keys %$data ) {
1242 my $v = $data->{$k};
1243 $self->_SWITCH_refkind($v, {
1245 if ($self->{array_datatypes}) { # array datatype
1246 push @all_bind, $self->_bindtype($k, $v);
1248 else { # literal SQL with bind
1249 my ($sql, @bind) = @$v;
1250 $self->_assert_bindval_matches_bindtype(@bind);
1251 push @all_bind, @bind;
1254 ARRAYREFREF => sub { # literal SQL with bind
1255 my ($sql, @bind) = @${$v};
1256 $self->_assert_bindval_matches_bindtype(@bind);
1257 push @all_bind, @bind;
1259 SCALARREF => sub { # literal SQL without bind
1261 SCALAR_or_UNDEF => sub {
1262 push @all_bind, $self->_bindtype($k, $v);
1273 my(@sql, @sqlq, @sqlv);
1277 if ($ref eq 'HASH') {
1278 for my $k (sort keys %$_) {
1281 my $label = $self->_quote($k);
1282 if ($r eq 'ARRAY') {
1283 # literal SQL with bind
1284 my ($sql, @bind) = @$v;
1285 $self->_assert_bindval_matches_bindtype(@bind);
1286 push @sqlq, "$label = $sql";
1288 } elsif ($r eq 'SCALAR') {
1289 # literal SQL without bind
1290 push @sqlq, "$label = $$v";
1292 push @sqlq, "$label = ?";
1293 push @sqlv, $self->_bindtype($k, $v);
1296 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1297 } elsif ($ref eq 'ARRAY') {
1298 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1301 if ($r eq 'ARRAY') { # literal SQL with bind
1302 my ($sql, @bind) = @$v;
1303 $self->_assert_bindval_matches_bindtype(@bind);
1306 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1307 # embedded literal SQL
1314 push @sql, '(' . join(', ', @sqlq) . ')';
1315 } elsif ($ref eq 'SCALAR') {
1319 # strings get case twiddled
1320 push @sql, $self->_sqlcase($_);
1324 my $sql = join ' ', @sql;
1326 # this is pretty tricky
1327 # if ask for an array, return ($stmt, @bind)
1328 # otherwise, s/?/shift @sqlv/ to put it inline
1330 return ($sql, @sqlv);
1332 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1333 ref $d ? $d->[1] : $d/e;
1342 # This allows us to check for a local, then _form, attr
1344 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1345 return $self->generate($name, @_);
1356 SQL::Abstract - Generate SQL from Perl data structures
1362 my $sql = SQL::Abstract->new;
1364 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1366 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1368 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1370 my($stmt, @bind) = $sql->delete($table, \%where);
1372 # Then, use these in your DBI statements
1373 my $sth = $dbh->prepare($stmt);
1374 $sth->execute(@bind);
1376 # Just generate the WHERE clause
1377 my($stmt, @bind) = $sql->where(\%where, \@order);
1379 # Return values in the same order, for hashed queries
1380 # See PERFORMANCE section for more details
1381 my @bind = $sql->values(\%fieldvals);
1385 This module was inspired by the excellent L<DBIx::Abstract>.
1386 However, in using that module I found that what I really wanted
1387 to do was generate SQL, but still retain complete control over my
1388 statement handles and use the DBI interface. So, I set out to
1389 create an abstract SQL generation module.
1391 While based on the concepts used by L<DBIx::Abstract>, there are
1392 several important differences, especially when it comes to WHERE
1393 clauses. I have modified the concepts used to make the SQL easier
1394 to generate from Perl data structures and, IMO, more intuitive.
1395 The underlying idea is for this module to do what you mean, based
1396 on the data structures you provide it. The big advantage is that
1397 you don't have to modify your code every time your data changes,
1398 as this module figures it out.
1400 To begin with, an SQL INSERT is as easy as just specifying a hash
1401 of C<key=value> pairs:
1404 name => 'Jimbo Bobson',
1405 phone => '123-456-7890',
1406 address => '42 Sister Lane',
1407 city => 'St. Louis',
1408 state => 'Louisiana',
1411 The SQL can then be generated with this:
1413 my($stmt, @bind) = $sql->insert('people', \%data);
1415 Which would give you something like this:
1417 $stmt = "INSERT INTO people
1418 (address, city, name, phone, state)
1419 VALUES (?, ?, ?, ?, ?)";
1420 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1421 '123-456-7890', 'Louisiana');
1423 These are then used directly in your DBI code:
1425 my $sth = $dbh->prepare($stmt);
1426 $sth->execute(@bind);
1428 =head2 Inserting and Updating Arrays
1430 If your database has array types (like for example Postgres),
1431 activate the special option C<< array_datatypes => 1 >>
1432 when creating the C<SQL::Abstract> object.
1433 Then you may use an arrayref to insert and update database array types:
1435 my $sql = SQL::Abstract->new(array_datatypes => 1);
1437 planets => [qw/Mercury Venus Earth Mars/]
1440 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1444 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1446 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1449 =head2 Inserting and Updating SQL
1451 In order to apply SQL functions to elements of your C<%data> you may
1452 specify a reference to an arrayref for the given hash value. For example,
1453 if you need to execute the Oracle C<to_date> function on a value, you can
1454 say something like this:
1458 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1461 The first value in the array is the actual SQL. Any other values are
1462 optional and would be included in the bind values array. This gives
1465 my($stmt, @bind) = $sql->insert('people', \%data);
1467 $stmt = "INSERT INTO people (name, date_entered)
1468 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1469 @bind = ('Bill', '03/02/2003');
1471 An UPDATE is just as easy, all you change is the name of the function:
1473 my($stmt, @bind) = $sql->update('people', \%data);
1475 Notice that your C<%data> isn't touched; the module will generate
1476 the appropriately quirky SQL for you automatically. Usually you'll
1477 want to specify a WHERE clause for your UPDATE, though, which is
1478 where handling C<%where> hashes comes in handy...
1480 =head2 Complex where statements
1482 This module can generate pretty complicated WHERE statements
1483 easily. For example, simple C<key=value> pairs are taken to mean
1484 equality, and if you want to see if a field is within a set
1485 of values, you can use an arrayref. Let's say we wanted to
1486 SELECT some data based on this criteria:
1489 requestor => 'inna',
1490 worker => ['nwiger', 'rcwe', 'sfz'],
1491 status => { '!=', 'completed' }
1494 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1496 The above would give you something like this:
1498 $stmt = "SELECT * FROM tickets WHERE
1499 ( requestor = ? ) AND ( status != ? )
1500 AND ( worker = ? OR worker = ? OR worker = ? )";
1501 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1503 Which you could then use in DBI code like so:
1505 my $sth = $dbh->prepare($stmt);
1506 $sth->execute(@bind);
1512 The functions are simple. There's one for each major SQL operation,
1513 and a constructor you use first. The arguments are specified in a
1514 similar order to each function (table, then fields, then a where
1515 clause) to try and simplify things.
1520 =head2 new(option => 'value')
1522 The C<new()> function takes a list of options and values, and returns
1523 a new B<SQL::Abstract> object which can then be used to generate SQL
1524 through the methods below. The options accepted are:
1530 If set to 'lower', then SQL will be generated in all lowercase. By
1531 default SQL is generated in "textbook" case meaning something like:
1533 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1535 Any setting other than 'lower' is ignored.
1539 This determines what the default comparison operator is. By default
1540 it is C<=>, meaning that a hash like this:
1542 %where = (name => 'nwiger', email => 'nate@wiger.org');
1544 Will generate SQL like this:
1546 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1548 However, you may want loose comparisons by default, so if you set
1549 C<cmp> to C<like> you would get SQL such as:
1551 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1553 You can also override the comparsion on an individual basis - see
1554 the huge section on L</"WHERE CLAUSES"> at the bottom.
1556 =item sqltrue, sqlfalse
1558 Expressions for inserting boolean values within SQL statements.
1559 By default these are C<1=1> and C<1=0>. They are used
1560 by the special operators C<-in> and C<-not_in> for generating
1561 correct SQL even when the argument is an empty array (see below).
1565 This determines the default logical operator for multiple WHERE
1566 statements in arrays or hashes. If absent, the default logic is "or"
1567 for arrays, and "and" for hashes. This means that a WHERE
1571 event_date => {'>=', '2/13/99'},
1572 event_date => {'<=', '4/24/03'},
1575 will generate SQL like this:
1577 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1579 This is probably not what you want given this query, though (look
1580 at the dates). To change the "OR" to an "AND", simply specify:
1582 my $sql = SQL::Abstract->new(logic => 'and');
1584 Which will change the above C<WHERE> to:
1586 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1588 The logic can also be changed locally by inserting
1589 a modifier in front of an arrayref :
1591 @where = (-and => [event_date => {'>=', '2/13/99'},
1592 event_date => {'<=', '4/24/03'} ]);
1594 See the L</"WHERE CLAUSES"> section for explanations.
1598 This will automatically convert comparisons using the specified SQL
1599 function for both column and value. This is mostly used with an argument
1600 of C<upper> or C<lower>, so that the SQL will have the effect of
1601 case-insensitive "searches". For example, this:
1603 $sql = SQL::Abstract->new(convert => 'upper');
1604 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1606 Will turn out the following SQL:
1608 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1610 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1611 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1612 not validate this option; it will just pass through what you specify verbatim).
1616 This is a kludge because many databases suck. For example, you can't
1617 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1618 Instead, you have to use C<bind_param()>:
1620 $sth->bind_param(1, 'reg data');
1621 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1623 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1624 which loses track of which field each slot refers to. Fear not.
1626 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1627 Currently, you can specify either C<normal> (default) or C<columns>. If you
1628 specify C<columns>, you will get an array that looks like this:
1630 my $sql = SQL::Abstract->new(bindtype => 'columns');
1631 my($stmt, @bind) = $sql->insert(...);
1634 [ 'column1', 'value1' ],
1635 [ 'column2', 'value2' ],
1636 [ 'column3', 'value3' ],
1639 You can then iterate through this manually, using DBI's C<bind_param()>.
1641 $sth->prepare($stmt);
1644 my($col, $data) = @$_;
1645 if ($col eq 'details' || $col eq 'comments') {
1646 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1647 } elsif ($col eq 'image') {
1648 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1650 $sth->bind_param($i, $data);
1654 $sth->execute; # execute without @bind now
1656 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1657 Basically, the advantage is still that you don't have to care which fields
1658 are or are not included. You could wrap that above C<for> loop in a simple
1659 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1660 get a layer of abstraction over manual SQL specification.
1662 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1663 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1664 will expect the bind values in this format.
1668 This is the character that a table or column name will be quoted
1669 with. By default this is an empty string, but you could set it to
1670 the character C<`>, to generate SQL like this:
1672 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1674 Alternatively, you can supply an array ref of two items, the first being the left
1675 hand quote character, and the second the right hand quote character. For
1676 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1677 that generates SQL like this:
1679 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1681 Quoting is useful if you have tables or columns names that are reserved
1682 words in your database's SQL dialect.
1686 This is the character that separates a table and column name. It is
1687 necessary to specify this when the C<quote_char> option is selected,
1688 so that tables and column names can be individually quoted like this:
1690 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1692 =item array_datatypes
1694 When this option is true, arrayrefs in INSERT or UPDATE are
1695 interpreted as array datatypes and are passed directly
1697 When this option is false, arrayrefs are interpreted
1698 as literal SQL, just like refs to arrayrefs
1699 (but this behavior is for backwards compatibility; when writing
1700 new queries, use the "reference to arrayref" syntax
1706 Takes a reference to a list of "special operators"
1707 to extend the syntax understood by L<SQL::Abstract>.
1708 See section L</"SPECIAL OPERATORS"> for details.
1712 Takes a reference to a list of "unary operators"
1713 to extend the syntax understood by L<SQL::Abstract>.
1714 See section L</"UNARY OPERATORS"> for details.
1720 =head2 insert($table, \@values || \%fieldvals, \%options)
1722 This is the simplest function. You simply give it a table name
1723 and either an arrayref of values or hashref of field/value pairs.
1724 It returns an SQL INSERT statement and a list of bind values.
1725 See the sections on L</"Inserting and Updating Arrays"> and
1726 L</"Inserting and Updating SQL"> for information on how to insert
1727 with those data types.
1729 The optional C<\%options> hash reference may contain additional
1730 options to generate the insert SQL. Currently supported options
1737 Takes either a scalar of raw SQL fields, or an array reference of
1738 field names, and adds on an SQL C<RETURNING> statement at the end.
1739 This allows you to return data generated by the insert statement
1740 (such as row IDs) without performing another C<SELECT> statement.
1741 Note, however, this is not part of the SQL standard and may not
1742 be supported by all database engines.
1746 =head2 update($table, \%fieldvals, \%where)
1748 This takes a table, hashref of field/value pairs, and an optional
1749 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1751 See the sections on L</"Inserting and Updating Arrays"> and
1752 L</"Inserting and Updating SQL"> for information on how to insert
1753 with those data types.
1755 =head2 select($source, $fields, $where, $order)
1757 This returns a SQL SELECT statement and associated list of bind values, as
1758 specified by the arguments :
1764 Specification of the 'FROM' part of the statement.
1765 The argument can be either a plain scalar (interpreted as a table
1766 name, will be quoted), or an arrayref (interpreted as a list
1767 of table names, joined by commas, quoted), or a scalarref
1768 (literal table name, not quoted), or a ref to an arrayref
1769 (list of literal table names, joined by commas, not quoted).
1773 Specification of the list of fields to retrieve from
1775 The argument can be either an arrayref (interpreted as a list
1776 of field names, will be joined by commas and quoted), or a
1777 plain scalar (literal SQL, not quoted).
1778 Please observe that this API is not as flexible as for
1779 the first argument C<$table>, for backwards compatibility reasons.
1783 Optional argument to specify the WHERE part of the query.
1784 The argument is most often a hashref, but can also be
1785 an arrayref or plain scalar --
1786 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1790 Optional argument to specify the ORDER BY part of the query.
1791 The argument can be a scalar, a hashref or an arrayref
1792 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1798 =head2 delete($table, \%where)
1800 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1801 It returns an SQL DELETE statement and list of bind values.
1803 =head2 where(\%where, \@order)
1805 This is used to generate just the WHERE clause. For example,
1806 if you have an arbitrary data structure and know what the
1807 rest of your SQL is going to look like, but want an easy way
1808 to produce a WHERE clause, use this. It returns an SQL WHERE
1809 clause and list of bind values.
1812 =head2 values(\%data)
1814 This just returns the values from the hash C<%data>, in the same
1815 order that would be returned from any of the other above queries.
1816 Using this allows you to markedly speed up your queries if you
1817 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1819 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1821 Warning: This is an experimental method and subject to change.
1823 This returns arbitrarily generated SQL. It's a really basic shortcut.
1824 It will return two different things, depending on return context:
1826 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1827 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1829 These would return the following:
1831 # First calling form
1832 $stmt = "CREATE TABLE test (?, ?)";
1833 @bind = (field1, field2);
1835 # Second calling form
1836 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1838 Depending on what you're trying to do, it's up to you to choose the correct
1839 format. In this example, the second form is what you would want.
1843 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1847 ALTER SESSION SET nls_date_format = 'MM/YY'
1849 You get the idea. Strings get their case twiddled, but everything
1850 else remains verbatim.
1855 =head1 WHERE CLAUSES
1859 This module uses a variation on the idea from L<DBIx::Abstract>. It
1860 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1861 module is that things in arrays are OR'ed, and things in hashes
1864 The easiest way to explain is to show lots of examples. After
1865 each C<%where> hash shown, it is assumed you used:
1867 my($stmt, @bind) = $sql->where(\%where);
1869 However, note that the C<%where> hash can be used directly in any
1870 of the other functions as well, as described above.
1872 =head2 Key-value pairs
1874 So, let's get started. To begin, a simple hash:
1878 status => 'completed'
1881 Is converted to SQL C<key = val> statements:
1883 $stmt = "WHERE user = ? AND status = ?";
1884 @bind = ('nwiger', 'completed');
1886 One common thing I end up doing is having a list of values that
1887 a field can be in. To do this, simply specify a list inside of
1892 status => ['assigned', 'in-progress', 'pending'];
1895 This simple code will create the following:
1897 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1898 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1900 A field associated to an empty arrayref will be considered a
1901 logical false and will generate 0=1.
1903 =head2 Specific comparison operators
1905 If you want to specify a different type of operator for your comparison,
1906 you can use a hashref for a given column:
1910 status => { '!=', 'completed' }
1913 Which would generate:
1915 $stmt = "WHERE user = ? AND status != ?";
1916 @bind = ('nwiger', 'completed');
1918 To test against multiple values, just enclose the values in an arrayref:
1920 status => { '=', ['assigned', 'in-progress', 'pending'] };
1922 Which would give you:
1924 "WHERE status = ? OR status = ? OR status = ?"
1927 The hashref can also contain multiple pairs, in which case it is expanded
1928 into an C<AND> of its elements:
1932 status => { '!=', 'completed', -not_like => 'pending%' }
1935 # Or more dynamically, like from a form
1936 $where{user} = 'nwiger';
1937 $where{status}{'!='} = 'completed';
1938 $where{status}{'-not_like'} = 'pending%';
1940 # Both generate this
1941 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1942 @bind = ('nwiger', 'completed', 'pending%');
1945 To get an OR instead, you can combine it with the arrayref idea:
1949 priority => [ {'=', 2}, {'!=', 1} ]
1952 Which would generate:
1954 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1955 @bind = ('nwiger', '2', '1');
1957 If you want to include literal SQL (with or without bind values), just use a
1958 scalar reference or array reference as the value:
1961 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1962 date_expires => { '<' => \"now()" }
1965 Which would generate:
1967 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1968 @bind = ('11/26/2008');
1971 =head2 Logic and nesting operators
1973 In the example above,
1974 there is a subtle trap if you want to say something like
1975 this (notice the C<AND>):
1977 WHERE priority != ? AND priority != ?
1979 Because, in Perl you I<can't> do this:
1981 priority => { '!=', 2, '!=', 1 }
1983 As the second C<!=> key will obliterate the first. The solution
1984 is to use the special C<-modifier> form inside an arrayref:
1986 priority => [ -and => {'!=', 2},
1990 Normally, these would be joined by C<OR>, but the modifier tells it
1991 to use C<AND> instead. (Hint: You can use this in conjunction with the
1992 C<logic> option to C<new()> in order to change the way your queries
1993 work by default.) B<Important:> Note that the C<-modifier> goes
1994 B<INSIDE> the arrayref, as an extra first element. This will
1995 B<NOT> do what you think it might:
1997 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1999 Here is a quick list of equivalencies, since there is some overlap:
2002 status => {'!=', 'completed', 'not like', 'pending%' }
2003 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2006 status => {'=', ['assigned', 'in-progress']}
2007 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2008 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2012 =head2 Special operators : IN, BETWEEN, etc.
2014 You can also use the hashref format to compare a list of fields using the
2015 C<IN> comparison operator, by specifying the list as an arrayref:
2018 status => 'completed',
2019 reportid => { -in => [567, 2335, 2] }
2022 Which would generate:
2024 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2025 @bind = ('completed', '567', '2335', '2');
2027 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2030 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2031 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2032 'sqltrue' (by default : C<1=1>).
2034 In addition to the array you can supply a chunk of literal sql or
2035 literal sql with bind:
2038 customer => { -in => \[
2039 'SELECT cust_id FROM cust WHERE balance > ?',
2042 status => { -in => \'SELECT status_codes FROM states' },
2048 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2049 AND status IN ( SELECT status_codes FROM states )
2055 Another pair of operators is C<-between> and C<-not_between>,
2056 used with an arrayref of two values:
2060 completion_date => {
2061 -not_between => ['2002-10-01', '2003-02-06']
2067 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2069 Just like with C<-in> all plausible combinations of literal SQL
2073 start0 => { -between => [ 1, 2 ] },
2074 start1 => { -between => \["? AND ?", 1, 2] },
2075 start2 => { -between => \"lower(x) AND upper(y)" },
2076 start3 => { -between => [
2078 \["upper(?)", 'stuff' ],
2085 ( start0 BETWEEN ? AND ? )
2086 AND ( start1 BETWEEN ? AND ? )
2087 AND ( start2 BETWEEN lower(x) AND upper(y) )
2088 AND ( start3 BETWEEN lower(x) AND upper(?) )
2090 @bind = (1, 2, 1, 2, 'stuff');
2093 These are the two builtin "special operators"; but the
2094 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2096 =head2 Unary operators: bool
2098 If you wish to test against boolean columns or functions within your
2099 database you can use the C<-bool> and C<-not_bool> operators. For
2100 example to test the column C<is_user> being true and the column
2101 <is_enabled> being false you would use:-
2105 -not_bool => 'is_enabled',
2110 WHERE is_user AND NOT is_enabled
2112 If a more complex combination is required, testing more conditions,
2113 then you should use the and/or operators:-
2120 -not_bool => 'four',
2126 WHERE one AND two AND three AND NOT four
2129 =head2 Nested conditions, -and/-or prefixes
2131 So far, we've seen how multiple conditions are joined with a top-level
2132 C<AND>. We can change this by putting the different conditions we want in
2133 hashes and then putting those hashes in an array. For example:
2138 status => { -like => ['pending%', 'dispatched'] },
2142 status => 'unassigned',
2146 This data structure would create the following:
2148 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2149 OR ( user = ? AND status = ? ) )";
2150 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2153 There is also a special C<-nest>
2154 operator which adds an additional set of parens, to create a subquery.
2155 For example, to get something like this:
2157 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2158 @bind = ('nwiger', '20', 'ASIA');
2164 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2168 Finally, clauses in hashrefs or arrayrefs can be
2169 prefixed with an C<-and> or C<-or> to change the logic
2176 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2177 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2184 WHERE ( user = ? AND
2185 ( ( workhrs > ? AND geo = ? )
2186 OR ( workhrs < ? AND geo = ? ) ) )
2189 =head2 Algebraic inconsistency, for historical reasons
2191 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2192 operator goes C<outside> of the nested structure; whereas when connecting
2193 several constraints on one column, the C<-and> operator goes
2194 C<inside> the arrayref. Here is an example combining both features :
2197 -and => [a => 1, b => 2],
2198 -or => [c => 3, d => 4],
2199 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2204 WHERE ( ( ( a = ? AND b = ? )
2205 OR ( c = ? OR d = ? )
2206 OR ( e LIKE ? AND e LIKE ? ) ) )
2208 This difference in syntax is unfortunate but must be preserved for
2209 historical reasons. So be careful : the two examples below would
2210 seem algebraically equivalent, but they are not
2212 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2213 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2215 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2216 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2221 Finally, sometimes only literal SQL will do. If you want to include
2222 literal SQL verbatim, you can specify it as a scalar reference, namely:
2224 my $inn = 'is Not Null';
2226 priority => { '<', 2 },
2232 $stmt = "WHERE priority < ? AND requestor is Not Null";
2235 Note that in this example, you only get one bind parameter back, since
2236 the verbatim SQL is passed as part of the statement.
2238 Of course, just to prove a point, the above can also be accomplished
2242 priority => { '<', 2 },
2243 requestor => { '!=', undef },
2249 Conditions on boolean columns can be expressed in the same way, passing
2250 a reference to an empty string, however using liternal SQL in this way
2251 is deprecated - the preferred method is to use the boolean operators -
2252 see L</"Unary operators: bool"> :
2255 priority => { '<', 2 },
2261 $stmt = "WHERE priority < ? AND is_ready";
2265 =head2 Literal SQL with placeholders and bind values (subqueries)
2267 If the literal SQL to be inserted has placeholders and bind values,
2268 use a reference to an arrayref (yes this is a double reference --
2269 not so common, but perfectly legal Perl). For example, to find a date
2270 in Postgres you can use something like this:
2273 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2278 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2281 Note that you must pass the bind values in the same format as they are returned
2282 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2283 provide the bind values in the C<< [ column_meta => value ] >> format, where
2284 C<column_meta> is an opaque scalar value; most commonly the column name, but
2285 you can use any scalar value (including references and blessed references),
2286 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2287 to C<columns> the above example will look like:
2290 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2293 Literal SQL is especially useful for nesting parenthesized clauses in the
2294 main SQL query. Here is a first example :
2296 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2300 bar => \["IN ($sub_stmt)" => @sub_bind],
2305 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2306 WHERE c2 < ? AND c3 LIKE ?))";
2307 @bind = (1234, 100, "foo%");
2309 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2310 are expressed in the same way. Of course the C<$sub_stmt> and
2311 its associated bind values can be generated through a former call
2314 my ($sub_stmt, @sub_bind)
2315 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2316 c3 => {-like => "foo%"}});
2319 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2322 In the examples above, the subquery was used as an operator on a column;
2323 but the same principle also applies for a clause within the main C<%where>
2324 hash, like an EXISTS subquery :
2326 my ($sub_stmt, @sub_bind)
2327 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2330 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2335 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2336 WHERE c1 = ? AND c2 > t0.c0))";
2340 Observe that the condition on C<c2> in the subquery refers to
2341 column C<t0.c0> of the main query : this is I<not> a bind
2342 value, so we have to express it through a scalar ref.
2343 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2344 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2345 what we wanted here.
2347 Another use of the subquery technique is when some SQL clauses need
2348 parentheses, as it often occurs with some proprietary SQL extensions
2349 like for example fulltext expressions, geospatial expressions,
2350 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2353 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2356 Finally, here is an example where a subquery is used
2357 for expressing unary negation:
2359 my ($sub_stmt, @sub_bind)
2360 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2361 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2363 lname => {like => '%son%'},
2364 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2369 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2370 @bind = ('%son%', 10, 20)
2376 These pages could go on for a while, since the nesting of the data
2377 structures this module can handle are pretty much unlimited (the
2378 module implements the C<WHERE> expansion as a recursive function
2379 internally). Your best bet is to "play around" with the module a
2380 little to see how the data structures behave, and choose the best
2381 format for your data based on that.
2383 And of course, all the values above will probably be replaced with
2384 variables gotten from forms or the command line. After all, if you
2385 knew everything ahead of time, you wouldn't have to worry about
2386 dynamically-generating SQL and could just hardwire it into your
2392 =head1 ORDER BY CLAUSES
2394 Some functions take an order by clause. This can either be a scalar (just a
2395 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2396 or an array of either of the two previous forms. Examples:
2398 Given | Will Generate
2399 ----------------------------------------------------------
2401 \'colA DESC' | ORDER BY colA DESC
2403 'colA' | ORDER BY colA
2405 [qw/colA colB/] | ORDER BY colA, colB
2407 {-asc => 'colA'} | ORDER BY colA ASC
2409 {-desc => 'colB'} | ORDER BY colB DESC
2411 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2413 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2416 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2417 { -desc => [qw/colB/], | colC ASC, colD ASC
2418 { -asc => [qw/colC colD/],|
2420 ===========================================================
2424 =head1 SPECIAL OPERATORS
2426 my $sqlmaker = SQL::Abstract->new(special_ops => [
2430 my ($self, $field, $op, $arg) = @_;
2436 handler => 'method_name',
2440 A "special operator" is a SQL syntactic clause that can be
2441 applied to a field, instead of a usual binary operator.
2444 WHERE field IN (?, ?, ?)
2445 WHERE field BETWEEN ? AND ?
2446 WHERE MATCH(field) AGAINST (?, ?)
2448 Special operators IN and BETWEEN are fairly standard and therefore
2449 are builtin within C<SQL::Abstract> (as the overridable methods
2450 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2451 like the MATCH .. AGAINST example above which is specific to MySQL,
2452 you can write your own operator handlers - supply a C<special_ops>
2453 argument to the C<new> method. That argument takes an arrayref of
2454 operator definitions; each operator definition is a hashref with two
2461 the regular expression to match the operator
2465 Either a coderef or a plain scalar method name. In both cases
2466 the expected return is C<< ($sql, @bind) >>.
2468 When supplied with a method name, it is simply called on the
2469 L<SQL::Abstract/> object as:
2471 $self->$method_name ($field, $op, $arg)
2475 $op is the part that matched the handler regex
2476 $field is the LHS of the operator
2479 When supplied with a coderef, it is called as:
2481 $coderef->($self, $field, $op, $arg)
2486 For example, here is an implementation
2487 of the MATCH .. AGAINST syntax for MySQL
2489 my $sqlmaker = SQL::Abstract->new(special_ops => [
2491 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2492 {regex => qr/^match$/i,
2494 my ($self, $field, $op, $arg) = @_;
2495 $arg = [$arg] if not ref $arg;
2496 my $label = $self->_quote($field);
2497 my ($placeholder) = $self->_convert('?');
2498 my $placeholders = join ", ", (($placeholder) x @$arg);
2499 my $sql = $self->_sqlcase('match') . " ($label) "
2500 . $self->_sqlcase('against') . " ($placeholders) ";
2501 my @bind = $self->_bindtype($field, @$arg);
2502 return ($sql, @bind);
2509 =head1 UNARY OPERATORS
2511 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2515 my ($self, $op, $arg) = @_;
2521 handler => 'method_name',
2525 A "unary operator" is a SQL syntactic clause that can be
2526 applied to a field - the operator goes before the field
2528 You can write your own operator handlers - supply a C<unary_ops>
2529 argument to the C<new> method. That argument takes an arrayref of
2530 operator definitions; each operator definition is a hashref with two
2537 the regular expression to match the operator
2541 Either a coderef or a plain scalar method name. In both cases
2542 the expected return is C<< $sql >>.
2544 When supplied with a method name, it is simply called on the
2545 L<SQL::Abstract/> object as:
2547 $self->$method_name ($op, $arg)
2551 $op is the part that matched the handler regex
2552 $arg is the RHS or argument of the operator
2554 When supplied with a coderef, it is called as:
2556 $coderef->($self, $op, $arg)
2564 Thanks to some benchmarking by Mark Stosberg, it turns out that
2565 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2566 I must admit this wasn't an intentional design issue, but it's a
2567 byproduct of the fact that you get to control your C<DBI> handles
2570 To maximize performance, use a code snippet like the following:
2572 # prepare a statement handle using the first row
2573 # and then reuse it for the rest of the rows
2575 for my $href (@array_of_hashrefs) {
2576 $stmt ||= $sql->insert('table', $href);
2577 $sth ||= $dbh->prepare($stmt);
2578 $sth->execute($sql->values($href));
2581 The reason this works is because the keys in your C<$href> are sorted
2582 internally by B<SQL::Abstract>. Thus, as long as your data retains
2583 the same structure, you only have to generate the SQL the first time
2584 around. On subsequent queries, simply use the C<values> function provided
2585 by this module to return your values in the correct order.
2590 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2591 really like this part (I do, at least). Building up a complex query
2592 can be as simple as the following:
2596 use CGI::FormBuilder;
2599 my $form = CGI::FormBuilder->new(...);
2600 my $sql = SQL::Abstract->new;
2602 if ($form->submitted) {
2603 my $field = $form->field;
2604 my $id = delete $field->{id};
2605 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2608 Of course, you would still have to connect using C<DBI> to run the
2609 query, but the point is that if you make your form look like your
2610 table, the actual query script can be extremely simplistic.
2612 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2613 a fast interface to returning and formatting data. I frequently
2614 use these three modules together to write complex database query
2615 apps in under 50 lines.
2620 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2621 Great care has been taken to preserve the I<published> behavior
2622 documented in previous versions in the 1.* family; however,
2623 some features that were previously undocumented, or behaved
2624 differently from the documentation, had to be changed in order
2625 to clarify the semantics. Hence, client code that was relying
2626 on some dark areas of C<SQL::Abstract> v1.*
2627 B<might behave differently> in v1.50.
2629 The main changes are :
2635 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2639 support for the { operator => \"..." } construct (to embed literal SQL)
2643 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2647 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2651 defensive programming : check arguments
2655 fixed bug with global logic, which was previously implemented
2656 through global variables yielding side-effects. Prior versions would
2657 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2658 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2659 Now this is interpreted
2660 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2665 fixed semantics of _bindtype on array args
2669 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2670 we just avoid shifting arrays within that tree.
2674 dropped the C<_modlogic> function
2680 =head1 ACKNOWLEDGEMENTS
2682 There are a number of individuals that have really helped out with
2683 this module. Unfortunately, most of them submitted bugs via CPAN
2684 so I have no idea who they are! But the people I do know are:
2686 Ash Berlin (order_by hash term support)
2687 Matt Trout (DBIx::Class support)
2688 Mark Stosberg (benchmarking)
2689 Chas Owens (initial "IN" operator support)
2690 Philip Collins (per-field SQL functions)
2691 Eric Kolve (hashref "AND" support)
2692 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2693 Dan Kubb (support for "quote_char" and "name_sep")
2694 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2695 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2696 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2697 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2698 Oliver Charles (support for "RETURNING" after "INSERT")
2704 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2708 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2710 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2712 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2713 While not an official support venue, C<DBIx::Class> makes heavy use of
2714 C<SQL::Abstract>, and as such list members there are very familiar with
2715 how to create queries.
2719 This module is free software; you may copy this under the same
2720 terms as perl itself (either the GNU General Public License or
2721 the Artistic License)