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.72';
20 # This would confuse some packagers
21 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
25 # special operators (-in, -between). May be extended/overridden by user.
26 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
27 my @BUILTIN_SPECIAL_OPS = (
28 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
29 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
32 # unaryish operators - key maps to handler
33 my @BUILTIN_UNARY_OPS = (
34 # the digits are backcompat stuff
35 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
36 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
37 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
38 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
41 #======================================================================
42 # DEBUGGING AND ERROR REPORTING
43 #======================================================================
46 return unless $_[0]->{debug}; shift; # a little faster
47 my $func = (caller(1))[3];
48 warn "[$func] ", @_, "\n";
52 my($func) = (caller(1))[3];
53 carp "[$func] Warning: ", @_;
57 my($func) = (caller(1))[3];
58 croak "[$func] Fatal: ", @_;
62 #======================================================================
64 #======================================================================
68 my $class = ref($self) || $self;
69 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
71 # choose our case by keeping an option around
72 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
74 # default logic for interpreting arrayrefs
75 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
77 # how to return bind vars
78 # LDNOTE: changed nwiger code : why this 'delete' ??
79 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
80 $opt{bindtype} ||= 'normal';
82 # default comparison is "=", but can be overridden
85 # try to recognize which are the 'equality' and 'unequality' ops
86 # (temporary quickfix, should go through a more seasoned API)
87 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
88 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
91 $opt{sqltrue} ||= '1=1';
92 $opt{sqlfalse} ||= '0=1';
95 $opt{special_ops} ||= [];
96 # regexes are applied in order, thus push after user-defines
97 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
100 $opt{unary_ops} ||= [];
101 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
103 # rudimentary saniy-check for user supplied bits treated as functions/operators
104 # If a purported function matches this regular expression, an exception is thrown.
105 # Literal SQL is *NOT* subject to this check, only functions (and column names
106 # when quoting is not in effect)
109 # need to guard against ()'s in column names too, but this will break tons of
110 # hacks... ideas anyone?
111 $opt{injection_guard} ||= qr/
117 return bless \%opt, $class;
121 sub _assert_pass_injection_guard {
122 if ($_[1] =~ $_[0]->{injection_guard}) {
123 my $class = ref $_[0];
124 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
125 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
126 . "{injection_guard} attribute to ${class}->new()"
131 #======================================================================
133 #======================================================================
137 my $table = $self->_table(shift);
138 my $data = shift || return;
141 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
142 my ($sql, @bind) = $self->$method($data);
143 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
145 if ($options->{returning}) {
146 my ($s, @b) = $self->_insert_returning ($options);
151 return wantarray ? ($sql, @bind) : $sql;
154 sub _insert_returning {
155 my ($self, $options) = @_;
157 my $f = $options->{returning};
159 my $fieldlist = $self->_SWITCH_refkind($f, {
160 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
161 SCALAR => sub {$self->_quote($f)},
162 SCALARREF => sub {$$f},
164 return $self->_sqlcase(' returning ') . $fieldlist;
167 sub _insert_HASHREF { # explicit list of fields and then values
168 my ($self, $data) = @_;
170 my @fields = sort keys %$data;
172 my ($sql, @bind) = $self->_insert_values($data);
175 $_ = $self->_quote($_) foreach @fields;
176 $sql = "( ".join(", ", @fields).") ".$sql;
178 return ($sql, @bind);
181 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
182 my ($self, $data) = @_;
184 # no names (arrayref) so can't generate bindtype
185 $self->{bindtype} ne 'columns'
186 or belch "can't do 'columns' bindtype when called with arrayref";
188 # fold the list of values into a hash of column name - value pairs
189 # (where the column names are artificially generated, and their
190 # lexicographical ordering keep the ordering of the original list)
191 my $i = "a"; # incremented values will be in lexicographical order
192 my $data_in_hash = { map { ($i++ => $_) } @$data };
194 return $self->_insert_values($data_in_hash);
197 sub _insert_ARRAYREFREF { # literal SQL with bind
198 my ($self, $data) = @_;
200 my ($sql, @bind) = @${$data};
201 $self->_assert_bindval_matches_bindtype(@bind);
203 return ($sql, @bind);
207 sub _insert_SCALARREF { # literal SQL without bind
208 my ($self, $data) = @_;
214 my ($self, $data) = @_;
216 my (@values, @all_bind);
217 foreach my $column (sort keys %$data) {
218 my $v = $data->{$column};
220 $self->_SWITCH_refkind($v, {
223 if ($self->{array_datatypes}) { # if array datatype are activated
225 push @all_bind, $self->_bindtype($column, $v);
227 else { # else literal SQL with bind
228 my ($sql, @bind) = @$v;
229 $self->_assert_bindval_matches_bindtype(@bind);
231 push @all_bind, @bind;
235 ARRAYREFREF => sub { # literal SQL with bind
236 my ($sql, @bind) = @${$v};
237 $self->_assert_bindval_matches_bindtype(@bind);
239 push @all_bind, @bind;
242 # THINK : anything useful to do with a HASHREF ?
243 HASHREF => sub { # (nothing, but old SQLA passed it through)
244 #TODO in SQLA >= 2.0 it will die instead
245 belch "HASH ref as bind value in insert is not supported";
247 push @all_bind, $self->_bindtype($column, $v);
250 SCALARREF => sub { # literal SQL without bind
254 SCALAR_or_UNDEF => sub {
256 push @all_bind, $self->_bindtype($column, $v);
263 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
264 return ($sql, @all_bind);
269 #======================================================================
271 #======================================================================
276 my $table = $self->_table(shift);
277 my $data = shift || return;
280 # first build the 'SET' part of the sql statement
281 my (@set, @all_bind);
282 puke "Unsupported data type specified to \$sql->update"
283 unless ref $data eq 'HASH';
285 for my $k (sort keys %$data) {
288 my $label = $self->_quote($k);
290 $self->_SWITCH_refkind($v, {
292 if ($self->{array_datatypes}) { # array datatype
293 push @set, "$label = ?";
294 push @all_bind, $self->_bindtype($k, $v);
296 else { # literal SQL with bind
297 my ($sql, @bind) = @$v;
298 $self->_assert_bindval_matches_bindtype(@bind);
299 push @set, "$label = $sql";
300 push @all_bind, @bind;
303 ARRAYREFREF => sub { # literal SQL with bind
304 my ($sql, @bind) = @${$v};
305 $self->_assert_bindval_matches_bindtype(@bind);
306 push @set, "$label = $sql";
307 push @all_bind, @bind;
309 SCALARREF => sub { # literal SQL without bind
310 push @set, "$label = $$v";
313 my ($op, $arg, @rest) = %$v;
315 puke 'Operator calls in update must be in the form { -op => $arg }'
316 if (@rest or not $op =~ /^\-(.+)/);
318 local $self->{_nested_func_lhs} = $k;
319 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
321 push @set, "$label = $sql";
322 push @all_bind, @bind;
324 SCALAR_or_UNDEF => sub {
325 push @set, "$label = ?";
326 push @all_bind, $self->_bindtype($k, $v);
332 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
336 my($where_sql, @where_bind) = $self->where($where);
338 push @all_bind, @where_bind;
341 return wantarray ? ($sql, @all_bind) : $sql;
347 #======================================================================
349 #======================================================================
354 my $table = $self->_table(shift);
355 my $fields = shift || '*';
359 my($where_sql, @bind) = $self->where($where, $order);
361 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields
363 my $sql = join(' ', $self->_sqlcase('select'), $f,
364 $self->_sqlcase('from'), $table)
367 return wantarray ? ($sql, @bind) : $sql;
370 #======================================================================
372 #======================================================================
377 my $table = $self->_table(shift);
381 my($where_sql, @bind) = $self->where($where);
382 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
384 return wantarray ? ($sql, @bind) : $sql;
388 #======================================================================
390 #======================================================================
394 # Finally, a separate routine just to handle WHERE clauses
396 my ($self, $where, $order) = @_;
399 my ($sql, @bind) = $self->_recurse_where($where);
400 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
404 $sql .= $self->_order_by($order);
407 return wantarray ? ($sql, @bind) : $sql;
412 my ($self, $where, $logic) = @_;
414 # dispatch on appropriate method according to refkind of $where
415 my $method = $self->_METHOD_FOR_refkind("_where", $where);
417 my ($sql, @bind) = $self->$method($where, $logic);
419 # DBIx::Class directly calls _recurse_where in scalar context, so
420 # we must implement it, even if not in the official API
421 return wantarray ? ($sql, @bind) : $sql;
426 #======================================================================
427 # WHERE: top-level ARRAYREF
428 #======================================================================
431 sub _where_ARRAYREF {
432 my ($self, $where, $logic) = @_;
434 $logic = uc($logic || $self->{logic});
435 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
437 my @clauses = @$where;
439 my (@sql_clauses, @all_bind);
440 # need to use while() so can shift() for pairs
441 while (my $el = shift @clauses) {
443 # switch according to kind of $el and get corresponding ($sql, @bind)
444 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
446 # skip empty elements, otherwise get invalid trailing AND stuff
447 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
451 $self->_assert_bindval_matches_bindtype(@b);
455 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
456 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
457 # side-effect: the first hashref within an array would change
458 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
459 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
460 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
462 SCALARREF => sub { ($$el); },
464 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
465 $self->_recurse_where({$el => shift(@clauses)})},
467 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
471 push @sql_clauses, $sql;
472 push @all_bind, @bind;
476 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
479 #======================================================================
480 # WHERE: top-level ARRAYREFREF
481 #======================================================================
483 sub _where_ARRAYREFREF {
484 my ($self, $where) = @_;
485 my ($sql, @bind) = @$$where;
486 $self->_assert_bindval_matches_bindtype(@bind);
487 return ($sql, @bind);
490 #======================================================================
491 # WHERE: top-level HASHREF
492 #======================================================================
495 my ($self, $where) = @_;
496 my (@sql_clauses, @all_bind);
498 for my $k (sort keys %$where) {
499 my $v = $where->{$k};
501 # ($k => $v) is either a special unary op or a regular hashpair
502 my ($sql, @bind) = do {
504 # put the operator in canonical form
506 $op = substr $op, 1; # remove initial dash
507 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
508 $op =~ s/\s+/ /g; # compress whitespace
510 # so that -not_foo works correctly
511 $op =~ s/^not_/NOT /i;
513 $self->_debug("Unary OP(-$op) within hashref, recursing...");
514 my ($s, @b) = $self->_where_unary_op ($op, $v);
516 # top level vs nested
517 # we assume that handled unary ops will take care of their ()s
519 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
521 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
526 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
527 $self->$method($k, $v);
531 push @sql_clauses, $sql;
532 push @all_bind, @bind;
535 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
538 sub _where_unary_op {
539 my ($self, $op, $rhs) = @_;
541 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
542 my $handler = $op_entry->{handler};
544 if (not ref $handler) {
545 if ($op =~ s/ [_\s]? \d+ $//x ) {
546 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
547 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
549 return $self->$handler ($op, $rhs);
551 elsif (ref $handler eq 'CODE') {
552 return $handler->($self, $op, $rhs);
555 puke "Illegal handler for operator $op - expecting a method name or a coderef";
559 $self->debug("Generic unary OP: $op - recursing as function");
561 $self->_assert_pass_injection_guard($op);
563 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
565 puke "Illegal use of top-level '$op'"
566 unless $self->{_nested_func_lhs};
569 $self->_convert('?'),
570 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
574 $self->_recurse_where ($rhs)
578 $sql = sprintf ('%s %s',
579 $self->_sqlcase($op),
583 return ($sql, @bind);
586 sub _where_op_ANDOR {
587 my ($self, $op, $v) = @_;
589 $self->_SWITCH_refkind($v, {
591 return $self->_where_ARRAYREF($v, $op);
595 return ( $op =~ /^or/i )
596 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
597 : $self->_where_HASHREF($v);
601 puke "-$op => \\\$scalar makes little sense, use " .
603 ? '[ \$scalar, \%rest_of_conditions ] instead'
604 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
609 puke "-$op => \\[...] makes little sense, use " .
611 ? '[ \[...], \%rest_of_conditions ] instead'
612 : '-and => [ \[...], \%rest_of_conditions ] instead'
616 SCALAR => sub { # permissively interpreted as SQL
617 puke "-$op => \$value makes little sense, use -bool => \$value instead";
621 puke "-$op => undef not supported";
627 my ($self, $op, $v) = @_;
629 $self->_SWITCH_refkind($v, {
631 SCALAR => sub { # permissively interpreted as SQL
632 belch "literal SQL should be -nest => \\'scalar' "
633 . "instead of -nest => 'scalar' ";
638 puke "-$op => undef not supported";
642 $self->_recurse_where ($v);
650 my ($self, $op, $v) = @_;
652 my ($s, @b) = $self->_SWITCH_refkind($v, {
653 SCALAR => sub { # interpreted as SQL column
654 $self->_convert($self->_quote($v));
658 puke "-$op => undef not supported";
662 $self->_recurse_where ($v);
666 $s = "(NOT $s)" if $op =~ /^not/i;
671 sub _where_hashpair_ARRAYREF {
672 my ($self, $k, $v) = @_;
675 my @v = @$v; # need copy because of shift below
676 $self->_debug("ARRAY($k) means distribute over elements");
678 # put apart first element if it is an operator (-and, -or)
680 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
684 my @distributed = map { {$k => $_} } @v;
687 $self->_debug("OP($op) reinjected into the distributed array");
688 unshift @distributed, $op;
691 my $logic = $op ? substr($op, 1) : '';
693 return $self->_recurse_where(\@distributed, $logic);
696 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
697 $self->_debug("empty ARRAY($k) means 0=1");
698 return ($self->{sqlfalse});
702 sub _where_hashpair_HASHREF {
703 my ($self, $k, $v, $logic) = @_;
706 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
708 my ($all_sql, @all_bind);
710 for my $orig_op (sort keys %$v) {
711 my $val = $v->{$orig_op};
713 # put the operator in canonical form
716 # FIXME - we need to phase out dash-less ops
717 $op =~ s/^-//; # remove possible initial dash
718 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
719 $op =~ s/\s+/ /g; # compress whitespace
721 $self->_assert_pass_injection_guard($op);
723 # so that -not_foo works correctly
724 $op =~ s/^not_/NOT /i;
728 # CASE: col-value logic modifiers
729 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
730 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
732 # CASE: special operators like -in or -between
733 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
734 my $handler = $special_op->{handler};
736 puke "No handler supplied for special operator $orig_op";
738 elsif (not ref $handler) {
739 ($sql, @bind) = $self->$handler ($k, $op, $val);
741 elsif (ref $handler eq 'CODE') {
742 ($sql, @bind) = $handler->($self, $k, $op, $val);
745 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
749 $self->_SWITCH_refkind($val, {
751 ARRAYREF => sub { # CASE: col => {op => \@vals}
752 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
755 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
756 my ($sub_sql, @sub_bind) = @$$val;
757 $self->_assert_bindval_matches_bindtype(@sub_bind);
758 $sql = join ' ', $self->_convert($self->_quote($k)),
759 $self->_sqlcase($op),
764 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
765 my $is = ($op =~ $self->{equality_op}) ? 'is' :
766 ($op =~ $self->{inequality_op}) ? 'is not' :
767 puke "unexpected operator '$orig_op' with undef operand";
768 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
771 FALLBACK => sub { # CASE: col => {op/func => $stuff}
773 # retain for proper column type bind
774 $self->{_nested_func_lhs} ||= $k;
776 ($sql, @bind) = $self->_where_unary_op ($op, $val);
779 $self->_convert($self->_quote($k)),
780 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
786 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
787 push @all_bind, @bind;
789 return ($all_sql, @all_bind);
794 sub _where_field_op_ARRAYREF {
795 my ($self, $k, $op, $vals) = @_;
797 my @vals = @$vals; #always work on a copy
800 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
802 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
805 # see if the first element is an -and/-or op
807 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
812 # distribute $op over each remaining member of @vals, append logic if exists
813 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
815 # LDNOTE : had planned to change the distribution logic when
816 # $op =~ $self->{inequality_op}, because of Morgan laws :
817 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
818 # WHERE field != 22 OR field != 33 : the user probably means
819 # WHERE field != 22 AND field != 33.
820 # To do this, replace the above to roughly :
821 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
822 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
826 # try to DWIM on equality operators
827 # LDNOTE : not 100% sure this is the correct thing to do ...
828 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
829 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
832 puke "operator '$op' applied on an empty array (field '$k')";
837 sub _where_hashpair_SCALARREF {
838 my ($self, $k, $v) = @_;
839 $self->_debug("SCALAR($k) means literal SQL: $$v");
840 my $sql = $self->_quote($k) . " " . $$v;
844 # literal SQL with bind
845 sub _where_hashpair_ARRAYREFREF {
846 my ($self, $k, $v) = @_;
847 $self->_debug("REF($k) means literal SQL: @${$v}");
848 my ($sql, @bind) = @$$v;
849 $self->_assert_bindval_matches_bindtype(@bind);
850 $sql = $self->_quote($k) . " " . $sql;
851 return ($sql, @bind );
854 # literal SQL without bind
855 sub _where_hashpair_SCALAR {
856 my ($self, $k, $v) = @_;
857 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
858 my $sql = join ' ', $self->_convert($self->_quote($k)),
859 $self->_sqlcase($self->{cmp}),
860 $self->_convert('?');
861 my @bind = $self->_bindtype($k, $v);
862 return ( $sql, @bind);
866 sub _where_hashpair_UNDEF {
867 my ($self, $k, $v) = @_;
868 $self->_debug("UNDEF($k) means IS NULL");
869 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
873 #======================================================================
874 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
875 #======================================================================
878 sub _where_SCALARREF {
879 my ($self, $where) = @_;
882 $self->_debug("SCALAR(*top) means literal SQL: $$where");
888 my ($self, $where) = @_;
891 $self->_debug("NOREF(*top) means literal SQL: $where");
902 #======================================================================
903 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
904 #======================================================================
907 sub _where_field_BETWEEN {
908 my ($self, $k, $op, $vals) = @_;
910 my ($label, $and, $placeholder);
911 $label = $self->_convert($self->_quote($k));
912 $and = ' ' . $self->_sqlcase('and') . ' ';
913 $placeholder = $self->_convert('?');
914 $op = $self->_sqlcase($op);
916 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
918 my ($s, @b) = @$$vals;
919 $self->_assert_bindval_matches_bindtype(@b);
926 puke "special op 'between' accepts an arrayref with exactly two values"
929 my (@all_sql, @all_bind);
930 foreach my $val (@$vals) {
931 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
933 return ($placeholder, $self->_bindtype($k, $val) );
939 my ($sql, @bind) = @$$val;
940 $self->_assert_bindval_matches_bindtype(@bind);
941 return ($sql, @bind);
944 my ($func, $arg, @rest) = %$val;
945 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
946 if (@rest or $func !~ /^ \- (.+)/x);
947 local $self->{_nested_func_lhs} = $k;
948 $self->_where_unary_op ($1 => $arg);
952 push @all_bind, @bind;
956 (join $and, @all_sql),
961 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
965 my $sql = "( $label $op $clause )";
970 sub _where_field_IN {
971 my ($self, $k, $op, $vals) = @_;
973 # backwards compatibility : if scalar, force into an arrayref
974 $vals = [$vals] if defined $vals && ! ref $vals;
976 my ($label) = $self->_convert($self->_quote($k));
977 my ($placeholder) = $self->_convert('?');
978 $op = $self->_sqlcase($op);
980 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
981 ARRAYREF => sub { # list of choices
982 if (@$vals) { # nonempty list
983 my (@all_sql, @all_bind);
985 for my $val (@$vals) {
986 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
988 return ($placeholder, $val);
994 my ($sql, @bind) = @$$val;
995 $self->_assert_bindval_matches_bindtype(@bind);
996 return ($sql, @bind);
999 my ($func, $arg, @rest) = %$val;
1000 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1001 if (@rest or $func !~ /^ \- (.+)/x);
1002 local $self->{_nested_func_lhs} = $k;
1003 $self->_where_unary_op ($1 => $arg);
1006 return $self->_sqlcase('null');
1009 push @all_sql, $sql;
1010 push @all_bind, @bind;
1014 sprintf ('%s %s ( %s )',
1017 join (', ', @all_sql)
1019 $self->_bindtype($k, @all_bind),
1022 else { # empty list : some databases won't understand "IN ()", so DWIM
1023 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1028 SCALARREF => sub { # literal SQL
1029 my $sql = $self->_open_outer_paren ($$vals);
1030 return ("$label $op ( $sql )");
1032 ARRAYREFREF => sub { # literal SQL with bind
1033 my ($sql, @bind) = @$$vals;
1034 $self->_assert_bindval_matches_bindtype(@bind);
1035 $sql = $self->_open_outer_paren ($sql);
1036 return ("$label $op ( $sql )", @bind);
1040 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1044 return ($sql, @bind);
1047 # Some databases (SQLite) treat col IN (1, 2) different from
1048 # col IN ( (1, 2) ). Use this to strip all outer parens while
1049 # adding them back in the corresponding method
1050 sub _open_outer_paren {
1051 my ($self, $sql) = @_;
1052 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1057 #======================================================================
1059 #======================================================================
1062 my ($self, $arg) = @_;
1065 for my $c ($self->_order_by_chunks ($arg) ) {
1066 $self->_SWITCH_refkind ($c, {
1067 SCALAR => sub { push @sql, $c },
1068 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1074 $self->_sqlcase(' order by'),
1080 return wantarray ? ($sql, @bind) : $sql;
1083 sub _order_by_chunks {
1084 my ($self, $arg) = @_;
1086 return $self->_SWITCH_refkind($arg, {
1089 map { $self->_order_by_chunks ($_ ) } @$arg;
1092 ARRAYREFREF => sub {
1093 my ($s, @b) = @$$arg;
1094 $self->_assert_bindval_matches_bindtype(@b);
1098 SCALAR => sub {$self->_quote($arg)},
1100 UNDEF => sub {return () },
1102 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1105 # get first pair in hash
1106 my ($key, $val, @rest) = %$arg;
1108 return () unless $key;
1110 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1111 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1117 for my $c ($self->_order_by_chunks ($val)) {
1120 $self->_SWITCH_refkind ($c, {
1125 ($sql, @bind) = @$c;
1129 $sql = $sql . ' ' . $self->_sqlcase($direction);
1131 push @ret, [ $sql, @bind];
1140 #======================================================================
1141 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1142 #======================================================================
1147 $self->_SWITCH_refkind($from, {
1148 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$from;},
1149 SCALAR => sub {$self->_quote($from)},
1150 SCALARREF => sub {$$from},
1151 ARRAYREFREF => sub {join ', ', @$from;},
1156 #======================================================================
1158 #======================================================================
1160 # highly optimized, as it's called way too often
1162 # my ($self, $label) = @_;
1164 return '' unless defined $_[1];
1165 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1167 unless ($_[0]->{quote_char}) {
1168 $_[0]->_assert_pass_injection_guard($_[1]);
1172 my $qref = ref $_[0]->{quote_char};
1175 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1177 elsif ($qref eq 'ARRAY') {
1178 ($l, $r) = @{$_[0]->{quote_char}};
1181 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1184 # parts containing * are naturally unquoted
1185 return join( $_[0]->{name_sep}||'', map
1186 { $_ eq '*' ? $_ : $l . $_ . $r }
1187 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1192 # Conversion, if applicable
1194 #my ($self, $arg) = @_;
1196 # LDNOTE : modified the previous implementation below because
1197 # it was not consistent : the first "return" is always an array,
1198 # the second "return" is context-dependent. Anyway, _convert
1199 # seems always used with just a single argument, so make it a
1201 # return @_ unless $self->{convert};
1202 # my $conv = $self->_sqlcase($self->{convert});
1203 # my @ret = map { $conv.'('.$_.')' } @_;
1204 # return wantarray ? @ret : $ret[0];
1205 if ($_[0]->{convert}) {
1206 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1213 #my ($self, $col, @vals) = @_;
1215 #LDNOTE : changed original implementation below because it did not make
1216 # sense when bindtype eq 'columns' and @vals > 1.
1217 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1219 # called often - tighten code
1220 return $_[0]->{bindtype} eq 'columns'
1221 ? map {[$_[1], $_]} @_[2 .. $#_]
1226 # Dies if any element of @bind is not in [colname => value] format
1227 # if bindtype is 'columns'.
1228 sub _assert_bindval_matches_bindtype {
1229 # my ($self, @bind) = @_;
1231 if ($self->{bindtype} eq 'columns') {
1233 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1234 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1240 sub _join_sql_clauses {
1241 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1243 if (@$clauses_aref > 1) {
1244 my $join = " " . $self->_sqlcase($logic) . " ";
1245 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1246 return ($sql, @$bind_aref);
1248 elsif (@$clauses_aref) {
1249 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1252 return (); # if no SQL, ignore @$bind_aref
1257 # Fix SQL case, if so requested
1259 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1260 # don't touch the argument ... crooked logic, but let's not change it!
1261 return $_[0]->{case} ? $_[1] : uc($_[1]);
1265 #======================================================================
1266 # DISPATCHING FROM REFKIND
1267 #======================================================================
1270 my ($self, $data) = @_;
1272 return 'UNDEF' unless defined $data;
1274 # blessed objects are treated like scalars
1275 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1277 return 'SCALAR' unless $ref;
1280 while ($ref eq 'REF') {
1282 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1286 return ($ref||'SCALAR') . ('REF' x $n_steps);
1290 my ($self, $data) = @_;
1291 my @try = ($self->_refkind($data));
1292 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1293 push @try, 'FALLBACK';
1297 sub _METHOD_FOR_refkind {
1298 my ($self, $meth_prefix, $data) = @_;
1301 for (@{$self->_try_refkind($data)}) {
1302 $method = $self->can($meth_prefix."_".$_)
1306 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1310 sub _SWITCH_refkind {
1311 my ($self, $data, $dispatch_table) = @_;
1314 for (@{$self->_try_refkind($data)}) {
1315 $coderef = $dispatch_table->{$_}
1319 puke "no dispatch entry for ".$self->_refkind($data)
1328 #======================================================================
1329 # VALUES, GENERATE, AUTOLOAD
1330 #======================================================================
1332 # LDNOTE: original code from nwiger, didn't touch code in that section
1333 # I feel the AUTOLOAD stuff should not be the default, it should
1334 # only be activated on explicit demand by user.
1338 my $data = shift || return;
1339 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1340 unless ref $data eq 'HASH';
1343 foreach my $k ( sort keys %$data ) {
1344 my $v = $data->{$k};
1345 $self->_SWITCH_refkind($v, {
1347 if ($self->{array_datatypes}) { # array datatype
1348 push @all_bind, $self->_bindtype($k, $v);
1350 else { # literal SQL with bind
1351 my ($sql, @bind) = @$v;
1352 $self->_assert_bindval_matches_bindtype(@bind);
1353 push @all_bind, @bind;
1356 ARRAYREFREF => sub { # literal SQL with bind
1357 my ($sql, @bind) = @${$v};
1358 $self->_assert_bindval_matches_bindtype(@bind);
1359 push @all_bind, @bind;
1361 SCALARREF => sub { # literal SQL without bind
1363 SCALAR_or_UNDEF => sub {
1364 push @all_bind, $self->_bindtype($k, $v);
1375 my(@sql, @sqlq, @sqlv);
1379 if ($ref eq 'HASH') {
1380 for my $k (sort keys %$_) {
1383 my $label = $self->_quote($k);
1384 if ($r eq 'ARRAY') {
1385 # literal SQL with bind
1386 my ($sql, @bind) = @$v;
1387 $self->_assert_bindval_matches_bindtype(@bind);
1388 push @sqlq, "$label = $sql";
1390 } elsif ($r eq 'SCALAR') {
1391 # literal SQL without bind
1392 push @sqlq, "$label = $$v";
1394 push @sqlq, "$label = ?";
1395 push @sqlv, $self->_bindtype($k, $v);
1398 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1399 } elsif ($ref eq 'ARRAY') {
1400 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1403 if ($r eq 'ARRAY') { # literal SQL with bind
1404 my ($sql, @bind) = @$v;
1405 $self->_assert_bindval_matches_bindtype(@bind);
1408 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1409 # embedded literal SQL
1416 push @sql, '(' . join(', ', @sqlq) . ')';
1417 } elsif ($ref eq 'SCALAR') {
1421 # strings get case twiddled
1422 push @sql, $self->_sqlcase($_);
1426 my $sql = join ' ', @sql;
1428 # this is pretty tricky
1429 # if ask for an array, return ($stmt, @bind)
1430 # otherwise, s/?/shift @sqlv/ to put it inline
1432 return ($sql, @sqlv);
1434 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1435 ref $d ? $d->[1] : $d/e;
1444 # This allows us to check for a local, then _form, attr
1446 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1447 return $self->generate($name, @_);
1458 SQL::Abstract - Generate SQL from Perl data structures
1464 my $sql = SQL::Abstract->new;
1466 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1468 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1470 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1472 my($stmt, @bind) = $sql->delete($table, \%where);
1474 # Then, use these in your DBI statements
1475 my $sth = $dbh->prepare($stmt);
1476 $sth->execute(@bind);
1478 # Just generate the WHERE clause
1479 my($stmt, @bind) = $sql->where(\%where, \@order);
1481 # Return values in the same order, for hashed queries
1482 # See PERFORMANCE section for more details
1483 my @bind = $sql->values(\%fieldvals);
1487 This module was inspired by the excellent L<DBIx::Abstract>.
1488 However, in using that module I found that what I really wanted
1489 to do was generate SQL, but still retain complete control over my
1490 statement handles and use the DBI interface. So, I set out to
1491 create an abstract SQL generation module.
1493 While based on the concepts used by L<DBIx::Abstract>, there are
1494 several important differences, especially when it comes to WHERE
1495 clauses. I have modified the concepts used to make the SQL easier
1496 to generate from Perl data structures and, IMO, more intuitive.
1497 The underlying idea is for this module to do what you mean, based
1498 on the data structures you provide it. The big advantage is that
1499 you don't have to modify your code every time your data changes,
1500 as this module figures it out.
1502 To begin with, an SQL INSERT is as easy as just specifying a hash
1503 of C<key=value> pairs:
1506 name => 'Jimbo Bobson',
1507 phone => '123-456-7890',
1508 address => '42 Sister Lane',
1509 city => 'St. Louis',
1510 state => 'Louisiana',
1513 The SQL can then be generated with this:
1515 my($stmt, @bind) = $sql->insert('people', \%data);
1517 Which would give you something like this:
1519 $stmt = "INSERT INTO people
1520 (address, city, name, phone, state)
1521 VALUES (?, ?, ?, ?, ?)";
1522 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1523 '123-456-7890', 'Louisiana');
1525 These are then used directly in your DBI code:
1527 my $sth = $dbh->prepare($stmt);
1528 $sth->execute(@bind);
1530 =head2 Inserting and Updating Arrays
1532 If your database has array types (like for example Postgres),
1533 activate the special option C<< array_datatypes => 1 >>
1534 when creating the C<SQL::Abstract> object.
1535 Then you may use an arrayref to insert and update database array types:
1537 my $sql = SQL::Abstract->new(array_datatypes => 1);
1539 planets => [qw/Mercury Venus Earth Mars/]
1542 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1546 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1548 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1551 =head2 Inserting and Updating SQL
1553 In order to apply SQL functions to elements of your C<%data> you may
1554 specify a reference to an arrayref for the given hash value. For example,
1555 if you need to execute the Oracle C<to_date> function on a value, you can
1556 say something like this:
1560 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1563 The first value in the array is the actual SQL. Any other values are
1564 optional and would be included in the bind values array. This gives
1567 my($stmt, @bind) = $sql->insert('people', \%data);
1569 $stmt = "INSERT INTO people (name, date_entered)
1570 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1571 @bind = ('Bill', '03/02/2003');
1573 An UPDATE is just as easy, all you change is the name of the function:
1575 my($stmt, @bind) = $sql->update('people', \%data);
1577 Notice that your C<%data> isn't touched; the module will generate
1578 the appropriately quirky SQL for you automatically. Usually you'll
1579 want to specify a WHERE clause for your UPDATE, though, which is
1580 where handling C<%where> hashes comes in handy...
1582 =head2 Complex where statements
1584 This module can generate pretty complicated WHERE statements
1585 easily. For example, simple C<key=value> pairs are taken to mean
1586 equality, and if you want to see if a field is within a set
1587 of values, you can use an arrayref. Let's say we wanted to
1588 SELECT some data based on this criteria:
1591 requestor => 'inna',
1592 worker => ['nwiger', 'rcwe', 'sfz'],
1593 status => { '!=', 'completed' }
1596 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1598 The above would give you something like this:
1600 $stmt = "SELECT * FROM tickets WHERE
1601 ( requestor = ? ) AND ( status != ? )
1602 AND ( worker = ? OR worker = ? OR worker = ? )";
1603 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1605 Which you could then use in DBI code like so:
1607 my $sth = $dbh->prepare($stmt);
1608 $sth->execute(@bind);
1614 The functions are simple. There's one for each major SQL operation,
1615 and a constructor you use first. The arguments are specified in a
1616 similar order to each function (table, then fields, then a where
1617 clause) to try and simplify things.
1622 =head2 new(option => 'value')
1624 The C<new()> function takes a list of options and values, and returns
1625 a new B<SQL::Abstract> object which can then be used to generate SQL
1626 through the methods below. The options accepted are:
1632 If set to 'lower', then SQL will be generated in all lowercase. By
1633 default SQL is generated in "textbook" case meaning something like:
1635 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1637 Any setting other than 'lower' is ignored.
1641 This determines what the default comparison operator is. By default
1642 it is C<=>, meaning that a hash like this:
1644 %where = (name => 'nwiger', email => 'nate@wiger.org');
1646 Will generate SQL like this:
1648 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1650 However, you may want loose comparisons by default, so if you set
1651 C<cmp> to C<like> you would get SQL such as:
1653 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1655 You can also override the comparsion on an individual basis - see
1656 the huge section on L</"WHERE CLAUSES"> at the bottom.
1658 =item sqltrue, sqlfalse
1660 Expressions for inserting boolean values within SQL statements.
1661 By default these are C<1=1> and C<1=0>. They are used
1662 by the special operators C<-in> and C<-not_in> for generating
1663 correct SQL even when the argument is an empty array (see below).
1667 This determines the default logical operator for multiple WHERE
1668 statements in arrays or hashes. If absent, the default logic is "or"
1669 for arrays, and "and" for hashes. This means that a WHERE
1673 event_date => {'>=', '2/13/99'},
1674 event_date => {'<=', '4/24/03'},
1677 will generate SQL like this:
1679 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1681 This is probably not what you want given this query, though (look
1682 at the dates). To change the "OR" to an "AND", simply specify:
1684 my $sql = SQL::Abstract->new(logic => 'and');
1686 Which will change the above C<WHERE> to:
1688 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1690 The logic can also be changed locally by inserting
1691 a modifier in front of an arrayref :
1693 @where = (-and => [event_date => {'>=', '2/13/99'},
1694 event_date => {'<=', '4/24/03'} ]);
1696 See the L</"WHERE CLAUSES"> section for explanations.
1700 This will automatically convert comparisons using the specified SQL
1701 function for both column and value. This is mostly used with an argument
1702 of C<upper> or C<lower>, so that the SQL will have the effect of
1703 case-insensitive "searches". For example, this:
1705 $sql = SQL::Abstract->new(convert => 'upper');
1706 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1708 Will turn out the following SQL:
1710 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1712 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1713 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1714 not validate this option; it will just pass through what you specify verbatim).
1718 This is a kludge because many databases suck. For example, you can't
1719 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1720 Instead, you have to use C<bind_param()>:
1722 $sth->bind_param(1, 'reg data');
1723 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1725 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1726 which loses track of which field each slot refers to. Fear not.
1728 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1729 Currently, you can specify either C<normal> (default) or C<columns>. If you
1730 specify C<columns>, you will get an array that looks like this:
1732 my $sql = SQL::Abstract->new(bindtype => 'columns');
1733 my($stmt, @bind) = $sql->insert(...);
1736 [ 'column1', 'value1' ],
1737 [ 'column2', 'value2' ],
1738 [ 'column3', 'value3' ],
1741 You can then iterate through this manually, using DBI's C<bind_param()>.
1743 $sth->prepare($stmt);
1746 my($col, $data) = @$_;
1747 if ($col eq 'details' || $col eq 'comments') {
1748 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1749 } elsif ($col eq 'image') {
1750 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1752 $sth->bind_param($i, $data);
1756 $sth->execute; # execute without @bind now
1758 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1759 Basically, the advantage is still that you don't have to care which fields
1760 are or are not included. You could wrap that above C<for> loop in a simple
1761 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1762 get a layer of abstraction over manual SQL specification.
1764 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1765 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1766 will expect the bind values in this format.
1770 This is the character that a table or column name will be quoted
1771 with. By default this is an empty string, but you could set it to
1772 the character C<`>, to generate SQL like this:
1774 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1776 Alternatively, you can supply an array ref of two items, the first being the left
1777 hand quote character, and the second the right hand quote character. For
1778 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1779 that generates SQL like this:
1781 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1783 Quoting is useful if you have tables or columns names that are reserved
1784 words in your database's SQL dialect.
1788 This is the character that separates a table and column name. It is
1789 necessary to specify this when the C<quote_char> option is selected,
1790 so that tables and column names can be individually quoted like this:
1792 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1794 =item injection_guard
1796 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1797 column name specified in a query structure. This is a safety mechanism to avoid
1798 injection attacks when mishandling user input e.g.:
1800 my %condition_as_column_value_pairs = get_values_from_user();
1801 $sqla->select( ... , \%condition_as_column_value_pairs );
1803 If the expression matches an exception is thrown. Note that literal SQL
1804 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1806 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1808 =item array_datatypes
1810 When this option is true, arrayrefs in INSERT or UPDATE are
1811 interpreted as array datatypes and are passed directly
1813 When this option is false, arrayrefs are interpreted
1814 as literal SQL, just like refs to arrayrefs
1815 (but this behavior is for backwards compatibility; when writing
1816 new queries, use the "reference to arrayref" syntax
1822 Takes a reference to a list of "special operators"
1823 to extend the syntax understood by L<SQL::Abstract>.
1824 See section L</"SPECIAL OPERATORS"> for details.
1828 Takes a reference to a list of "unary operators"
1829 to extend the syntax understood by L<SQL::Abstract>.
1830 See section L</"UNARY OPERATORS"> for details.
1836 =head2 insert($table, \@values || \%fieldvals, \%options)
1838 This is the simplest function. You simply give it a table name
1839 and either an arrayref of values or hashref of field/value pairs.
1840 It returns an SQL INSERT statement and a list of bind values.
1841 See the sections on L</"Inserting and Updating Arrays"> and
1842 L</"Inserting and Updating SQL"> for information on how to insert
1843 with those data types.
1845 The optional C<\%options> hash reference may contain additional
1846 options to generate the insert SQL. Currently supported options
1853 Takes either a scalar of raw SQL fields, or an array reference of
1854 field names, and adds on an SQL C<RETURNING> statement at the end.
1855 This allows you to return data generated by the insert statement
1856 (such as row IDs) without performing another C<SELECT> statement.
1857 Note, however, this is not part of the SQL standard and may not
1858 be supported by all database engines.
1862 =head2 update($table, \%fieldvals, \%where)
1864 This takes a table, hashref of field/value pairs, and an optional
1865 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1867 See the sections on L</"Inserting and Updating Arrays"> and
1868 L</"Inserting and Updating SQL"> for information on how to insert
1869 with those data types.
1871 =head2 select($source, $fields, $where, $order)
1873 This returns a SQL SELECT statement and associated list of bind values, as
1874 specified by the arguments :
1880 Specification of the 'FROM' part of the statement.
1881 The argument can be either a plain scalar (interpreted as a table
1882 name, will be quoted), or an arrayref (interpreted as a list
1883 of table names, joined by commas, quoted), or a scalarref
1884 (literal table name, not quoted), or a ref to an arrayref
1885 (list of literal table names, joined by commas, not quoted).
1889 Specification of the list of fields to retrieve from
1891 The argument can be either an arrayref (interpreted as a list
1892 of field names, will be joined by commas and quoted), or a
1893 plain scalar (literal SQL, not quoted).
1894 Please observe that this API is not as flexible as for
1895 the first argument C<$table>, for backwards compatibility reasons.
1899 Optional argument to specify the WHERE part of the query.
1900 The argument is most often a hashref, but can also be
1901 an arrayref or plain scalar --
1902 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
1906 Optional argument to specify the ORDER BY part of the query.
1907 The argument can be a scalar, a hashref or an arrayref
1908 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1914 =head2 delete($table, \%where)
1916 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
1917 It returns an SQL DELETE statement and list of bind values.
1919 =head2 where(\%where, \@order)
1921 This is used to generate just the WHERE clause. For example,
1922 if you have an arbitrary data structure and know what the
1923 rest of your SQL is going to look like, but want an easy way
1924 to produce a WHERE clause, use this. It returns an SQL WHERE
1925 clause and list of bind values.
1928 =head2 values(\%data)
1930 This just returns the values from the hash C<%data>, in the same
1931 order that would be returned from any of the other above queries.
1932 Using this allows you to markedly speed up your queries if you
1933 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
1935 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
1937 Warning: This is an experimental method and subject to change.
1939 This returns arbitrarily generated SQL. It's a really basic shortcut.
1940 It will return two different things, depending on return context:
1942 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
1943 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
1945 These would return the following:
1947 # First calling form
1948 $stmt = "CREATE TABLE test (?, ?)";
1949 @bind = (field1, field2);
1951 # Second calling form
1952 $stmt_and_val = "CREATE TABLE test (field1, field2)";
1954 Depending on what you're trying to do, it's up to you to choose the correct
1955 format. In this example, the second form is what you would want.
1959 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
1963 ALTER SESSION SET nls_date_format = 'MM/YY'
1965 You get the idea. Strings get their case twiddled, but everything
1966 else remains verbatim.
1971 =head1 WHERE CLAUSES
1975 This module uses a variation on the idea from L<DBIx::Abstract>. It
1976 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1977 module is that things in arrays are OR'ed, and things in hashes
1980 The easiest way to explain is to show lots of examples. After
1981 each C<%where> hash shown, it is assumed you used:
1983 my($stmt, @bind) = $sql->where(\%where);
1985 However, note that the C<%where> hash can be used directly in any
1986 of the other functions as well, as described above.
1988 =head2 Key-value pairs
1990 So, let's get started. To begin, a simple hash:
1994 status => 'completed'
1997 Is converted to SQL C<key = val> statements:
1999 $stmt = "WHERE user = ? AND status = ?";
2000 @bind = ('nwiger', 'completed');
2002 One common thing I end up doing is having a list of values that
2003 a field can be in. To do this, simply specify a list inside of
2008 status => ['assigned', 'in-progress', 'pending'];
2011 This simple code will create the following:
2013 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2014 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2016 A field associated to an empty arrayref will be considered a
2017 logical false and will generate 0=1.
2019 =head2 Tests for NULL values
2021 If the value part is C<undef> then this is converted to SQL <IS NULL>
2030 $stmt = "WHERE user = ? AND status IS NULL";
2033 =head2 Specific comparison operators
2035 If you want to specify a different type of operator for your comparison,
2036 you can use a hashref for a given column:
2040 status => { '!=', 'completed' }
2043 Which would generate:
2045 $stmt = "WHERE user = ? AND status != ?";
2046 @bind = ('nwiger', 'completed');
2048 To test against multiple values, just enclose the values in an arrayref:
2050 status => { '=', ['assigned', 'in-progress', 'pending'] };
2052 Which would give you:
2054 "WHERE status = ? OR status = ? OR status = ?"
2057 The hashref can also contain multiple pairs, in which case it is expanded
2058 into an C<AND> of its elements:
2062 status => { '!=', 'completed', -not_like => 'pending%' }
2065 # Or more dynamically, like from a form
2066 $where{user} = 'nwiger';
2067 $where{status}{'!='} = 'completed';
2068 $where{status}{'-not_like'} = 'pending%';
2070 # Both generate this
2071 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2072 @bind = ('nwiger', 'completed', 'pending%');
2075 To get an OR instead, you can combine it with the arrayref idea:
2079 priority => [ {'=', 2}, {'!=', 1} ]
2082 Which would generate:
2084 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
2085 @bind = ('nwiger', '2', '1');
2087 If you want to include literal SQL (with or without bind values), just use a
2088 scalar reference or array reference as the value:
2091 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2092 date_expires => { '<' => \"now()" }
2095 Which would generate:
2097 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2098 @bind = ('11/26/2008');
2101 =head2 Logic and nesting operators
2103 In the example above,
2104 there is a subtle trap if you want to say something like
2105 this (notice the C<AND>):
2107 WHERE priority != ? AND priority != ?
2109 Because, in Perl you I<can't> do this:
2111 priority => { '!=', 2, '!=', 1 }
2113 As the second C<!=> key will obliterate the first. The solution
2114 is to use the special C<-modifier> form inside an arrayref:
2116 priority => [ -and => {'!=', 2},
2120 Normally, these would be joined by C<OR>, but the modifier tells it
2121 to use C<AND> instead. (Hint: You can use this in conjunction with the
2122 C<logic> option to C<new()> in order to change the way your queries
2123 work by default.) B<Important:> Note that the C<-modifier> goes
2124 B<INSIDE> the arrayref, as an extra first element. This will
2125 B<NOT> do what you think it might:
2127 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2129 Here is a quick list of equivalencies, since there is some overlap:
2132 status => {'!=', 'completed', 'not like', 'pending%' }
2133 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2136 status => {'=', ['assigned', 'in-progress']}
2137 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2138 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2142 =head2 Special operators : IN, BETWEEN, etc.
2144 You can also use the hashref format to compare a list of fields using the
2145 C<IN> comparison operator, by specifying the list as an arrayref:
2148 status => 'completed',
2149 reportid => { -in => [567, 2335, 2] }
2152 Which would generate:
2154 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2155 @bind = ('completed', '567', '2335', '2');
2157 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2160 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2161 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2162 'sqltrue' (by default : C<1=1>).
2164 In addition to the array you can supply a chunk of literal sql or
2165 literal sql with bind:
2168 customer => { -in => \[
2169 'SELECT cust_id FROM cust WHERE balance > ?',
2172 status => { -in => \'SELECT status_codes FROM states' },
2178 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2179 AND status IN ( SELECT status_codes FROM states )
2185 Another pair of operators is C<-between> and C<-not_between>,
2186 used with an arrayref of two values:
2190 completion_date => {
2191 -not_between => ['2002-10-01', '2003-02-06']
2197 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2199 Just like with C<-in> all plausible combinations of literal SQL
2203 start0 => { -between => [ 1, 2 ] },
2204 start1 => { -between => \["? AND ?", 1, 2] },
2205 start2 => { -between => \"lower(x) AND upper(y)" },
2206 start3 => { -between => [
2208 \["upper(?)", 'stuff' ],
2215 ( start0 BETWEEN ? AND ? )
2216 AND ( start1 BETWEEN ? AND ? )
2217 AND ( start2 BETWEEN lower(x) AND upper(y) )
2218 AND ( start3 BETWEEN lower(x) AND upper(?) )
2220 @bind = (1, 2, 1, 2, 'stuff');
2223 These are the two builtin "special operators"; but the
2224 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2226 =head2 Unary operators: bool
2228 If you wish to test against boolean columns or functions within your
2229 database you can use the C<-bool> and C<-not_bool> operators. For
2230 example to test the column C<is_user> being true and the column
2231 C<is_enabled> being false you would use:-
2235 -not_bool => 'is_enabled',
2240 WHERE is_user AND NOT is_enabled
2242 If a more complex combination is required, testing more conditions,
2243 then you should use the and/or operators:-
2250 -not_bool => 'four',
2256 WHERE one AND two AND three AND NOT four
2259 =head2 Nested conditions, -and/-or prefixes
2261 So far, we've seen how multiple conditions are joined with a top-level
2262 C<AND>. We can change this by putting the different conditions we want in
2263 hashes and then putting those hashes in an array. For example:
2268 status => { -like => ['pending%', 'dispatched'] },
2272 status => 'unassigned',
2276 This data structure would create the following:
2278 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2279 OR ( user = ? AND status = ? ) )";
2280 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2283 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2284 to change the logic inside :
2290 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2291 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2298 WHERE ( user = ? AND (
2299 ( workhrs > ? AND geo = ? )
2300 OR ( workhrs < ? OR geo = ? )
2303 =head2 Algebraic inconsistency, for historical reasons
2305 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2306 operator goes C<outside> of the nested structure; whereas when connecting
2307 several constraints on one column, the C<-and> operator goes
2308 C<inside> the arrayref. Here is an example combining both features :
2311 -and => [a => 1, b => 2],
2312 -or => [c => 3, d => 4],
2313 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2318 WHERE ( ( ( a = ? AND b = ? )
2319 OR ( c = ? OR d = ? )
2320 OR ( e LIKE ? AND e LIKE ? ) ) )
2322 This difference in syntax is unfortunate but must be preserved for
2323 historical reasons. So be careful : the two examples below would
2324 seem algebraically equivalent, but they are not
2326 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2327 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2329 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2330 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2335 Finally, sometimes only literal SQL will do. If you want to include
2336 literal SQL verbatim, you can specify it as a scalar reference, namely:
2338 my $inn = 'is Not Null';
2340 priority => { '<', 2 },
2346 $stmt = "WHERE priority < ? AND requestor is Not Null";
2349 Note that in this example, you only get one bind parameter back, since
2350 the verbatim SQL is passed as part of the statement.
2352 Of course, just to prove a point, the above can also be accomplished
2356 priority => { '<', 2 },
2357 requestor => { '!=', undef },
2363 Conditions on boolean columns can be expressed in the same way, passing
2364 a reference to an empty string, however using liternal SQL in this way
2365 is deprecated - the preferred method is to use the boolean operators -
2366 see L</"Unary operators: bool"> :
2369 priority => { '<', 2 },
2375 $stmt = "WHERE priority < ? AND is_ready";
2378 Literal SQL is also the only way to compare 2 columns to one another:
2381 priority => { '<', 2 },
2382 requestor => \'= submittor'
2387 $stmt = "WHERE priority < ? AND requestor = submitter";
2390 =head2 Literal SQL with placeholders and bind values (subqueries)
2392 If the literal SQL to be inserted has placeholders and bind values,
2393 use a reference to an arrayref (yes this is a double reference --
2394 not so common, but perfectly legal Perl). For example, to find a date
2395 in Postgres you can use something like this:
2398 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2403 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2406 Note that you must pass the bind values in the same format as they are returned
2407 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2408 provide the bind values in the C<< [ column_meta => value ] >> format, where
2409 C<column_meta> is an opaque scalar value; most commonly the column name, but
2410 you can use any scalar value (including references and blessed references),
2411 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2412 to C<columns> the above example will look like:
2415 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2418 Literal SQL is especially useful for nesting parenthesized clauses in the
2419 main SQL query. Here is a first example :
2421 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2425 bar => \["IN ($sub_stmt)" => @sub_bind],
2430 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2431 WHERE c2 < ? AND c3 LIKE ?))";
2432 @bind = (1234, 100, "foo%");
2434 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2435 are expressed in the same way. Of course the C<$sub_stmt> and
2436 its associated bind values can be generated through a former call
2439 my ($sub_stmt, @sub_bind)
2440 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2441 c3 => {-like => "foo%"}});
2444 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2447 In the examples above, the subquery was used as an operator on a column;
2448 but the same principle also applies for a clause within the main C<%where>
2449 hash, like an EXISTS subquery :
2451 my ($sub_stmt, @sub_bind)
2452 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2453 my %where = ( -and => [
2455 \["EXISTS ($sub_stmt)" => @sub_bind],
2460 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2461 WHERE c1 = ? AND c2 > t0.c0))";
2465 Observe that the condition on C<c2> in the subquery refers to
2466 column C<t0.c0> of the main query : this is I<not> a bind
2467 value, so we have to express it through a scalar ref.
2468 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2469 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2470 what we wanted here.
2472 Finally, here is an example where a subquery is used
2473 for expressing unary negation:
2475 my ($sub_stmt, @sub_bind)
2476 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2477 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2479 lname => {like => '%son%'},
2480 \["NOT ($sub_stmt)" => @sub_bind],
2485 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2486 @bind = ('%son%', 10, 20)
2492 These pages could go on for a while, since the nesting of the data
2493 structures this module can handle are pretty much unlimited (the
2494 module implements the C<WHERE> expansion as a recursive function
2495 internally). Your best bet is to "play around" with the module a
2496 little to see how the data structures behave, and choose the best
2497 format for your data based on that.
2499 And of course, all the values above will probably be replaced with
2500 variables gotten from forms or the command line. After all, if you
2501 knew everything ahead of time, you wouldn't have to worry about
2502 dynamically-generating SQL and could just hardwire it into your
2508 =head1 ORDER BY CLAUSES
2510 Some functions take an order by clause. This can either be a scalar (just a
2511 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2512 or an array of either of the two previous forms. Examples:
2514 Given | Will Generate
2515 ----------------------------------------------------------
2517 \'colA DESC' | ORDER BY colA DESC
2519 'colA' | ORDER BY colA
2521 [qw/colA colB/] | ORDER BY colA, colB
2523 {-asc => 'colA'} | ORDER BY colA ASC
2525 {-desc => 'colB'} | ORDER BY colB DESC
2527 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2529 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2532 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2533 { -desc => [qw/colB/], | colC ASC, colD ASC
2534 { -asc => [qw/colC colD/],|
2536 ===========================================================
2540 =head1 SPECIAL OPERATORS
2542 my $sqlmaker = SQL::Abstract->new(special_ops => [
2546 my ($self, $field, $op, $arg) = @_;
2552 handler => 'method_name',
2556 A "special operator" is a SQL syntactic clause that can be
2557 applied to a field, instead of a usual binary operator.
2560 WHERE field IN (?, ?, ?)
2561 WHERE field BETWEEN ? AND ?
2562 WHERE MATCH(field) AGAINST (?, ?)
2564 Special operators IN and BETWEEN are fairly standard and therefore
2565 are builtin within C<SQL::Abstract> (as the overridable methods
2566 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2567 like the MATCH .. AGAINST example above which is specific to MySQL,
2568 you can write your own operator handlers - supply a C<special_ops>
2569 argument to the C<new> method. That argument takes an arrayref of
2570 operator definitions; each operator definition is a hashref with two
2577 the regular expression to match the operator
2581 Either a coderef or a plain scalar method name. In both cases
2582 the expected return is C<< ($sql, @bind) >>.
2584 When supplied with a method name, it is simply called on the
2585 L<SQL::Abstract/> object as:
2587 $self->$method_name ($field, $op, $arg)
2591 $op is the part that matched the handler regex
2592 $field is the LHS of the operator
2595 When supplied with a coderef, it is called as:
2597 $coderef->($self, $field, $op, $arg)
2602 For example, here is an implementation
2603 of the MATCH .. AGAINST syntax for MySQL
2605 my $sqlmaker = SQL::Abstract->new(special_ops => [
2607 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2608 {regex => qr/^match$/i,
2610 my ($self, $field, $op, $arg) = @_;
2611 $arg = [$arg] if not ref $arg;
2612 my $label = $self->_quote($field);
2613 my ($placeholder) = $self->_convert('?');
2614 my $placeholders = join ", ", (($placeholder) x @$arg);
2615 my $sql = $self->_sqlcase('match') . " ($label) "
2616 . $self->_sqlcase('against') . " ($placeholders) ";
2617 my @bind = $self->_bindtype($field, @$arg);
2618 return ($sql, @bind);
2625 =head1 UNARY OPERATORS
2627 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2631 my ($self, $op, $arg) = @_;
2637 handler => 'method_name',
2641 A "unary operator" is a SQL syntactic clause that can be
2642 applied to a field - the operator goes before the field
2644 You can write your own operator handlers - supply a C<unary_ops>
2645 argument to the C<new> method. That argument takes an arrayref of
2646 operator definitions; each operator definition is a hashref with two
2653 the regular expression to match the operator
2657 Either a coderef or a plain scalar method name. In both cases
2658 the expected return is C<< $sql >>.
2660 When supplied with a method name, it is simply called on the
2661 L<SQL::Abstract/> object as:
2663 $self->$method_name ($op, $arg)
2667 $op is the part that matched the handler regex
2668 $arg is the RHS or argument of the operator
2670 When supplied with a coderef, it is called as:
2672 $coderef->($self, $op, $arg)
2680 Thanks to some benchmarking by Mark Stosberg, it turns out that
2681 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2682 I must admit this wasn't an intentional design issue, but it's a
2683 byproduct of the fact that you get to control your C<DBI> handles
2686 To maximize performance, use a code snippet like the following:
2688 # prepare a statement handle using the first row
2689 # and then reuse it for the rest of the rows
2691 for my $href (@array_of_hashrefs) {
2692 $stmt ||= $sql->insert('table', $href);
2693 $sth ||= $dbh->prepare($stmt);
2694 $sth->execute($sql->values($href));
2697 The reason this works is because the keys in your C<$href> are sorted
2698 internally by B<SQL::Abstract>. Thus, as long as your data retains
2699 the same structure, you only have to generate the SQL the first time
2700 around. On subsequent queries, simply use the C<values> function provided
2701 by this module to return your values in the correct order.
2703 However this depends on the values having the same type - if, for
2704 example, the values of a where clause may either have values
2705 (resulting in sql of the form C<column = ?> with a single bind
2706 value), or alternatively the values might be C<undef> (resulting in
2707 sql of the form C<column IS NULL> with no bind value) then the
2708 caching technique suggested will not work.
2712 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2713 really like this part (I do, at least). Building up a complex query
2714 can be as simple as the following:
2718 use CGI::FormBuilder;
2721 my $form = CGI::FormBuilder->new(...);
2722 my $sql = SQL::Abstract->new;
2724 if ($form->submitted) {
2725 my $field = $form->field;
2726 my $id = delete $field->{id};
2727 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2730 Of course, you would still have to connect using C<DBI> to run the
2731 query, but the point is that if you make your form look like your
2732 table, the actual query script can be extremely simplistic.
2734 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2735 a fast interface to returning and formatting data. I frequently
2736 use these three modules together to write complex database query
2737 apps in under 50 lines.
2743 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/DBIx-Class.git>
2745 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/DBIx-Class.git>
2751 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2752 Great care has been taken to preserve the I<published> behavior
2753 documented in previous versions in the 1.* family; however,
2754 some features that were previously undocumented, or behaved
2755 differently from the documentation, had to be changed in order
2756 to clarify the semantics. Hence, client code that was relying
2757 on some dark areas of C<SQL::Abstract> v1.*
2758 B<might behave differently> in v1.50.
2760 The main changes are :
2766 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2770 support for the { operator => \"..." } construct (to embed literal SQL)
2774 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2778 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2782 defensive programming : check arguments
2786 fixed bug with global logic, which was previously implemented
2787 through global variables yielding side-effects. Prior versions would
2788 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2789 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2790 Now this is interpreted
2791 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2796 fixed semantics of _bindtype on array args
2800 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2801 we just avoid shifting arrays within that tree.
2805 dropped the C<_modlogic> function
2811 =head1 ACKNOWLEDGEMENTS
2813 There are a number of individuals that have really helped out with
2814 this module. Unfortunately, most of them submitted bugs via CPAN
2815 so I have no idea who they are! But the people I do know are:
2817 Ash Berlin (order_by hash term support)
2818 Matt Trout (DBIx::Class support)
2819 Mark Stosberg (benchmarking)
2820 Chas Owens (initial "IN" operator support)
2821 Philip Collins (per-field SQL functions)
2822 Eric Kolve (hashref "AND" support)
2823 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2824 Dan Kubb (support for "quote_char" and "name_sep")
2825 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2826 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2827 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2828 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2829 Oliver Charles (support for "RETURNING" after "INSERT")
2835 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
2839 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
2841 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
2843 For support, your best bet is to try the C<DBIx::Class> users mailing list.
2844 While not an official support venue, C<DBIx::Class> makes heavy use of
2845 C<SQL::Abstract>, and as such list members there are very familiar with
2846 how to create queries.
2850 This module is free software; you may copy this under the same
2851 terms as perl itself (either the GNU General Public License or
2852 the Artistic License)