Commit | Line | Data |
32eab2da |
1 | package SQL::Abstract; |
2 | |
3 | =head1 NAME |
4 | |
5 | SQL::Abstract - Generate SQL from Perl data structures |
6 | |
7 | =head1 SYNOPSIS |
8 | |
9 | use SQL::Abstract; |
10 | |
11 | my $sql = SQL::Abstract->new; |
12 | |
13 | my($stmt, @bind) = $sql->select($table, \@fields, \%where, \@order); |
14 | |
15 | my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values); |
16 | |
17 | my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where); |
18 | |
19 | my($stmt, @bind) = $sql->delete($table, \%where); |
20 | |
21 | # Then, use these in your DBI statements |
22 | my $sth = $dbh->prepare($stmt); |
23 | $sth->execute(@bind); |
24 | |
25 | # Just generate the WHERE clause |
abe72f94 |
26 | my($stmt, @bind) = $sql->where(\%where, \@order); |
32eab2da |
27 | |
28 | # Return values in the same order, for hashed queries |
29 | # See PERFORMANCE section for more details |
30 | my @bind = $sql->values(\%fieldvals); |
31 | |
32 | =head1 DESCRIPTION |
33 | |
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. |
39 | |
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. |
48 | |
49 | To begin with, an SQL INSERT is as easy as just specifying a hash |
50 | of C<key=value> pairs: |
51 | |
52 | my %data = ( |
53 | name => 'Jimbo Bobson', |
54 | phone => '123-456-7890', |
55 | address => '42 Sister Lane', |
56 | city => 'St. Louis', |
57 | state => 'Louisiana', |
58 | ); |
59 | |
60 | The SQL can then be generated with this: |
61 | |
62 | my($stmt, @bind) = $sql->insert('people', \%data); |
63 | |
64 | Which would give you something like this: |
65 | |
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'); |
71 | |
72 | These are then used directly in your DBI code: |
73 | |
74 | my $sth = $dbh->prepare($stmt); |
75 | $sth->execute(@bind); |
76 | |
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: |
81 | |
82 | my %data = ( |
83 | name => 'Bill', |
84 | date_entered => ["to_date(?,'MM/DD/YYYY')", "03/02/2003"], |
85 | ); |
86 | |
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 |
89 | you: |
90 | |
91 | my($stmt, @bind) = $sql->insert('people', \%data); |
92 | |
93 | $stmt = "INSERT INTO people (name, date_entered) |
94 | VALUES (?, to_date(?,'MM/DD/YYYY'))"; |
95 | @bind = ('Bill', '03/02/2003'); |
96 | |
97 | An UPDATE is just as easy, all you change is the name of the function: |
98 | |
99 | my($stmt, @bind) = $sql->update('people', \%data); |
100 | |
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... |
105 | |
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: |
111 | |
112 | my %where = ( |
113 | requestor => 'inna', |
114 | worker => ['nwiger', 'rcwe', 'sfz'], |
115 | status => { '!=', 'completed' } |
116 | ); |
117 | |
118 | my($stmt, @bind) = $sql->select('tickets', '*', \%where); |
119 | |
120 | The above would give you something like this: |
121 | |
122 | $stmt = "SELECT * FROM tickets WHERE |
123 | ( requestor = ? ) AND ( status != ? ) |
124 | AND ( worker = ? OR worker = ? OR worker = ? )"; |
125 | @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz'); |
126 | |
127 | Which you could then use in DBI code like so: |
128 | |
129 | my $sth = $dbh->prepare($stmt); |
130 | $sth->execute(@bind); |
131 | |
132 | Easy, eh? |
133 | |
134 | =head1 FUNCTIONS |
135 | |
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. |
140 | |
141 | =cut |
142 | |
143 | use Carp; |
144 | use strict; |
145 | |
69f2a249 |
146 | our $VERSION = '1.22'; |
147 | our $REVISION = '$Id$'; |
32eab2da |
148 | our $AUTOLOAD; |
149 | |
150 | # Fix SQL case, if so requested |
151 | sub _sqlcase { |
152 | my $self = shift; |
153 | return $self->{case} ? $_[0] : uc($_[0]); |
154 | } |
155 | |
156 | # Anon copies of arrays/hashes |
157 | # Based on deep_copy example by merlyn |
158 | # http://www.stonehenge.com/merlyn/UnixReview/col30.html |
159 | sub _anoncopy { |
160 | my $orig = shift; |
161 | return (ref $orig eq 'HASH') ? +{map { $_ => _anoncopy($orig->{$_}) } keys %$orig} |
162 | : (ref $orig eq 'ARRAY') ? [map _anoncopy($_), @$orig] |
163 | : $orig; |
164 | } |
165 | |
166 | # Debug |
167 | sub _debug { |
168 | return unless $_[0]->{debug}; shift; # a little faster |
169 | my $func = (caller(1))[3]; |
170 | warn "[$func] ", @_, "\n"; |
171 | } |
172 | |
173 | sub belch (@) { |
174 | my($func) = (caller(1))[3]; |
175 | carp "[$func] Warning: ", @_; |
176 | } |
177 | |
178 | sub puke (@) { |
179 | my($func) = (caller(1))[3]; |
180 | croak "[$func] Fatal: ", @_; |
181 | } |
182 | |
183 | # Utility functions |
184 | sub _table { |
185 | my $self = shift; |
83cab70b |
186 | my $from = shift; |
187 | if (ref $from eq 'ARRAY') { |
188 | return $self->_recurse_from(@$from); |
189 | } elsif (ref $from eq 'HASH') { |
190 | return $self->_make_as($from); |
32eab2da |
191 | } else { |
83cab70b |
192 | return $self->_quote($from); |
32eab2da |
193 | } |
194 | } |
195 | |
83cab70b |
196 | sub _recurse_from { |
197 | my ($self, $from, @join) = @_; |
198 | my @sqlf; |
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'; |
203 | my ($to, $on) = @$j; |
204 | |
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 '); |
210 | } else { |
211 | $join_clause = $self->_sqlcase(' JOIN '); |
212 | } |
213 | push(@sqlf, $join_clause); |
214 | |
215 | if (ref $to eq 'ARRAY') { |
216 | push(@sqlf, '(', $self->_recurse_from(@$to), ')'); |
217 | } else { |
218 | push(@sqlf, $self->_make_as($to)); |
219 | } |
220 | push(@sqlf, $self->_sqlcase(' ON '), $self->_join_condition($on)); |
221 | } |
222 | return join('', @sqlf); |
223 | } |
224 | |
225 | sub _make_as { |
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)}); |
231 | } |
232 | |
233 | sub _skip_options { |
234 | my ($self, $hash) = @_; |
235 | my $clean_hash = {}; |
236 | $clean_hash->{$_} = $hash->{$_} |
237 | for grep {!/^-/} keys %$hash; |
238 | return $clean_hash; |
239 | } |
240 | |
241 | sub _join_condition { |
242 | my ($self, $cond) = @_; |
243 | if (ref $cond eq 'HASH') { |
244 | my %j; |
245 | for (keys %$cond) { |
246 | my $x = '= '.$self->_quote($cond->{$_}); $j{$_} = \$x; |
247 | }; |
248 | return $self->_recurse_where(\%j); |
249 | } elsif (ref $cond eq 'ARRAY') { |
250 | return join(' OR ', map { $self->_join_condition($_) } @$cond); |
251 | } else { |
252 | die "Can't handle this yet!"; |
253 | } |
254 | } |
255 | |
256 | |
32eab2da |
257 | sub _quote { |
258 | my $self = shift; |
259 | my $label = shift; |
260 | |
83cab70b |
261 | return '' unless defined $label; |
262 | |
32eab2da |
263 | return $label |
264 | if $label eq '*'; |
265 | |
28f137a0 |
266 | return $$label if ref($label) eq 'SCALAR'; |
267 | |
83cab70b |
268 | return $label unless $self->{quote_char}; |
269 | |
270 | if (ref $self->{quote_char} eq "ARRAY") { |
271 | |
272 | return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1] |
273 | if !defined $self->{name_sep}; |
274 | |
275 | my $sep = $self->{name_sep}; |
276 | return join($self->{name_sep}, |
28f137a0 |
277 | map { $_ eq '*' |
278 | ? $_ |
279 | : $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] } |
83cab70b |
280 | split( /\Q$sep\E/, $label ) ); |
281 | } |
282 | |
283 | |
32eab2da |
284 | return $self->{quote_char} . $label . $self->{quote_char} |
285 | if !defined $self->{name_sep}; |
286 | |
287 | return join $self->{name_sep}, |
28f137a0 |
288 | map { $_ eq '*' ? $_ : $self->{quote_char} . $_ . $self->{quote_char} } |
32eab2da |
289 | split /\Q$self->{name_sep}\E/, $label; |
290 | } |
291 | |
292 | # Conversion, if applicable |
293 | sub _convert ($) { |
294 | my $self = shift; |
295 | return @_ unless $self->{convert}; |
296 | my $conv = $self->_sqlcase($self->{convert}); |
297 | my @ret = map { $conv.'('.$_.')' } @_; |
298 | return wantarray ? @ret : $ret[0]; |
299 | } |
300 | |
301 | # And bindtype |
302 | sub _bindtype (@) { |
303 | my $self = shift; |
304 | my($col,@val) = @_; |
305 | return $self->{bindtype} eq 'columns' ? [ @_ ] : @val; |
306 | } |
307 | |
308 | # Modified -logic or -nest |
309 | sub _modlogic ($) { |
310 | my $self = shift; |
311 | my $sym = @_ ? lc(shift) : $self->{logic}; |
312 | $sym =~ tr/_/ /; |
313 | $sym = $self->{logic} if $sym eq 'nest'; |
314 | return $self->_sqlcase($sym); # override join |
315 | } |
316 | |
317 | =head2 new(option => 'value') |
318 | |
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: |
322 | |
323 | =over |
324 | |
325 | =item case |
326 | |
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: |
329 | |
330 | SELECT a_field FROM a_table WHERE some_field LIKE '%someval%' |
331 | |
332 | =item cmp |
333 | |
334 | This determines what the default comparison operator is. By default |
335 | it is C<=>, meaning that a hash like this: |
336 | |
337 | %where = (name => 'nwiger', email => 'nate@wiger.org'); |
338 | |
339 | Will generate SQL like this: |
340 | |
341 | WHERE name = 'nwiger' AND email = 'nate@wiger.org' |
342 | |
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: |
345 | |
346 | WHERE name like 'nwiger' AND email like 'nate@wiger.org' |
347 | |
348 | You can also override the comparsion on an individual basis - see |
349 | the huge section on L</"WHERE CLAUSES"> at the bottom. |
350 | |
351 | =item logic |
352 | |
353 | This determines the default logical operator for multiple WHERE |
354 | statements in arrays. By default it is "or", meaning that a WHERE |
355 | array of the form: |
356 | |
357 | @where = ( |
358 | event_date => {'>=', '2/13/99'}, |
359 | event_date => {'<=', '4/24/03'}, |
360 | ); |
361 | |
362 | Will generate SQL like this: |
363 | |
364 | WHERE event_date >= '2/13/99' OR event_date <= '4/24/03' |
365 | |
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: |
368 | |
369 | my $sql = SQL::Abstract->new(logic => 'and'); |
370 | |
371 | Which will change the above C<WHERE> to: |
372 | |
373 | WHERE event_date >= '2/13/99' AND event_date <= '4/24/03' |
374 | |
375 | =item convert |
376 | |
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: |
381 | |
382 | $sql = SQL::Abstract->new(convert => 'upper'); |
383 | %where = (keywords => 'MaKe iT CAse inSeNSItive'); |
384 | |
385 | Will turn out the following SQL: |
386 | |
387 | WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive') |
388 | |
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). |
392 | |
393 | =item bindtype |
394 | |
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()>: |
398 | |
399 | $sth->bind_param(1, 'reg data'); |
400 | $sth->bind_param(2, $lots, {ora_type => ORA_CLOB}); |
401 | |
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. |
404 | |
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: |
408 | |
409 | my $sql = SQL::Abstract->new(bindtype => 'columns'); |
410 | my($stmt, @bind) = $sql->insert(...); |
411 | |
412 | @bind = ( |
413 | [ 'column1', 'value1' ], |
414 | [ 'column2', 'value2' ], |
415 | [ 'column3', 'value3' ], |
416 | ); |
417 | |
418 | You can then iterate through this manually, using DBI's C<bind_param()>. |
419 | |
420 | $sth->prepare($stmt); |
421 | my $i = 1; |
422 | for (@bind) { |
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}); |
428 | } else { |
429 | $sth->bind_param($i, $data); |
430 | } |
431 | $i++; |
432 | } |
433 | $sth->execute; # execute without @bind now |
434 | |
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. |
440 | |
441 | =item quote_char |
442 | |
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: |
446 | |
447 | SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%' |
448 | |
449 | This is useful if you have tables or columns that are reserved words |
450 | in your database's SQL dialect. |
451 | |
452 | =item name_sep |
453 | |
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: |
457 | |
458 | SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1 |
459 | |
460 | =back |
461 | |
462 | =cut |
463 | |
464 | sub new { |
465 | my $self = shift; |
466 | my $class = ref($self) || $self; |
467 | my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_; |
468 | |
469 | # choose our case by keeping an option around |
470 | delete $opt{case} if $opt{case} && $opt{case} ne 'lower'; |
471 | |
472 | # override logical operator |
473 | $opt{logic} = uc $opt{logic} if $opt{logic}; |
474 | |
475 | # how to return bind vars |
476 | $opt{bindtype} ||= delete($opt{bind_type}) || 'normal'; |
477 | |
478 | # default comparison is "=", but can be overridden |
479 | $opt{cmp} ||= '='; |
480 | |
481 | # default quotation character around tables/columns |
482 | $opt{quote_char} ||= ''; |
483 | |
484 | return bless \%opt, $class; |
485 | } |
486 | |
487 | =head2 insert($table, \@values || \%fieldvals) |
488 | |
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. |
492 | |
493 | =cut |
494 | |
495 | sub insert { |
496 | my $self = shift; |
497 | my $table = $self->_table(shift); |
498 | my $data = shift || return; |
499 | |
500 | my $sql = $self->_sqlcase('insert into') . " $table "; |
501 | my(@sqlf, @sqlv, @sqlq) = (); |
502 | |
503 | my $ref = ref $data; |
504 | if ($ref eq 'HASH') { |
505 | for my $k (sort keys %$data) { |
506 | my $v = $data->{$k}; |
507 | my $r = ref $v; |
508 | # named fields, so must save names in order |
509 | push @sqlf, $self->_quote($k); |
510 | if ($r eq 'ARRAY') { |
511 | # SQL included for values |
512 | my @val = @$v; |
513 | push @sqlq, shift @val; |
514 | push @sqlv, $self->_bindtype($k, @val); |
515 | } elsif ($r eq 'SCALAR') { |
516 | # embedded literal SQL |
517 | push @sqlq, $$v; |
518 | } else { |
519 | push @sqlq, '?'; |
520 | push @sqlv, $self->_bindtype($k, $v); |
521 | } |
522 | } |
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'; |
529 | for my $v (@$data) { |
530 | my $r = ref $v; |
531 | if ($r eq 'ARRAY') { |
532 | my @val = @$v; |
533 | push @sqlq, shift @val; |
534 | push @sqlv, @val; |
535 | } elsif ($r eq 'SCALAR') { |
536 | # embedded literal SQL |
537 | push @sqlq, $$v; |
538 | } else { |
539 | push @sqlq, '?'; |
540 | push @sqlv, $v; |
541 | } |
542 | } |
543 | $sql .= $self->_sqlcase('values') . ' ('. join(', ', @sqlq) .')'; |
544 | } elsif ($ref eq 'SCALAR') { |
545 | # literal SQL |
546 | $sql .= $$data; |
547 | } else { |
548 | puke "Unsupported data type specified to \$sql->insert"; |
549 | } |
550 | |
551 | return wantarray ? ($sql, @sqlv) : $sql; |
552 | } |
553 | |
554 | =head2 update($table, \%fieldvals, \%where) |
555 | |
556 | This takes a table, hashref of field/value pairs, and an optional |
86298391 |
557 | hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list |
32eab2da |
558 | of bind values. |
559 | |
560 | =cut |
561 | |
562 | sub update { |
563 | my $self = shift; |
564 | my $table = $self->_table(shift); |
565 | my $data = shift || return; |
566 | my $where = shift; |
567 | |
568 | my $sql = $self->_sqlcase('update') . " $table " . $self->_sqlcase('set '); |
569 | my(@sqlf, @sqlv) = (); |
570 | |
571 | puke "Unsupported data type specified to \$sql->update" |
572 | unless ref $data eq 'HASH'; |
573 | |
574 | for my $k (sort keys %$data) { |
575 | my $v = $data->{$k}; |
576 | my $r = ref $v; |
577 | my $label = $self->_quote($k); |
578 | if ($r eq 'ARRAY') { |
579 | # SQL included for values |
580 | my @bind = @$v; |
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"; |
587 | } else { |
588 | push @sqlf, "$label = ?"; |
589 | push @sqlv, $self->_bindtype($k, $v); |
590 | } |
591 | } |
592 | |
593 | $sql .= join ', ', @sqlf; |
594 | |
595 | if ($where) { |
596 | my($wsql, @wval) = $self->where($where); |
597 | $sql .= $wsql; |
598 | push @sqlv, @wval; |
599 | } |
600 | |
601 | return wantarray ? ($sql, @sqlv) : $sql; |
602 | } |
603 | |
604 | =head2 select($table, \@fields, \%where, \@order) |
605 | |
606 | This takes a table, arrayref of fields (or '*'), optional hashref |
86298391 |
607 | L<WHERE clause|/WHERE CLAUSES>, and optional array or hash ref L<ORDER BY clause|/ORDER BY CLAUSES>, and returns the |
32eab2da |
608 | corresponding SQL SELECT statement and list of bind values. |
609 | |
610 | =cut |
611 | |
612 | sub select { |
613 | my $self = shift; |
614 | my $table = $self->_table(shift); |
615 | my $fields = shift || '*'; |
616 | my $where = shift; |
617 | my $order = shift; |
618 | |
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; |
621 | |
622 | my(@sqlf, @sqlv) = (); |
623 | my($wsql, @wval) = $self->where($where, $order); |
624 | $sql .= $wsql; |
625 | push @sqlv, @wval; |
626 | |
627 | return wantarray ? ($sql, @sqlv) : $sql; |
628 | } |
629 | |
630 | =head2 delete($table, \%where) |
631 | |
86298391 |
632 | This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>. |
32eab2da |
633 | It returns an SQL DELETE statement and list of bind values. |
634 | |
635 | =cut |
636 | |
637 | sub delete { |
638 | my $self = shift; |
639 | my $table = $self->_table(shift); |
640 | my $where = shift; |
641 | |
642 | my $sql = $self->_sqlcase('delete from') . " $table"; |
643 | my(@sqlf, @sqlv) = (); |
644 | |
645 | if ($where) { |
646 | my($wsql, @wval) = $self->where($where); |
647 | $sql .= $wsql; |
648 | push @sqlv, @wval; |
649 | } |
650 | |
651 | return wantarray ? ($sql, @sqlv) : $sql; |
652 | } |
653 | |
654 | =head2 where(\%where, \@order) |
655 | |
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. |
661 | |
662 | =cut |
663 | |
664 | # Finally, a separate routine just to handle WHERE clauses |
665 | sub where { |
666 | my $self = shift; |
667 | my $where = shift; |
668 | my $order = shift; |
669 | |
670 | # Need a separate routine to properly wrap w/ "where" |
671 | my $sql = ''; |
672 | my @ret = $self->_recurse_where($where); |
673 | if (@ret) { |
674 | my $wh = shift @ret; |
675 | $sql .= $self->_sqlcase(' where ') . $wh if $wh; |
676 | } |
677 | |
678 | # order by? |
679 | if ($order) { |
680 | $sql .= $self->_order_by($order); |
681 | } |
682 | |
683 | return wantarray ? ($sql, @ret) : $sql; |
684 | } |
685 | |
686 | |
687 | sub _recurse_where { |
688 | local $^W = 0; # really, you've gotta be fucking kidding me |
689 | my $self = shift; |
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')); |
694 | |
695 | # For assembling SQL fields and values |
696 | my(@sqlf, @sqlv) = (); |
697 | |
698 | # If an arrayref, then we join each element |
699 | if ($ref eq 'ARRAY') { |
700 | # need to use while() so can shift() for arrays |
701 | my $subjoin; |
702 | while (my $el = shift @$where) { |
703 | |
704 | # skip empty elements, otherwise get invalid trailing AND stuff |
705 | if (my $ref2 = ref $el) { |
706 | if ($ref2 eq 'ARRAY') { |
707 | next unless @$el; |
708 | } elsif ($ref2 eq 'HASH') { |
709 | next unless %$el; |
710 | $subjoin ||= $self->_sqlcase('and'); |
711 | } elsif ($ref2 eq 'SCALAR') { |
712 | # literal SQL |
713 | push @sqlf, $$el; |
714 | next; |
715 | } |
716 | $self->_debug("$ref2(*top) means join with $subjoin"); |
717 | } else { |
718 | # top-level arrayref with scalars, recurse in pairs |
719 | $self->_debug("NOREF(*top) means join with $subjoin"); |
720 | $el = {$el => shift(@$where)}; |
721 | } |
722 | my @ret = $self->_recurse_where($el, $subjoin); |
723 | push @sqlf, shift @ret; |
724 | push @sqlv, @ret; |
725 | } |
726 | } |
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); |
61fdf29c |
733 | |
32eab2da |
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; |
740 | push @sqlv, @ret; |
741 | } elsif (! defined($v)) { |
742 | # undef = null |
743 | $self->_debug("UNDEF($k) means IS NULL"); |
744 | push @sqlf, $label . $self->_sqlcase(' is null'); |
745 | } elsif (ref $v eq 'ARRAY') { |
746 | my @v = @$v; |
747 | |
748 | # multiple elements: multiple options |
749 | $self->_debug("ARRAY($k) means multiple elements: [ @v ]"); |
750 | |
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..."); |
756 | shift @v; |
757 | } |
758 | |
759 | # map into an array of hashrefs and recurse |
760 | my @ret = $self->_recurse_where([map { {$k => $_} } @v], $subjoin); |
761 | |
762 | # push results into our structure |
763 | push @sqlf, shift @ret; |
764 | push @sqlv, @ret; |
765 | } elsif (ref $v eq 'HASH') { |
766 | # modified operator { '!=', 'completed' } |
767 | for my $f (sort keys %$v) { |
768 | my $x = $v->{$f}; |
61fdf29c |
769 | |
770 | # do the right thing for single -in values |
771 | $x = [$x] if ($f =~ /^-?\s*(not[\s_]+)?in\s*$/i && ref $x ne 'ARRAY'); |
772 | |
32eab2da |
773 | $self->_debug("HASH($k) means modified operator: { $f }"); |
774 | |
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) { |
781 | # SQL sucks |
61fdf29c |
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; |
32eab2da |
785 | push @sqlf, join ' ', $self->_convert($label), $u, $self->_convert('?'), |
786 | $self->_sqlcase('and'), $self->_convert('?'); |
61fdf29c |
787 | } elsif (@$x) { |
788 | # DWIM for empty arrayrefs |
32eab2da |
789 | push @sqlf, join ' ', $self->_convert($label), $u, '(', |
790 | join(', ', map { $self->_convert('?') } @$x), |
791 | ')'; |
61fdf29c |
792 | } elsif(@$x == 0){ |
793 | # Empty IN defaults to 0=1 and empty NOT IN to 1=1 |
794 | push(@sqlf, ($u =~ /not/i ? "1=1" : "0=1")); |
32eab2da |
795 | } |
796 | push @sqlv, $self->_bindtype($k, @$x); |
797 | } else { |
798 | # multiple elements: multiple options |
799 | $self->_debug("ARRAY($x) means multiple elements: [ @$x ]"); |
800 | |
801 | # map into an array of hashrefs and recurse |
802 | my @ret = $self->_recurse_where([map { {$k => {$f, $_}} } @$x]); |
803 | |
804 | # push results into our structure |
805 | push @sqlf, shift @ret; |
806 | push @sqlv, @ret; |
807 | } |
808 | } elsif (! defined($x)) { |
809 | # undef = NOT null |
810 | my $not = ($f eq '!=' || $f eq 'not like') ? ' not' : ''; |
811 | push @sqlf, $label . $self->_sqlcase(" is$not null"); |
812 | } else { |
813 | # regular ol' value |
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); |
818 | } |
819 | } |
820 | } elsif (ref $v eq 'SCALAR') { |
821 | # literal SQL |
822 | $self->_debug("SCALAR($k) means literal SQL: $$v"); |
823 | push @sqlf, "$label $$v"; |
824 | } else { |
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); |
829 | } |
830 | } |
831 | } |
832 | elsif ($ref eq 'SCALAR') { |
833 | # literal sql |
834 | $self->_debug("SCALAR(*top) means literal SQL: $$where"); |
835 | push @sqlf, $$where; |
836 | } |
837 | elsif (defined $where) { |
838 | # literal sql |
839 | $self->_debug("NOREF(*top) means literal SQL: $where"); |
840 | push @sqlf, $where; |
841 | } |
842 | |
843 | # assemble and return sql |
844 | my $wsql = @sqlf ? '( ' . join(" $join ", @sqlf) . ' )' : ''; |
845 | return wantarray ? ($wsql, @sqlv) : $wsql; |
846 | } |
847 | |
848 | sub _order_by { |
849 | my $self = shift; |
86298391 |
850 | my $ref = ref $_[0] || ''; |
851 | |
852 | my $_order_hash = sub { |
853 | local *__ANON__ = '_order_by_hash'; |
854 | my ($col, $order); |
855 | if ( $col = $_->{-desc} ) { |
856 | $order = 'DESC' |
857 | } elsif ( $col = $_->{-asc} ) { |
858 | $order = 'ASC'; |
859 | } else { |
860 | puke "Hash must have a key of '-desc' or '-asc' for ORDER BY"; |
861 | } |
862 | return $self->_quote($col) . " $order"; |
863 | |
864 | }; |
865 | |
866 | my @vals; |
867 | if ($ref eq 'ARRAY') { |
868 | foreach (@{ $_[0] }) { |
869 | my $ref = ref $_; |
870 | if (!$ref || $ref eq 'SCALAR') { |
871 | push @vals, $self->_quote($_); |
872 | } elsif ($ref eq 'HASH') { |
873 | push @vals, $_order_hash->($_); |
874 | } else { |
875 | puke "Unsupported nested data struct $ref for ORDER BY"; |
876 | } |
877 | } |
878 | } elsif ($ref eq 'HASH') { |
879 | push @vals, $_order_hash->($_[0]); |
880 | } elsif (!$ref || $ref eq 'SCALAR') { |
881 | push @vals, $self->_quote($_[0]); |
882 | } else { |
883 | puke "Unsupported data struct $ref for ORDER BY"; |
884 | } |
32eab2da |
885 | |
86298391 |
886 | my $val = join ', ', @vals; |
32eab2da |
887 | return $val ? $self->_sqlcase(' order by')." $val" : ''; |
888 | } |
889 | |
890 | =head2 values(\%data) |
891 | |
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. |
896 | |
897 | =cut |
898 | |
899 | sub values { |
900 | my $self = shift; |
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; |
905 | } |
906 | |
907 | =head2 generate($any, 'number', $of, \@data, $struct, \%types) |
908 | |
909 | Warning: This is an experimental method and subject to change. |
910 | |
911 | This returns arbitrarily generated SQL. It's a really basic shortcut. |
912 | It will return two different things, depending on return context: |
913 | |
914 | my($stmt, @bind) = $sql->generate('create table', \$table, \@fields); |
915 | my $stmt_and_val = $sql->generate('create table', \$table, \@fields); |
916 | |
917 | These would return the following: |
918 | |
919 | # First calling form |
920 | $stmt = "CREATE TABLE test (?, ?)"; |
921 | @bind = (field1, field2); |
922 | |
923 | # Second calling form |
924 | $stmt_and_val = "CREATE TABLE test (field1, field2)"; |
925 | |
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. |
928 | |
929 | By the same token: |
930 | |
931 | $sql->generate('alter session', { nls_date_format => 'MM/YY' }); |
932 | |
933 | Might give you: |
934 | |
935 | ALTER SESSION SET nls_date_format = 'MM/YY' |
936 | |
937 | You get the idea. Strings get their case twiddled, but everything |
938 | else remains verbatim. |
939 | |
940 | =cut |
941 | |
942 | sub generate { |
943 | my $self = shift; |
944 | |
945 | my(@sql, @sqlq, @sqlv); |
946 | |
947 | for (@_) { |
948 | my $ref = ref $_; |
949 | if ($ref eq 'HASH') { |
950 | for my $k (sort keys %$_) { |
951 | my $v = $_->{$k}; |
952 | my $r = ref $v; |
953 | my $label = $self->_quote($k); |
954 | if ($r eq 'ARRAY') { |
955 | # SQL included for values |
956 | my @bind = @$v; |
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"; |
963 | } else { |
964 | push @sqlq, "$label = ?"; |
965 | push @sqlv, $self->_bindtype($k, $v); |
966 | } |
967 | } |
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 |
971 | for my $v (@$_) { |
972 | my $r = ref $v; |
973 | if ($r eq 'ARRAY') { |
974 | my @val = @$v; |
975 | push @sqlq, shift @val; |
976 | push @sqlv, @val; |
977 | } elsif ($r eq 'SCALAR') { |
978 | # embedded literal SQL |
979 | push @sqlq, $$v; |
980 | } else { |
981 | push @sqlq, '?'; |
982 | push @sqlv, $v; |
983 | } |
984 | } |
985 | push @sql, '(' . join(', ', @sqlq) . ')'; |
986 | } elsif ($ref eq 'SCALAR') { |
987 | # literal SQL |
988 | push @sql, $$_; |
989 | } else { |
990 | # strings get case twiddled |
991 | push @sql, $self->_sqlcase($_); |
992 | } |
993 | } |
994 | |
995 | my $sql = join ' ', @sql; |
996 | |
997 | # this is pretty tricky |
998 | # if ask for an array, return ($stmt, @bind) |
999 | # otherwise, s/?/shift @sqlv/ to put it inline |
1000 | if (wantarray) { |
1001 | return ($sql, @sqlv); |
1002 | } else { |
1003 | 1 while $sql =~ s/\?/my $d = shift(@sqlv); |
1004 | ref $d ? $d->[1] : $d/e; |
1005 | return $sql; |
1006 | } |
1007 | } |
1008 | |
1009 | sub DESTROY { 1 } |
1010 | sub AUTOLOAD { |
1011 | # This allows us to check for a local, then _form, attr |
1012 | my $self = shift; |
1013 | my($name) = $AUTOLOAD =~ /.*::(.+)/; |
1014 | return $self->generate($name, @_); |
1015 | } |
1016 | |
1017 | 1; |
1018 | |
1019 | __END__ |
1020 | |
1021 | =head1 WHERE CLAUSES |
1022 | |
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 |
1026 | are AND'ed.> |
1027 | |
1028 | The easiest way to explain is to show lots of examples. After |
1029 | each C<%where> hash shown, it is assumed you used: |
1030 | |
1031 | my($stmt, @bind) = $sql->where(\%where); |
1032 | |
1033 | However, note that the C<%where> hash can be used directly in any |
1034 | of the other functions as well, as described above. |
1035 | |
1036 | So, let's get started. To begin, a simple hash: |
1037 | |
1038 | my %where = ( |
1039 | user => 'nwiger', |
1040 | status => 'completed' |
1041 | ); |
1042 | |
1043 | Is converted to SQL C<key = val> statements: |
1044 | |
1045 | $stmt = "WHERE user = ? AND status = ?"; |
1046 | @bind = ('nwiger', 'completed'); |
1047 | |
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 |
1050 | an arrayref: |
1051 | |
1052 | my %where = ( |
1053 | user => 'nwiger', |
1054 | status => ['assigned', 'in-progress', 'pending']; |
1055 | ); |
1056 | |
1057 | This simple code will create the following: |
1058 | |
1059 | $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )"; |
1060 | @bind = ('nwiger', 'assigned', 'in-progress', 'pending'); |
1061 | |
1062 | If you want to specify a different type of operator for your comparison, |
1063 | you can use a hashref for a given column: |
1064 | |
1065 | my %where = ( |
1066 | user => 'nwiger', |
1067 | status => { '!=', 'completed' } |
1068 | ); |
1069 | |
1070 | Which would generate: |
1071 | |
1072 | $stmt = "WHERE user = ? AND status != ?"; |
1073 | @bind = ('nwiger', 'completed'); |
1074 | |
1075 | To test against multiple values, just enclose the values in an arrayref: |
1076 | |
1077 | status => { '!=', ['assigned', 'in-progress', 'pending'] }; |
1078 | |
1079 | Which would give you: |
1080 | |
1081 | "WHERE status != ? OR status != ? OR status != ?" |
1082 | |
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: |
1086 | |
1087 | my %where = ( |
1088 | user => 'nwiger', |
1089 | status => { '!=', 'completed', -not_like => 'pending%' } |
1090 | ); |
1091 | |
1092 | # Or more dynamically, like from a form |
1093 | $where{user} = 'nwiger'; |
1094 | $where{status}{'!='} = 'completed'; |
1095 | $where{status}{'-not_like'} = 'pending%'; |
1096 | |
1097 | # Both generate this |
1098 | $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?"; |
1099 | @bind = ('nwiger', 'completed', 'pending%'); |
1100 | |
1101 | To get an OR instead, you can combine it with the arrayref idea: |
1102 | |
1103 | my %where => ( |
1104 | user => 'nwiger', |
1105 | priority => [ {'=', 2}, {'!=', 1} ] |
1106 | ); |
1107 | |
1108 | Which would generate: |
1109 | |
1110 | $stmt = "WHERE user = ? AND priority = ? OR priority != ?"; |
1111 | @bind = ('nwiger', '2', '1'); |
1112 | |
1113 | However, there is a subtle trap if you want to say something like |
1114 | this (notice the C<AND>): |
1115 | |
1116 | WHERE priority != ? AND priority != ? |
1117 | |
1118 | Because, in Perl you I<can't> do this: |
1119 | |
1120 | priority => { '!=', 2, '!=', 1 } |
1121 | |
1122 | As the second C<!=> key will obliterate the first. The solution |
1123 | is to use the special C<-modifier> form inside an arrayref: |
1124 | |
1125 | priority => [ -and => {'!=', 2}, {'!=', 1} ] |
1126 | |
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: |
1133 | |
1134 | priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG! |
1135 | |
1136 | Here is a quick list of equivalencies, since there is some overlap: |
1137 | |
1138 | # Same |
1139 | status => {'!=', 'completed', 'not like', 'pending%' } |
1140 | status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}] |
1141 | |
1142 | # Same |
1143 | status => {'=', ['assigned', 'in-progress']} |
1144 | status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}] |
1145 | status => [ {'=', 'assigned'}, {'=', 'in-progress'} ] |
1146 | |
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: |
1150 | |
86298391 |
1151 | $stmt = "WHERE user = ? AND ( workhrs > ? OR geo = ? )"; |
32eab2da |
1152 | @bind = ('nwiger', '20', 'ASIA'); |
1153 | |
1154 | You would do: |
1155 | |
1156 | my %where = ( |
1157 | user => 'nwiger', |
1158 | -nest => [ workhrs => {'>', 20}, geo => 'ASIA' ], |
1159 | ); |
1160 | |
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: |
1163 | |
1164 | my %where = ( |
1165 | status => 'completed', |
1166 | reportid => { -in => [567, 2335, 2] } |
1167 | ); |
1168 | |
1169 | Which would generate: |
1170 | |
1171 | $stmt = "WHERE status = ? AND reportid IN (?,?,?)"; |
1172 | @bind = ('completed', '567', '2335', '2'); |
1173 | |
1174 | You can use this same format to use other grouping functions, such |
1175 | as C<BETWEEN>, C<SOME>, and so forth. For example: |
1176 | |
1177 | my %where = ( |
1178 | user => 'nwiger', |
1179 | completion_date => { |
1180 | -not_between => ['2002-10-01', '2003-02-06'] |
1181 | } |
1182 | ); |
1183 | |
1184 | Would give you: |
1185 | |
1186 | WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? ) |
1187 | |
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: |
1191 | |
1192 | my @where = ( |
1193 | { |
1194 | user => 'nwiger', |
1195 | status => { -like => ['pending%', 'dispatched'] }, |
1196 | }, |
1197 | { |
1198 | user => 'robot', |
1199 | status => 'unassigned', |
1200 | } |
1201 | ); |
1202 | |
1203 | This data structure would create the following: |
1204 | |
1205 | $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) ) |
1206 | OR ( user = ? AND status = ? ) )"; |
1207 | @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned'); |
1208 | |
1209 | This can be combined with the C<-nest> operator to properly group |
1210 | SQL statements: |
1211 | |
1212 | my @where = ( |
1213 | -and => [ |
1214 | user => 'nwiger', |
1215 | -nest => [ |
1216 | -and => [workhrs => {'>', 20}, geo => 'ASIA' ], |
1217 | -and => [workhrs => {'<', 50}, geo => 'EURO' ] |
1218 | ], |
1219 | ], |
1220 | ); |
1221 | |
1222 | That would yield: |
1223 | |
1224 | WHERE ( user = ? AND |
1225 | ( ( workhrs > ? AND geo = ? ) |
1226 | OR ( workhrs < ? AND geo = ? ) ) ) |
1227 | |
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: |
1230 | |
1231 | my $inn = 'is Not Null'; |
1232 | my %where = ( |
1233 | priority => { '<', 2 }, |
1234 | requestor => \$inn |
1235 | ); |
1236 | |
1237 | This would create: |
1238 | |
1239 | $stmt = "WHERE priority < ? AND requestor is Not Null"; |
1240 | @bind = ('2'); |
1241 | |
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. |
1244 | |
1245 | Of course, just to prove a point, the above can also be accomplished |
1246 | with this: |
1247 | |
1248 | my %where = ( |
1249 | priority => { '<', 2 }, |
1250 | requestor => { '!=', undef }, |
1251 | ); |
1252 | |
1253 | TMTOWTDI. |
1254 | |
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. |
1261 | |
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 |
1266 | script. |
1267 | |
86298391 |
1268 | =head1 ORDER BY CLAUSES |
1269 | |
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. |
1273 | |
32eab2da |
1274 | =head1 PERFORMANCE |
1275 | |
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 |
1280 | yourself. |
1281 | |
1282 | To maximize performance, use a code snippet like the following: |
1283 | |
1284 | # prepare a statement handle using the first row |
1285 | # and then reuse it for the rest of the rows |
1286 | my($sth, $stmt); |
1287 | for my $href (@array_of_hashrefs) { |
1288 | $stmt ||= $sql->insert('table', $href); |
1289 | $sth ||= $dbh->prepare($stmt); |
1290 | $sth->execute($sql->values($href)); |
1291 | } |
1292 | |
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. |
1298 | |
1299 | =head1 FORMBUILDER |
1300 | |
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: |
1304 | |
1305 | #!/usr/bin/perl |
1306 | |
1307 | use CGI::FormBuilder; |
1308 | use SQL::Abstract; |
1309 | |
1310 | my $form = CGI::FormBuilder->new(...); |
1311 | my $sql = SQL::Abstract->new; |
1312 | |
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}); |
1317 | } |
1318 | |
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. |
1322 | |
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. |
1327 | |
1328 | =head1 NOTES |
1329 | |
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: |
1333 | |
1334 | "lname LIKE '%son%' AND NOT ( age < 10 OR age > 20 )" |
1335 | |
1336 | Becomes: |
1337 | |
1338 | "lname LIKE '%son%' AND ( age >= 10 AND age <= 20 )" |
1339 | |
1340 | With the corresponding C<%where> hash: |
1341 | |
1342 | %where = ( |
1343 | lname => {like => '%son%'}, |
1344 | age => [-and => {'>=', 10}, {'<=', 20}], |
1345 | ); |
1346 | |
1347 | Again, remember that the C<-and> goes I<inside> the arrayref. |
1348 | |
1349 | =head1 ACKNOWLEDGEMENTS |
1350 | |
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: |
1354 | |
86298391 |
1355 | Ash Berlin (order_by hash term support) |
b643abe1 |
1356 | Matt Trout (DBIx::Class support) |
32eab2da |
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") |
b643abe1 |
1363 | Guillermo Roditi (patch to cleanup "IN" and "BETWEEN") |
32eab2da |
1364 | |
1365 | Thanks! |
1366 | |
32eab2da |
1367 | =head1 SEE ALSO |
1368 | |
86298391 |
1369 | L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>. |
32eab2da |
1370 | |
32eab2da |
1371 | =head1 AUTHOR |
1372 | |
b643abe1 |
1373 | Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved. |
1374 | |
1375 | This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk> |
32eab2da |
1376 | |
abe72f94 |
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. |
1381 | |
32eab2da |
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. |
1385 | |
1386 | =cut |
1387 | |