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)
11 use List::Util qw/first/;
12 use Scalar::Util qw/blessed/;
14 #======================================================================
16 #======================================================================
18 our $VERSION = '1.61';
20 # This would confuse some packagers
21 #$VERSION = eval $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 $fields = $options->{returning}) {
122 my $f = $self->_SWITCH_refkind($fields, {
123 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$fields;},
124 SCALAR => sub {$self->_quote($fields)},
125 SCALARREF => sub {$$fields},
127 $sql .= join " ", $self->_sqlcase(' returning'), $f;
130 return wantarray ? ($sql, @bind) : $sql;
133 sub _insert_HASHREF { # explicit list of fields and then values
134 my ($self, $data) = @_;
136 my @fields = sort keys %$data;
138 my ($sql, @bind) = $self->_insert_values($data);
141 $_ = $self->_quote($_) foreach @fields;
142 $sql = "( ".join(", ", @fields).") ".$sql;
144 return ($sql, @bind);
147 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
148 my ($self, $data) = @_;
150 # no names (arrayref) so can't generate bindtype
151 $self->{bindtype} ne 'columns'
152 or belch "can't do 'columns' bindtype when called with arrayref";
154 # fold the list of values into a hash of column name - value pairs
155 # (where the column names are artificially generated, and their
156 # lexicographical ordering keep the ordering of the original list)
157 my $i = "a"; # incremented values will be in lexicographical order
158 my $data_in_hash = { map { ($i++ => $_) } @$data };
160 return $self->_insert_values($data_in_hash);
163 sub _insert_ARRAYREFREF { # literal SQL with bind
164 my ($self, $data) = @_;
166 my ($sql, @bind) = @${$data};
167 $self->_assert_bindval_matches_bindtype(@bind);
169 return ($sql, @bind);
173 sub _insert_SCALARREF { # literal SQL without bind
174 my ($self, $data) = @_;
180 my ($self, $data) = @_;
182 my (@values, @all_bind);
183 foreach my $column (sort keys %$data) {
184 my $v = $data->{$column};
186 $self->_SWITCH_refkind($v, {
189 if ($self->{array_datatypes}) { # if array datatype are activated
191 push @all_bind, $self->_bindtype($column, $v);
193 else { # else literal SQL with bind
194 my ($sql, @bind) = @$v;
195 $self->_assert_bindval_matches_bindtype(@bind);
197 push @all_bind, @bind;
201 ARRAYREFREF => sub { # literal SQL with bind
202 my ($sql, @bind) = @${$v};
203 $self->_assert_bindval_matches_bindtype(@bind);
205 push @all_bind, @bind;
208 # THINK : anything useful to do with a HASHREF ?
209 HASHREF => sub { # (nothing, but old SQLA passed it through)
210 #TODO in SQLA >= 2.0 it will die instead
211 belch "HASH ref as bind value in insert is not supported";
213 push @all_bind, $self->_bindtype($column, $v);
216 SCALARREF => sub { # literal SQL without bind
220 SCALAR_or_UNDEF => sub {
222 push @all_bind, $self->_bindtype($column, $v);
229 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
230 return ($sql, @all_bind);
235 #======================================================================
237 #======================================================================
242 my $table = $self->_table(shift);
243 my $data = shift || return;
246 # first build the 'SET' part of the sql statement
247 my (@set, @all_bind);
248 puke "Unsupported data type specified to \$sql->update"
249 unless ref $data eq 'HASH';
251 for my $k (sort keys %$data) {
254 my $label = $self->_quote($k);
256 $self->_SWITCH_refkind($v, {
258 if ($self->{array_datatypes}) { # array datatype
259 push @set, "$label = ?";
260 push @all_bind, $self->_bindtype($k, $v);
262 else { # literal SQL with bind
263 my ($sql, @bind) = @$v;
264 $self->_assert_bindval_matches_bindtype(@bind);
265 push @set, "$label = $sql";
266 push @all_bind, @bind;
269 ARRAYREFREF => sub { # literal SQL with bind
270 my ($sql, @bind) = @${$v};
271 $self->_assert_bindval_matches_bindtype(@bind);
272 push @set, "$label = $sql";
273 push @all_bind, @bind;
275 SCALARREF => sub { # literal SQL without bind
276 push @set, "$label = $$v";
278 SCALAR_or_UNDEF => sub {
279 push @set, "$label = ?";
280 push @all_bind, $self->_bindtype($k, $v);
286 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
290 my($where_sql, @where_bind) = $self->where($where);
292 push @all_bind, @where_bind;
295 return wantarray ? ($sql, @all_bind) : $sql;
301 #======================================================================
303 #======================================================================
308 my $table = $self->_table(shift);
309 my $fields = shift || '*';
313 my($where_sql, @bind) = $self->where($where, $order);
315 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
317 my $sql = join(' ', $self->_sqlcase('select'), $f,
318 $self->_sqlcase('from'), $table)
321 return wantarray ? ($sql, @bind) : $sql;
324 #======================================================================
326 #======================================================================
331 my $table = $self->_table(shift);
335 my($where_sql, @bind) = $self->where($where);
336 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
338 return wantarray ? ($sql, @bind) : $sql;
342 #======================================================================
344 #======================================================================
348 # Finally, a separate routine just to handle WHERE clauses
350 my ($self, $where, $order) = @_;
353 my ($sql, @bind) = $self->_recurse_where($where);
354 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
358 $sql .= $self->_order_by($order);
361 return wantarray ? ($sql, @bind) : $sql;
366 my ($self, $where, $logic) = @_;
368 # dispatch on appropriate method according to refkind of $where
369 my $method = $self->_METHOD_FOR_refkind("_where", $where);
372 my ($sql, @bind) = $self->$method($where, $logic);
374 # DBIx::Class directly calls _recurse_where in scalar context, so
375 # we must implement it, even if not in the official API
376 return wantarray ? ($sql, @bind) : $sql;
381 #======================================================================
382 # WHERE: top-level ARRAYREF
383 #======================================================================
386 sub _where_ARRAYREF {
387 my ($self, $where, $logic) = @_;
389 $logic = uc($logic || $self->{logic});
390 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
392 my @clauses = @$where;
394 my (@sql_clauses, @all_bind);
395 # need to use while() so can shift() for pairs
396 while (my $el = shift @clauses) {
398 # switch according to kind of $el and get corresponding ($sql, @bind)
399 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
401 # skip empty elements, otherwise get invalid trailing AND stuff
402 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
404 ARRAYREFREF => sub { @{${$el}} if @{${$el}}},
406 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
407 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
408 # side-effect: the first hashref within an array would change
409 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
410 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
411 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
413 SCALARREF => sub { ($$el); },
415 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
416 $self->_recurse_where({$el => shift(@clauses)})},
418 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
422 push @sql_clauses, $sql;
423 push @all_bind, @bind;
427 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
430 #======================================================================
431 # WHERE: top-level ARRAYREFREF
432 #======================================================================
434 sub _where_ARRAYREFREF {
435 my ($self, $where) = @_;
436 my ($sql, @bind) = @{${$where}};
438 return ($sql, @bind);
441 #======================================================================
442 # WHERE: top-level HASHREF
443 #======================================================================
446 my ($self, $where) = @_;
447 my (@sql_clauses, @all_bind);
449 for my $k (sort keys %$where) {
450 my $v = $where->{$k};
452 # ($k => $v) is either a special op or a regular hashpair
453 my ($sql, @bind) = ($k =~ /^(-.+)/) ? $self->_where_op_in_hash($1, $v)
455 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
456 $self->$method($k, $v);
459 push @sql_clauses, $sql;
460 push @all_bind, @bind;
463 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
467 sub _where_op_in_hash {
468 my ($self, $orig_op, $v) = @_;
470 # put the operator in canonical form
472 $op =~ s/^-//; # remove initial dash
473 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
474 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
476 $self->_debug("OP(-$op) within hashref, recursing...");
478 my $op_entry = first {$op =~ $_->{regex}} @{$self->{unary_ops}};
479 my $handler = $op_entry->{handler};
481 puke "unknown operator: $orig_op";
483 elsif (not ref $handler) {
484 if ($op =~ s/\s?\d+$//) {
485 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
486 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
488 return $self->$handler ($op, $v);
490 elsif (ref $handler eq 'CODE') {
491 return $handler->($self, $op, $v);
494 puke "Illegal handler for operator $orig_op - expecting a method name or a coderef";
498 sub _where_op_ANDOR {
499 my ($self, $op, $v) = @_;
501 $self->_SWITCH_refkind($v, {
503 return $self->_where_ARRAYREF($v, $op);
507 return ( $op =~ /^or/i )
508 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
509 : $self->_where_HASHREF($v);
513 puke "-$op => \\\$scalar not supported, use -nest => ...";
517 puke "-$op => \\[..] not supported, use -nest => ...";
520 SCALAR => sub { # permissively interpreted as SQL
521 puke "-$op => 'scalar' not supported, use -nest => \\'scalar'";
525 puke "-$op => undef not supported";
531 my ($self, $op, $v) = @_;
533 $self->_SWITCH_refkind($v, {
536 return $self->_where_ARRAYREF($v, '');
540 return $self->_where_HASHREF($v);
543 SCALARREF => sub { # literal SQL
547 ARRAYREFREF => sub { # literal SQL
551 SCALAR => sub { # permissively interpreted as SQL
552 belch "literal SQL should be -nest => \\'scalar' "
553 . "instead of -nest => 'scalar' ";
558 puke "-$op => undef not supported";
565 my ($self, $op, $v) = @_;
567 my ( $prefix, $suffix ) = ( $op =~ /\bnot\b/i )
570 $self->_SWITCH_refkind($v, {
572 my ( $sql, @bind ) = $self->_where_ARRAYREF($v, '');
573 return ( ($prefix . $sql . $suffix), @bind );
577 my ( $sql, @bind ) = @{ ${$v} };
578 return ( ($prefix . $sql . $suffix), @bind );
582 my ( $sql, @bind ) = $self->_where_HASHREF($v);
583 return ( ($prefix . $sql . $suffix), @bind );
586 SCALARREF => sub { # literal SQL
587 return ($prefix . $$v . $suffix);
590 SCALAR => sub { # interpreted as SQL column
591 return ($prefix . $self->_convert($self->_quote($v)) . $suffix);
595 puke "-$op => undef not supported";
601 sub _where_hashpair_ARRAYREF {
602 my ($self, $k, $v) = @_;
605 my @v = @$v; # need copy because of shift below
606 $self->_debug("ARRAY($k) means distribute over elements");
608 # put apart first element if it is an operator (-and, -or)
610 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
614 my @distributed = map { {$k => $_} } @v;
617 $self->_debug("OP($op) reinjected into the distributed array");
618 unshift @distributed, $op;
621 my $logic = $op ? substr($op, 1) : '';
623 return $self->_recurse_where(\@distributed, $logic);
626 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
627 $self->_debug("empty ARRAY($k) means 0=1");
628 return ($self->{sqlfalse});
632 sub _where_hashpair_HASHREF {
633 my ($self, $k, $v, $logic) = @_;
636 my ($all_sql, @all_bind);
638 for my $orig_op (sort keys %$v) {
639 my $val = $v->{$orig_op};
641 # put the operator in canonical form
643 $op =~ s/^-//; # remove initial dash
644 $op =~ s/[_\t ]+/ /g; # underscores and whitespace become single spaces
645 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
649 # CASE: special operators like -in or -between
650 my $special_op = first {$op =~ $_->{regex}} @{$self->{special_ops}};
652 my $handler = $special_op->{handler};
654 puke "No handler supplied for special operator $orig_op";
656 elsif (not ref $handler) {
657 ($sql, @bind) = $self->$handler ($k, $op, $val);
659 elsif (ref $handler eq 'CODE') {
660 ($sql, @bind) = $handler->($self, $k, $op, $val);
663 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
667 $self->_SWITCH_refkind($val, {
669 ARRAYREF => sub { # CASE: col => {op => \@vals}
670 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
673 SCALARREF => sub { # CASE: col => {op => \$scalar} (literal SQL without bind)
674 $sql = join ' ', $self->_convert($self->_quote($k)),
675 $self->_sqlcase($op),
679 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
680 my ($sub_sql, @sub_bind) = @$$val;
681 $self->_assert_bindval_matches_bindtype(@sub_bind);
682 $sql = join ' ', $self->_convert($self->_quote($k)),
683 $self->_sqlcase($op),
689 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $op);
692 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
693 my $is = ($op =~ $self->{equality_op}) ? 'is' :
694 ($op =~ $self->{inequality_op}) ? 'is not' :
695 puke "unexpected operator '$orig_op' with undef operand";
696 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
699 FALLBACK => sub { # CASE: col => {op => $scalar}
700 $sql = join ' ', $self->_convert($self->_quote($k)),
701 $self->_sqlcase($op),
702 $self->_convert('?');
703 @bind = $self->_bindtype($k, $val);
708 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
709 push @all_bind, @bind;
711 return ($all_sql, @all_bind);
716 sub _where_field_op_ARRAYREF {
717 my ($self, $k, $op, $vals) = @_;
719 my @vals = @$vals; #always work on a copy
722 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
724 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
727 # see if the first element is an -and/-or op
729 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
734 # distribute $op over each remaining member of @vals, append logic if exists
735 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
737 # LDNOTE : had planned to change the distribution logic when
738 # $op =~ $self->{inequality_op}, because of Morgan laws :
739 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
740 # WHERE field != 22 OR field != 33 : the user probably means
741 # WHERE field != 22 AND field != 33.
742 # To do this, replace the above to roughly :
743 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
744 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
748 # try to DWIM on equality operators
749 # LDNOTE : not 100% sure this is the correct thing to do ...
750 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
751 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
754 puke "operator '$op' applied on an empty array (field '$k')";
759 sub _where_hashpair_SCALARREF {
760 my ($self, $k, $v) = @_;
761 $self->_debug("SCALAR($k) means literal SQL: $$v");
762 my $sql = $self->_quote($k) . " " . $$v;
766 # literal SQL with bind
767 sub _where_hashpair_ARRAYREFREF {
768 my ($self, $k, $v) = @_;
769 $self->_debug("REF($k) means literal SQL: @${$v}");
770 my ($sql, @bind) = @${$v};
771 $self->_assert_bindval_matches_bindtype(@bind);
772 $sql = $self->_quote($k) . " " . $sql;
773 return ($sql, @bind );
776 # literal SQL without bind
777 sub _where_hashpair_SCALAR {
778 my ($self, $k, $v) = @_;
779 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
780 my $sql = join ' ', $self->_convert($self->_quote($k)),
781 $self->_sqlcase($self->{cmp}),
782 $self->_convert('?');
783 my @bind = $self->_bindtype($k, $v);
784 return ( $sql, @bind);
788 sub _where_hashpair_UNDEF {
789 my ($self, $k, $v) = @_;
790 $self->_debug("UNDEF($k) means IS NULL");
791 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
795 #======================================================================
796 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
797 #======================================================================
800 sub _where_SCALARREF {
801 my ($self, $where) = @_;
804 $self->_debug("SCALAR(*top) means literal SQL: $$where");
810 my ($self, $where) = @_;
813 $self->_debug("NOREF(*top) means literal SQL: $where");
824 #======================================================================
825 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
826 #======================================================================
829 sub _where_field_BETWEEN {
830 my ($self, $k, $op, $vals) = @_;
832 my ($label, $and, $placeholder);
833 $label = $self->_convert($self->_quote($k));
834 $and = ' ' . $self->_sqlcase('and') . ' ';
835 $placeholder = $self->_convert('?');
836 $op = $self->_sqlcase($op);
838 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
846 puke "special op 'between' accepts an arrayref with exactly two values"
849 my (@all_sql, @all_bind);
850 foreach my $val (@$vals) {
851 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
853 return ($placeholder, ($val));
856 return ($self->_convert($$val), ());
859 my ($sql, @bind) = @$$val;
860 return ($self->_convert($sql), @bind);
864 push @all_bind, @bind;
868 (join $and, @all_sql),
869 $self->_bindtype($k, @all_bind),
873 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
877 my $sql = "( $label $op $clause )";
882 sub _where_field_IN {
883 my ($self, $k, $op, $vals) = @_;
885 # backwards compatibility : if scalar, force into an arrayref
886 $vals = [$vals] if defined $vals && ! ref $vals;
888 my ($label) = $self->_convert($self->_quote($k));
889 my ($placeholder) = $self->_convert('?');
890 $op = $self->_sqlcase($op);
892 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
893 ARRAYREF => sub { # list of choices
894 if (@$vals) { # nonempty list
895 my $placeholders = join ", ", (($placeholder) x @$vals);
896 my $sql = "$label $op ( $placeholders )";
897 my @bind = $self->_bindtype($k, @$vals);
899 return ($sql, @bind);
901 else { # empty list : some databases won't understand "IN ()", so DWIM
902 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
907 SCALARREF => sub { # literal SQL
908 my $sql = $self->_open_outer_paren ($$vals);
909 return ("$label $op ( $sql )");
911 ARRAYREFREF => sub { # literal SQL with bind
912 my ($sql, @bind) = @$$vals;
913 $self->_assert_bindval_matches_bindtype(@bind);
914 $sql = $self->_open_outer_paren ($sql);
915 return ("$label $op ( $sql )", @bind);
919 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
923 return ($sql, @bind);
926 # Some databases (SQLite) treat col IN (1, 2) different from
927 # col IN ( (1, 2) ). Use this to strip all outer parens while
928 # adding them back in the corresponding method
929 sub _open_outer_paren {
930 my ($self, $sql) = @_;
931 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
936 #======================================================================
938 #======================================================================
941 my ($self, $arg) = @_;
944 for my $c ($self->_order_by_chunks ($arg) ) {
945 $self->_SWITCH_refkind ($c, {
946 SCALAR => sub { push @sql, $c },
947 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
953 $self->_sqlcase(' order by'),
959 return wantarray ? ($sql, @bind) : $sql;
962 sub _order_by_chunks {
963 my ($self, $arg) = @_;
965 return $self->_SWITCH_refkind($arg, {
968 map { $self->_order_by_chunks ($_ ) } @$arg;
971 ARRAYREFREF => sub { [ @$$arg ] },
973 SCALAR => sub {$self->_quote($arg)},
975 UNDEF => sub {return () },
977 SCALARREF => sub {$$arg}, # literal SQL, no quoting
980 # get first pair in hash
981 my ($key, $val) = each %$arg;
983 return () unless $key;
985 if ( (keys %$arg) > 1 or not $key =~ /^-(desc|asc)/i ) {
986 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
992 for my $c ($self->_order_by_chunks ($val)) {
995 $self->_SWITCH_refkind ($c, {
1000 ($sql, @bind) = @$c;
1004 $sql = $sql . ' ' . $self->_sqlcase($direction);
1006 push @ret, [ $sql, @bind];
1015 #======================================================================
1016 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1017 #======================================================================
1022 $self->_SWITCH_refkind($from, {
1023 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1024 SCALAR => sub {$self->_quote($from)},
1025 SCALARREF => sub {$$from},
1026 ARRAYREFREF => sub {join ', ', @$from;},
1031 #======================================================================
1033 #======================================================================
1039 $label or puke "can't quote an empty label";
1041 # left and right quote characters
1042 my ($ql, $qr, @other) = $self->_SWITCH_refkind($self->{quote_char}, {
1043 SCALAR => sub {($self->{quote_char}, $self->{quote_char})},
1044 ARRAYREF => sub {@{$self->{quote_char}}},
1048 or puke "quote_char must be an arrayref of 2 values";
1050 # no quoting if no quoting chars
1051 $ql or return $label;
1053 # no quoting for literal SQL
1054 return $$label if ref($label) eq 'SCALAR';
1056 # separate table / column (if applicable)
1057 my $sep = $self->{name_sep} || '';
1058 my @to_quote = $sep ? split /\Q$sep\E/, $label : ($label);
1060 # do the quoting, except for "*" or for `table`.*
1061 my @quoted = map { $_ eq '*' ? $_: $ql.$_.$qr} @to_quote;
1063 # reassemble and return.
1064 return join $sep, @quoted;
1068 # Conversion, if applicable
1070 my ($self, $arg) = @_;
1072 # LDNOTE : modified the previous implementation below because
1073 # it was not consistent : the first "return" is always an array,
1074 # the second "return" is context-dependent. Anyway, _convert
1075 # seems always used with just a single argument, so make it a
1077 # return @_ unless $self->{convert};
1078 # my $conv = $self->_sqlcase($self->{convert});
1079 # my @ret = map { $conv.'('.$_.')' } @_;
1080 # return wantarray ? @ret : $ret[0];
1081 if ($self->{convert}) {
1082 my $conv = $self->_sqlcase($self->{convert});
1083 $arg = $conv.'('.$arg.')';
1091 my($col, @vals) = @_;
1093 #LDNOTE : changed original implementation below because it did not make
1094 # sense when bindtype eq 'columns' and @vals > 1.
1095 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1097 return $self->{bindtype} eq 'columns' ? map {[$col, $_]} @vals : @vals;
1100 # Dies if any element of @bind is not in [colname => value] format
1101 # if bindtype is 'columns'.
1102 sub _assert_bindval_matches_bindtype {
1103 my ($self, @bind) = @_;
1105 if ($self->{bindtype} eq 'columns') {
1106 foreach my $val (@bind) {
1107 if (!defined $val || ref($val) ne 'ARRAY' || @$val != 2) {
1108 die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1114 sub _join_sql_clauses {
1115 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1117 if (@$clauses_aref > 1) {
1118 my $join = " " . $self->_sqlcase($logic) . " ";
1119 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1120 return ($sql, @$bind_aref);
1122 elsif (@$clauses_aref) {
1123 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1126 return (); # if no SQL, ignore @$bind_aref
1131 # Fix SQL case, if so requested
1135 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1136 # don't touch the argument ... crooked logic, but let's not change it!
1137 return $self->{case} ? $_[0] : uc($_[0]);
1141 #======================================================================
1142 # DISPATCHING FROM REFKIND
1143 #======================================================================
1146 my ($self, $data) = @_;
1152 # blessed objects are treated like scalars
1153 $ref = (blessed $data) ? '' : ref $data;
1154 $n_steps += 1 if $ref;
1155 last if $ref ne 'REF';
1159 my $base = $ref || (defined $data ? 'SCALAR' : 'UNDEF');
1161 return $base . ('REF' x $n_steps);
1167 my ($self, $data) = @_;
1168 my @try = ($self->_refkind($data));
1169 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1170 push @try, 'FALLBACK';
1174 sub _METHOD_FOR_refkind {
1175 my ($self, $meth_prefix, $data) = @_;
1176 my $method = first {$_} map {$self->can($meth_prefix."_".$_)}
1177 $self->_try_refkind($data)
1178 or puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1183 sub _SWITCH_refkind {
1184 my ($self, $data, $dispatch_table) = @_;
1186 my $coderef = first {$_} map {$dispatch_table->{$_}}
1187 $self->_try_refkind($data)
1188 or puke "no dispatch entry for ".$self->_refkind($data);
1195 #======================================================================
1196 # VALUES, GENERATE, AUTOLOAD
1197 #======================================================================
1199 # LDNOTE: original code from nwiger, didn't touch code in that section
1200 # I feel the AUTOLOAD stuff should not be the default, it should
1201 # only be activated on explicit demand by user.
1205 my $data = shift || return;
1206 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1207 unless ref $data eq 'HASH';
1210 foreach my $k ( sort keys %$data ) {
1211 my $v = $data->{$k};
1212 $self->_SWITCH_refkind($v, {
1214 if ($self->{array_datatypes}) { # array datatype
1215 push @all_bind, $self->_bindtype($k, $v);
1217 else { # literal SQL with bind
1218 my ($sql, @bind) = @$v;
1219 $self->_assert_bindval_matches_bindtype(@bind);
1220 push @all_bind, @bind;
1223 ARRAYREFREF => sub { # literal SQL with bind
1224 my ($sql, @bind) = @${$v};
1225 $self->_assert_bindval_matches_bindtype(@bind);
1226 push @all_bind, @bind;
1228 SCALARREF => sub { # literal SQL without bind
1230 SCALAR_or_UNDEF => sub {
1231 push @all_bind, $self->_bindtype($k, $v);
1242 my(@sql, @sqlq, @sqlv);
1246 if ($ref eq 'HASH') {
1247 for my $k (sort keys %$_) {
1250 my $label = $self->_quote($k);
1251 if ($r eq 'ARRAY') {
1252 # literal SQL with bind
1253 my ($sql, @bind) = @$v;
1254 $self->_assert_bindval_matches_bindtype(@bind);
1255 push @sqlq, "$label = $sql";
1257 } elsif ($r eq 'SCALAR') {
1258 # literal SQL without bind
1259 push @sqlq, "$label = $$v";
1261 push @sqlq, "$label = ?";
1262 push @sqlv, $self->_bindtype($k, $v);
1265 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1266 } elsif ($ref eq 'ARRAY') {
1267 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1270 if ($r eq 'ARRAY') { # literal SQL with bind
1271 my ($sql, @bind) = @$v;
1272 $self->_assert_bindval_matches_bindtype(@bind);
1275 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1276 # embedded literal SQL
1283 push @sql, '(' . join(', ', @sqlq) . ')';
1284 } elsif ($ref eq 'SCALAR') {
1288 # strings get case twiddled
1289 push @sql, $self->_sqlcase($_);
1293 my $sql = join ' ', @sql;
1295 # this is pretty tricky
1296 # if ask for an array, return ($stmt, @bind)
1297 # otherwise, s/?/shift @sqlv/ to put it inline
1299 return ($sql, @sqlv);
1301 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1302 ref $d ? $d->[1] : $d/e;
1311 # This allows us to check for a local, then _form, attr
1313 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1314 return $self->generate($name, @_);
1325 SQL::Abstract - Generate SQL from Perl data structures
1331 my $sql = SQL::Abstract->new;
1333 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1335 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1337 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1339 my($stmt, @bind) = $sql->delete($table, \%where);
1341 # Then, use these in your DBI statements
1342 my $sth = $dbh->prepare($stmt);
1343 $sth->execute(@bind);
1345 # Just generate the WHERE clause
1346 my($stmt, @bind) = $sql->where(\%where, \@order);
1348 # Return values in the same order, for hashed queries
1349 # See PERFORMANCE section for more details
1350 my @bind = $sql->values(\%fieldvals);
1354 This module was inspired by the excellent L<DBIx::Abstract>.
1355 However, in using that module I found that what I really wanted
1356 to do was generate SQL, but still retain complete control over my
1357 statement handles and use the DBI interface. So, I set out to
1358 create an abstract SQL generation module.
1360 While based on the concepts used by L<DBIx::Abstract>, there are
1361 several important differences, especially when it comes to WHERE
1362 clauses. I have modified the concepts used to make the SQL easier
1363 to generate from Perl data structures and, IMO, more intuitive.
1364 The underlying idea is for this module to do what you mean, based
1365 on the data structures you provide it. The big advantage is that
1366 you don't have to modify your code every time your data changes,
1367 as this module figures it out.
1369 To begin with, an SQL INSERT is as easy as just specifying a hash
1370 of C<key=value> pairs:
1373 name => 'Jimbo Bobson',
1374 phone => '123-456-7890',
1375 address => '42 Sister Lane',
1376 city => 'St. Louis',
1377 state => 'Louisiana',
1380 The SQL can then be generated with this:
1382 my($stmt, @bind) = $sql->insert('people', \%data);
1384 Which would give you something like this:
1386 $stmt = "INSERT INTO people
1387 (address, city, name, phone, state)
1388 VALUES (?, ?, ?, ?, ?)";
1389 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1390 '123-456-7890', 'Louisiana');
1392 These are then used directly in your DBI code:
1394 my $sth = $dbh->prepare($stmt);
1395 $sth->execute(@bind);
1397 =head2 Inserting and Updating Arrays
1399 If your database has array types (like for example Postgres),
1400 activate the special option C<< array_datatypes => 1 >>
1401 when creating the C<SQL::Abstract> object.
1402 Then you may use an arrayref to insert and update database array types:
1404 my $sql = SQL::Abstract->new(array_datatypes => 1);
1406 planets => [qw/Mercury Venus Earth Mars/]
1409 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1413 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1415 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1418 =head2 Inserting and Updating SQL
1420 In order to apply SQL functions to elements of your C<%data> you may
1421 specify a reference to an arrayref for the given hash value. For example,
1422 if you need to execute the Oracle C<to_date> function on a value, you can
1423 say something like this:
1427 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1430 The first value in the array is the actual SQL. Any other values are
1431 optional and would be included in the bind values array. This gives
1434 my($stmt, @bind) = $sql->insert('people', \%data);
1436 $stmt = "INSERT INTO people (name, date_entered)
1437 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1438 @bind = ('Bill', '03/02/2003');
1440 An UPDATE is just as easy, all you change is the name of the function:
1442 my($stmt, @bind) = $sql->update('people', \%data);
1444 Notice that your C<%data> isn't touched; the module will generate
1445 the appropriately quirky SQL for you automatically. Usually you'll
1446 want to specify a WHERE clause for your UPDATE, though, which is
1447 where handling C<%where> hashes comes in handy...
1449 =head2 Complex where statements
1451 This module can generate pretty complicated WHERE statements
1452 easily. For example, simple C<key=value> pairs are taken to mean
1453 equality, and if you want to see if a field is within a set
1454 of values, you can use an arrayref. Let's say we wanted to
1455 SELECT some data based on this criteria:
1458 requestor => 'inna',
1459 worker => ['nwiger', 'rcwe', 'sfz'],
1460 status => { '!=', 'completed' }
1463 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1465 The above would give you something like this:
1467 $stmt = "SELECT * FROM tickets WHERE
1468 ( requestor = ? ) AND ( status != ? )
1469 AND ( worker = ? OR worker = ? OR worker = ? )";
1470 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1472 Which you could then use in DBI code like so:
1474 my $sth = $dbh->prepare($stmt);
1475 $sth->execute(@bind);
1481 The functions are simple. There's one for each major SQL operation,
1482 and a constructor you use first. The arguments are specified in a
1483 similar order to each function (table, then fields, then a where
1484 clause) to try and simplify things.
1489 =head2 new(option => 'value')
1491 The C<new()> function takes a list of options and values, and returns
1492 a new B<SQL::Abstract> object which can then be used to generate SQL
1493 through the methods below. The options accepted are:
1499 If set to 'lower', then SQL will be generated in all lowercase. By
1500 default SQL is generated in "textbook" case meaning something like:
1502 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1504 Any setting other than 'lower' is ignored.
1508 This determines what the default comparison operator is. By default
1509 it is C<=>, meaning that a hash like this:
1511 %where = (name => 'nwiger', email => 'nate@wiger.org');
1513 Will generate SQL like this:
1515 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1517 However, you may want loose comparisons by default, so if you set
1518 C<cmp> to C<like> you would get SQL such as:
1520 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1522 You can also override the comparsion on an individual basis - see
1523 the huge section on L</"WHERE CLAUSES"> at the bottom.
1525 =item sqltrue, sqlfalse
1527 Expressions for inserting boolean values within SQL statements.
1528 By default these are C<1=1> and C<1=0>. They are used
1529 by the special operators C<-in> and C<-not_in> for generating
1530 correct SQL even when the argument is an empty array (see below).
1534 This determines the default logical operator for multiple WHERE
1535 statements in arrays or hashes. If absent, the default logic is "or"
1536 for arrays, and "and" for hashes. This means that a WHERE
1540 event_date => {'>=', '2/13/99'},
1541 event_date => {'<=', '4/24/03'},
1544 will generate SQL like this:
1546 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1548 This is probably not what you want given this query, though (look
1549 at the dates). To change the "OR" to an "AND", simply specify:
1551 my $sql = SQL::Abstract->new(logic => 'and');
1553 Which will change the above C<WHERE> to:
1555 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1557 The logic can also be changed locally by inserting
1558 a modifier in front of an arrayref :
1560 @where = (-and => [event_date => {'>=', '2/13/99'},
1561 event_date => {'<=', '4/24/03'} ]);
1563 See the L</"WHERE CLAUSES"> section for explanations.
1567 This will automatically convert comparisons using the specified SQL
1568 function for both column and value. This is mostly used with an argument
1569 of C<upper> or C<lower>, so that the SQL will have the effect of
1570 case-insensitive "searches". For example, this:
1572 $sql = SQL::Abstract->new(convert => 'upper');
1573 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1575 Will turn out the following SQL:
1577 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1579 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1580 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1581 not validate this option; it will just pass through what you specify verbatim).
1585 This is a kludge because many databases suck. For example, you can't
1586 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1587 Instead, you have to use C<bind_param()>:
1589 $sth->bind_param(1, 'reg data');
1590 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1592 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1593 which loses track of which field each slot refers to. Fear not.
1595 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1596 Currently, you can specify either C<normal> (default) or C<columns>. If you
1597 specify C<columns>, you will get an array that looks like this:
1599 my $sql = SQL::Abstract->new(bindtype => 'columns');
1600 my($stmt, @bind) = $sql->insert(...);
1603 [ 'column1', 'value1' ],
1604 [ 'column2', 'value2' ],
1605 [ 'column3', 'value3' ],
1608 You can then iterate through this manually, using DBI's C<bind_param()>.
1610 $sth->prepare($stmt);
1613 my($col, $data) = @$_;
1614 if ($col eq 'details' || $col eq 'comments') {
1615 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1616 } elsif ($col eq 'image') {
1617 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1619 $sth->bind_param($i, $data);
1623 $sth->execute; # execute without @bind now
1625 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1626 Basically, the advantage is still that you don't have to care which fields
1627 are or are not included. You could wrap that above C<for> loop in a simple
1628 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1629 get a layer of abstraction over manual SQL specification.
1631 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1632 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1633 will expect the bind values in this format.
1637 This is the character that a table or column name will be quoted
1638 with. By default this is an empty string, but you could set it to
1639 the character C<`>, to generate SQL like this:
1641 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1643 Alternatively, you can supply an array ref of two items, the first being the left
1644 hand quote character, and the second the right hand quote character. For
1645 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1646 that generates SQL like this:
1648 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1650 Quoting is useful if you have tables or columns names that are reserved
1651 words in your database's SQL dialect.
1655 This is the character that separates a table and column name. It is
1656 necessary to specify this when the C<quote_char> option is selected,
1657 so that tables and column names can be individually quoted like this:
1659 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1661 =item array_datatypes
1663 When this option is true, arrayrefs in INSERT or UPDATE are
1664 interpreted as array datatypes and are passed directly
1666 When this option is false, arrayrefs are interpreted
1667 as literal SQL, just like refs to arrayrefs
1668 (but this behavior is for backwards compatibility; when writing
1669 new queries, use the "reference to arrayref" syntax
1675 Takes a reference to a list of "special operators"
1676 to extend the syntax understood by L<SQL::Abstract>.
1677 See section L</"SPECIAL OPERATORS"> for details.
1681 Takes a reference to a list of "unary operators"
1682 to extend the syntax understood by L<SQL::Abstract>.
1683 See section L</"UNARY OPERATORS"> for details.
1689 =head2 insert($table, \@values || \%fieldvals, \%options)
1691 This is the simplest function. You simply give it a table name
1692 and either an arrayref of values or hashref of field/value pairs.
1693 It returns an SQL INSERT statement and a list of bind values.
1694 See the sections on L</"Inserting and Updating Arrays"> and
1695 L</"Inserting and Updating SQL"> for information on how to insert
1696 with those data types.
1698 The optional C<\%options> hash reference may contain additional
1699 options to generate the insert SQL. Currently supported options
1706 Takes either a scalar of raw SQL fields, or an array reference of
1707 field names, and adds on an SQL C<RETURNING> statement at the end.
1708 This allows you to return data generated by the insert statement
1709 (such as row IDs) without performing another C<SELECT> statement.
1710 Note, however, this is not part of the SQL standard and may not
1711 be supported by all database engines.
1715 =head2 update($table, \%fieldvals, \%where)
1717 This takes a table, hashref of field/value pairs, and an optional
1718 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1720 See the sections on L</"Inserting and Updating Arrays"> and
1721 L</"Inserting and Updating SQL"> for information on how to insert
1722 with those data types.
1724 =head2 select($source, $fields, $where, $order)
1726 This returns a SQL SELECT statement and associated list of bind values, as
1727 specified by the arguments :
1733 Specification of the 'FROM' part of the statement.
1734 The argument can be either a plain scalar (interpreted as a table
1735 name, will be quoted), or an arrayref (interpreted as a list
1736 of table names, joined by commas, quoted), or a scalarref
1737 (literal table name, not quoted), or a ref to an arrayref
1738 (list of literal table names, joined by commas, not quoted).
1742 Specification of the list of fields to retrieve from
1744 The argument can be either an arrayref (interpreted as a list
1745 of field names, will be joined by commas and quoted), or a
1746 plain scalar (literal SQL, not quoted).
1747 Please observe that this API is not as flexible as for
1748 the first argument C<$table>, for backwards compatibility reasons.
1752 Optional argument to specify the WHERE part of the query.
1753 The argument is most often a hashref, but can also be
1754 an arrayref or plain scalar --
1755 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1759 Optional argument to specify the ORDER BY part of the query.
1760 The argument can be a scalar, a hashref or an arrayref
1761 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1767 =head2 delete($table, \%where)
1769 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1770 It returns an SQL DELETE statement and list of bind values.
1772 =head2 where(\%where, \@order)
1774 This is used to generate just the WHERE clause. For example,
1775 if you have an arbitrary data structure and know what the
1776 rest of your SQL is going to look like, but want an easy way
1777 to produce a WHERE clause, use this. It returns an SQL WHERE
1778 clause and list of bind values.
1781 =head2 values(\%data)
1783 This just returns the values from the hash C<%data>, in the same
1784 order that would be returned from any of the other above queries.
1785 Using this allows you to markedly speed up your queries if you
1786 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1788 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1790 Warning: This is an experimental method and subject to change.
1792 This returns arbitrarily generated SQL. It's a really basic shortcut.
1793 It will return two different things, depending on return context:
1795 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1796 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1798 These would return the following:
1800 # First calling form
1801 $stmt = "CREATE TABLE test (?, ?)";
1802 @bind = (field1, field2);
1804 # Second calling form
1805 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1807 Depending on what you're trying to do, it's up to you to choose the correct
1808 format. In this example, the second form is what you would want.
1812 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1816 ALTER SESSION SET nls_date_format = 'MM/YY'
1818 You get the idea. Strings get their case twiddled, but everything
1819 else remains verbatim.
1824 =head1 WHERE CLAUSES
1828 This module uses a variation on the idea from L<DBIx::Abstract>. It
1829 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1830 module is that things in arrays are OR'ed, and things in hashes
1833 The easiest way to explain is to show lots of examples. After
1834 each C<%where> hash shown, it is assumed you used:
1836 my($stmt, @bind) = $sql->where(\%where);
1838 However, note that the C<%where> hash can be used directly in any
1839 of the other functions as well, as described above.
1841 =head2 Key-value pairs
1843 So, let's get started. To begin, a simple hash:
1847 status => 'completed'
1850 Is converted to SQL C<key = val> statements:
1852 $stmt = "WHERE user = ? AND status = ?";
1853 @bind = ('nwiger', 'completed');
1855 One common thing I end up doing is having a list of values that
1856 a field can be in. To do this, simply specify a list inside of
1861 status => ['assigned', 'in-progress', 'pending'];
1864 This simple code will create the following:
1866 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1867 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1869 A field associated to an empty arrayref will be considered a
1870 logical false and will generate 0=1.
1872 =head2 Specific comparison operators
1874 If you want to specify a different type of operator for your comparison,
1875 you can use a hashref for a given column:
1879 status => { '!=', 'completed' }
1882 Which would generate:
1884 $stmt = "WHERE user = ? AND status != ?";
1885 @bind = ('nwiger', 'completed');
1887 To test against multiple values, just enclose the values in an arrayref:
1889 status => { '=', ['assigned', 'in-progress', 'pending'] };
1891 Which would give you:
1893 "WHERE status = ? OR status = ? OR status = ?"
1896 The hashref can also contain multiple pairs, in which case it is expanded
1897 into an C<AND> of its elements:
1901 status => { '!=', 'completed', -not_like => 'pending%' }
1904 # Or more dynamically, like from a form
1905 $where{user} = 'nwiger';
1906 $where{status}{'!='} = 'completed';
1907 $where{status}{'-not_like'} = 'pending%';
1909 # Both generate this
1910 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1911 @bind = ('nwiger', 'completed', 'pending%');
1914 To get an OR instead, you can combine it with the arrayref idea:
1918 priority => [ {'=', 2}, {'!=', 1} ]
1921 Which would generate:
1923 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1924 @bind = ('nwiger', '2', '1');
1926 If you want to include literal SQL (with or without bind values), just use a
1927 scalar reference or array reference as the value:
1930 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1931 date_expires => { '<' => \"now()" }
1934 Which would generate:
1936 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1937 @bind = ('11/26/2008');
1940 =head2 Logic and nesting operators
1942 In the example above,
1943 there is a subtle trap if you want to say something like
1944 this (notice the C<AND>):
1946 WHERE priority != ? AND priority != ?
1948 Because, in Perl you I<can't> do this:
1950 priority => { '!=', 2, '!=', 1 }
1952 As the second C<!=> key will obliterate the first. The solution
1953 is to use the special C<-modifier> form inside an arrayref:
1955 priority => [ -and => {'!=', 2},
1959 Normally, these would be joined by C<OR>, but the modifier tells it
1960 to use C<AND> instead. (Hint: You can use this in conjunction with the
1961 C<logic> option to C<new()> in order to change the way your queries
1962 work by default.) B<Important:> Note that the C<-modifier> goes
1963 B<INSIDE> the arrayref, as an extra first element. This will
1964 B<NOT> do what you think it might:
1966 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1968 Here is a quick list of equivalencies, since there is some overlap:
1971 status => {'!=', 'completed', 'not like', 'pending%' }
1972 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1975 status => {'=', ['assigned', 'in-progress']}
1976 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1977 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1981 =head2 Special operators : IN, BETWEEN, etc.
1983 You can also use the hashref format to compare a list of fields using the
1984 C<IN> comparison operator, by specifying the list as an arrayref:
1987 status => 'completed',
1988 reportid => { -in => [567, 2335, 2] }
1991 Which would generate:
1993 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1994 @bind = ('completed', '567', '2335', '2');
1996 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1999 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2000 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2001 'sqltrue' (by default : C<1=1>).
2003 In addition to the array you can supply a chunk of literal sql or
2004 literal sql with bind:
2007 customer => { -in => \[
2008 'SELECT cust_id FROM cust WHERE balance > ?',
2011 status => { -in => \'SELECT status_codes FROM states' },
2017 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2018 AND status IN ( SELECT status_codes FROM states )
2024 Another pair of operators is C<-between> and C<-not_between>,
2025 used with an arrayref of two values:
2029 completion_date => {
2030 -not_between => ['2002-10-01', '2003-02-06']
2036 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2038 Just like with C<-in> all plausible combinations of literal SQL
2042 start0 => { -between => [ 1, 2 ] },
2043 start1 => { -between => \["? AND ?", 1, 2] },
2044 start2 => { -between => \"lower(x) AND upper(y)" },
2045 start3 => { -between => [
2047 \["upper(?)", 'stuff' ],
2054 ( start0 BETWEEN ? AND ? )
2055 AND ( start1 BETWEEN ? AND ? )
2056 AND ( start2 BETWEEN lower(x) AND upper(y) )
2057 AND ( start3 BETWEEN lower(x) AND upper(?) )
2059 @bind = (1, 2, 1, 2, 'stuff');
2062 These are the two builtin "special operators"; but the
2063 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2065 =head2 Unary operators: bool
2067 If you wish to test against boolean columns or functions within your
2068 database you can use the C<-bool> and C<-not_bool> operators. For
2069 example to test the column C<is_user> being true and the column
2070 <is_enabled> being false you would use:-
2074 -not_bool => 'is_enabled',
2079 WHERE is_user AND NOT is_enabled
2081 If a more complex combination is required, testing more conditions,
2082 then you should use the and/or operators:-
2089 -not_bool => 'four',
2095 WHERE one AND two AND three AND NOT four
2098 =head2 Nested conditions, -and/-or prefixes
2100 So far, we've seen how multiple conditions are joined with a top-level
2101 C<AND>. We can change this by putting the different conditions we want in
2102 hashes and then putting those hashes in an array. For example:
2107 status => { -like => ['pending%', 'dispatched'] },
2111 status => 'unassigned',
2115 This data structure would create the following:
2117 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2118 OR ( user = ? AND status = ? ) )";
2119 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2122 There is also a special C<-nest>
2123 operator which adds an additional set of parens, to create a subquery.
2124 For example, to get something like this:
2126 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
2127 @bind = ('nwiger', '20', 'ASIA');
2133 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2137 Finally, clauses in hashrefs or arrayrefs can be
2138 prefixed with an C<-and> or C<-or> to change the logic
2145 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
2146 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
2153 WHERE ( user = ? AND
2154 ( ( workhrs > ? AND geo = ? )
2155 OR ( workhrs < ? AND geo = ? ) ) )
2158 =head2 Algebraic inconsistency, for historical reasons
2160 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2161 operator goes C<outside> of the nested structure; whereas when connecting
2162 several constraints on one column, the C<-and> operator goes
2163 C<inside> the arrayref. Here is an example combining both features :
2166 -and => [a => 1, b => 2],
2167 -or => [c => 3, d => 4],
2168 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2173 WHERE ( ( ( a = ? AND b = ? )
2174 OR ( c = ? OR d = ? )
2175 OR ( e LIKE ? AND e LIKE ? ) ) )
2177 This difference in syntax is unfortunate but must be preserved for
2178 historical reasons. So be careful : the two examples below would
2179 seem algebraically equivalent, but they are not
2181 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2182 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2184 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2185 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2190 Finally, sometimes only literal SQL will do. If you want to include
2191 literal SQL verbatim, you can specify it as a scalar reference, namely:
2193 my $inn = 'is Not Null';
2195 priority => { '<', 2 },
2201 $stmt = "WHERE priority < ? AND requestor is Not Null";
2204 Note that in this example, you only get one bind parameter back, since
2205 the verbatim SQL is passed as part of the statement.
2207 Of course, just to prove a point, the above can also be accomplished
2211 priority => { '<', 2 },
2212 requestor => { '!=', undef },
2218 Conditions on boolean columns can be expressed in the same way, passing
2219 a reference to an empty string, however using liternal SQL in this way
2220 is deprecated - the preferred method is to use the boolean operators -
2221 see L</"Unary operators: bool"> :
2224 priority => { '<', 2 },
2230 $stmt = "WHERE priority < ? AND is_ready";
2234 =head2 Literal SQL with placeholders and bind values (subqueries)
2236 If the literal SQL to be inserted has placeholders and bind values,
2237 use a reference to an arrayref (yes this is a double reference --
2238 not so common, but perfectly legal Perl). For example, to find a date
2239 in Postgres you can use something like this:
2242 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2247 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2250 Note that you must pass the bind values in the same format as they are returned
2251 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2252 provide the bind values in the C<< [ column_meta => value ] >> format, where
2253 C<column_meta> is an opaque scalar value; most commonly the column name, but
2254 you can use any scalar value (including references and blessed references),
2255 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2256 to C<columns> the above example will look like:
2259 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2262 Literal SQL is especially useful for nesting parenthesized clauses in the
2263 main SQL query. Here is a first example :
2265 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2269 bar => \["IN ($sub_stmt)" => @sub_bind],
2274 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2275 WHERE c2 < ? AND c3 LIKE ?))";
2276 @bind = (1234, 100, "foo%");
2278 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2279 are expressed in the same way. Of course the C<$sub_stmt> and
2280 its associated bind values can be generated through a former call
2283 my ($sub_stmt, @sub_bind)
2284 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2285 c3 => {-like => "foo%"}});
2288 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2291 In the examples above, the subquery was used as an operator on a column;
2292 but the same principle also applies for a clause within the main C<%where>
2293 hash, like an EXISTS subquery :
2295 my ($sub_stmt, @sub_bind)
2296 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2299 -nest => \["EXISTS ($sub_stmt)" => @sub_bind],
2304 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2305 WHERE c1 = ? AND c2 > t0.c0))";
2309 Observe that the condition on C<c2> in the subquery refers to
2310 column C<t0.c0> of the main query : this is I<not> a bind
2311 value, so we have to express it through a scalar ref.
2312 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2313 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2314 what we wanted here.
2316 Another use of the subquery technique is when some SQL clauses need
2317 parentheses, as it often occurs with some proprietary SQL extensions
2318 like for example fulltext expressions, geospatial expressions,
2319 NATIVE clauses, etc. Here is an example of a fulltext query in MySQL :
2322 -nest => \["MATCH (col1, col2) AGAINST (?)" => qw/apples/]
2325 Finally, here is an example where a subquery is used
2326 for expressing unary negation:
2328 my ($sub_stmt, @sub_bind)
2329 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2330 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2332 lname => {like => '%son%'},
2333 -nest => \["NOT ($sub_stmt)" => @sub_bind],
2338 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2339 @bind = ('%son%', 10, 20)
2345 These pages could go on for a while, since the nesting of the data
2346 structures this module can handle are pretty much unlimited (the
2347 module implements the C<WHERE> expansion as a recursive function
2348 internally). Your best bet is to "play around" with the module a
2349 little to see how the data structures behave, and choose the best
2350 format for your data based on that.
2352 And of course, all the values above will probably be replaced with
2353 variables gotten from forms or the command line. After all, if you
2354 knew everything ahead of time, you wouldn't have to worry about
2355 dynamically-generating SQL and could just hardwire it into your
2361 =head1 ORDER BY CLAUSES
2363 Some functions take an order by clause. This can either be a scalar (just a
2364 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2365 or an array of either of the two previous forms. Examples:
2367 Given | Will Generate
2368 ----------------------------------------------------------
2370 \'colA DESC' | ORDER BY colA DESC
2372 'colA' | ORDER BY colA
2374 [qw/colA colB/] | ORDER BY colA, colB
2376 {-asc => 'colA'} | ORDER BY colA ASC
2378 {-desc => 'colB'} | ORDER BY colB DESC
2380 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2382 { -asc => [qw/colA colB] } | ORDER BY colA ASC, colB ASC
2385 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2386 { -desc => [qw/colB/], | colC ASC, colD ASC
2387 { -asc => [qw/colC colD/],|
2389 ===========================================================
2393 =head1 SPECIAL OPERATORS
2395 my $sqlmaker = SQL::Abstract->new(special_ops => [
2399 my ($self, $field, $op, $arg) = @_;
2405 handler => 'method_name',
2409 A "special operator" is a SQL syntactic clause that can be
2410 applied to a field, instead of a usual binary operator.
2413 WHERE field IN (?, ?, ?)
2414 WHERE field BETWEEN ? AND ?
2415 WHERE MATCH(field) AGAINST (?, ?)
2417 Special operators IN and BETWEEN are fairly standard and therefore
2418 are builtin within C<SQL::Abstract> (as the overridable methods
2419 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2420 like the MATCH .. AGAINST example above which is specific to MySQL,
2421 you can write your own operator handlers - supply a C<special_ops>
2422 argument to the C<new> method. That argument takes an arrayref of
2423 operator definitions; each operator definition is a hashref with two
2430 the regular expression to match the operator
2434 Either a coderef or a plain scalar method name. In both cases
2435 the expected return is C<< ($sql, @bind) >>.
2437 When supplied with a method name, it is simply called on the
2438 L<SQL::Abstract/> object as:
2440 $self->$method_name ($field, $op, $arg)
2444 $op is the part that matched the handler regex
2445 $field is the LHS of the operator
2448 When supplied with a coderef, it is called as:
2450 $coderef->($self, $field, $op, $arg)
2455 For example, here is an implementation
2456 of the MATCH .. AGAINST syntax for MySQL
2458 my $sqlmaker = SQL::Abstract->new(special_ops => [
2460 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2461 {regex => qr/^match$/i,
2463 my ($self, $field, $op, $arg) = @_;
2464 $arg = [$arg] if not ref $arg;
2465 my $label = $self->_quote($field);
2466 my ($placeholder) = $self->_convert('?');
2467 my $placeholders = join ", ", (($placeholder) x @$arg);
2468 my $sql = $self->_sqlcase('match') . " ($label) "
2469 . $self->_sqlcase('against') . " ($placeholders) ";
2470 my @bind = $self->_bindtype($field, @$arg);
2471 return ($sql, @bind);
2478 =head1 UNARY OPERATORS
2480 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2484 my ($self, $op, $arg) = @_;
2490 handler => 'method_name',
2494 A "unary operator" is a SQL syntactic clause that can be
2495 applied to a field - the operator goes before the field
2497 You can write your own operator handlers - supply a C<unary_ops>
2498 argument to the C<new> method. That argument takes an arrayref of
2499 operator definitions; each operator definition is a hashref with two
2506 the regular expression to match the operator
2510 Either a coderef or a plain scalar method name. In both cases
2511 the expected return is C<< $sql >>.
2513 When supplied with a method name, it is simply called on the
2514 L<SQL::Abstract/> object as:
2516 $self->$method_name ($op, $arg)
2520 $op is the part that matched the handler regex
2521 $arg is the RHS or argument of the operator
2523 When supplied with a coderef, it is called as:
2525 $coderef->($self, $op, $arg)
2533 Thanks to some benchmarking by Mark Stosberg, it turns out that
2534 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2535 I must admit this wasn't an intentional design issue, but it's a
2536 byproduct of the fact that you get to control your C<DBI> handles
2539 To maximize performance, use a code snippet like the following:
2541 # prepare a statement handle using the first row
2542 # and then reuse it for the rest of the rows
2544 for my $href (@array_of_hashrefs) {
2545 $stmt ||= $sql->insert('table', $href);
2546 $sth ||= $dbh->prepare($stmt);
2547 $sth->execute($sql->values($href));
2550 The reason this works is because the keys in your C<$href> are sorted
2551 internally by B<SQL::Abstract>. Thus, as long as your data retains
2552 the same structure, you only have to generate the SQL the first time
2553 around. On subsequent queries, simply use the C<values> function provided
2554 by this module to return your values in the correct order.
2559 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2560 really like this part (I do, at least). Building up a complex query
2561 can be as simple as the following:
2565 use CGI::FormBuilder;
2568 my $form = CGI::FormBuilder->new(...);
2569 my $sql = SQL::Abstract->new;
2571 if ($form->submitted) {
2572 my $field = $form->field;
2573 my $id = delete $field->{id};
2574 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2577 Of course, you would still have to connect using C<DBI> to run the
2578 query, but the point is that if you make your form look like your
2579 table, the actual query script can be extremely simplistic.
2581 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2582 a fast interface to returning and formatting data. I frequently
2583 use these three modules together to write complex database query
2584 apps in under 50 lines.
2589 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2590 Great care has been taken to preserve the I<published> behavior
2591 documented in previous versions in the 1.* family; however,
2592 some features that were previously undocumented, or behaved
2593 differently from the documentation, had to be changed in order
2594 to clarify the semantics. Hence, client code that was relying
2595 on some dark areas of C<SQL::Abstract> v1.*
2596 B<might behave differently> in v1.50.
2598 The main changes are :
2604 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2608 support for the { operator => \"..." } construct (to embed literal SQL)
2612 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2616 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2620 defensive programming : check arguments
2624 fixed bug with global logic, which was previously implemented
2625 through global variables yielding side-effects. Prior versions would
2626 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2627 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2628 Now this is interpreted
2629 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2634 fixed semantics of _bindtype on array args
2638 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2639 we just avoid shifting arrays within that tree.
2643 dropped the C<_modlogic> function
2649 =head1 ACKNOWLEDGEMENTS
2651 There are a number of individuals that have really helped out with
2652 this module. Unfortunately, most of them submitted bugs via CPAN
2653 so I have no idea who they are! But the people I do know are:
2655 Ash Berlin (order_by hash term support)
2656 Matt Trout (DBIx::Class support)
2657 Mark Stosberg (benchmarking)
2658 Chas Owens (initial "IN" operator support)
2659 Philip Collins (per-field SQL functions)
2660 Eric Kolve (hashref "AND" support)
2661 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2662 Dan Kubb (support for "quote_char" and "name_sep")
2663 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2664 Laurent Dami (internal refactoring, multiple -nest, extensible list of special operators, literal SQL)
2665 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2666 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2667 Oliver Charles (support for "RETURNING" after "INSERT")
2673 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2677 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2679 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2681 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2682 While not an official support venue, C<DBIx::Class> makes heavy use of
2683 C<SQL::Abstract>, and as such list members there are very familiar with
2684 how to create queries.
2688 This module is free software; you may copy this under the same
2689 terms as perl itself (either the GNU General Public License or
2690 the Artistic License)