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.23';
147 #XXX don't understand this below, leaving it for someone else. did bump the $VERSION --groditi
148 our $REVISION = '$Id$';
151 # Fix SQL case, if so requested
154 return $self->{case} ? $_[0] : uc($_[0]);
157 # Anon copies of arrays/hashes
158 # Based on deep_copy example by merlyn
159 # http://www.stonehenge.com/merlyn/UnixReview/col30.html
162 return (ref $orig eq 'HASH') ? +{map { $_ => _anoncopy($orig->{$_}) } keys %$orig}
163 : (ref $orig eq 'ARRAY') ? [map _anoncopy($_), @$orig]
169 return unless $_[0]->{debug}; shift; # a little faster
170 my $func = (caller(1))[3];
171 warn "[$func] ", @_, "\n";
175 my($func) = (caller(1))[3];
176 carp "[$func] Warning: ", @_;
180 my($func) = (caller(1))[3];
181 croak "[$func] Fatal: ", @_;
188 if (ref $from eq 'ARRAY') {
189 return $self->_recurse_from(@$from);
190 } elsif (ref $from eq 'HASH') {
191 return $self->_make_as($from);
193 return $self->_quote($from);
198 my ($self, $from, @join) = @_;
200 push(@sqlf, $self->_make_as($from));
201 foreach my $j (@join) {
202 push @sqlf, ', ' . $self->_quote($j) and next unless ref $j;
203 push @sqlf, ', ' . $$j and next if ref $j eq 'SCALAR';
206 # check whether a join type exists
207 my $join_clause = '';
208 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
209 if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
210 $join_clause = $self->_sqlcase(' '.($to_jt->{-join_type}).' JOIN ');
212 $join_clause = $self->_sqlcase(' JOIN ');
214 push(@sqlf, $join_clause);
216 if (ref $to eq 'ARRAY') {
217 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
219 push(@sqlf, $self->_make_as($to));
221 push(@sqlf, $self->_sqlcase(' ON '), $self->_join_condition($on));
223 return join('', @sqlf);
227 my ($self, $from) = @_;
228 return $self->_quote($from) unless ref $from;
229 return $$from if ref $from eq 'SCALAR';
230 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_ : $self->_quote($_)) }
231 reverse each %{$self->_skip_options($from)});
235 my ($self, $hash) = @_;
237 $clean_hash->{$_} = $hash->{$_}
238 for grep {!/^-/} keys %$hash;
242 sub _join_condition {
243 my ($self, $cond) = @_;
244 if (ref $cond eq 'HASH') {
247 my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x;
249 return $self->_recurse_where(\%j);
250 } elsif (ref $cond eq 'ARRAY') {
251 return join(' OR ', map { $self->_join_condition($_) } @$cond);
253 die "Can't handle this yet!";
262 return '' unless defined $label;
267 return $$label if ref($label) eq 'SCALAR';
269 return $label unless $self->{quote_char};
271 if (ref $self->{quote_char} eq "ARRAY") {
273 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
274 if !defined $self->{name_sep};
276 my $sep = $self->{name_sep};
277 return join($self->{name_sep},
280 : $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
281 split( /\Q$sep\E/, $label ) );
285 return $self->{quote_char} . $label . $self->{quote_char}
286 if !defined $self->{name_sep};
288 return join $self->{name_sep},
289 map { $_ eq '*' ? $_ : $self->{quote_char} . $_ . $self->{quote_char} }
290 split /\Q$self->{name_sep}\E/, $label;
293 # Conversion, if applicable
296 return @_ unless $self->{convert};
297 my $conv = $self->_sqlcase($self->{convert});
298 my @ret = map { $conv.'('.$_.')' } @_;
299 return wantarray ? @ret : $ret[0];
306 return $self->{bindtype} eq 'columns' ? [ @_ ] : @val;
309 # Modified -logic or -nest
312 my $sym = @_ ? lc(shift) : $self->{logic};
314 $sym = $self->{logic} if $sym eq 'nest';
315 return $self->_sqlcase($sym); # override join
318 =head2 new(option => 'value')
320 The C<new()> function takes a list of options and values, and returns
321 a new B<SQL::Abstract> object which can then be used to generate SQL
322 through the methods below. The options accepted are:
328 If set to 'lower', then SQL will be generated in all lowercase. By
329 default SQL is generated in "textbook" case meaning something like:
331 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
335 This determines what the default comparison operator is. By default
336 it is C<=>, meaning that a hash like this:
338 %where = (name => 'nwiger', email => 'nate@wiger.org');
340 Will generate SQL like this:
342 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
344 However, you may want loose comparisons by default, so if you set
345 C<cmp> to C<like> you would get SQL such as:
347 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
349 You can also override the comparsion on an individual basis - see
350 the huge section on L</"WHERE CLAUSES"> at the bottom.
354 This determines the default logical operator for multiple WHERE
355 statements in arrays. By default it is "or", meaning that a WHERE
359 event_date => {'>=', '2/13/99'},
360 event_date => {'<=', '4/24/03'},
363 Will generate SQL like this:
365 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
367 This is probably not what you want given this query, though (look
368 at the dates). To change the "OR" to an "AND", simply specify:
370 my $sql = SQL::Abstract->new(logic => 'and');
372 Which will change the above C<WHERE> to:
374 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
378 This will automatically convert comparisons using the specified SQL
379 function for both column and value. This is mostly used with an argument
380 of C<upper> or C<lower>, so that the SQL will have the effect of
381 case-insensitive "searches". For example, this:
383 $sql = SQL::Abstract->new(convert => 'upper');
384 %where = (keywords => 'MaKe iT CAse inSeNSItive');
386 Will turn out the following SQL:
388 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
390 The conversion can be C<upper()>, C<lower()>, or any other SQL function
391 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
392 not validate this option; it will just pass through what you specify verbatim).
396 This is a kludge because many databases suck. For example, you can't
397 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
398 Instead, you have to use C<bind_param()>:
400 $sth->bind_param(1, 'reg data');
401 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
403 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
404 which loses track of which field each slot refers to. Fear not.
406 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
407 Currently, you can specify either C<normal> (default) or C<columns>. If you
408 specify C<columns>, you will get an array that looks like this:
410 my $sql = SQL::Abstract->new(bindtype => 'columns');
411 my($stmt, @bind) = $sql->insert(...);
414 [ 'column1', 'value1' ],
415 [ 'column2', 'value2' ],
416 [ 'column3', 'value3' ],
419 You can then iterate through this manually, using DBI's C<bind_param()>.
421 $sth->prepare($stmt);
424 my($col, $data) = @$_;
425 if ($col eq 'details' || $col eq 'comments') {
426 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
427 } elsif ($col eq 'image') {
428 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
430 $sth->bind_param($i, $data);
434 $sth->execute; # execute without @bind now
436 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
437 Basically, the advantage is still that you don't have to care which fields
438 are or are not included. You could wrap that above C<for> loop in a simple
439 sub called C<bind_fields()> or something and reuse it repeatedly. You still
440 get a layer of abstraction over manual SQL specification.
444 This is the character that a table or column name will be quoted
445 with. By default this is an empty string, but you could set it to
446 the character C<`>, to generate SQL like this:
448 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
450 This is useful if you have tables or columns that are reserved words
451 in your database's SQL dialect.
455 This is the character that separates a table and column name. It is
456 necessary to specify this when the C<quote_char> option is selected,
457 so that tables and column names can be individually quoted like this:
459 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
467 my $class = ref($self) || $self;
468 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
470 # choose our case by keeping an option around
471 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
473 # override logical operator
474 $opt{logic} = uc $opt{logic} if $opt{logic};
476 # how to return bind vars
477 $opt{bindtype} ||= delete($opt{bind_type}) || 'normal';
479 # default comparison is "=", but can be overridden
482 # default quotation character around tables/columns
483 $opt{quote_char} ||= '';
485 return bless \%opt, $class;
488 =head2 insert($table, \@values || \%fieldvals)
490 This is the simplest function. You simply give it a table name
491 and either an arrayref of values or hashref of field/value pairs.
492 It returns an SQL INSERT statement and a list of bind values.
498 my $table = $self->_table(shift);
499 my $data = shift || return;
501 my $sql = $self->_sqlcase('insert into') . " $table ";
502 my(@sqlf, @sqlv, @sqlq) = ();
505 if ($ref eq 'HASH') {
506 for my $k (sort keys %$data) {
509 # named fields, so must save names in order
510 push @sqlf, $self->_quote($k);
512 # SQL included for values
514 push @sqlq, shift @val;
515 push @sqlv, $self->_bindtype($k, @val);
516 } elsif ($r eq 'SCALAR') {
517 # embedded literal SQL
521 push @sqlv, $self->_bindtype($k, $v);
524 $sql .= '(' . join(', ', @sqlf) .') '. $self->_sqlcase('values') . ' ('. join(', ', @sqlq) .')';
525 } elsif ($ref eq 'ARRAY') {
526 # just generate values(?,?) part
527 # no names (arrayref) so can't generate bindtype
528 carp "Warning: ",__PACKAGE__,"->insert called with arrayref when bindtype set"
529 if $self->{bindtype} ne 'normal';
534 push @sqlq, shift @val;
536 } elsif ($r eq 'SCALAR') {
537 # embedded literal SQL
544 $sql .= $self->_sqlcase('values') . ' ('. join(', ', @sqlq) .')';
545 } elsif ($ref eq 'SCALAR') {
549 puke "Unsupported data type specified to \$sql->insert";
552 return wantarray ? ($sql, @sqlv) : $sql;
555 =head2 update($table, \%fieldvals, \%where)
557 This takes a table, hashref of field/value pairs, and an optional
558 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
565 my $table = $self->_table(shift);
566 my $data = shift || return;
569 my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set ');
570 my(@sqlf, @sqlv) = ();
572 puke "Unsupported data type specified to \$sql->update"
573 unless ref $data eq 'HASH';
575 for my $k (sort keys %$data) {
578 my $label = $self->_quote($k);
580 # SQL included for values
582 my $sql = shift @bind;
583 push @sqlf, "$label = $sql";
584 push @sqlv, $self->_bindtype($k, @bind);
585 } elsif ($r eq 'SCALAR') {
586 # embedded literal SQL
587 push @sqlf, "$label = $$v";
589 push @sqlf, "$label = ?";
590 push @sqlv, $self->_bindtype($k, $v);
594 $sql .= join ', ', @sqlf;
597 my($wsql, @wval) = $self->where($where);
602 return wantarray ? ($sql, @sqlv) : $sql;
605 =head2 select($table, \@fields, \%where, \@order)
607 This takes a table, arrayref of fields (or '*'), optional hashref
608 L<WHERE clause|/WHERE CLAUSES>, and optional array or hash ref L<ORDER BY clause|/ORDER BY CLAUSES>, and returns the
609 corresponding SQL SELECT statement and list of bind values.
615 my $table = $self->_table(shift);
616 my $fields = shift || '*';
620 my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields : $fields;
621 my $sql = join ' ', $self->_sqlcase('select'), $f, $self->_sqlcase('from'), $table;
623 my(@sqlf, @sqlv) = ();
624 my($wsql, @wval) = $self->where($where, $order);
628 return wantarray ? ($sql, @sqlv) : $sql;
631 =head2 delete($table, \%where)
633 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
634 It returns an SQL DELETE statement and list of bind values.
640 my $table = $self->_table(shift);
643 my $sql = $self->_sqlcase('delete from') . " $table";
644 my(@sqlf, @sqlv) = ();
647 my($wsql, @wval) = $self->where($where);
652 return wantarray ? ($sql, @sqlv) : $sql;
655 =head2 where(\%where, \@order)
657 This is used to generate just the WHERE clause. For example,
658 if you have an arbitrary data structure and know what the
659 rest of your SQL is going to look like, but want an easy way
660 to produce a WHERE clause, use this. It returns an SQL WHERE
661 clause and list of bind values.
665 # Finally, a separate routine just to handle WHERE clauses
671 # Need a separate routine to properly wrap w/ "where"
673 my @ret = $self->_recurse_where($where);
676 $sql .= $self->_sqlcase(' where ') . $wh if $wh;
681 $sql .= $self->_order_by($order);
684 return wantarray ? ($sql, @ret) : $sql;
689 local $^W = 0; # really, you've gotta be fucking kidding me
691 my $where = _anoncopy(shift); # prevent destroying original
692 my $ref = ref $where || '';
693 my $join = shift || $self->{logic} ||
694 ($ref eq 'ARRAY' ? $self->_sqlcase('or') : $self->_sqlcase('and'));
696 # For assembling SQL fields and values
697 my(@sqlf, @sqlv) = ();
699 # If an arrayref, then we join each element
700 if ($ref eq 'ARRAY') {
701 # need to use while() so can shift() for arrays
703 while (my $el = shift @$where) {
705 # skip empty elements, otherwise get invalid trailing AND stuff
706 if (my $ref2 = ref $el) {
707 if ($ref2 eq 'ARRAY') {
709 } elsif ($ref2 eq 'HASH') {
711 $subjoin ||= $self->_sqlcase('and');
712 } elsif ($ref2 eq 'SCALAR') {
717 $self->_debug("$ref2(*top) means join with $subjoin");
719 # top-level arrayref with scalars, recurse in pairs
720 $self->_debug("NOREF(*top) means join with $subjoin");
721 $el = {$el => shift(@$where)};
723 my @ret = $self->_recurse_where($el, $subjoin);
724 push @sqlf, shift @ret;
728 elsif ($ref eq 'HASH') {
729 # Note: during recursion, the last element will always be a hashref,
730 # since it needs to point a column => value. So this be the end.
731 for my $k (sort keys %$where) {
732 my $v = $where->{$k};
733 my $label = $self->_quote($k);
735 if ($k =~ /^-(\D+)/) {
736 # special nesting, like -and, -or, -nest, so shift over
737 my $subjoin = $self->_modlogic($1);
738 $self->_debug("OP(-$1) means special logic ($subjoin), recursing...");
739 my @ret = $self->_recurse_where($v, $subjoin);
740 push @sqlf, shift @ret;
742 } elsif (! defined($v)) {
744 $self->_debug("UNDEF($k) means IS NULL");
745 push @sqlf, $label . $self->_sqlcase(' is null');
746 } elsif (ref $v eq 'ARRAY') {
749 # multiple elements: multiple options
750 $self->_debug("ARRAY($k) means multiple elements: [ @v ]");
752 # special nesting, like -and, -or, -nest, so shift over
753 my $subjoin = $self->_sqlcase('or');
754 if ($v[0] =~ /^-(\D+)/) {
755 $subjoin = $self->_modlogic($1); # override subjoin
756 $self->_debug("OP(-$1) means special logic ($subjoin), shifting...");
760 # map into an array of hashrefs and recurse
761 my @ret = $self->_recurse_where([map { {$k => $_} } @v], $subjoin);
763 # push results into our structure
764 push @sqlf, shift @ret;
766 } elsif (ref $v eq 'HASH') {
767 # modified operator { '!=', 'completed' }
768 for my $f (sort keys %$v) {
771 # do the right thing for single -in values
772 $x = [$x] if ($f =~ /^-?\s*(not[\s_]+)?in\s*$/i && ref $x ne 'ARRAY');
774 $self->_debug("HASH($k) means modified operator: { $f }");
776 # check for the operator being "IN" or "BETWEEN" or whatever
777 if (ref $x eq 'ARRAY') {
778 if ($f =~ /^-?\s*(not[\s_]+)?(in|between)\s*$/i) {
779 my $u = $self->_modlogic($1 . $2);
780 $self->_debug("HASH($f => $x) uses special operator: [ $u ]");
781 if ($u =~ /between/i) {
783 # Throw an exception if you try to use between with
784 # anything other than 2 values
785 $self->puke("You need two values to use between") unless @$x == 2;
786 push @sqlf, join ' ', $self->_convert($label), $u, $self->_convert('?'),
787 $self->_sqlcase('and'), $self->_convert('?');
789 # DWIM for empty arrayrefs
790 push @sqlf, join ' ', $self->_convert($label), $u, '(',
791 join(', ', map { $self->_convert('?') } @$x),
794 # Empty IN defaults to 0=1 and empty NOT IN to 1=1
795 push(@sqlf, ($u =~ /not/i ? "1=1" : "0=1"));
797 push @sqlv, $self->_bindtype($k, @$x);
799 # multiple elements: multiple options
800 $self->_debug("ARRAY($x) means multiple elements: [ @$x ]");
802 # map into an array of hashrefs and recurse
803 my @ret = $self->_recurse_where([map { {$k => {$f, $_}} } @$x]);
805 # push results into our structure
806 push @sqlf, shift @ret;
809 } elsif (! defined($x)) {
811 my $not = ($f eq '!=' || $f eq 'not like') ? ' not' : '';
812 push @sqlf, $label . $self->_sqlcase(" is$not null");
815 $f =~ s/^-//; # strip leading -like =>
816 $f =~ s/_/ /; # _ => " "
817 push @sqlf, join ' ', $self->_convert($label), $self->_sqlcase($f), $self->_convert('?');
818 push @sqlv, $self->_bindtype($k, $x);
821 } elsif (ref $v eq 'SCALAR') {
823 $self->_debug("SCALAR($k) means literal SQL: $$v");
824 push @sqlf, "$label $$v";
826 # standard key => val
827 $self->_debug("NOREF($k) means simple key=val: $k $self->{cmp} $v");
828 push @sqlf, join ' ', $self->_convert($label), $self->_sqlcase($self->{cmp}), $self->_convert('?');
829 push @sqlv, $self->_bindtype($k, $v);
833 elsif ($ref eq 'SCALAR') {
835 $self->_debug("SCALAR(*top) means literal SQL: $$where");
838 elsif (defined $where) {
840 $self->_debug("NOREF(*top) means literal SQL: $where");
844 # assemble and return sql
845 my $wsql = @sqlf ? '( ' . join(" $join ", @sqlf) . ' )' : '';
846 return wantarray ? ($wsql, @sqlv) : $wsql;
851 my $ref = ref $_[0] || '';
853 my $_order_hash = sub {
854 local *__ANON__ = '_order_by_hash';
856 my $hash = shift; # $_ was failing in some cases for me --groditi
857 if ( $col = $hash->{'-desc'} ) {
859 } elsif ( $col = $hash->{'-asc'} ) {
862 puke "Hash must have a key of '-desc' or '-asc' for ORDER BY";
864 return $self->_quote($col) . " $order";
869 if ($ref eq 'ARRAY') {
870 foreach (@{ $_[0] }) {
872 if (!$ref || $ref eq 'SCALAR') {
873 push @vals, $self->_quote($_);
874 } elsif ($ref eq 'HASH') {
875 push @vals, $_order_hash->($_);
877 puke "Unsupported nested data struct $ref for ORDER BY";
880 } elsif ($ref eq 'HASH') {
881 push @vals, $_order_hash->($_[0]);
882 } elsif (!$ref || $ref eq 'SCALAR') {
883 push @vals, $self->_quote($_[0]);
885 puke "Unsupported data struct $ref for ORDER BY";
888 my $val = join ', ', @vals;
889 return $val ? $self->_sqlcase(' order by')." $val" : '';
892 =head2 values(\%data)
894 This just returns the values from the hash C<%data>, in the same
895 order that would be returned from any of the other above queries.
896 Using this allows you to markedly speed up your queries if you
897 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
903 my $data = shift || return;
904 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
905 unless ref $data eq 'HASH';
906 return map { $self->_bindtype($_, $data->{$_}) } sort keys %$data;
909 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
911 Warning: This is an experimental method and subject to change.
913 This returns arbitrarily generated SQL. It's a really basic shortcut.
914 It will return two different things, depending on return context:
916 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
917 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
919 These would return the following:
922 $stmt = "CREATE TABLE test (?, ?)";
923 @bind = (field1, field2);
925 # Second calling form
926 $stmt_and_val = "CREATE TABLE test (field1, field2)";
928 Depending on what you're trying to do, it's up to you to choose the correct
929 format. In this example, the second form is what you would want.
933 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
937 ALTER SESSION SET nls_date_format = 'MM/YY'
939 You get the idea. Strings get their case twiddled, but everything
940 else remains verbatim.
947 my(@sql, @sqlq, @sqlv);
951 if ($ref eq 'HASH') {
952 for my $k (sort keys %$_) {
955 my $label = $self->_quote($k);
957 # SQL included for values
959 my $sql = shift @bind;
960 push @sqlq, "$label = $sql";
961 push @sqlv, $self->_bindtype($k, @bind);
962 } elsif ($r eq 'SCALAR') {
963 # embedded literal SQL
964 push @sqlq, "$label = $$v";
966 push @sqlq, "$label = ?";
967 push @sqlv, $self->_bindtype($k, $v);
970 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
971 } elsif ($ref eq 'ARRAY') {
972 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
977 push @sqlq, shift @val;
979 } elsif ($r eq 'SCALAR') {
980 # embedded literal SQL
987 push @sql, '(' . join(', ', @sqlq) . ')';
988 } elsif ($ref eq 'SCALAR') {
992 # strings get case twiddled
993 push @sql, $self->_sqlcase($_);
997 my $sql = join ' ', @sql;
999 # this is pretty tricky
1000 # if ask for an array, return ($stmt, @bind)
1001 # otherwise, s/?/shift @sqlv/ to put it inline
1003 return ($sql, @sqlv);
1005 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1006 ref $d ? $d->[1] : $d/e;
1013 # This allows us to check for a local, then _form, attr
1015 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1016 return $self->generate($name, @_);
1023 =head1 WHERE CLAUSES
1025 This module uses a variation on the idea from L<DBIx::Abstract>. It
1026 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
1027 module is that things in arrays are OR'ed, and things in hashes
1030 The easiest way to explain is to show lots of examples. After
1031 each C<%where> hash shown, it is assumed you used:
1033 my($stmt, @bind) = $sql->where(\%where);
1035 However, note that the C<%where> hash can be used directly in any
1036 of the other functions as well, as described above.
1038 So, let's get started. To begin, a simple hash:
1042 status => 'completed'
1045 Is converted to SQL C<key = val> statements:
1047 $stmt = "WHERE user = ? AND status = ?";
1048 @bind = ('nwiger', 'completed');
1050 One common thing I end up doing is having a list of values that
1051 a field can be in. To do this, simply specify a list inside of
1056 status => ['assigned', 'in-progress', 'pending'];
1059 This simple code will create the following:
1061 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
1062 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
1064 If you want to specify a different type of operator for your comparison,
1065 you can use a hashref for a given column:
1069 status => { '!=', 'completed' }
1072 Which would generate:
1074 $stmt = "WHERE user = ? AND status != ?";
1075 @bind = ('nwiger', 'completed');
1077 To test against multiple values, just enclose the values in an arrayref:
1079 status => { '!=', ['assigned', 'in-progress', 'pending'] };
1081 Which would give you:
1083 "WHERE status != ? OR status != ? OR status != ?"
1085 But, this is probably not what you want in this case (look at it). So
1086 the hashref can also contain multiple pairs, in which case it is expanded
1087 into an C<AND> of its elements:
1091 status => { '!=', 'completed', -not_like => 'pending%' }
1094 # Or more dynamically, like from a form
1095 $where{user} = 'nwiger';
1096 $where{status}{'!='} = 'completed';
1097 $where{status}{'-not_like'} = 'pending%';
1099 # Both generate this
1100 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1101 @bind = ('nwiger', 'completed', 'pending%');
1103 To get an OR instead, you can combine it with the arrayref idea:
1107 priority => [ {'=', 2}, {'!=', 1} ]
1110 Which would generate:
1112 $stmt = "WHERE user = ? AND priority = ? OR priority != ?";
1113 @bind = ('nwiger', '2', '1');
1115 However, there is a subtle trap if you want to say something like
1116 this (notice the C<AND>):
1118 WHERE priority != ? AND priority != ?
1120 Because, in Perl you I<can't> do this:
1122 priority => { '!=', 2, '!=', 1 }
1124 As the second C<!=> key will obliterate the first. The solution
1125 is to use the special C<-modifier> form inside an arrayref:
1127 priority => [ -and => {'!=', 2}, {'!=', 1} ]
1129 Normally, these would be joined by C<OR>, but the modifier tells it
1130 to use C<AND> instead. (Hint: You can use this in conjunction with the
1131 C<logic> option to C<new()> in order to change the way your queries
1132 work by default.) B<Important:> Note that the C<-modifier> goes
1133 B<INSIDE> the arrayref, as an extra first element. This will
1134 B<NOT> do what you think it might:
1136 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
1138 Here is a quick list of equivalencies, since there is some overlap:
1141 status => {'!=', 'completed', 'not like', 'pending%' }
1142 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1145 status => {'=', ['assigned', 'in-progress']}
1146 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1147 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1149 In addition to C<-and> and C<-or>, there is also a special C<-nest>
1150 operator which adds an additional set of parens, to create a subquery.
1151 For example, to get something like this:
1153 $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )";
1154 @bind = ('nwiger', '20', 'ASIA');
1160 -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1163 You can also use the hashref format to compare a list of fields using the
1164 C<IN> comparison operator, by specifying the list as an arrayref:
1167 status => 'completed',
1168 reportid => { -in => [567, 2335, 2] }
1171 Which would generate:
1173 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1174 @bind = ('completed', '567', '2335', '2');
1176 You can use this same format to use other grouping functions, such
1177 as C<BETWEEN>, C<SOME>, and so forth. For example:
1181 completion_date => {
1182 -not_between => ['2002-10-01', '2003-02-06']
1188 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1190 So far, we've seen how multiple conditions are joined with a top-level
1191 C<AND>. We can change this by putting the different conditions we want in
1192 hashes and then putting those hashes in an array. For example:
1197 status => { -like => ['pending%', 'dispatched'] },
1201 status => 'unassigned',
1205 This data structure would create the following:
1207 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1208 OR ( user = ? AND status = ? ) )";
1209 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1211 This can be combined with the C<-nest> operator to properly group
1218 -and => [workhrs => {'>', 20}, geo => 'ASIA' ],
1219 -and => [workhrs => {'<', 50}, geo => 'EURO' ]
1226 WHERE ( user = ? AND
1227 ( ( workhrs > ? AND geo = ? )
1228 OR ( workhrs < ? AND geo = ? ) ) )
1230 Finally, sometimes only literal SQL will do. If you want to include
1231 literal SQL verbatim, you can specify it as a scalar reference, namely:
1233 my $inn = 'is Not Null';
1235 priority => { '<', 2 },
1241 $stmt = "WHERE priority < ? AND requestor is Not Null";
1244 Note that in this example, you only get one bind parameter back, since
1245 the verbatim SQL is passed as part of the statement.
1247 Of course, just to prove a point, the above can also be accomplished
1251 priority => { '<', 2 },
1252 requestor => { '!=', undef },
1257 These pages could go on for a while, since the nesting of the data
1258 structures this module can handle are pretty much unlimited (the
1259 module implements the C<WHERE> expansion as a recursive function
1260 internally). Your best bet is to "play around" with the module a
1261 little to see how the data structures behave, and choose the best
1262 format for your data based on that.
1264 And of course, all the values above will probably be replaced with
1265 variables gotten from forms or the command line. After all, if you
1266 knew everything ahead of time, you wouldn't have to worry about
1267 dynamically-generating SQL and could just hardwire it into your
1270 =head1 ORDER BY CLAUSES
1272 Some functions take an order by clause. This can either be a scalar (just a
1273 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1274 or an array of either of the two previous forms. Examples:
1276 Given | Will Generate
1277 ----------------------------------------------------------
1278 \'colA DESC' | ORDER BY colA DESC
1279 'colA' | ORDER BY colA
1280 [qw/colA colB/] | ORDER BY colA, colB
1281 {-asc => 'colA'} | ORDER BY colA ASC
1282 {-desc => 'colB'} | ORDER BY colB DESC
1284 {-asc => 'colA'}, | ORDER BY colA ASC, colB DESC
1287 [colA => {-asc => 'colB'}] | ORDER BY colA, colB ASC
1288 ==========================================================
1292 Thanks to some benchmarking by Mark Stosberg, it turns out that
1293 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
1294 I must admit this wasn't an intentional design issue, but it's a
1295 byproduct of the fact that you get to control your C<DBI> handles
1298 To maximize performance, use a code snippet like the following:
1300 # prepare a statement handle using the first row
1301 # and then reuse it for the rest of the rows
1303 for my $href (@array_of_hashrefs) {
1304 $stmt ||= $sql->insert('table', $href);
1305 $sth ||= $dbh->prepare($stmt);
1306 $sth->execute($sql->values($href));
1309 The reason this works is because the keys in your C<$href> are sorted
1310 internally by B<SQL::Abstract>. Thus, as long as your data retains
1311 the same structure, you only have to generate the SQL the first time
1312 around. On subsequent queries, simply use the C<values> function provided
1313 by this module to return your values in the correct order.
1317 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
1318 really like this part (I do, at least). Building up a complex query
1319 can be as simple as the following:
1323 use CGI::FormBuilder;
1326 my $form = CGI::FormBuilder->new(...);
1327 my $sql = SQL::Abstract->new;
1329 if ($form->submitted) {
1330 my $field = $form->field;
1331 my $id = delete $field->{id};
1332 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
1335 Of course, you would still have to connect using C<DBI> to run the
1336 query, but the point is that if you make your form look like your
1337 table, the actual query script can be extremely simplistic.
1339 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
1340 a fast interface to returning and formatting data. I frequently
1341 use these three modules together to write complex database query
1342 apps in under 50 lines.
1346 There is not (yet) any explicit support for SQL compound logic
1347 statements like "AND NOT". Instead, just do the de Morgan's
1348 law transformations yourself. For example, this:
1350 "lname LIKE '%son%' AND NOT ( age < 10 OR age > 20 )"
1354 "lname LIKE '%son%' AND ( age >= 10 AND age <= 20 )"
1356 With the corresponding C<%where> hash:
1359 lname => {like => '%son%'},
1360 age => [-and => {'>=', 10}, {'<=', 20}],
1363 Again, remember that the C<-and> goes I<inside> the arrayref.
1365 =head1 ACKNOWLEDGEMENTS
1367 There are a number of individuals that have really helped out with
1368 this module. Unfortunately, most of them submitted bugs via CPAN
1369 so I have no idea who they are! But the people I do know are:
1371 Ash Berlin (order_by hash term support)
1372 Matt Trout (DBIx::Class support)
1373 Mark Stosberg (benchmarking)
1374 Chas Owens (initial "IN" operator support)
1375 Philip Collins (per-field SQL functions)
1376 Eric Kolve (hashref "AND" support)
1377 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
1378 Dan Kubb (support for "quote_char" and "name_sep")
1379 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
1385 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
1389 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
1391 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
1393 For support, your best bet is to try the C<DBIx::Class> users mailing list.
1394 While not an official support venue, C<DBIx::Class> makes heavy use of
1395 C<SQL::Abstract>, and as such list members there are very familiar with
1396 how to create queries.
1398 This module is free software; you may copy this under the terms of
1399 the GNU General Public License, or the Artistic License, copies of
1400 which should have accompanied your Perl kit.