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)
13 use Data::Query::Constants qw(
14 DQ_IDENTIFIER DQ_OPERATOR DQ_VALUE DQ_LITERAL DQ_JOIN DQ_SELECT
17 #======================================================================
19 #======================================================================
21 our $VERSION = '1.72';
23 # This would confuse some packagers
24 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
28 # special operators (-in, -between). May be extended/overridden by user.
29 # See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
30 my @BUILTIN_SPECIAL_OPS = (
31 {regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
32 {regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
33 {regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
34 {regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
37 # unaryish operators - key maps to handler
38 my @BUILTIN_UNARY_OPS = (
39 # the digits are backcompat stuff
40 { regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
41 { regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
42 { regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
43 { regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
44 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
45 { regex => qr/^ value $/ix, handler => '_where_op_VALUE' },
48 #======================================================================
49 # DEBUGGING AND ERROR REPORTING
50 #======================================================================
53 return unless $_[0]->{debug}; shift; # a little faster
54 my $func = (caller(1))[3];
55 warn "[$func] ", @_, "\n";
59 my($func) = (caller(1))[3];
60 Carp::carp "[$func] Warning: ", @_;
64 my($func) = (caller(1))[3];
65 Carp::croak "[$func] Fatal: ", @_;
69 #======================================================================
71 #======================================================================
75 my $class = ref($self) || $self;
76 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
78 # choose our case by keeping an option around
79 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
81 # default logic for interpreting arrayrefs
82 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
84 # how to return bind vars
85 # LDNOTE: changed nwiger code : why this 'delete' ??
86 # $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
87 $opt{bindtype} ||= 'normal';
89 # default comparison is "=", but can be overridden
92 # try to recognize which are the 'equality' and 'unequality' ops
93 # (temporary quickfix, should go through a more seasoned API)
94 $opt{equality_op} = qr/^(\Q$opt{cmp}\E|is|(is\s+)?like)$/i;
95 $opt{inequality_op} = qr/^(!=|<>|(is\s+)?not(\s+like)?)$/i;
98 $opt{sqltrue} ||= '1=1';
99 $opt{sqlfalse} ||= '0=1';
102 $opt{special_ops} ||= [];
103 # regexes are applied in order, thus push after user-defines
104 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
107 $opt{unary_ops} ||= [];
108 push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
110 # rudimentary saniy-check for user supplied bits treated as functions/operators
111 # If a purported function matches this regular expression, an exception is thrown.
112 # Literal SQL is *NOT* subject to this check, only functions (and column names
113 # when quoting is not in effect)
116 # need to guard against ()'s in column names too, but this will break tons of
117 # hacks... ideas anyone?
118 $opt{injection_guard} ||= qr/
124 $opt{name_sep} ||= '.';
126 $opt{renderer} ||= do {
127 require Data::Query::Renderer::SQL::Naive;
128 my ($always, $chars);
129 for ($opt{quote_char}) {
130 $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
133 Data::Query::Renderer::SQL::Naive->new({
134 quote_chars => $chars, always_quote => $always,
138 return bless \%opt, $class;
142 my ($self, $dq) = @_;
143 my ($sql, @bind) = @{$self->{renderer}->render($dq)};
144 wantarray ? ($sql, map $_->{value}, @bind) : $sql;
147 sub _assert_pass_injection_guard {
148 if ($_[1] =~ $_[0]->{injection_guard}) {
149 my $class = ref $_[0];
150 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
151 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
152 . "{injection_guard} attribute to ${class}->new()"
157 #======================================================================
159 #======================================================================
163 my $table = $self->_table(shift);
164 my $data = shift || return;
167 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
168 my ($sql, @bind) = $self->$method($data);
169 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
171 if ($options->{returning}) {
172 my ($s, @b) = $self->_insert_returning ($options);
177 return wantarray ? ($sql, @bind) : $sql;
180 sub _insert_returning {
181 my ($self, $options) = @_;
183 my $f = $options->{returning};
185 my $fieldlist = $self->_SWITCH_refkind($f, {
186 ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
187 SCALAR => sub {$self->_quote($f)},
188 SCALARREF => sub {$$f},
190 return $self->_sqlcase(' returning ') . $fieldlist;
193 sub _insert_HASHREF { # explicit list of fields and then values
194 my ($self, $data) = @_;
196 my @fields = sort keys %$data;
198 my ($sql, @bind) = $self->_insert_values($data);
201 $_ = $self->_quote($_) foreach @fields;
202 $sql = "( ".join(", ", @fields).") ".$sql;
204 return ($sql, @bind);
207 sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
208 my ($self, $data) = @_;
210 # no names (arrayref) so can't generate bindtype
211 $self->{bindtype} ne 'columns'
212 or belch "can't do 'columns' bindtype when called with arrayref";
214 # fold the list of values into a hash of column name - value pairs
215 # (where the column names are artificially generated, and their
216 # lexicographical ordering keep the ordering of the original list)
217 my $i = "a"; # incremented values will be in lexicographical order
218 my $data_in_hash = { map { ($i++ => $_) } @$data };
220 return $self->_insert_values($data_in_hash);
223 sub _insert_ARRAYREFREF { # literal SQL with bind
224 my ($self, $data) = @_;
226 my ($sql, @bind) = @${$data};
227 $self->_assert_bindval_matches_bindtype(@bind);
229 return ($sql, @bind);
233 sub _insert_SCALARREF { # literal SQL without bind
234 my ($self, $data) = @_;
240 my ($self, $data) = @_;
242 my (@values, @all_bind);
243 foreach my $column (sort keys %$data) {
244 my $v = $data->{$column};
246 $self->_SWITCH_refkind($v, {
249 if ($self->{array_datatypes}) { # if array datatype are activated
251 push @all_bind, $self->_bindtype($column, $v);
253 else { # else literal SQL with bind
254 my ($sql, @bind) = @$v;
255 $self->_assert_bindval_matches_bindtype(@bind);
257 push @all_bind, @bind;
261 ARRAYREFREF => sub { # literal SQL with bind
262 my ($sql, @bind) = @${$v};
263 $self->_assert_bindval_matches_bindtype(@bind);
265 push @all_bind, @bind;
268 # THINK : anything useful to do with a HASHREF ?
269 HASHREF => sub { # (nothing, but old SQLA passed it through)
270 #TODO in SQLA >= 2.0 it will die instead
271 belch "HASH ref as bind value in insert is not supported";
273 push @all_bind, $self->_bindtype($column, $v);
276 SCALARREF => sub { # literal SQL without bind
280 SCALAR_or_UNDEF => sub {
282 push @all_bind, $self->_bindtype($column, $v);
289 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
290 return ($sql, @all_bind);
295 #======================================================================
297 #======================================================================
302 my $table = $self->_table(shift);
303 my $data = shift || return;
306 # first build the 'SET' part of the sql statement
307 my (@set, @all_bind);
308 puke "Unsupported data type specified to \$sql->update"
309 unless ref $data eq 'HASH';
311 for my $k (sort keys %$data) {
314 my $label = $self->_quote($k);
316 $self->_SWITCH_refkind($v, {
318 if ($self->{array_datatypes}) { # array datatype
319 push @set, "$label = ?";
320 push @all_bind, $self->_bindtype($k, $v);
322 else { # literal SQL with bind
323 my ($sql, @bind) = @$v;
324 $self->_assert_bindval_matches_bindtype(@bind);
325 push @set, "$label = $sql";
326 push @all_bind, @bind;
329 ARRAYREFREF => sub { # literal SQL with bind
330 my ($sql, @bind) = @${$v};
331 $self->_assert_bindval_matches_bindtype(@bind);
332 push @set, "$label = $sql";
333 push @all_bind, @bind;
335 SCALARREF => sub { # literal SQL without bind
336 push @set, "$label = $$v";
339 my ($op, $arg, @rest) = %$v;
341 puke 'Operator calls in update must be in the form { -op => $arg }'
342 if (@rest or not $op =~ /^\-(.+)/);
344 local $self->{_nested_func_lhs} = $k;
345 my ($sql, @bind) = $self->_where_unary_op ($1, $arg);
347 push @set, "$label = $sql";
348 push @all_bind, @bind;
350 SCALAR_or_UNDEF => sub {
351 push @set, "$label = ?";
352 push @all_bind, $self->_bindtype($k, $v);
358 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ')
362 my($where_sql, @where_bind) = $self->where($where);
364 push @all_bind, @where_bind;
367 return wantarray ? ($sql, @all_bind) : $sql;
373 #======================================================================
375 #======================================================================
380 my $table = $self->_table(shift);
381 my $fields = shift || '*';
385 my($where_sql, @bind) = $self->where($where, $order);
387 my $select = $self->_render_dq({
391 type => DQ_IDENTIFIER,
392 elements => [ split /\Q$self->{name_sep}/, $_ ],
393 }, ref($fields) eq 'ARRAY' ? @$fields : $fields
396 my $sql = join(' ', $select, $self->_sqlcase('from'), $table)
399 return wantarray ? ($sql, @bind) : $sql;
402 #======================================================================
404 #======================================================================
409 my $table = $self->_table(shift);
413 my($where_sql, @bind) = $self->where($where);
414 my $sql = $self->_sqlcase('delete from') . " $table" . $where_sql;
416 return wantarray ? ($sql, @bind) : $sql;
420 #======================================================================
422 #======================================================================
426 # Finally, a separate routine just to handle WHERE clauses
428 my ($self, $where, $order) = @_;
431 my ($sql, @bind) = $self->_recurse_where($where);
432 $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
436 $sql .= $self->_order_by($order);
439 return wantarray ? ($sql, @bind) : $sql;
444 my ($self, $where, $logic) = @_;
446 # dispatch on appropriate method according to refkind of $where
447 my $method = $self->_METHOD_FOR_refkind("_where", $where);
449 my ($sql, @bind) = $self->$method($where, $logic);
451 # DBIx::Class directly calls _recurse_where in scalar context, so
452 # we must implement it, even if not in the official API
453 return wantarray ? ($sql, @bind) : $sql;
458 #======================================================================
459 # WHERE: top-level ARRAYREF
460 #======================================================================
463 sub _where_ARRAYREF {
464 my ($self, $where, $logic) = @_;
466 $logic = uc($logic || $self->{logic});
467 $logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
469 my @clauses = @$where;
471 my (@sql_clauses, @all_bind);
472 # need to use while() so can shift() for pairs
473 while (my $el = shift @clauses) {
475 # switch according to kind of $el and get corresponding ($sql, @bind)
476 my ($sql, @bind) = $self->_SWITCH_refkind($el, {
478 # skip empty elements, otherwise get invalid trailing AND stuff
479 ARRAYREF => sub {$self->_recurse_where($el) if @$el},
483 $self->_assert_bindval_matches_bindtype(@b);
487 HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
488 # LDNOTE : previous SQLA code for hashrefs was creating a dirty
489 # side-effect: the first hashref within an array would change
490 # the global logic to 'AND'. So [ {cond1, cond2}, [cond3, cond4] ]
491 # was interpreted as "(cond1 AND cond2) OR (cond3 AND cond4)",
492 # whereas it should be "(cond1 AND cond2) OR (cond3 OR cond4)".
494 SCALARREF => sub { ($$el); },
496 SCALAR => sub {# top-level arrayref with scalars, recurse in pairs
497 $self->_recurse_where({$el => shift(@clauses)})},
499 UNDEF => sub {puke "not supported : UNDEF in arrayref" },
503 push @sql_clauses, $sql;
504 push @all_bind, @bind;
508 return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
511 #======================================================================
512 # WHERE: top-level ARRAYREFREF
513 #======================================================================
515 sub _where_ARRAYREFREF {
516 my ($self, $where) = @_;
517 my ($sql, @bind) = @$$where;
518 $self->_assert_bindval_matches_bindtype(@bind);
519 return ($sql, @bind);
522 #======================================================================
523 # WHERE: top-level HASHREF
524 #======================================================================
527 my ($self, $where) = @_;
528 my (@sql_clauses, @all_bind);
530 for my $k (sort keys %$where) {
531 my $v = $where->{$k};
533 # ($k => $v) is either a special unary op or a regular hashpair
534 my ($sql, @bind) = do {
536 # put the operator in canonical form
538 $op = substr $op, 1; # remove initial dash
539 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
540 $op =~ s/\s+/ /g; # compress whitespace
542 # so that -not_foo works correctly
543 $op =~ s/^not_/NOT /i;
545 $self->_debug("Unary OP(-$op) within hashref, recursing...");
546 my ($s, @b) = $self->_where_unary_op ($op, $v);
548 # top level vs nested
549 # we assume that handled unary ops will take care of their ()s
551 List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
553 defined($self->{_nested_func_lhs}) && ($self->{_nested_func_lhs} eq $k)
558 my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
559 $self->$method($k, $v);
563 push @sql_clauses, $sql;
564 push @all_bind, @bind;
567 return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
570 sub _where_unary_op {
571 my ($self, $op, $rhs) = @_;
573 if (my $op_entry = List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}) {
574 my $handler = $op_entry->{handler};
576 if (not ref $handler) {
577 if ($op =~ s/ [_\s]? \d+ $//x ) {
578 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
579 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
581 return $self->$handler ($op, $rhs);
583 elsif (ref $handler eq 'CODE') {
584 return $handler->($self, $op, $rhs);
587 puke "Illegal handler for operator $op - expecting a method name or a coderef";
591 $self->_debug("Generic unary OP: $op - recursing as function");
593 $self->_assert_pass_injection_guard($op);
595 my ($sql, @bind) = $self->_SWITCH_refkind ($rhs, {
597 puke "Illegal use of top-level '$op'"
598 unless $self->{_nested_func_lhs};
601 $self->_convert('?'),
602 $self->_bindtype($self->{_nested_func_lhs}, $rhs)
606 $self->_recurse_where ($rhs)
610 $sql = sprintf ('%s %s',
611 $self->_sqlcase($op),
615 return ($sql, @bind);
618 sub _where_op_ANDOR {
619 my ($self, $op, $v) = @_;
621 $self->_SWITCH_refkind($v, {
623 return $self->_where_ARRAYREF($v, $op);
627 return ( $op =~ /^or/i )
628 ? $self->_where_ARRAYREF( [ map { $_ => $v->{$_} } ( sort keys %$v ) ], $op )
629 : $self->_where_HASHREF($v);
633 puke "-$op => \\\$scalar makes little sense, use " .
635 ? '[ \$scalar, \%rest_of_conditions ] instead'
636 : '-and => [ \$scalar, \%rest_of_conditions ] instead'
641 puke "-$op => \\[...] makes little sense, use " .
643 ? '[ \[...], \%rest_of_conditions ] instead'
644 : '-and => [ \[...], \%rest_of_conditions ] instead'
648 SCALAR => sub { # permissively interpreted as SQL
649 puke "-$op => \$value makes little sense, use -bool => \$value instead";
653 puke "-$op => undef not supported";
659 my ($self, $op, $v) = @_;
661 $self->_SWITCH_refkind($v, {
663 SCALAR => sub { # permissively interpreted as SQL
664 belch "literal SQL should be -nest => \\'scalar' "
665 . "instead of -nest => 'scalar' ";
670 puke "-$op => undef not supported";
674 $self->_recurse_where ($v);
682 my ($self, $op, $v) = @_;
684 my ($s, @b) = $self->_SWITCH_refkind($v, {
685 SCALAR => sub { # interpreted as SQL column
686 $self->_convert($self->_quote($v));
690 puke "-$op => undef not supported";
694 $self->_recurse_where ($v);
698 $s = "(NOT $s)" if $op =~ /^not/i;
703 sub _where_op_IDENT {
705 my ($op, $rhs) = splice @_, -2;
707 puke "-$op takes a single scalar argument (a quotable identifier)";
710 # in case we are called as a top level special op (no '=')
713 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
721 sub _where_op_VALUE {
723 my ($op, $rhs) = splice @_, -2;
725 # in case we are called as a top level special op (no '=')
730 ($lhs || $self->{_nested_func_lhs}),
737 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
741 $self->_convert('?'),
747 sub _where_hashpair_ARRAYREF {
748 my ($self, $k, $v) = @_;
751 my @v = @$v; # need copy because of shift below
752 $self->_debug("ARRAY($k) means distribute over elements");
754 # put apart first element if it is an operator (-and, -or)
756 (defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
760 my @distributed = map { {$k => $_} } @v;
763 $self->_debug("OP($op) reinjected into the distributed array");
764 unshift @distributed, $op;
767 my $logic = $op ? substr($op, 1) : '';
769 return $self->_recurse_where(\@distributed, $logic);
772 # LDNOTE : not sure of this one. What does "distribute over nothing" mean?
773 $self->_debug("empty ARRAY($k) means 0=1");
774 return ($self->{sqlfalse});
778 sub _where_hashpair_HASHREF {
779 my ($self, $k, $v, $logic) = @_;
782 local $self->{_nested_func_lhs} = $self->{_nested_func_lhs};
784 my ($all_sql, @all_bind);
786 for my $orig_op (sort keys %$v) {
787 my $val = $v->{$orig_op};
789 # put the operator in canonical form
792 # FIXME - we need to phase out dash-less ops
793 $op =~ s/^-//; # remove possible initial dash
794 $op =~ s/^\s+|\s+$//g;# remove leading/trailing space
795 $op =~ s/\s+/ /g; # compress whitespace
797 $self->_assert_pass_injection_guard($op);
799 # so that -not_foo works correctly
800 $op =~ s/^not_/NOT /i;
804 # CASE: col-value logic modifiers
805 if ( $orig_op =~ /^ \- (and|or) $/xi ) {
806 ($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
808 # CASE: special operators like -in or -between
809 elsif ( my $special_op = List::Util::first {$op =~ $_->{regex}} @{$self->{special_ops}} ) {
810 my $handler = $special_op->{handler};
812 puke "No handler supplied for special operator $orig_op";
814 elsif (not ref $handler) {
815 ($sql, @bind) = $self->$handler ($k, $op, $val);
817 elsif (ref $handler eq 'CODE') {
818 ($sql, @bind) = $handler->($self, $k, $op, $val);
821 puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
825 $self->_SWITCH_refkind($val, {
827 ARRAYREF => sub { # CASE: col => {op => \@vals}
828 ($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
831 ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
832 my ($sub_sql, @sub_bind) = @$$val;
833 $self->_assert_bindval_matches_bindtype(@sub_bind);
834 $sql = join ' ', $self->_convert($self->_quote($k)),
835 $self->_sqlcase($op),
840 UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
841 my $is = ($op =~ $self->{equality_op}) ? 'is' :
842 ($op =~ $self->{inequality_op}) ? 'is not' :
843 puke "unexpected operator '$orig_op' with undef operand";
844 $sql = $self->_quote($k) . $self->_sqlcase(" $is null");
847 FALLBACK => sub { # CASE: col => {op/func => $stuff}
849 # retain for proper column type bind
850 $self->{_nested_func_lhs} ||= $k;
852 ($sql, @bind) = $self->_where_unary_op ($op, $val);
855 $self->_convert($self->_quote($k)),
856 $self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
862 ($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
863 push @all_bind, @bind;
865 return ($all_sql, @all_bind);
870 sub _where_field_op_ARRAYREF {
871 my ($self, $k, $op, $vals) = @_;
873 my @vals = @$vals; #always work on a copy
876 $self->_debug(sprintf '%s means multiple elements: [ %s ]',
878 join (', ', map { defined $_ ? "'$_'" : 'NULL' } @vals ),
881 # see if the first element is an -and/-or op
883 if (defined $vals[0] && $vals[0] =~ /^ - ( AND|OR ) $/ix) {
888 # distribute $op over each remaining member of @vals, append logic if exists
889 return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
891 # LDNOTE : had planned to change the distribution logic when
892 # $op =~ $self->{inequality_op}, because of Morgan laws :
893 # with {field => {'!=' => [22, 33]}}, it would be ridiculous to generate
894 # WHERE field != 22 OR field != 33 : the user probably means
895 # WHERE field != 22 AND field != 33.
896 # To do this, replace the above to roughly :
897 # my $logic = ($op =~ $self->{inequality_op}) ? 'AND' : 'OR';
898 # return $self->_recurse_where([map { {$k => {$op, $_}} } @vals], $logic);
902 # try to DWIM on equality operators
903 # LDNOTE : not 100% sure this is the correct thing to do ...
904 return ($self->{sqlfalse}) if $op =~ $self->{equality_op};
905 return ($self->{sqltrue}) if $op =~ $self->{inequality_op};
908 puke "operator '$op' applied on an empty array (field '$k')";
913 sub _where_hashpair_SCALARREF {
914 my ($self, $k, $v) = @_;
915 $self->_debug("SCALAR($k) means literal SQL: $$v");
916 my $sql = $self->_quote($k) . " " . $$v;
920 # literal SQL with bind
921 sub _where_hashpair_ARRAYREFREF {
922 my ($self, $k, $v) = @_;
923 $self->_debug("REF($k) means literal SQL: @${$v}");
924 my ($sql, @bind) = @$$v;
925 $self->_assert_bindval_matches_bindtype(@bind);
926 $sql = $self->_quote($k) . " " . $sql;
927 return ($sql, @bind );
930 # literal SQL without bind
931 sub _where_hashpair_SCALAR {
932 my ($self, $k, $v) = @_;
933 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
934 my $sql = join ' ', $self->_convert($self->_quote($k)),
935 $self->_sqlcase($self->{cmp}),
936 $self->_convert('?');
937 my @bind = $self->_bindtype($k, $v);
938 return ( $sql, @bind);
942 sub _where_hashpair_UNDEF {
943 my ($self, $k, $v) = @_;
944 $self->_debug("UNDEF($k) means IS NULL");
945 my $sql = $self->_quote($k) . $self->_sqlcase(' is null');
949 #======================================================================
950 # WHERE: TOP-LEVEL OTHERS (SCALARREF, SCALAR, UNDEF)
951 #======================================================================
954 sub _where_SCALARREF {
955 my ($self, $where) = @_;
958 $self->_debug("SCALAR(*top) means literal SQL: $$where");
964 my ($self, $where) = @_;
967 $self->_debug("NOREF(*top) means literal SQL: $where");
978 #======================================================================
979 # WHERE: BUILTIN SPECIAL OPERATORS (-in, -between)
980 #======================================================================
983 sub _where_field_BETWEEN {
984 my ($self, $k, $op, $vals) = @_;
986 my ($label, $and, $placeholder);
987 $label = $self->_convert($self->_quote($k));
988 $and = ' ' . $self->_sqlcase('and') . ' ';
989 $placeholder = $self->_convert('?');
990 $op = $self->_sqlcase($op);
992 my ($clause, @bind) = $self->_SWITCH_refkind($vals, {
994 my ($s, @b) = @$$vals;
995 $self->_assert_bindval_matches_bindtype(@b);
1002 puke "special op 'between' accepts an arrayref with exactly two values"
1005 my (@all_sql, @all_bind);
1006 foreach my $val (@$vals) {
1007 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1009 return ($placeholder, $self->_bindtype($k, $val) );
1014 ARRAYREFREF => sub {
1015 my ($sql, @bind) = @$$val;
1016 $self->_assert_bindval_matches_bindtype(@bind);
1017 return ($sql, @bind);
1020 my ($func, $arg, @rest) = %$val;
1021 puke ("Only simple { -func => arg } functions accepted as sub-arguments to BETWEEN")
1022 if (@rest or $func !~ /^ \- (.+)/x);
1023 local $self->{_nested_func_lhs} = $k;
1024 $self->_where_unary_op ($1 => $arg);
1027 push @all_sql, $sql;
1028 push @all_bind, @bind;
1032 (join $and, @all_sql),
1037 puke "special op 'between' accepts an arrayref with two values, or a single literal scalarref/arrayref-ref";
1041 my $sql = "( $label $op $clause )";
1042 return ($sql, @bind)
1046 sub _where_field_IN {
1047 my ($self, $k, $op, $vals) = @_;
1049 # backwards compatibility : if scalar, force into an arrayref
1050 $vals = [$vals] if defined $vals && ! ref $vals;
1052 my ($label) = $self->_convert($self->_quote($k));
1053 my ($placeholder) = $self->_convert('?');
1054 $op = $self->_sqlcase($op);
1056 my ($sql, @bind) = $self->_SWITCH_refkind($vals, {
1057 ARRAYREF => sub { # list of choices
1058 if (@$vals) { # nonempty list
1059 my (@all_sql, @all_bind);
1061 for my $val (@$vals) {
1062 my ($sql, @bind) = $self->_SWITCH_refkind($val, {
1064 return ($placeholder, $val);
1069 ARRAYREFREF => sub {
1070 my ($sql, @bind) = @$$val;
1071 $self->_assert_bindval_matches_bindtype(@bind);
1072 return ($sql, @bind);
1075 my ($func, $arg, @rest) = %$val;
1076 puke ("Only simple { -func => arg } functions accepted as sub-arguments to IN")
1077 if (@rest or $func !~ /^ \- (.+)/x);
1078 local $self->{_nested_func_lhs} = $k;
1079 $self->_where_unary_op ($1 => $arg);
1082 return $self->_sqlcase('null');
1085 push @all_sql, $sql;
1086 push @all_bind, @bind;
1090 sprintf ('%s %s ( %s )',
1093 join (', ', @all_sql)
1095 $self->_bindtype($k, @all_bind),
1098 else { # empty list : some databases won't understand "IN ()", so DWIM
1099 my $sql = ($op =~ /\bnot\b/i) ? $self->{sqltrue} : $self->{sqlfalse};
1104 SCALARREF => sub { # literal SQL
1105 my $sql = $self->_open_outer_paren ($$vals);
1106 return ("$label $op ( $sql )");
1108 ARRAYREFREF => sub { # literal SQL with bind
1109 my ($sql, @bind) = @$$vals;
1110 $self->_assert_bindval_matches_bindtype(@bind);
1111 $sql = $self->_open_outer_paren ($sql);
1112 return ("$label $op ( $sql )", @bind);
1116 puke "special op 'in' requires an arrayref (or scalarref/arrayref-ref)";
1120 return ($sql, @bind);
1123 # Some databases (SQLite) treat col IN (1, 2) different from
1124 # col IN ( (1, 2) ). Use this to strip all outer parens while
1125 # adding them back in the corresponding method
1126 sub _open_outer_paren {
1127 my ($self, $sql) = @_;
1128 $sql = $1 while $sql =~ /^ \s* \( (.*) \) \s* $/xs;
1133 #======================================================================
1135 #======================================================================
1138 my ($self, $arg) = @_;
1141 for my $c ($self->_order_by_chunks ($arg) ) {
1142 $self->_SWITCH_refkind ($c, {
1143 SCALAR => sub { push @sql, $c },
1144 ARRAYREF => sub { push @sql, shift @$c; push @bind, @$c },
1150 $self->_sqlcase(' order by'),
1156 return wantarray ? ($sql, @bind) : $sql;
1159 sub _order_by_chunks {
1160 my ($self, $arg) = @_;
1162 return $self->_SWITCH_refkind($arg, {
1165 map { $self->_order_by_chunks ($_ ) } @$arg;
1168 ARRAYREFREF => sub {
1169 my ($s, @b) = @$$arg;
1170 $self->_assert_bindval_matches_bindtype(@b);
1174 SCALAR => sub {$self->_quote($arg)},
1176 UNDEF => sub {return () },
1178 SCALARREF => sub {$$arg}, # literal SQL, no quoting
1181 # get first pair in hash
1182 my ($key, $val, @rest) = %$arg;
1184 return () unless $key;
1186 if ( @rest or not $key =~ /^-(desc|asc)/i ) {
1187 puke "hash passed to _order_by must have exactly one key (-desc or -asc)";
1193 for my $c ($self->_order_by_chunks ($val)) {
1196 $self->_SWITCH_refkind ($c, {
1201 ($sql, @bind) = @$c;
1205 $sql = $sql . ' ' . $self->_sqlcase($direction);
1207 push @ret, [ $sql, @bind];
1216 #======================================================================
1217 # DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1218 #======================================================================
1224 $self->_SWITCH_refkind($from, {
1226 die "Empty FROM list" unless my @f = @$from;
1228 type => DQ_IDENTIFIER,
1229 elements => [ split /\Q$self->{name_sep}/, shift @f ],
1231 while (my $x = shift @f) {
1235 type => DQ_IDENTIFIER,
1236 elements => [ split /\Q$self->{name_sep}/, $x ],
1244 type => DQ_IDENTIFIER,
1245 elements => [ split /\Q$self->{name_sep}/, $from ],
1260 #======================================================================
1262 #======================================================================
1264 # highly optimized, as it's called way too often
1266 # my ($self, $label) = @_;
1268 return '' unless defined $_[1];
1269 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
1271 unless ($_[0]->{quote_char}) {
1272 $_[0]->_assert_pass_injection_guard($_[1]);
1276 my $qref = ref $_[0]->{quote_char};
1279 ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
1281 elsif ($qref eq 'ARRAY') {
1282 ($l, $r) = @{$_[0]->{quote_char}};
1285 puke "Unsupported quote_char format: $_[0]->{quote_char}";
1288 # parts containing * are naturally unquoted
1289 return join( $_[0]->{name_sep}||'', map
1290 { $_ eq '*' ? $_ : $l . $_ . $r }
1291 ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
1296 # Conversion, if applicable
1298 #my ($self, $arg) = @_;
1300 # LDNOTE : modified the previous implementation below because
1301 # it was not consistent : the first "return" is always an array,
1302 # the second "return" is context-dependent. Anyway, _convert
1303 # seems always used with just a single argument, so make it a
1305 # return @_ unless $self->{convert};
1306 # my $conv = $self->_sqlcase($self->{convert});
1307 # my @ret = map { $conv.'('.$_.')' } @_;
1308 # return wantarray ? @ret : $ret[0];
1309 if ($_[0]->{convert}) {
1310 return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
1317 #my ($self, $col, @vals) = @_;
1319 #LDNOTE : changed original implementation below because it did not make
1320 # sense when bindtype eq 'columns' and @vals > 1.
1321 # return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
1323 # called often - tighten code
1324 return $_[0]->{bindtype} eq 'columns'
1325 ? map {[$_[1], $_]} @_[2 .. $#_]
1330 # Dies if any element of @bind is not in [colname => value] format
1331 # if bindtype is 'columns'.
1332 sub _assert_bindval_matches_bindtype {
1333 # my ($self, @bind) = @_;
1335 if ($self->{bindtype} eq 'columns') {
1337 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
1338 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
1344 sub _join_sql_clauses {
1345 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1347 if (@$clauses_aref > 1) {
1348 my $join = " " . $self->_sqlcase($logic) . " ";
1349 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1350 return ($sql, @$bind_aref);
1352 elsif (@$clauses_aref) {
1353 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1356 return (); # if no SQL, ignore @$bind_aref
1361 # Fix SQL case, if so requested
1363 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1364 # don't touch the argument ... crooked logic, but let's not change it!
1365 return $_[0]->{case} ? $_[1] : uc($_[1]);
1369 #======================================================================
1370 # DISPATCHING FROM REFKIND
1371 #======================================================================
1374 my ($self, $data) = @_;
1376 return 'UNDEF' unless defined $data;
1378 # blessed objects are treated like scalars
1379 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1381 return 'SCALAR' unless $ref;
1384 while ($ref eq 'REF') {
1386 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1390 return ($ref||'SCALAR') . ('REF' x $n_steps);
1394 my ($self, $data) = @_;
1395 my @try = ($self->_refkind($data));
1396 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1397 push @try, 'FALLBACK';
1401 sub _METHOD_FOR_refkind {
1402 my ($self, $meth_prefix, $data) = @_;
1405 for (@{$self->_try_refkind($data)}) {
1406 $method = $self->can($meth_prefix."_".$_)
1410 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
1414 sub _SWITCH_refkind {
1415 my ($self, $data, $dispatch_table) = @_;
1418 for (@{$self->_try_refkind($data)}) {
1419 $coderef = $dispatch_table->{$_}
1423 puke "no dispatch entry for ".$self->_refkind($data)
1432 #======================================================================
1433 # VALUES, GENERATE, AUTOLOAD
1434 #======================================================================
1436 # LDNOTE: original code from nwiger, didn't touch code in that section
1437 # I feel the AUTOLOAD stuff should not be the default, it should
1438 # only be activated on explicit demand by user.
1442 my $data = shift || return;
1443 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1444 unless ref $data eq 'HASH';
1447 foreach my $k ( sort keys %$data ) {
1448 my $v = $data->{$k};
1449 $self->_SWITCH_refkind($v, {
1451 if ($self->{array_datatypes}) { # array datatype
1452 push @all_bind, $self->_bindtype($k, $v);
1454 else { # literal SQL with bind
1455 my ($sql, @bind) = @$v;
1456 $self->_assert_bindval_matches_bindtype(@bind);
1457 push @all_bind, @bind;
1460 ARRAYREFREF => sub { # literal SQL with bind
1461 my ($sql, @bind) = @${$v};
1462 $self->_assert_bindval_matches_bindtype(@bind);
1463 push @all_bind, @bind;
1465 SCALARREF => sub { # literal SQL without bind
1467 SCALAR_or_UNDEF => sub {
1468 push @all_bind, $self->_bindtype($k, $v);
1479 my(@sql, @sqlq, @sqlv);
1483 if ($ref eq 'HASH') {
1484 for my $k (sort keys %$_) {
1487 my $label = $self->_quote($k);
1488 if ($r eq 'ARRAY') {
1489 # literal SQL with bind
1490 my ($sql, @bind) = @$v;
1491 $self->_assert_bindval_matches_bindtype(@bind);
1492 push @sqlq, "$label = $sql";
1494 } elsif ($r eq 'SCALAR') {
1495 # literal SQL without bind
1496 push @sqlq, "$label = $$v";
1498 push @sqlq, "$label = ?";
1499 push @sqlv, $self->_bindtype($k, $v);
1502 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1503 } elsif ($ref eq 'ARRAY') {
1504 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1507 if ($r eq 'ARRAY') { # literal SQL with bind
1508 my ($sql, @bind) = @$v;
1509 $self->_assert_bindval_matches_bindtype(@bind);
1512 } elsif ($r eq 'SCALAR') { # literal SQL without bind
1513 # embedded literal SQL
1520 push @sql, '(' . join(', ', @sqlq) . ')';
1521 } elsif ($ref eq 'SCALAR') {
1525 # strings get case twiddled
1526 push @sql, $self->_sqlcase($_);
1530 my $sql = join ' ', @sql;
1532 # this is pretty tricky
1533 # if ask for an array, return ($stmt, @bind)
1534 # otherwise, s/?/shift @sqlv/ to put it inline
1536 return ($sql, @sqlv);
1538 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1539 ref $d ? $d->[1] : $d/e;
1548 # This allows us to check for a local, then _form, attr
1550 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1551 return $self->generate($name, @_);
1562 SQL::Abstract - Generate SQL from Perl data structures
1568 my $sql = SQL::Abstract->new;
1570 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
1572 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1574 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1576 my($stmt, @bind) = $sql->delete($table, \%where);
1578 # Then, use these in your DBI statements
1579 my $sth = $dbh->prepare($stmt);
1580 $sth->execute(@bind);
1582 # Just generate the WHERE clause
1583 my($stmt, @bind) = $sql->where(\%where, \@order);
1585 # Return values in the same order, for hashed queries
1586 # See PERFORMANCE section for more details
1587 my @bind = $sql->values(\%fieldvals);
1591 This module was inspired by the excellent L<DBIx::Abstract>.
1592 However, in using that module I found that what I really wanted
1593 to do was generate SQL, but still retain complete control over my
1594 statement handles and use the DBI interface. So, I set out to
1595 create an abstract SQL generation module.
1597 While based on the concepts used by L<DBIx::Abstract>, there are
1598 several important differences, especially when it comes to WHERE
1599 clauses. I have modified the concepts used to make the SQL easier
1600 to generate from Perl data structures and, IMO, more intuitive.
1601 The underlying idea is for this module to do what you mean, based
1602 on the data structures you provide it. The big advantage is that
1603 you don't have to modify your code every time your data changes,
1604 as this module figures it out.
1606 To begin with, an SQL INSERT is as easy as just specifying a hash
1607 of C<key=value> pairs:
1610 name => 'Jimbo Bobson',
1611 phone => '123-456-7890',
1612 address => '42 Sister Lane',
1613 city => 'St. Louis',
1614 state => 'Louisiana',
1617 The SQL can then be generated with this:
1619 my($stmt, @bind) = $sql->insert('people', \%data);
1621 Which would give you something like this:
1623 $stmt = "INSERT INTO people
1624 (address, city, name, phone, state)
1625 VALUES (?, ?, ?, ?, ?)";
1626 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1627 '123-456-7890', 'Louisiana');
1629 These are then used directly in your DBI code:
1631 my $sth = $dbh->prepare($stmt);
1632 $sth->execute(@bind);
1634 =head2 Inserting and Updating Arrays
1636 If your database has array types (like for example Postgres),
1637 activate the special option C<< array_datatypes => 1 >>
1638 when creating the C<SQL::Abstract> object.
1639 Then you may use an arrayref to insert and update database array types:
1641 my $sql = SQL::Abstract->new(array_datatypes => 1);
1643 planets => [qw/Mercury Venus Earth Mars/]
1646 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1650 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1652 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1655 =head2 Inserting and Updating SQL
1657 In order to apply SQL functions to elements of your C<%data> you may
1658 specify a reference to an arrayref for the given hash value. For example,
1659 if you need to execute the Oracle C<to_date> function on a value, you can
1660 say something like this:
1664 date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
1667 The first value in the array is the actual SQL. Any other values are
1668 optional and would be included in the bind values array. This gives
1671 my($stmt, @bind) = $sql->insert('people', \%data);
1673 $stmt = "INSERT INTO people (name, date_entered)
1674 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1675 @bind = ('Bill', '03/02/2003');
1677 An UPDATE is just as easy, all you change is the name of the function:
1679 my($stmt, @bind) = $sql->update('people', \%data);
1681 Notice that your C<%data> isn't touched; the module will generate
1682 the appropriately quirky SQL for you automatically. Usually you'll
1683 want to specify a WHERE clause for your UPDATE, though, which is
1684 where handling C<%where> hashes comes in handy...
1686 =head2 Complex where statements
1688 This module can generate pretty complicated WHERE statements
1689 easily. For example, simple C<key=value> pairs are taken to mean
1690 equality, and if you want to see if a field is within a set
1691 of values, you can use an arrayref. Let's say we wanted to
1692 SELECT some data based on this criteria:
1695 requestor => 'inna',
1696 worker => ['nwiger', 'rcwe', 'sfz'],
1697 status => { '!=', 'completed' }
1700 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1702 The above would give you something like this:
1704 $stmt = "SELECT * FROM tickets WHERE
1705 ( requestor = ? ) AND ( status != ? )
1706 AND ( worker = ? OR worker = ? OR worker = ? )";
1707 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1709 Which you could then use in DBI code like so:
1711 my $sth = $dbh->prepare($stmt);
1712 $sth->execute(@bind);
1718 The functions are simple. There's one for each major SQL operation,
1719 and a constructor you use first. The arguments are specified in a
1720 similar order to each function (table, then fields, then a where
1721 clause) to try and simplify things.
1726 =head2 new(option => 'value')
1728 The C<new()> function takes a list of options and values, and returns
1729 a new B<SQL::Abstract> object which can then be used to generate SQL
1730 through the methods below. The options accepted are:
1736 If set to 'lower', then SQL will be generated in all lowercase. By
1737 default SQL is generated in "textbook" case meaning something like:
1739 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1741 Any setting other than 'lower' is ignored.
1745 This determines what the default comparison operator is. By default
1746 it is C<=>, meaning that a hash like this:
1748 %where = (name => 'nwiger', email => 'nate@wiger.org');
1750 Will generate SQL like this:
1752 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1754 However, you may want loose comparisons by default, so if you set
1755 C<cmp> to C<like> you would get SQL such as:
1757 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1759 You can also override the comparsion on an individual basis - see
1760 the huge section on L</"WHERE CLAUSES"> at the bottom.
1762 =item sqltrue, sqlfalse
1764 Expressions for inserting boolean values within SQL statements.
1765 By default these are C<1=1> and C<1=0>. They are used
1766 by the special operators C<-in> and C<-not_in> for generating
1767 correct SQL even when the argument is an empty array (see below).
1771 This determines the default logical operator for multiple WHERE
1772 statements in arrays or hashes. If absent, the default logic is "or"
1773 for arrays, and "and" for hashes. This means that a WHERE
1777 event_date => {'>=', '2/13/99'},
1778 event_date => {'<=', '4/24/03'},
1781 will generate SQL like this:
1783 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1785 This is probably not what you want given this query, though (look
1786 at the dates). To change the "OR" to an "AND", simply specify:
1788 my $sql = SQL::Abstract->new(logic => 'and');
1790 Which will change the above C<WHERE> to:
1792 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1794 The logic can also be changed locally by inserting
1795 a modifier in front of an arrayref :
1797 @where = (-and => [event_date => {'>=', '2/13/99'},
1798 event_date => {'<=', '4/24/03'} ]);
1800 See the L</"WHERE CLAUSES"> section for explanations.
1804 This will automatically convert comparisons using the specified SQL
1805 function for both column and value. This is mostly used with an argument
1806 of C<upper> or C<lower>, so that the SQL will have the effect of
1807 case-insensitive "searches". For example, this:
1809 $sql = SQL::Abstract->new(convert => 'upper');
1810 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1812 Will turn out the following SQL:
1814 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1816 The conversion can be C<upper()>, C<lower()>, or any other SQL function
1817 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1818 not validate this option; it will just pass through what you specify verbatim).
1822 This is a kludge because many databases suck. For example, you can't
1823 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1824 Instead, you have to use C<bind_param()>:
1826 $sth->bind_param(1, 'reg data');
1827 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1829 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1830 which loses track of which field each slot refers to. Fear not.
1832 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1833 Currently, you can specify either C<normal> (default) or C<columns>. If you
1834 specify C<columns>, you will get an array that looks like this:
1836 my $sql = SQL::Abstract->new(bindtype => 'columns');
1837 my($stmt, @bind) = $sql->insert(...);
1840 [ 'column1', 'value1' ],
1841 [ 'column2', 'value2' ],
1842 [ 'column3', 'value3' ],
1845 You can then iterate through this manually, using DBI's C<bind_param()>.
1847 $sth->prepare($stmt);
1850 my($col, $data) = @$_;
1851 if ($col eq 'details' || $col eq 'comments') {
1852 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1853 } elsif ($col eq 'image') {
1854 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1856 $sth->bind_param($i, $data);
1860 $sth->execute; # execute without @bind now
1862 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1863 Basically, the advantage is still that you don't have to care which fields
1864 are or are not included. You could wrap that above C<for> loop in a simple
1865 sub called C<bind_fields()> or something and reuse it repeatedly. You still
1866 get a layer of abstraction over manual SQL specification.
1868 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
1869 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1870 will expect the bind values in this format.
1874 This is the character that a table or column name will be quoted
1875 with. By default this is an empty string, but you could set it to
1876 the character C<`>, to generate SQL like this:
1878 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1880 Alternatively, you can supply an array ref of two items, the first being the left
1881 hand quote character, and the second the right hand quote character. For
1882 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1883 that generates SQL like this:
1885 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1887 Quoting is useful if you have tables or columns names that are reserved
1888 words in your database's SQL dialect.
1892 This is the character that separates a table and column name. It is
1893 necessary to specify this when the C<quote_char> option is selected,
1894 so that tables and column names can be individually quoted like this:
1896 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1898 =item injection_guard
1900 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1901 column name specified in a query structure. This is a safety mechanism to avoid
1902 injection attacks when mishandling user input e.g.:
1904 my %condition_as_column_value_pairs = get_values_from_user();
1905 $sqla->select( ... , \%condition_as_column_value_pairs );
1907 If the expression matches an exception is thrown. Note that literal SQL
1908 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1910 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1912 =item array_datatypes
1914 When this option is true, arrayrefs in INSERT or UPDATE are
1915 interpreted as array datatypes and are passed directly
1917 When this option is false, arrayrefs are interpreted
1918 as literal SQL, just like refs to arrayrefs
1919 (but this behavior is for backwards compatibility; when writing
1920 new queries, use the "reference to arrayref" syntax
1926 Takes a reference to a list of "special operators"
1927 to extend the syntax understood by L<SQL::Abstract>.
1928 See section L</"SPECIAL OPERATORS"> for details.
1932 Takes a reference to a list of "unary operators"
1933 to extend the syntax understood by L<SQL::Abstract>.
1934 See section L</"UNARY OPERATORS"> for details.
1940 =head2 insert($table, \@values || \%fieldvals, \%options)
1942 This is the simplest function. You simply give it a table name
1943 and either an arrayref of values or hashref of field/value pairs.
1944 It returns an SQL INSERT statement and a list of bind values.
1945 See the sections on L</"Inserting and Updating Arrays"> and
1946 L</"Inserting and Updating SQL"> for information on how to insert
1947 with those data types.
1949 The optional C<\%options> hash reference may contain additional
1950 options to generate the insert SQL. Currently supported options
1957 Takes either a scalar of raw SQL fields, or an array reference of
1958 field names, and adds on an SQL C<RETURNING> statement at the end.
1959 This allows you to return data generated by the insert statement
1960 (such as row IDs) without performing another C<SELECT> statement.
1961 Note, however, this is not part of the SQL standard and may not
1962 be supported by all database engines.
1966 =head2 update($table, \%fieldvals, \%where)
1968 This takes a table, hashref of field/value pairs, and an optional
1969 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
1971 See the sections on L</"Inserting and Updating Arrays"> and
1972 L</"Inserting and Updating SQL"> for information on how to insert
1973 with those data types.
1975 =head2 select($source, $fields, $where, $order)
1977 This returns a SQL SELECT statement and associated list of bind values, as
1978 specified by the arguments :
1984 Specification of the 'FROM' part of the statement.
1985 The argument can be either a plain scalar (interpreted as a table
1986 name, will be quoted), or an arrayref (interpreted as a list
1987 of table names, joined by commas, quoted), or a scalarref
1988 (literal table name, not quoted), or a ref to an arrayref
1989 (list of literal table names, joined by commas, not quoted).
1993 Specification of the list of fields to retrieve from
1995 The argument can be either an arrayref (interpreted as a list
1996 of field names, will be joined by commas and quoted), or a
1997 plain scalar (literal SQL, not quoted).
1998 Please observe that this API is not as flexible as for
1999 the first argument C<$table>, for backwards compatibility reasons.
2003 Optional argument to specify the WHERE part of the query.
2004 The argument is most often a hashref, but can also be
2005 an arrayref or plain scalar --
2006 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
2010 Optional argument to specify the ORDER BY part of the query.
2011 The argument can be a scalar, a hashref or an arrayref
2012 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
2018 =head2 delete($table, \%where)
2020 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
2021 It returns an SQL DELETE statement and list of bind values.
2023 =head2 where(\%where, \@order)
2025 This is used to generate just the WHERE clause. For example,
2026 if you have an arbitrary data structure and know what the
2027 rest of your SQL is going to look like, but want an easy way
2028 to produce a WHERE clause, use this. It returns an SQL WHERE
2029 clause and list of bind values.
2032 =head2 values(\%data)
2034 This just returns the values from the hash C<%data>, in the same
2035 order that would be returned from any of the other above queries.
2036 Using this allows you to markedly speed up your queries if you
2037 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2039 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
2041 Warning: This is an experimental method and subject to change.
2043 This returns arbitrarily generated SQL. It's a really basic shortcut.
2044 It will return two different things, depending on return context:
2046 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2047 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2049 These would return the following:
2051 # First calling form
2052 $stmt = "CREATE TABLE test (?, ?)";
2053 @bind = (field1, field2);
2055 # Second calling form
2056 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2058 Depending on what you're trying to do, it's up to you to choose the correct
2059 format. In this example, the second form is what you would want.
2063 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2067 ALTER SESSION SET nls_date_format = 'MM/YY'
2069 You get the idea. Strings get their case twiddled, but everything
2070 else remains verbatim.
2072 =head1 WHERE CLAUSES
2076 This module uses a variation on the idea from L<DBIx::Abstract>. It
2077 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2078 module is that things in arrays are OR'ed, and things in hashes
2081 The easiest way to explain is to show lots of examples. After
2082 each C<%where> hash shown, it is assumed you used:
2084 my($stmt, @bind) = $sql->where(\%where);
2086 However, note that the C<%where> hash can be used directly in any
2087 of the other functions as well, as described above.
2089 =head2 Key-value pairs
2091 So, let's get started. To begin, a simple hash:
2095 status => 'completed'
2098 Is converted to SQL C<key = val> statements:
2100 $stmt = "WHERE user = ? AND status = ?";
2101 @bind = ('nwiger', 'completed');
2103 One common thing I end up doing is having a list of values that
2104 a field can be in. To do this, simply specify a list inside of
2109 status => ['assigned', 'in-progress', 'pending'];
2112 This simple code will create the following:
2114 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2115 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2117 A field associated to an empty arrayref will be considered a
2118 logical false and will generate 0=1.
2120 =head2 Tests for NULL values
2122 If the value part is C<undef> then this is converted to SQL <IS NULL>
2131 $stmt = "WHERE user = ? AND status IS NULL";
2134 To test if a column IS NOT NULL:
2138 status => { '!=', undef },
2141 =head2 Specific comparison operators
2143 If you want to specify a different type of operator for your comparison,
2144 you can use a hashref for a given column:
2148 status => { '!=', 'completed' }
2151 Which would generate:
2153 $stmt = "WHERE user = ? AND status != ?";
2154 @bind = ('nwiger', 'completed');
2156 To test against multiple values, just enclose the values in an arrayref:
2158 status => { '=', ['assigned', 'in-progress', 'pending'] };
2160 Which would give you:
2162 "WHERE status = ? OR status = ? OR status = ?"
2165 The hashref can also contain multiple pairs, in which case it is expanded
2166 into an C<AND> of its elements:
2170 status => { '!=', 'completed', -not_like => 'pending%' }
2173 # Or more dynamically, like from a form
2174 $where{user} = 'nwiger';
2175 $where{status}{'!='} = 'completed';
2176 $where{status}{'-not_like'} = 'pending%';
2178 # Both generate this
2179 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2180 @bind = ('nwiger', 'completed', 'pending%');
2183 To get an OR instead, you can combine it with the arrayref idea:
2187 priority => [ { '=', 2 }, { '>', 5 } ]
2190 Which would generate:
2192 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2193 @bind = ('2', '5', 'nwiger');
2195 If you want to include literal SQL (with or without bind values), just use a
2196 scalar reference or array reference as the value:
2199 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2200 date_expires => { '<' => \"now()" }
2203 Which would generate:
2205 $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
2206 @bind = ('11/26/2008');
2209 =head2 Logic and nesting operators
2211 In the example above,
2212 there is a subtle trap if you want to say something like
2213 this (notice the C<AND>):
2215 WHERE priority != ? AND priority != ?
2217 Because, in Perl you I<can't> do this:
2219 priority => { '!=', 2, '!=', 1 }
2221 As the second C<!=> key will obliterate the first. The solution
2222 is to use the special C<-modifier> form inside an arrayref:
2224 priority => [ -and => {'!=', 2},
2228 Normally, these would be joined by C<OR>, but the modifier tells it
2229 to use C<AND> instead. (Hint: You can use this in conjunction with the
2230 C<logic> option to C<new()> in order to change the way your queries
2231 work by default.) B<Important:> Note that the C<-modifier> goes
2232 B<INSIDE> the arrayref, as an extra first element. This will
2233 B<NOT> do what you think it might:
2235 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2237 Here is a quick list of equivalencies, since there is some overlap:
2240 status => {'!=', 'completed', 'not like', 'pending%' }
2241 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2244 status => {'=', ['assigned', 'in-progress']}
2245 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2246 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2250 =head2 Special operators : IN, BETWEEN, etc.
2252 You can also use the hashref format to compare a list of fields using the
2253 C<IN> comparison operator, by specifying the list as an arrayref:
2256 status => 'completed',
2257 reportid => { -in => [567, 2335, 2] }
2260 Which would generate:
2262 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2263 @bind = ('completed', '567', '2335', '2');
2265 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
2268 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
2269 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
2270 'sqltrue' (by default : C<1=1>).
2272 In addition to the array you can supply a chunk of literal sql or
2273 literal sql with bind:
2276 customer => { -in => \[
2277 'SELECT cust_id FROM cust WHERE balance > ?',
2280 status => { -in => \'SELECT status_codes FROM states' },
2286 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2287 AND status IN ( SELECT status_codes FROM states )
2293 Another pair of operators is C<-between> and C<-not_between>,
2294 used with an arrayref of two values:
2298 completion_date => {
2299 -not_between => ['2002-10-01', '2003-02-06']
2305 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2307 Just like with C<-in> all plausible combinations of literal SQL
2311 start0 => { -between => [ 1, 2 ] },
2312 start1 => { -between => \["? AND ?", 1, 2] },
2313 start2 => { -between => \"lower(x) AND upper(y)" },
2314 start3 => { -between => [
2316 \["upper(?)", 'stuff' ],
2323 ( start0 BETWEEN ? AND ? )
2324 AND ( start1 BETWEEN ? AND ? )
2325 AND ( start2 BETWEEN lower(x) AND upper(y) )
2326 AND ( start3 BETWEEN lower(x) AND upper(?) )
2328 @bind = (1, 2, 1, 2, 'stuff');
2331 These are the two builtin "special operators"; but the
2332 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
2334 =head2 Unary operators: bool
2336 If you wish to test against boolean columns or functions within your
2337 database you can use the C<-bool> and C<-not_bool> operators. For
2338 example to test the column C<is_user> being true and the column
2339 C<is_enabled> being false you would use:-
2343 -not_bool => 'is_enabled',
2348 WHERE is_user AND NOT is_enabled
2350 If a more complex combination is required, testing more conditions,
2351 then you should use the and/or operators:-
2358 -not_bool => 'four',
2364 WHERE one AND two AND three AND NOT four
2367 =head2 Nested conditions, -and/-or prefixes
2369 So far, we've seen how multiple conditions are joined with a top-level
2370 C<AND>. We can change this by putting the different conditions we want in
2371 hashes and then putting those hashes in an array. For example:
2376 status => { -like => ['pending%', 'dispatched'] },
2380 status => 'unassigned',
2384 This data structure would create the following:
2386 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2387 OR ( user = ? AND status = ? ) )";
2388 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2391 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
2392 to change the logic inside :
2398 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2399 -or => { workhrs => {'<', 50}, geo => 'EURO' },
2406 WHERE ( user = ? AND (
2407 ( workhrs > ? AND geo = ? )
2408 OR ( workhrs < ? OR geo = ? )
2411 =head3 Algebraic inconsistency, for historical reasons
2413 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2414 operator goes C<outside> of the nested structure; whereas when connecting
2415 several constraints on one column, the C<-and> operator goes
2416 C<inside> the arrayref. Here is an example combining both features :
2419 -and => [a => 1, b => 2],
2420 -or => [c => 3, d => 4],
2421 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2426 WHERE ( ( ( a = ? AND b = ? )
2427 OR ( c = ? OR d = ? )
2428 OR ( e LIKE ? AND e LIKE ? ) ) )
2430 This difference in syntax is unfortunate but must be preserved for
2431 historical reasons. So be careful : the two examples below would
2432 seem algebraically equivalent, but they are not
2434 {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
2435 # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
2437 [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
2438 # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
2441 =head2 Literal SQL and value type operators
2443 The basic premise of SQL::Abstract is that in WHERE specifications the "left
2444 side" is a column name and the "right side" is a value (normally rendered as
2445 a placeholder). This holds true for both hashrefs and arrayref pairs as you
2446 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2447 alter this behavior. There are several ways of doing so.
2451 This is a virtual operator that signals the string to its right side is an
2452 identifier (a column name) and not a value. For example to compare two
2453 columns you would write:
2456 priority => { '<', 2 },
2457 requestor => { -ident => 'submitter' },
2462 $stmt = "WHERE priority < ? AND requestor = submitter";
2465 If you are maintaining legacy code you may see a different construct as
2466 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2471 This is a virtual operator that signals that the construct to its right side
2472 is a value to be passed to DBI. This is for example necessary when you want
2473 to write a where clause against an array (for RDBMS that support such
2474 datatypes). For example:
2477 array => { -value => [1, 2, 3] }
2482 $stmt = 'WHERE array = ?';
2483 @bind = ([1, 2, 3]);
2485 Note that if you were to simply say:
2491 the result would porbably be not what you wanted:
2493 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2498 Finally, sometimes only literal SQL will do. To include a random snippet
2499 of SQL verbatim, you specify it as a scalar reference. Consider this only
2500 as a last resort. Usually there is a better way. For example:
2503 priority => { '<', 2 },
2504 requestor => { -in => \'(SELECT name FROM hitmen)' },
2509 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2512 Note that in this example, you only get one bind parameter back, since
2513 the verbatim SQL is passed as part of the statement.
2517 Never use untrusted input as a literal SQL argument - this is a massive
2518 security risk (there is no way to check literal snippets for SQL
2519 injections and other nastyness). If you need to deal with untrusted input
2520 use literal SQL with placeholders as described next.
2522 =head3 Literal SQL with placeholders and bind values (subqueries)
2524 If the literal SQL to be inserted has placeholders and bind values,
2525 use a reference to an arrayref (yes this is a double reference --
2526 not so common, but perfectly legal Perl). For example, to find a date
2527 in Postgres you can use something like this:
2530 date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
2535 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
2538 Note that you must pass the bind values in the same format as they are returned
2539 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
2540 provide the bind values in the C<< [ column_meta => value ] >> format, where
2541 C<column_meta> is an opaque scalar value; most commonly the column name, but
2542 you can use any scalar value (including references and blessed references),
2543 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
2544 to C<columns> the above example will look like:
2547 date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
2550 Literal SQL is especially useful for nesting parenthesized clauses in the
2551 main SQL query. Here is a first example :
2553 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2557 bar => \["IN ($sub_stmt)" => @sub_bind],
2562 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
2563 WHERE c2 < ? AND c3 LIKE ?))";
2564 @bind = (1234, 100, "foo%");
2566 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
2567 are expressed in the same way. Of course the C<$sub_stmt> and
2568 its associated bind values can be generated through a former call
2571 my ($sub_stmt, @sub_bind)
2572 = $sql->select("t1", "c1", {c2 => {"<" => 100},
2573 c3 => {-like => "foo%"}});
2576 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2579 In the examples above, the subquery was used as an operator on a column;
2580 but the same principle also applies for a clause within the main C<%where>
2581 hash, like an EXISTS subquery :
2583 my ($sub_stmt, @sub_bind)
2584 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
2585 my %where = ( -and => [
2587 \["EXISTS ($sub_stmt)" => @sub_bind],
2592 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
2593 WHERE c1 = ? AND c2 > t0.c0))";
2597 Observe that the condition on C<c2> in the subquery refers to
2598 column C<t0.c0> of the main query : this is I<not> a bind
2599 value, so we have to express it through a scalar ref.
2600 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2601 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2602 what we wanted here.
2604 Finally, here is an example where a subquery is used
2605 for expressing unary negation:
2607 my ($sub_stmt, @sub_bind)
2608 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2609 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2611 lname => {like => '%son%'},
2612 \["NOT ($sub_stmt)" => @sub_bind],
2617 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2618 @bind = ('%son%', 10, 20)
2620 =head3 Deprecated usage of Literal SQL
2622 Below are some examples of archaic use of literal SQL. It is shown only as
2623 reference for those who deal with legacy code. Each example has a much
2624 better, cleaner and safer alternative that users should opt for in new code.
2630 my %where = ( requestor => \'IS NOT NULL' )
2632 $stmt = "WHERE requestor IS NOT NULL"
2634 This used to be the way of generating NULL comparisons, before the handling
2635 of C<undef> got formalized. For new code please use the superior syntax as
2636 described in L</Tests for NULL values>.
2640 my %where = ( requestor => \'= submitter' )
2642 $stmt = "WHERE requestor = submitter"
2644 This used to be the only way to compare columns. Use the superior L</-ident>
2645 method for all new code. For example an identifier declared in such a way
2646 will be properly quoted if L</quote_char> is properly set, while the legacy
2647 form will remain as supplied.
2651 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2653 $stmt = "WHERE completed > ? AND is_ready"
2654 @bind = ('2012-12-21')
2656 Using an empty string literal used to be the only way to express a boolean.
2657 For all new code please use the much more readable
2658 L<-bool|/Unary operators: bool> operator.
2664 These pages could go on for a while, since the nesting of the data
2665 structures this module can handle are pretty much unlimited (the
2666 module implements the C<WHERE> expansion as a recursive function
2667 internally). Your best bet is to "play around" with the module a
2668 little to see how the data structures behave, and choose the best
2669 format for your data based on that.
2671 And of course, all the values above will probably be replaced with
2672 variables gotten from forms or the command line. After all, if you
2673 knew everything ahead of time, you wouldn't have to worry about
2674 dynamically-generating SQL and could just hardwire it into your
2677 =head1 ORDER BY CLAUSES
2679 Some functions take an order by clause. This can either be a scalar (just a
2680 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
2681 or an array of either of the two previous forms. Examples:
2683 Given | Will Generate
2684 ----------------------------------------------------------
2686 \'colA DESC' | ORDER BY colA DESC
2688 'colA' | ORDER BY colA
2690 [qw/colA colB/] | ORDER BY colA, colB
2692 {-asc => 'colA'} | ORDER BY colA ASC
2694 {-desc => 'colB'} | ORDER BY colB DESC
2696 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2698 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2701 { -asc => 'colA' }, | ORDER BY colA ASC, colB DESC,
2702 { -desc => [qw/colB/], | colC ASC, colD ASC
2703 { -asc => [qw/colC colD/],|
2705 ===========================================================
2709 =head1 SPECIAL OPERATORS
2711 my $sqlmaker = SQL::Abstract->new(special_ops => [
2715 my ($self, $field, $op, $arg) = @_;
2721 handler => 'method_name',
2725 A "special operator" is a SQL syntactic clause that can be
2726 applied to a field, instead of a usual binary operator.
2729 WHERE field IN (?, ?, ?)
2730 WHERE field BETWEEN ? AND ?
2731 WHERE MATCH(field) AGAINST (?, ?)
2733 Special operators IN and BETWEEN are fairly standard and therefore
2734 are builtin within C<SQL::Abstract> (as the overridable methods
2735 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2736 like the MATCH .. AGAINST example above which is specific to MySQL,
2737 you can write your own operator handlers - supply a C<special_ops>
2738 argument to the C<new> method. That argument takes an arrayref of
2739 operator definitions; each operator definition is a hashref with two
2746 the regular expression to match the operator
2750 Either a coderef or a plain scalar method name. In both cases
2751 the expected return is C<< ($sql, @bind) >>.
2753 When supplied with a method name, it is simply called on the
2754 L<SQL::Abstract/> object as:
2756 $self->$method_name ($field, $op, $arg)
2760 $op is the part that matched the handler regex
2761 $field is the LHS of the operator
2764 When supplied with a coderef, it is called as:
2766 $coderef->($self, $field, $op, $arg)
2771 For example, here is an implementation
2772 of the MATCH .. AGAINST syntax for MySQL
2774 my $sqlmaker = SQL::Abstract->new(special_ops => [
2776 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
2777 {regex => qr/^match$/i,
2779 my ($self, $field, $op, $arg) = @_;
2780 $arg = [$arg] if not ref $arg;
2781 my $label = $self->_quote($field);
2782 my ($placeholder) = $self->_convert('?');
2783 my $placeholders = join ", ", (($placeholder) x @$arg);
2784 my $sql = $self->_sqlcase('match') . " ($label) "
2785 . $self->_sqlcase('against') . " ($placeholders) ";
2786 my @bind = $self->_bindtype($field, @$arg);
2787 return ($sql, @bind);
2794 =head1 UNARY OPERATORS
2796 my $sqlmaker = SQL::Abstract->new(unary_ops => [
2800 my ($self, $op, $arg) = @_;
2806 handler => 'method_name',
2810 A "unary operator" is a SQL syntactic clause that can be
2811 applied to a field - the operator goes before the field
2813 You can write your own operator handlers - supply a C<unary_ops>
2814 argument to the C<new> method. That argument takes an arrayref of
2815 operator definitions; each operator definition is a hashref with two
2822 the regular expression to match the operator
2826 Either a coderef or a plain scalar method name. In both cases
2827 the expected return is C<< $sql >>.
2829 When supplied with a method name, it is simply called on the
2830 L<SQL::Abstract/> object as:
2832 $self->$method_name ($op, $arg)
2836 $op is the part that matched the handler regex
2837 $arg is the RHS or argument of the operator
2839 When supplied with a coderef, it is called as:
2841 $coderef->($self, $op, $arg)
2849 Thanks to some benchmarking by Mark Stosberg, it turns out that
2850 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2851 I must admit this wasn't an intentional design issue, but it's a
2852 byproduct of the fact that you get to control your C<DBI> handles
2855 To maximize performance, use a code snippet like the following:
2857 # prepare a statement handle using the first row
2858 # and then reuse it for the rest of the rows
2860 for my $href (@array_of_hashrefs) {
2861 $stmt ||= $sql->insert('table', $href);
2862 $sth ||= $dbh->prepare($stmt);
2863 $sth->execute($sql->values($href));
2866 The reason this works is because the keys in your C<$href> are sorted
2867 internally by B<SQL::Abstract>. Thus, as long as your data retains
2868 the same structure, you only have to generate the SQL the first time
2869 around. On subsequent queries, simply use the C<values> function provided
2870 by this module to return your values in the correct order.
2872 However this depends on the values having the same type - if, for
2873 example, the values of a where clause may either have values
2874 (resulting in sql of the form C<column = ?> with a single bind
2875 value), or alternatively the values might be C<undef> (resulting in
2876 sql of the form C<column IS NULL> with no bind value) then the
2877 caching technique suggested will not work.
2881 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2882 really like this part (I do, at least). Building up a complex query
2883 can be as simple as the following:
2887 use CGI::FormBuilder;
2890 my $form = CGI::FormBuilder->new(...);
2891 my $sql = SQL::Abstract->new;
2893 if ($form->submitted) {
2894 my $field = $form->field;
2895 my $id = delete $field->{id};
2896 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2899 Of course, you would still have to connect using C<DBI> to run the
2900 query, but the point is that if you make your form look like your
2901 table, the actual query script can be extremely simplistic.
2903 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
2904 a fast interface to returning and formatting data. I frequently
2905 use these three modules together to write complex database query
2906 apps in under 50 lines.
2912 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
2914 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
2920 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
2921 Great care has been taken to preserve the I<published> behavior
2922 documented in previous versions in the 1.* family; however,
2923 some features that were previously undocumented, or behaved
2924 differently from the documentation, had to be changed in order
2925 to clarify the semantics. Hence, client code that was relying
2926 on some dark areas of C<SQL::Abstract> v1.*
2927 B<might behave differently> in v1.50.
2929 The main changes are :
2935 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
2939 support for the { operator => \"..." } construct (to embed literal SQL)
2943 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
2947 optional support for L<array datatypes|/"Inserting and Updating Arrays">
2951 defensive programming : check arguments
2955 fixed bug with global logic, which was previously implemented
2956 through global variables yielding side-effects. Prior versions would
2957 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
2958 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
2959 Now this is interpreted
2960 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
2965 fixed semantics of _bindtype on array args
2969 dropped the C<_anoncopy> of the %where tree. No longer necessary,
2970 we just avoid shifting arrays within that tree.
2974 dropped the C<_modlogic> function
2978 =head1 ACKNOWLEDGEMENTS
2980 There are a number of individuals that have really helped out with
2981 this module. Unfortunately, most of them submitted bugs via CPAN
2982 so I have no idea who they are! But the people I do know are:
2984 Ash Berlin (order_by hash term support)
2985 Matt Trout (DBIx::Class support)
2986 Mark Stosberg (benchmarking)
2987 Chas Owens (initial "IN" operator support)
2988 Philip Collins (per-field SQL functions)
2989 Eric Kolve (hashref "AND" support)
2990 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
2991 Dan Kubb (support for "quote_char" and "name_sep")
2992 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
2993 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
2994 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
2995 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
2996 Oliver Charles (support for "RETURNING" after "INSERT")
3002 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
3006 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3008 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
3010 For support, your best bet is to try the C<DBIx::Class> users mailing list.
3011 While not an official support venue, C<DBIx::Class> makes heavy use of
3012 C<SQL::Abstract>, and as such list members there are very familiar with
3013 how to create queries.
3017 This module is free software; you may copy this under the same
3018 terms as perl itself (either the GNU General Public License or
3019 the Artistic License)