5 SQL::Abstract - Generate SQL from Perl data structures
11 my $sql = SQL::Abstract->new;
13 my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order);
15 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
17 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
19 my($stmt, @bind) = $sql->delete($table, \%where);
21 # Then, use these in your DBI statements
22 my $sth = $dbh->prepare($stmt);
25 # Just generate the WHERE clause
26 my($stmt, @bind) = $sql->where(\%where, \@order);
28 # Return values in the same order, for hashed queries
29 # See PERFORMANCE section for more details
30 my @bind = $sql->values(\%fieldvals);
34 This module was inspired by the excellent L<DBIx::Abstract>.
35 However, in using that module I found that what I really wanted
36 to do was generate SQL, but still retain complete control over my
37 statement handles and use the DBI interface. So, I set out to
38 create an abstract SQL generation module.
40 While based on the concepts used by L<DBIx::Abstract>, there are
41 several important differences, especially when it comes to WHERE
42 clauses. I have modified the concepts used to make the SQL easier
43 to generate from Perl data structures and, IMO, more intuitive.
44 The underlying idea is for this module to do what you mean, based
45 on the data structures you provide it. The big advantage is that
46 you don't have to modify your code every time your data changes,
47 as this module figures it out.
49 To begin with, an SQL INSERT is as easy as just specifying a hash
50 of C<key=value> pairs:
53 name => 'Jimbo Bobson',
54 phone => '123-456-7890',
55 address => '42 Sister Lane',
60 The SQL can then be generated with this:
62 my($stmt, @bind) = $sql->insert('people', \%data);
64 Which would give you something like this:
66 $stmt = "INSERT INTO people
67 (address, city, name, phone, state)
68 VALUES (?, ?, ?, ?, ?)";
69 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
70 '123-456-7890', 'Louisiana');
72 These are then used directly in your DBI code:
74 my $sth = $dbh->prepare($stmt);
77 In addition, you can apply SQL functions to elements of your C<%data>
78 by specifying an arrayref for the given hash value. For example, if
79 you need to execute the Oracle C<to_date> function on a value, you
80 can say something like this:
84 date_entered => ["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
87 The first value in the array is the actual SQL. Any other values are
88 optional and would be included in the bind values array. This gives
91 my($stmt, @bind) = $sql->insert('people', \%data);
93 $stmt = "INSERT INTO people (name, date_entered)
94 VALUES (?, to_date(?,'MM/DD/YYYY'))";
95 @bind = ('Bill', '03/02/2003');
97 An UPDATE is just as easy, all you change is the name of the function:
99 my($stmt, @bind) = $sql->update('people', \%data);
101 Notice that your C<%data> isn't touched; the module will generate
102 the appropriately quirky SQL for you automatically. Usually you'll
103 want to specify a WHERE clause for your UPDATE, though, which is
104 where handling C<%where> hashes comes in handy...
106 This module can generate pretty complicated WHERE statements
107 easily. For example, simple C<key=value> pairs are taken to mean
108 equality, and if you want to see if a field is within a set
109 of values, you can use an arrayref. Let's say we wanted to
110 SELECT some data based on this criteria:
114 worker => ['nwiger', 'rcwe', 'sfz'],
115 status => { '!=', 'completed' }
118 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
120 The above would give you something like this:
122 $stmt = "SELECT * FROM tickets WHERE
123 ( requestor = ? ) AND ( status != ? )
124 AND ( worker = ? OR worker = ? OR worker = ? )";
125 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
127 Which you could then use in DBI code like so:
129 my $sth = $dbh->prepare($stmt);
130 $sth->execute(@bind);
136 The functions are simple. There's one for each major SQL operation,
137 and a constructor you use first. The arguments are specified in a
138 similar order to each function (table, then fields, then a where
139 clause) to try and simplify things.
146 our $VERSION = '1.22';
147 our $REVISION = '$Id$';
150 # Fix SQL case, if so requested
153 return $self->{case} ? $_[0] : uc($_[0]);
156 # Anon copies of arrays/hashes
157 # Based on deep_copy example by merlyn
158 # http://www.stonehenge.com/merlyn/UnixReview/col30.html
161 return (ref $orig eq 'HASH') ? +{map { $_ => _anoncopy($orig->{$_}) } keys %$orig}
162 : (ref $orig eq 'ARRAY') ? [map _anoncopy($_), @$orig]
168 return unless $_[0]->{debug}; shift; # a little faster
169 my $func = (caller(1))[3];
170 warn "[$func] ", @_, "\n";
174 my($func) = (caller(1))[3];
175 carp "[$func] Warning: ", @_;
179 my($func) = (caller(1))[3];
180 croak "[$func] Fatal: ", @_;
187 if (ref $from eq 'ARRAY') {
188 return $self->_recurse_from(@$from);
189 } elsif (ref $from eq 'HASH') {
190 return $self->_make_as($from);
192 return $self->_quote($from);
197 my ($self, $from, @join) = @_;
199 push(@sqlf, $self->_make_as($from));
200 foreach my $j (@join) {
201 push @sqlf, ', ' . $self->_quote($j) and next unless ref $j;
202 push @sqlf, ', ' . $$j and next if ref $j eq 'SCALAR';
205 # check whether a join type exists
206 my $join_clause = '';
207 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
208 if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
209 $join_clause = $self->_sqlcase(' '.($to_jt->{-join_type}).' JOIN ');
211 $join_clause = $self->_sqlcase(' JOIN ');
213 push(@sqlf, $join_clause);
215 if (ref $to eq 'ARRAY') {
216 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
218 push(@sqlf, $self->_make_as($to));
220 push(@sqlf, $self->_sqlcase(' ON '), $self->_join_condition($on));
222 return join('', @sqlf);
226 my ($self, $from) = @_;
227 return $self->_quote($from) unless ref $from;
228 return $$from if ref $from eq 'SCALAR';
229 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
230 reverse each %{$self->_skip_options($from)});
234 my ($self, $hash) = @_;
236 $clean_hash->{$_} = $hash->{$_}
237 for grep {!/^-/} keys %$hash;
241 sub _join_condition {
242 my ($self, $cond) = @_;
243 if (ref $cond eq 'HASH') {
246 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
248 return $self->_recurse_where(\%j);
249 } elsif (ref $cond eq 'ARRAY') {
250 return join(' OR ', map { $self->_join_condition($_) } @$cond);
252 die "Can't handle this yet!";
261 return '' unless defined $label;
266 return $$label if ref($label) eq 'SCALAR';
268 return $label unless $self->{quote_char};
270 if (ref $self->{quote_char} eq "ARRAY") {
272 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
273 if !defined $self->{name_sep};
275 my $sep = $self->{name_sep};
276 return join($self->{name_sep},
279 : $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
280 split( /\Q$sep\E/, $label ) );
284 return $self->{quote_char} . $label . $self->{quote_char}
285 if !defined $self->{name_sep};
287 return join $self->{name_sep},
288 map { $_ eq '*' ? $_ : $self->{quote_char} . $_ . $self->{quote_char} }
289 split /\Q$self->{name_sep}\E/, $label;
292 # Conversion, if applicable
295 return @_ unless $self->{convert};
296 my $conv = $self->_sqlcase($self->{convert});
297 my @ret = map { $conv.'('.$_.')' } @_;
298 return wantarray ? @ret : $ret[0];
305 return $self->{bindtype} eq 'columns' ? [ @_ ] : @val;
308 # Modified -logic or -nest
311 my $sym = @_ ? lc(shift) : $self->{logic};
313 $sym = $self->{logic} if $sym eq 'nest';
314 return $self->_sqlcase($sym); # override join
317 =head2 new(option => 'value')
319 The C<new()> function takes a list of options and values, and returns
320 a new B<SQL::Abstract> object which can then be used to generate SQL
321 through the methods below. The options accepted are:
327 If set to 'lower', then SQL will be generated in all lowercase. By
328 default SQL is generated in "textbook" case meaning something like:
330 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
334 This determines what the default comparison operator is. By default
335 it is C<=>, meaning that a hash like this:
337 %where = (name => 'nwiger', email => 'nate@wiger.org');
339 Will generate SQL like this:
341 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
343 However, you may want loose comparisons by default, so if you set
344 C<cmp> to C<like> you would get SQL such as:
346 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
348 You can also override the comparsion on an individual basis - see
349 the huge section on L</"WHERE CLAUSES"> at the bottom.
353 This determines the default logical operator for multiple WHERE
354 statements in arrays. By default it is "or", meaning that a WHERE
358 event_date => {'>=', '2/13/99'},
359 event_date => {'<=', '4/24/03'},
362 Will generate SQL like this:
364 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
366 This is probably not what you want given this query, though (look
367 at the dates). To change the "OR" to an "AND", simply specify:
369 my $sql = SQL::Abstract->new(logic => 'and');
371 Which will change the above C<WHERE> to:
373 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
377 This will automatically convert comparisons using the specified SQL
378 function for both column and value. This is mostly used with an argument
379 of C<upper> or C<lower>, so that the SQL will have the effect of
380 case-insensitive "searches". For example, this:
382 $sql = SQL::Abstract->new(convert => 'upper');
383 %where = (keywords => 'MaKe iT CAse inSeNSItive');
385 Will turn out the following SQL:
387 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
389 The conversion can be C<upper()>, C<lower()>, or any other SQL function
390 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
391 not validate this option; it will just pass through what you specify verbatim).
395 This is a kludge because many databases suck. For example, you can't
396 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
397 Instead, you have to use C<bind_param()>:
399 $sth->bind_param(1, 'reg data');
400 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
402 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
403 which loses track of which field each slot refers to. Fear not.
405 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
406 Currently, you can specify either C<normal> (default) or C<columns>. If you
407 specify C<columns>, you will get an array that looks like this:
409 my $sql = SQL::Abstract->new(bindtype => 'columns');
410 my($stmt, @bind) = $sql->insert(...);
413 [ 'column1', 'value1' ],
414 [ 'column2', 'value2' ],
415 [ 'column3', 'value3' ],
418 You can then iterate through this manually, using DBI's C<bind_param()>.
420 $sth->prepare($stmt);
423 my($col, $data) = @$_;
424 if ($col eq 'details' || $col eq 'comments') {
425 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
426 } elsif ($col eq 'image') {
427 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
429 $sth->bind_param($i, $data);
433 $sth->execute; # execute without @bind now
435 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
436 Basically, the advantage is still that you don't have to care which fields
437 are or are not included. You could wrap that above C<for> loop in a simple
438 sub called C<bind_fields()> or something and reuse it repeatedly. You still
439 get a layer of abstraction over manual SQL specification.
443 This is the character that a table or column name will be quoted
444 with. By default this is an empty string, but you could set it to
445 the character C<`>, to generate SQL like this:
447 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
449 This is useful if you have tables or columns that are reserved words
450 in your database's SQL dialect.
454 This is the character that separates a table and column name. It is
455 necessary to specify this when the C<quote_char> option is selected,
456 so that tables and column names can be individually quoted like this:
458 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
466 my $class = ref($self) || $self;
467 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
469 # choose our case by keeping an option around
470 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
472 # override logical operator
473 $opt{logic} = uc $opt{logic} if $opt{logic};
475 # how to return bind vars
476 $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
478 # default comparison is "=", but can be overridden
481 # default quotation character around tables/columns
482 $opt{quote_char} ||= '';
484 return bless \%opt, $class;
487 =head2 insert($table, \@values || \%fieldvals)
489 This is the simplest function. You simply give it a table name
490 and either an arrayref of values or hashref of field/value pairs.
491 It returns an SQL INSERT statement and a list of bind values.
497 my $table = $self->_table(shift);
498 my $data = shift || return;
500 my $sql = $self->_sqlcase('insert into') . " $table ";
501 my(@sqlf, @sqlv, @sqlq) = ();
504 if ($ref eq 'HASH') {
505 for my $k (sort keys %$data) {
508 # named fields, so must save names in order
509 push @sqlf, $self->_quote($k);
511 # SQL included for values
513 push @sqlq, shift @val;
514 push @sqlv, $self->_bindtype($k, @val);
515 } elsif ($r eq 'SCALAR') {
516 # embedded literal SQL
520 push @sqlv, $self->_bindtype($k, $v);
523 $sql .= '(' . join(', ', @sqlf) .') '. $self->_sqlcase('values') . ' ('. join(', ', @sqlq) .')';
524 } elsif ($ref eq 'ARRAY') {
525 # just generate values(?,?) part
526 # no names (arrayref) so can't generate bindtype
527 carp "Warning: ",__PACKAGE__,"->insert called with arrayref when bindtype set"
528 if $self->{bindtype} ne 'normal';
533 push @sqlq, shift @val;
535 } elsif ($r eq 'SCALAR') {
536 # embedded literal SQL
543 $sql .= $self->_sqlcase('values') . ' ('. join(', ', @sqlq) .')';
544 } elsif ($ref eq 'SCALAR') {
548 puke "Unsupported data type specified to \$sql->insert";
551 return wantarray ? ($sql, @sqlv) : $sql;
554 =head2 update($table, \%fieldvals, \%where)
556 This takes a table, hashref of field/value pairs, and an optional
557 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
564 my $table = $self->_table(shift);
565 my $data = shift || return;
568 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ');
569 my(@sqlf, @sqlv) = ();
571 puke "Unsupported data type specified to \$sql->update"
572 unless ref $data eq 'HASH';
574 for my $k (sort keys %$data) {
577 my $label = $self->_quote($k);
579 # SQL included for values
581 my $sql = shift @bind;
582 push @sqlf, "$label = $sql";
583 push @sqlv, $self->_bindtype($k, @bind);
584 } elsif ($r eq 'SCALAR') {
585 # embedded literal SQL
586 push @sqlf, "$label = $$v";
588 push @sqlf, "$label = ?";
589 push @sqlv, $self->_bindtype($k, $v);
593 $sql .= join ', ', @sqlf;
596 my($wsql, @wval) = $self->where($where);
601 return wantarray ? ($sql, @sqlv) : $sql;
604 =head2 select($table, \@fields, \%where, \@order)
606 This takes a table, arrayref of fields (or '*'), optional hashref
607 L<WHERE clause|/WHERE CLAUSES>, and optional array or hash ref L<ORDER BY clause|/ORDER BY CLAUSES>, and returns the
608 corresponding SQL SELECT statement and list of bind values.
614 my $table = $self->_table(shift);
615 my $fields = shift || '*';
619 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields : $fields;
620 my $sql = join ' ', $self->_sqlcase('select'), $f, $self->_sqlcase('from'), $table;
622 my(@sqlf, @sqlv) = ();
623 my($wsql, @wval) = $self->where($where, $order);
627 return wantarray ? ($sql, @sqlv) : $sql;
630 =head2 delete($table, \%where)
632 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
633 It returns an SQL DELETE statement and list of bind values.
639 my $table = $self->_table(shift);
642 my $sql = $self->_sqlcase('delete from') . " $table";
643 my(@sqlf, @sqlv) = ();
646 my($wsql, @wval) = $self->where($where);
651 return wantarray ? ($sql, @sqlv) : $sql;
654 =head2 where(\%where, \@order)
656 This is used to generate just the WHERE clause. For example,
657 if you have an arbitrary data structure and know what the
658 rest of your SQL is going to look like, but want an easy way
659 to produce a WHERE clause, use this. It returns an SQL WHERE
660 clause and list of bind values.
664 # Finally, a separate routine just to handle WHERE clauses
670 # Need a separate routine to properly wrap w/ "where"
672 my @ret = $self->_recurse_where($where);
675 $sql .= $self->_sqlcase(' where ') . $wh if $wh;
680 $sql .= $self->_order_by($order);
683 return wantarray ? ($sql, @ret) : $sql;
688 local $^W = 0; # really, you've gotta be fucking kidding me
690 my $where = _anoncopy(shift); # prevent destroying original
691 my $ref = ref $where || '';
692 my $join = shift || $self->{logic} ||
693 ($ref eq 'ARRAY' ? $self->_sqlcase('or') : $self->_sqlcase('and'));
695 # For assembling SQL fields and values
696 my(@sqlf, @sqlv) = ();
698 # If an arrayref, then we join each element
699 if ($ref eq 'ARRAY') {
700 # need to use while() so can shift() for arrays
702 while (my $el = shift @$where) {
704 # skip empty elements, otherwise get invalid trailing AND stuff
705 if (my $ref2 = ref $el) {
706 if ($ref2 eq 'ARRAY') {
708 } elsif ($ref2 eq 'HASH') {
710 $subjoin ||= $self->_sqlcase('and');
711 } elsif ($ref2 eq 'SCALAR') {
716 $self->_debug("$ref2(*top) means join with $subjoin");
718 # top-level arrayref with scalars, recurse in pairs
719 $self->_debug("NOREF(*top) means join with $subjoin");
720 $el = {$el => shift(@$where)};
722 my @ret = $self->_recurse_where($el, $subjoin);
723 push @sqlf, shift @ret;
727 elsif ($ref eq 'HASH') {
728 # Note: during recursion, the last element will always be a hashref,
729 # since it needs to point a column => value. So this be the end.
730 for my $k (sort keys %$where) {
731 my $v = $where->{$k};
732 my $label = $self->_quote($k);
734 if ($k =~ /^-(\D+)/) {
735 # special nesting, like -and, -or, -nest, so shift over
736 my $subjoin = $self->_modlogic($1);
737 $self->_debug("OP(-$1) means special logic ($subjoin), recursing...");
738 my @ret = $self->_recurse_where($v, $subjoin);
739 push @sqlf, shift @ret;
741 } elsif (! defined($v)) {
743 $self->_debug("UNDEF($k) means IS NULL");
744 push @sqlf, $label . $self->_sqlcase(' is null');
745 } elsif (ref $v eq 'ARRAY') {
748 # multiple elements: multiple options
749 $self->_debug("ARRAY($k) means multiple elements: [ @v ]");
751 # special nesting, like -and, -or, -nest, so shift over
752 my $subjoin = $self->_sqlcase('or');
753 if ($v[0] =~ /^-(\D+)/) {
754 $subjoin = $self->_modlogic($1); # override subjoin
755 $self->_debug("OP(-$1) means special logic ($subjoin), shifting...");
759 # map into an array of hashrefs and recurse
760 my @ret = $self->_recurse_where([map { {$k => $_} } @v], $subjoin);
762 # push results into our structure
763 push @sqlf, shift @ret;
765 } elsif (ref $v eq 'HASH') {
766 # modified operator { '!=', 'completed' }
767 for my $f (sort keys %$v) {
770 # do the right thing for single -in values
771 $x = [$x] if ($f =~ /^-?\s*(not[\s_]+)?in\s*$/i && ref $x ne 'ARRAY');
773 $self->_debug("HASH($k) means modified operator: { $f }");
775 # check for the operator being "IN" or "BETWEEN" or whatever
776 if (ref $x eq 'ARRAY') {
777 if ($f =~ /^-?\s*(not[\s_]+)?(in|between)\s*$/i) {
778 my $u = $self->_modlogic($1 . $2);
779 $self->_debug("HASH($f => $x) uses special operator: [ $u ]");
780 if ($u =~ /between/i) {
782 # Throw an exception if you try to use between with
783 # anything other than 2 values
784 $self->puke("You need two values to use between") unless @$x == 2;
785 push @sqlf, join ' ', $self->_convert($label), $u, $self->_convert('?'),
786 $self->_sqlcase('and'), $self->_convert('?');
788 # DWIM for empty arrayrefs
789 push @sqlf, join ' ', $self->_convert($label), $u, '(',
790 join(', ', map { $self->_convert('?') } @$x),
793 # Empty IN defaults to 0=1 and empty NOT IN to 1=1
794 push(@sqlf, ($u =~ /not/i ? "1=1" : "0=1"));
796 push @sqlv, $self->_bindtype($k, @$x);
798 # multiple elements: multiple options
799 $self->_debug("ARRAY($x) means multiple elements: [ @$x ]");
801 # map into an array of hashrefs and recurse
802 my @ret = $self->_recurse_where([map { {$k => {$f, $_}} } @$x]);
804 # push results into our structure
805 push @sqlf, shift @ret;
808 } elsif (! defined($x)) {
810 my $not = ($f eq '!=' || $f eq 'not like') ? ' not' : '';
811 push @sqlf, $label . $self->_sqlcase(" is$not null");
814 $f =~ s/^-//; # strip leading -like =>
815 $f =~ s/_/ /; # _ => " "
816 push @sqlf, join ' ', $self->_convert($label), $self->_sqlcase($f), $self->_convert('?');
817 push @sqlv, $self->_bindtype($k, $x);
820 } elsif (ref $v eq 'SCALAR') {
822 $self->_debug("SCALAR($k) means literal SQL: $$v");
823 push @sqlf, "$label $$v";
825 # standard key => val
826 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
827 push @sqlf, join ' ', $self->_convert($label), $self->_sqlcase($self->{cmp}), $self->_convert('?');
828 push @sqlv, $self->_bindtype($k, $v);
832 elsif ($ref eq 'SCALAR') {
834 $self->_debug("SCALAR(*top) means literal SQL: $$where");
837 elsif (defined $where) {
839 $self->_debug("NOREF(*top) means literal SQL: $where");
843 # assemble and return sql
844 my $wsql = @sqlf ? '( ' . join(" $join ", @sqlf) . ' )' : '';
845 return wantarray ? ($wsql, @sqlv) : $wsql;
850 my $ref = ref $_[0] || '';
852 my $_order_hash = sub {
853 local *__ANON__ = '_order_by_hash';
855 if ( $col = $_->{-desc} ) {
857 } elsif ( $col = $_->{-asc} ) {
860 puke "Hash must have a key of '-desc' or '-asc' for ORDER BY";
862 return $self->_quote($col) . " $order";
867 if ($ref eq 'ARRAY') {
868 foreach (@{ $_[0] }) {
870 if (!$ref || $ref eq 'SCALAR') {
871 push @vals, $self->_quote($_);
872 } elsif ($ref eq 'HASH') {
873 push @vals, $_order_hash->($_);
875 puke "Unsupported nested data struct $ref for ORDER BY";
878 } elsif ($ref eq 'HASH') {
879 push @vals, $_order_hash->($_[0]);
880 } elsif (!$ref || $ref eq 'SCALAR') {
881 push @vals, $self->_quote($_[0]);
883 puke "Unsupported data struct $ref for ORDER BY";
886 my $val = join ', ', @vals;
887 return $val ? $self->_sqlcase(' order by')." $val" : '';
890 =head2 values(\%data)
892 This just returns the values from the hash C<%data>, in the same
893 order that would be returned from any of the other above queries.
894 Using this allows you to markedly speed up your queries if you
895 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
901 my $data = shift || return;
902 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
903 unless ref $data eq 'HASH';
904 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
907 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
909 Warning: This is an experimental method and subject to change.
911 This returns arbitrarily generated SQL. It's a really basic shortcut.
912 It will return two different things, depending on return context:
914 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
915 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
917 These would return the following:
920 $stmt = "CREATE TABLE test (?, ?)";
921 @bind = (field1, field2);
923 # Second calling form
924 $stmt_and_val = "CREATE TABLE test (field1, field2)";
926 Depending on what you're trying to do, it's up to you to choose the correct
927 format. In this example, the second form is what you would want.
931 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
935 ALTER SESSION SET nls_date_format = 'MM/YY'
937 You get the idea. Strings get their case twiddled, but everything
938 else remains verbatim.
945 my(@sql, @sqlq, @sqlv);
949 if ($ref eq 'HASH') {
950 for my $k (sort keys %$_) {
953 my $label = $self->_quote($k);
955 # SQL included for values
957 my $sql = shift @bind;
958 push @sqlq, "$label = $sql";
959 push @sqlv, $self->_bindtype($k, @bind);
960 } elsif ($r eq 'SCALAR') {
961 # embedded literal SQL
962 push @sqlq, "$label = $$v";
964 push @sqlq, "$label = ?";
965 push @sqlv, $self->_bindtype($k, $v);
968 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
969 } elsif ($ref eq 'ARRAY') {
970 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
975 push @sqlq, shift @val;
977 } elsif ($r eq 'SCALAR') {
978 # embedded literal SQL
985 push @sql, '(' . join(', ', @sqlq) . ')';
986 } elsif ($ref eq 'SCALAR') {
990 # strings get case twiddled
991 push @sql, $self->_sqlcase($_);
995 my $sql = join ' ', @sql;
997 # this is pretty tricky
998 # if ask for an array, return ($stmt, @bind)
999 # otherwise, s/?/shift @sqlv/ to put it inline
1001 return ($sql, @sqlv);
1003 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1004 ref $d ? $d->[1] : $d/e;
1011 # This allows us to check for a local, then _form, attr
1013 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1014 return $self->generate($name, @_);
1021 =head1 WHERE CLAUSES
1023 This module uses a variation on the idea from L<DBIx::Abstract>. It
1024 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1025 module is that things in arrays are OR'ed, and things in hashes
1028 The easiest way to explain is to show lots of examples. After
1029 each C<%where> hash shown, it is assumed you used:
1031 my($stmt, @bind) = $sql->where(\%where);
1033 However, note that the C<%where> hash can be used directly in any
1034 of the other functions as well, as described above.
1036 So, let's get started. To begin, a simple hash:
1040 status => 'completed'
1043 Is converted to SQL C<key = val> statements:
1045 $stmt = "WHERE user = ? AND status = ?";
1046 @bind = ('nwiger', 'completed');
1048 One common thing I end up doing is having a list of values that
1049 a field can be in. To do this, simply specify a list inside of
1054 status => ['assigned', 'in-progress', 'pending'];
1057 This simple code will create the following:
1059 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1060 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1062 If you want to specify a different type of operator for your comparison,
1063 you can use a hashref for a given column:
1067 status => { '!=', 'completed' }
1070 Which would generate:
1072 $stmt = "WHERE user = ? AND status != ?";
1073 @bind = ('nwiger', 'completed');
1075 To test against multiple values, just enclose the values in an arrayref:
1077 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1079 Which would give you:
1081 "WHERE status != ? OR status != ? OR status != ?"
1083 But, this is probably not what you want in this case (look at it). So
1084 the hashref can also contain multiple pairs, in which case it is expanded
1085 into an C<AND> of its elements:
1089 status => { '!=', 'completed', -not_like => 'pending%' }
1092 # Or more dynamically, like from a form
1093 $where{user} = 'nwiger';
1094 $where{status}{'!='} = 'completed';
1095 $where{status}{'-not_like'} = 'pending%';
1097 # Both generate this
1098 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1099 @bind = ('nwiger', 'completed', 'pending%');
1101 To get an OR instead, you can combine it with the arrayref idea:
1105 priority => [ {'=', 2}, {'!=', 1} ]
1108 Which would generate:
1110 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1111 @bind = ('nwiger', '2', '1');
1113 However, there is a subtle trap if you want to say something like
1114 this (notice the C<AND>):
1116 WHERE priority != ? AND priority != ?
1118 Because, in Perl you I<can't> do this:
1120 priority => { '!=', 2, '!=', 1 }
1122 As the second C<!=> key will obliterate the first. The solution
1123 is to use the special C<-modifier> form inside an arrayref:
1125 priority => [ -and => {'!=', 2}, {'!=', 1} ]
1127 Normally, these would be joined by C<OR>, but the modifier tells it
1128 to use C<AND> instead. (Hint: You can use this in conjunction with the
1129 C<logic> option to C<new()> in order to change the way your queries
1130 work by default.) B<Important:> Note that the C<-modifier> goes
1131 B<INSIDE> the arrayref, as an extra first element. This will
1132 B<NOT> do what you think it might:
1134 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1136 Here is a quick list of equivalencies, since there is some overlap:
1139 status => {'!=', 'completed', 'not like', 'pending%' }
1140 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1143 status => {'=', ['assigned', 'in-progress']}
1144 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1145 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1147 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1148 operator which adds an additional set of parens, to create a subquery.
1149 For example, to get something like this:
1151 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1152 @bind = ('nwiger', '20', 'ASIA');
1158 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1161 You can also use the hashref format to compare a list of fields using the
1162 C<IN> comparison operator, by specifying the list as an arrayref:
1165 status => 'completed',
1166 reportid => { -in => [567, 2335, 2] }
1169 Which would generate:
1171 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1172 @bind = ('completed', '567', '2335', '2');
1174 You can use this same format to use other grouping functions, such
1175 as C<BETWEEN>, C<SOME>, and so forth. For example:
1179 completion_date => {
1180 -not_between => ['2002-10-01', '2003-02-06']
1186 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1188 So far, we've seen how multiple conditions are joined with a top-level
1189 C<AND>. We can change this by putting the different conditions we want in
1190 hashes and then putting those hashes in an array. For example:
1195 status => { -like => ['pending%', 'dispatched'] },
1199 status => 'unassigned',
1203 This data structure would create the following:
1205 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1206 OR ( user = ? AND status = ? ) )";
1207 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1209 This can be combined with the C<-nest> operator to properly group
1216 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
1217 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
1224 WHERE ( user = ? AND
1225 ( ( workhrs > ? AND geo = ? )
1226 OR ( workhrs < ? AND geo = ? ) ) )
1228 Finally, sometimes only literal SQL will do. If you want to include
1229 literal SQL verbatim, you can specify it as a scalar reference, namely:
1231 my $inn = 'is Not Null';
1233 priority => { '<', 2 },
1239 $stmt = "WHERE priority < ? AND requestor is Not Null";
1242 Note that in this example, you only get one bind parameter back, since
1243 the verbatim SQL is passed as part of the statement.
1245 Of course, just to prove a point, the above can also be accomplished
1249 priority => { '<', 2 },
1250 requestor => { '!=', undef },
1255 These pages could go on for a while, since the nesting of the data
1256 structures this module can handle are pretty much unlimited (the
1257 module implements the C<WHERE> expansion as a recursive function
1258 internally). Your best bet is to "play around" with the module a
1259 little to see how the data structures behave, and choose the best
1260 format for your data based on that.
1262 And of course, all the values above will probably be replaced with
1263 variables gotten from forms or the command line. After all, if you
1264 knew everything ahead of time, you wouldn't have to worry about
1265 dynamically-generating SQL and could just hardwire it into your
1268 =head1 ORDER BY CLAUSES
1270 Some functions take an order by clause. This can either be a scalar (just a
1271 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1272 or an array of either of the two previous forms.
1276 Thanks to some benchmarking by Mark Stosberg, it turns out that
1277 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
1278 I must admit this wasn't an intentional design issue, but it's a
1279 byproduct of the fact that you get to control your C<DBI> handles
1282 To maximize performance, use a code snippet like the following:
1284 # prepare a statement handle using the first row
1285 # and then reuse it for the rest of the rows
1287 for my $href (@array_of_hashrefs) {
1288 $stmt ||= $sql->insert('table', $href);
1289 $sth ||= $dbh->prepare($stmt);
1290 $sth->execute($sql->values($href));
1293 The reason this works is because the keys in your C<$href> are sorted
1294 internally by B<SQL::Abstract>. Thus, as long as your data retains
1295 the same structure, you only have to generate the SQL the first time
1296 around. On subsequent queries, simply use the C<values> function provided
1297 by this module to return your values in the correct order.
1301 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
1302 really like this part (I do, at least). Building up a complex query
1303 can be as simple as the following:
1307 use CGI::FormBuilder;
1310 my $form = CGI::FormBuilder->new(...);
1311 my $sql = SQL::Abstract->new;
1313 if ($form->submitted) {
1314 my $field = $form->field;
1315 my $id = delete $field->{id};
1316 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
1319 Of course, you would still have to connect using C<DBI> to run the
1320 query, but the point is that if you make your form look like your
1321 table, the actual query script can be extremely simplistic.
1323 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
1324 a fast interface to returning and formatting data. I frequently
1325 use these three modules together to write complex database query
1326 apps in under 50 lines.
1330 There is not (yet) any explicit support for SQL compound logic
1331 statements like "AND NOT". Instead, just do the de Morgan's
1332 law transformations yourself. For example, this:
1334 "lname LIKE '%son%' AND NOT ( age < 10 OR age > 20 )"
1338 "lname LIKE '%son%' AND ( age >= 10 AND age <= 20 )"
1340 With the corresponding C<%where> hash:
1343 lname => {like => '%son%'},
1344 age => [-and => {'>=', 10}, {'<=', 20}],
1347 Again, remember that the C<-and> goes I<inside> the arrayref.
1349 =head1 ACKNOWLEDGEMENTS
1351 There are a number of individuals that have really helped out with
1352 this module. Unfortunately, most of them submitted bugs via CPAN
1353 so I have no idea who they are! But the people I do know are:
1355 Ash Berlin (order_by hash term support)
1356 Matt Trout (DBIx::Class support)
1357 Mark Stosberg (benchmarking)
1358 Chas Owens (initial "IN" operator support)
1359 Philip Collins (per-field SQL functions)
1360 Eric Kolve (hashref "AND" support)
1361 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
1362 Dan Kubb (support for "quote_char" and "name_sep")
1363 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN")
1369 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
1373 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
1375 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
1377 For support, your best bet is to try the C<DBIx::Class> users mailing list.
1378 While not an official support venue, C<DBIx::Class> makes heavy use of
1379 C<SQL::Abstract>, and as such list members there are very familiar with
1380 how to create queries.
1382 This module is free software; you may copy this under the terms of
1383 the GNU General Public License, or the Artistic License, copies of
1384 which should have accompanied your Perl kit.