8f1fe83c733a0f7311f772f35ed1809080f191ca
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract.pm
1 package SQL::Abstract; # see doc at end of file
2
3 use Carp ();
4 use List::Util ();
5 use Scalar::Util ();
6 use Module::Runtime qw(use_module);
7 use Moo;
8 use namespace::clean;
9
10 our $VERSION  = '1.77';
11
12 # This would confuse some packagers
13 $VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
14
15 sub belch (@) {
16   my($func) = (caller(1))[3];
17   Carp::carp "[$func] Warning: ", @_;
18 }
19
20 sub puke (@) {
21   my($func) = (caller(1))[3];
22   Carp::croak "[$func] Fatal: ", @_;
23 }
24
25 has converter => (is => 'lazy', clearer => 'clear_converter');
26
27 has case => (
28   is => 'ro', coerce => sub { $_[0] eq 'lower' ? 'lower' : undef }
29 );
30
31 has logic => (
32   is => 'ro', coerce => sub { uc($_[0]) }, default => sub { 'OR' }
33 );
34
35 has bindtype => (
36   is => 'ro', default => sub { 'normal' }
37 );
38
39 has cmp => (is => 'ro', default => sub { '=' });
40
41 has sqltrue => (is => 'ro', default => sub { '1=1' });
42 has sqlfalse => (is => 'ro', default => sub { '0=1' });
43
44 has special_ops => (is => 'ro', default => sub { [] });
45 has unary_ops => (is => 'ro', default => sub { [] });
46
47 # FIXME
48 # need to guard against ()'s in column names too, but this will break tons of
49 # hacks... ideas anyone?
50
51 has injection_guard => (
52   is => 'ro',
53   default => sub {
54     qr/
55       \;
56         |
57       ^ \s* go \s
58     /xmi;
59   }
60 );
61
62 has renderer => (is => 'lazy', clearer => 'clear_renderer');
63
64 has name_sep => (
65   is => 'rw', default => sub { '.' },
66   trigger => sub {
67     $_[0]->clear_renderer;
68     $_[0]->clear_converter;
69   },
70 );
71
72 has quote_char => (
73   is => 'rw',
74   trigger => sub {
75     $_[0]->clear_renderer;
76     $_[0]->clear_converter;
77   },
78 );
79
80 has collapse_aliases => (
81   is => 'ro',
82   default => sub { 0 }
83 );
84
85 has always_quote => (
86   is => 'rw', default => sub { 1 },
87   trigger => sub {
88     $_[0]->clear_renderer;
89     $_[0]->clear_converter;
90   },
91 );
92
93 has convert => (is => 'ro');
94
95 has array_datatypes => (is => 'ro');
96
97 has converter_class => (
98   is => 'rw', lazy => 1, builder => '_build_converter_class',
99   trigger => sub { shift->clear_converter },
100 );
101
102 sub _build_converter_class {
103   use_module('SQL::Abstract::Converter')
104 }
105
106 has renderer_class => (
107   is => 'rw', lazy => 1, clearer => 1, builder => 1,
108   trigger => sub { shift->clear_renderer },
109 );
110
111 after clear_renderer_class => sub { shift->clear_renderer };
112
113 sub _build_renderer_class {
114   my ($self) = @_;
115   my ($class, @roles) = (
116     $self->_build_base_renderer_class, $self->_build_renderer_roles
117   );
118   return $class unless @roles;
119   return use_module('Moo::Role')->create_class_with_roles($class, @roles);
120 }
121
122 sub _build_base_renderer_class {
123   use_module('Data::Query::Renderer::SQL::Naive')
124 }
125
126 sub _build_renderer_roles { () }
127
128 sub _converter_args {
129   my ($self) = @_;
130   Scalar::Util::weaken($self);
131   +{
132     lower_case => $self->case,
133     default_logic => $self->logic,
134     bind_meta => not($self->bindtype eq 'normal'),
135     identifier_sep => $self->name_sep,
136     (map +($_ => $self->$_), qw(
137       cmp sqltrue sqlfalse injection_guard convert array_datatypes
138     )),
139     special_ops => [
140       map {
141         my $sub = $_->{handler};
142         +{
143           %$_,
144           handler => sub { $self->$sub(@_) }
145         }
146       } @{$self->special_ops}
147     ],
148     renderer_will_quote => (
149       defined($self->quote_char) and $self->always_quote
150     ),
151   }
152 }
153
154 sub _build_converter {
155   my ($self) = @_;
156   $self->converter_class->new($self->_converter_args);
157 }
158
159 sub _renderer_args {
160   my ($self) = @_;
161   my ($chars);
162   for ($self->quote_char) {
163     $chars = defined() ? (ref() ? $_ : [$_]) : ['',''];
164   }
165   +{
166     quote_chars => $chars, always_quote => $self->always_quote,
167     identifier_sep => $self->name_sep,
168     collapse_aliases => $self->collapse_aliases,
169     ($self->case ? (lc_keywords => 1) : ()), # always 'lower' if it exists
170   };
171 }
172
173 sub _build_renderer {
174   my ($self) = @_;
175   $self->renderer_class->new($self->_renderer_args);
176 }
177
178 sub _render_dq {
179   my ($self, $dq) = @_;
180   if (!$dq) {
181     return '';
182   }
183   my ($sql, @bind) = @{$self->renderer->render($dq)};
184   wantarray ?
185     ($self->{bindtype} eq 'normal'
186       ? ($sql, map $_->{value}, @bind)
187       : ($sql, map [ $_->{value_meta}, $_->{value} ], @bind)
188     )
189     : $sql;
190 }
191
192 sub _render_sqla {
193   my ($self, $type, @args) = @_;
194   $self->_render_dq($self->converter->${\"_${type}_to_dq"}(@args));
195 }
196
197 sub insert { shift->_render_sqla(insert => @_) }
198
199 sub update { shift->_render_sqla(update => @_) }
200
201 sub select { shift->_render_sqla(select => @_) }
202
203 sub delete { shift->_render_sqla(delete => @_) }
204
205 sub where {
206   my ($self, $where, $order) = @_;
207
208   my $sql = '';
209   my @bind;
210
211   # where ?
212   ($sql, @bind) = $self->_recurse_where($where) if defined($where);
213   $sql = $sql ? $self->_sqlcase(' where ') . "( $sql )" : '';
214
215   # order by?
216   if ($order) {
217     $sql .= $self->_order_by($order);
218   }
219
220   return wantarray ? ($sql, @bind) : $sql;
221 }
222
223 sub _recurse_where { shift->_render_sqla(where => @_) }
224
225 sub _order_by {
226   my ($self, $arg) = @_;
227   if (my $dq = $self->converter->_order_by_to_dq($arg)) {
228     # SQLA generates ' ORDER BY foo'. The hilarity.
229     wantarray
230       ? do { my @r = $self->_render_dq($dq); $r[0] = ' '.$r[0]; @r }
231       : ' '.$self->_render_dq($dq);
232   } else {
233     '';
234   }
235 }
236
237 # highly optimized, as it's called way too often
238 sub _quote {
239   # my ($self, $label) = @_;
240
241   return '' unless defined $_[1];
242   return ${$_[1]} if ref($_[1]) eq 'SCALAR';
243
244   unless ($_[0]->{quote_char}) {
245     $_[0]->_assert_pass_injection_guard($_[1]);
246     return $_[1];
247   }
248
249   my $qref = ref $_[0]->{quote_char};
250   my ($l, $r);
251   if (!$qref) {
252     ($l, $r) = ( $_[0]->{quote_char}, $_[0]->{quote_char} );
253   }
254   elsif ($qref eq 'ARRAY') {
255     ($l, $r) = @{$_[0]->{quote_char}};
256   }
257   else {
258     puke "Unsupported quote_char format: $_[0]->{quote_char}";
259   }
260
261   # parts containing * are naturally unquoted
262   return join( $_[0]->{name_sep}||'', map
263     { $_ eq '*' ? $_ : $l . $_ . $r }
264     ( $_[0]->{name_sep} ? split (/\Q$_[0]->{name_sep}\E/, $_[1] ) : $_[1] )
265   );
266 }
267
268 sub _assert_pass_injection_guard {
269   if ($_[1] =~ $_[0]->{injection_guard}) {
270     my $class = ref $_[0];
271     die "Possible SQL injection attempt '$_[1]'. If this is indeed a part of "
272       . "the desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply "
273       . "your own {injection_guard} attribute to ${class}->new()"
274   }
275 }
276
277 # Conversion, if applicable
278 sub _convert ($) {
279   #my ($self, $arg) = @_;
280   if ($_[0]->{convert}) {
281     return $_[0]->_sqlcase($_[0]->{convert}) .'(' . $_[1] . ')';
282   }
283   return $_[1];
284 }
285
286 # And bindtype
287 sub _bindtype (@) {
288   #my ($self, $col, @vals) = @_;
289   # called often - tighten code
290   return $_[0]->{bindtype} eq 'columns'
291     ? map {[$_[1], $_]} @_[2 .. $#_]
292     : @_[2 .. $#_]
293   ;
294 }
295
296 # Dies if any element of @bind is not in [colname => value] format
297 # if bindtype is 'columns'.
298 sub _assert_bindval_matches_bindtype {
299 #  my ($self, @bind) = @_;
300   my $self = shift;
301   if ($self->{bindtype} eq 'columns') {
302     for (@_) {
303       if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
304         puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
305       }
306     }
307   }
308 }
309
310 # Fix SQL case, if so requested
311 sub _sqlcase {
312   # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
313   # don't touch the argument ... crooked logic, but let's not change it!
314   return $_[0]->{case} ? $_[1] : uc($_[1]);
315 }
316
317 sub values {
318     my $self = shift;
319     my $data = shift || return;
320     puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
321         unless ref $data eq 'HASH';
322
323     my @all_bind;
324     foreach my $k ( sort keys %$data ) {
325         my $v = $data->{$k};
326         local our $Cur_Col_Meta = $k;
327         my ($sql, @bind) = $self->_render_sqla(
328             mutation_rhs => $v
329         );
330         push @all_bind, @bind;
331     }
332
333     return @all_bind;
334 }
335
336 sub generate {
337     my $self  = shift;
338
339     my(@sql, @sqlq, @sqlv);
340
341     for (@_) {
342         my $ref = ref $_;
343         if ($ref eq 'HASH') {
344             for my $k (sort keys %$_) {
345                 my $v = $_->{$k};
346                 my $r = ref $v;
347                 my $label = $self->_quote($k);
348                 if ($r eq 'ARRAY') {
349                     # literal SQL with bind
350                     my ($sql, @bind) = @$v;
351                     $self->_assert_bindval_matches_bindtype(@bind);
352                     push @sqlq, "$label = $sql";
353                     push @sqlv, @bind;
354                 } elsif ($r eq 'SCALAR') {
355                     # literal SQL without bind
356                     push @sqlq, "$label = $$v";
357                 } else {
358                     push @sqlq, "$label = ?";
359                     push @sqlv, $self->_bindtype($k, $v);
360                 }
361             }
362             push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
363         } elsif ($ref eq 'ARRAY') {
364             # unlike insert(), assume these are ONLY the column names, i.e. for SQL
365             for my $v (@$_) {
366                 my $r = ref $v;
367                 if ($r eq 'ARRAY') {   # literal SQL with bind
368                     my ($sql, @bind) = @$v;
369                     $self->_assert_bindval_matches_bindtype(@bind);
370                     push @sqlq, $sql;
371                     push @sqlv, @bind;
372                 } elsif ($r eq 'SCALAR') {  # literal SQL without bind
373                     # embedded literal SQL
374                     push @sqlq, $$v;
375                 } else {
376                     push @sqlq, '?';
377                     push @sqlv, $v;
378                 }
379             }
380             push @sql, '(' . join(', ', @sqlq) . ')';
381         } elsif ($ref eq 'SCALAR') {
382             # literal SQL
383             push @sql, $$_;
384         } else {
385             # strings get case twiddled
386             push @sql, $self->_sqlcase($_);
387         }
388     }
389
390     my $sql = join ' ', @sql;
391
392     # this is pretty tricky
393     # if ask for an array, return ($stmt, @bind)
394     # otherwise, s/?/shift @sqlv/ to put it inline
395     if (wantarray) {
396         return ($sql, @sqlv);
397     } else {
398         1 while $sql =~ s/\?/my $d = shift(@sqlv);
399                              ref $d ? $d->[1] : $d/e;
400         return $sql;
401     }
402 }
403
404 1;
405
406
407 __END__
408
409 =head1 NAME
410
411 SQL::Abstract - Generate SQL from Perl data structures
412
413 =head1 SYNOPSIS
414
415     use SQL::Abstract;
416
417     my $sql = SQL::Abstract->new;
418
419     my($stmt, @bind) = $sql->select($source, \@fields, \%where, \@order);
420
421     my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
422
423     my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
424
425     my($stmt, @bind) = $sql->delete($table, \%where);
426
427     # Then, use these in your DBI statements
428     my $sth = $dbh->prepare($stmt);
429     $sth->execute(@bind);
430
431     # Just generate the WHERE clause
432     my($stmt, @bind) = $sql->where(\%where, \@order);
433
434     # Return values in the same order, for hashed queries
435     # See PERFORMANCE section for more details
436     my @bind = $sql->values(\%fieldvals);
437
438 =head1 DESCRIPTION
439
440 This module was inspired by the excellent L<DBIx::Abstract>.
441 However, in using that module I found that what I really wanted
442 to do was generate SQL, but still retain complete control over my
443 statement handles and use the DBI interface. So, I set out to
444 create an abstract SQL generation module.
445
446 While based on the concepts used by L<DBIx::Abstract>, there are
447 several important differences, especially when it comes to WHERE
448 clauses. I have modified the concepts used to make the SQL easier
449 to generate from Perl data structures and, IMO, more intuitive.
450 The underlying idea is for this module to do what you mean, based
451 on the data structures you provide it. The big advantage is that
452 you don't have to modify your code every time your data changes,
453 as this module figures it out.
454
455 To begin with, an SQL INSERT is as easy as just specifying a hash
456 of C<key=value> pairs:
457
458     my %data = (
459         name => 'Jimbo Bobson',
460         phone => '123-456-7890',
461         address => '42 Sister Lane',
462         city => 'St. Louis',
463         state => 'Louisiana',
464     );
465
466 The SQL can then be generated with this:
467
468     my($stmt, @bind) = $sql->insert('people', \%data);
469
470 Which would give you something like this:
471
472     $stmt = "INSERT INTO people
473                     (address, city, name, phone, state)
474                     VALUES (?, ?, ?, ?, ?)";
475     @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
476              '123-456-7890', 'Louisiana');
477
478 These are then used directly in your DBI code:
479
480     my $sth = $dbh->prepare($stmt);
481     $sth->execute(@bind);
482
483 =head2 Inserting and Updating Arrays
484
485 If your database has array types (like for example Postgres),
486 activate the special option C<< array_datatypes => 1 >>
487 when creating the C<SQL::Abstract> object.
488 Then you may use an arrayref to insert and update database array types:
489
490     my $sql = SQL::Abstract->new(array_datatypes => 1);
491     my %data = (
492         planets => [qw/Mercury Venus Earth Mars/]
493     );
494
495     my($stmt, @bind) = $sql->insert('solar_system', \%data);
496
497 This results in:
498
499     $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
500
501     @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
502
503
504 =head2 Inserting and Updating SQL
505
506 In order to apply SQL functions to elements of your C<%data> you may
507 specify a reference to an arrayref for the given hash value. For example,
508 if you need to execute the Oracle C<to_date> function on a value, you can
509 say something like this:
510
511     my %data = (
512         name => 'Bill',
513         date_entered => \["to_date(?,'MM/DD/YYYY')", "03/02/2003"],
514     );
515
516 The first value in the array is the actual SQL. Any other values are
517 optional and would be included in the bind values array. This gives
518 you:
519
520     my($stmt, @bind) = $sql->insert('people', \%data);
521
522     $stmt = "INSERT INTO people (name, date_entered)
523                 VALUES (?, to_date(?,'MM/DD/YYYY'))";
524     @bind = ('Bill', '03/02/2003');
525
526 An UPDATE is just as easy, all you change is the name of the function:
527
528     my($stmt, @bind) = $sql->update('people', \%data);
529
530 Notice that your C<%data> isn't touched; the module will generate
531 the appropriately quirky SQL for you automatically. Usually you'll
532 want to specify a WHERE clause for your UPDATE, though, which is
533 where handling C<%where> hashes comes in handy...
534
535 =head2 Complex where statements
536
537 This module can generate pretty complicated WHERE statements
538 easily. For example, simple C<key=value> pairs are taken to mean
539 equality, and if you want to see if a field is within a set
540 of values, you can use an arrayref. Let's say we wanted to
541 SELECT some data based on this criteria:
542
543     my %where = (
544        requestor => 'inna',
545        worker => ['nwiger', 'rcwe', 'sfz'],
546        status => { '!=', 'completed' }
547     );
548
549     my($stmt, @bind) = $sql->select('tickets', '*', \%where);
550
551 The above would give you something like this:
552
553     $stmt = "SELECT * FROM tickets WHERE
554                 ( requestor = ? ) AND ( status != ? )
555                 AND ( worker = ? OR worker = ? OR worker = ? )";
556     @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
557
558 Which you could then use in DBI code like so:
559
560     my $sth = $dbh->prepare($stmt);
561     $sth->execute(@bind);
562
563 Easy, eh?
564
565 =head1 FUNCTIONS
566
567 The functions are simple. There's one for each major SQL operation,
568 and a constructor you use first. The arguments are specified in a
569 similar order to each function (table, then fields, then a where
570 clause) to try and simplify things.
571
572
573
574
575 =head2 new(option => 'value')
576
577 The C<new()> function takes a list of options and values, and returns
578 a new B<SQL::Abstract> object which can then be used to generate SQL
579 through the methods below. The options accepted are:
580
581 =over
582
583 =item case
584
585 If set to 'lower', then SQL will be generated in all lowercase. By
586 default SQL is generated in "textbook" case meaning something like:
587
588     SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
589
590 Any setting other than 'lower' is ignored.
591
592 =item cmp
593
594 This determines what the default comparison operator is. By default
595 it is C<=>, meaning that a hash like this:
596
597     %where = (name => 'nwiger', email => 'nate@wiger.org');
598
599 Will generate SQL like this:
600
601     WHERE name = 'nwiger' AND email = 'nate@wiger.org'
602
603 However, you may want loose comparisons by default, so if you set
604 C<cmp> to C<like> you would get SQL such as:
605
606     WHERE name like 'nwiger' AND email like 'nate@wiger.org'
607
608 You can also override the comparison on an individual basis - see
609 the huge section on L</"WHERE CLAUSES"> at the bottom.
610
611 =item sqltrue, sqlfalse
612
613 Expressions for inserting boolean values within SQL statements.
614 By default these are C<1=1> and C<1=0>. They are used
615 by the special operators C<-in> and C<-not_in> for generating
616 correct SQL even when the argument is an empty array (see below).
617
618 =item logic
619
620 This determines the default logical operator for multiple WHERE
621 statements in arrays or hashes. If absent, the default logic is "or"
622 for arrays, and "and" for hashes. This means that a WHERE
623 array of the form:
624
625     @where = (
626         event_date => {'>=', '2/13/99'},
627         event_date => {'<=', '4/24/03'},
628     );
629
630 will generate SQL like this:
631
632     WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
633
634 This is probably not what you want given this query, though (look
635 at the dates). To change the "OR" to an "AND", simply specify:
636
637     my $sql = SQL::Abstract->new(logic => 'and');
638
639 Which will change the above C<WHERE> to:
640
641     WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
642
643 The logic can also be changed locally by inserting
644 a modifier in front of an arrayref :
645
646     @where = (-and => [event_date => {'>=', '2/13/99'},
647                        event_date => {'<=', '4/24/03'} ]);
648
649 See the L</"WHERE CLAUSES"> section for explanations.
650
651 =item convert
652
653 This will automatically convert comparisons using the specified SQL
654 function for both column and value. This is mostly used with an argument
655 of C<upper> or C<lower>, so that the SQL will have the effect of
656 case-insensitive "searches". For example, this:
657
658     $sql = SQL::Abstract->new(convert => 'upper');
659     %where = (keywords => 'MaKe iT CAse inSeNSItive');
660
661 Will turn out the following SQL:
662
663     WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
664
665 The conversion can be C<upper()>, C<lower()>, or any other SQL function
666 that can be applied symmetrically to fields (actually B<SQL::Abstract> does
667 not validate this option; it will just pass through what you specify verbatim).
668
669 =item bindtype
670
671 This is a kludge because many databases suck. For example, you can't
672 just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
673 Instead, you have to use C<bind_param()>:
674
675     $sth->bind_param(1, 'reg data');
676     $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
677
678 The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
679 which loses track of which field each slot refers to. Fear not.
680
681 If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
682 Currently, you can specify either C<normal> (default) or C<columns>. If you
683 specify C<columns>, you will get an array that looks like this:
684
685     my $sql = SQL::Abstract->new(bindtype => 'columns');
686     my($stmt, @bind) = $sql->insert(...);
687
688     @bind = (
689         [ 'column1', 'value1' ],
690         [ 'column2', 'value2' ],
691         [ 'column3', 'value3' ],
692     );
693
694 You can then iterate through this manually, using DBI's C<bind_param()>.
695
696     $sth->prepare($stmt);
697     my $i = 1;
698     for (@bind) {
699         my($col, $data) = @$_;
700         if ($col eq 'details' || $col eq 'comments') {
701             $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
702         } elsif ($col eq 'image') {
703             $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
704         } else {
705             $sth->bind_param($i, $data);
706         }
707         $i++;
708     }
709     $sth->execute;      # execute without @bind now
710
711 Now, why would you still use B<SQL::Abstract> if you have to do this crap?
712 Basically, the advantage is still that you don't have to care which fields
713 are or are not included. You could wrap that above C<for> loop in a simple
714 sub called C<bind_fields()> or something and reuse it repeatedly. You still
715 get a layer of abstraction over manual SQL specification.
716
717 Note that if you set L</bindtype> to C<columns>, the C<\[$sql, @bind]>
718 construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
719 will expect the bind values in this format.
720
721 =item quote_char
722
723 This is the character that a table or column name will be quoted
724 with.  By default this is an empty string, but you could set it to
725 the character C<`>, to generate SQL like this:
726
727   SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
728
729 Alternatively, you can supply an array ref of two items, the first being the left
730 hand quote character, and the second the right hand quote character. For
731 example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
732 that generates SQL like this:
733
734   SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
735
736 Quoting is useful if you have tables or columns names that are reserved
737 words in your database's SQL dialect.
738
739 =item name_sep
740
741 This is the character that separates a table and column name.  It is
742 necessary to specify this when the C<quote_char> option is selected,
743 so that tables and column names can be individually quoted like this:
744
745   SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
746
747 =item injection_guard
748
749 A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
750 column name specified in a query structure. This is a safety mechanism to avoid
751 injection attacks when mishandling user input e.g.:
752
753   my %condition_as_column_value_pairs = get_values_from_user();
754   $sqla->select( ... , \%condition_as_column_value_pairs );
755
756 If the expression matches an exception is thrown. Note that literal SQL
757 supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
758
759 Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
760
761 =item array_datatypes
762
763 When this option is true, arrayrefs in INSERT or UPDATE are
764 interpreted as array datatypes and are passed directly
765 to the DBI layer.
766 When this option is false, arrayrefs are interpreted
767 as literal SQL, just like refs to arrayrefs
768 (but this behavior is for backwards compatibility; when writing
769 new queries, use the "reference to arrayref" syntax
770 for literal SQL).
771
772
773 =item special_ops
774
775 Takes a reference to a list of "special operators"
776 to extend the syntax understood by L<SQL::Abstract>.
777 See section L</"SPECIAL OPERATORS"> for details.
778
779 =item unary_ops
780
781 Takes a reference to a list of "unary operators"
782 to extend the syntax understood by L<SQL::Abstract>.
783 See section L</"UNARY OPERATORS"> for details.
784
785
786
787 =back
788
789 =head2 insert($table, \@values || \%fieldvals, \%options)
790
791 This is the simplest function. You simply give it a table name
792 and either an arrayref of values or hashref of field/value pairs.
793 It returns an SQL INSERT statement and a list of bind values.
794 See the sections on L</"Inserting and Updating Arrays"> and
795 L</"Inserting and Updating SQL"> for information on how to insert
796 with those data types.
797
798 The optional C<\%options> hash reference may contain additional
799 options to generate the insert SQL. Currently supported options
800 are:
801
802 =over 4
803
804 =item returning
805
806 Takes either a scalar of raw SQL fields, or an array reference of
807 field names, and adds on an SQL C<RETURNING> statement at the end.
808 This allows you to return data generated by the insert statement
809 (such as row IDs) without performing another C<SELECT> statement.
810 Note, however, this is not part of the SQL standard and may not
811 be supported by all database engines.
812
813 =back
814
815 =head2 update($table, \%fieldvals, \%where)
816
817 This takes a table, hashref of field/value pairs, and an optional
818 hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
819 of bind values.
820 See the sections on L</"Inserting and Updating Arrays"> and
821 L</"Inserting and Updating SQL"> for information on how to insert
822 with those data types.
823
824 =head2 select($source, $fields, $where, $order)
825
826 This returns a SQL SELECT statement and associated list of bind values, as
827 specified by the arguments  :
828
829 =over
830
831 =item $source
832
833 Specification of the 'FROM' part of the statement.
834 The argument can be either a plain scalar (interpreted as a table
835 name, will be quoted), or an arrayref (interpreted as a list
836 of table names, joined by commas, quoted), or a scalarref
837 (literal table name, not quoted), or a ref to an arrayref
838 (list of literal table names, joined by commas, not quoted).
839
840 =item $fields
841
842 Specification of the list of fields to retrieve from
843 the source.
844 The argument can be either an arrayref (interpreted as a list
845 of field names, will be joined by commas and quoted), or a
846 plain scalar (literal SQL, not quoted).
847 Please observe that this API is not as flexible as that of
848 the first argument C<$source>, for backwards compatibility reasons.
849
850 =item $where
851
852 Optional argument to specify the WHERE part of the query.
853 The argument is most often a hashref, but can also be
854 an arrayref or plain scalar --
855 see section L<WHERE clause|/"WHERE CLAUSES"> for details.
856
857 =item $order
858
859 Optional argument to specify the ORDER BY part of the query.
860 The argument can be a scalar, a hashref or an arrayref
861 -- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
862 for details.
863
864 =back
865
866
867 =head2 delete($table, \%where)
868
869 This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
870 It returns an SQL DELETE statement and list of bind values.
871
872 =head2 where(\%where, \@order)
873
874 This is used to generate just the WHERE clause. For example,
875 if you have an arbitrary data structure and know what the
876 rest of your SQL is going to look like, but want an easy way
877 to produce a WHERE clause, use this. It returns an SQL WHERE
878 clause and list of bind values.
879
880
881 =head2 values(\%data)
882
883 This just returns the values from the hash C<%data>, in the same
884 order that would be returned from any of the other above queries.
885 Using this allows you to markedly speed up your queries if you
886 are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
887
888 =head2 generate($any, 'number', $of, \@data, $struct, \%types)
889
890 Warning: This is an experimental method and subject to change.
891
892 This returns arbitrarily generated SQL. It's a really basic shortcut.
893 It will return two different things, depending on return context:
894
895     my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
896     my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
897
898 These would return the following:
899
900     # First calling form
901     $stmt = "CREATE TABLE test (?, ?)";
902     @bind = (field1, field2);
903
904     # Second calling form
905     $stmt_and_val = "CREATE TABLE test (field1, field2)";
906
907 Depending on what you're trying to do, it's up to you to choose the correct
908 format. In this example, the second form is what you would want.
909
910 By the same token:
911
912     $sql->generate('alter session', { nls_date_format => 'MM/YY' });
913
914 Might give you:
915
916     ALTER SESSION SET nls_date_format = 'MM/YY'
917
918 You get the idea. Strings get their case twiddled, but everything
919 else remains verbatim.
920
921 =head1 WHERE CLAUSES
922
923 =head2 Introduction
924
925 This module uses a variation on the idea from L<DBIx::Abstract>. It
926 is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
927 module is that things in arrays are OR'ed, and things in hashes
928 are AND'ed.>
929
930 The easiest way to explain is to show lots of examples. After
931 each C<%where> hash shown, it is assumed you used:
932
933     my($stmt, @bind) = $sql->where(\%where);
934
935 However, note that the C<%where> hash can be used directly in any
936 of the other functions as well, as described above.
937
938 =head2 Key-value pairs
939
940 So, let's get started. To begin, a simple hash:
941
942     my %where  = (
943         user   => 'nwiger',
944         status => 'completed'
945     );
946
947 Is converted to SQL C<key = val> statements:
948
949     $stmt = "WHERE user = ? AND status = ?";
950     @bind = ('nwiger', 'completed');
951
952 One common thing I end up doing is having a list of values that
953 a field can be in. To do this, simply specify a list inside of
954 an arrayref:
955
956     my %where  = (
957         user   => 'nwiger',
958         status => ['assigned', 'in-progress', 'pending'];
959     );
960
961 This simple code will create the following:
962
963     $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
964     @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
965
966 A field associated to an empty arrayref will be considered a
967 logical false and will generate 0=1.
968
969 =head2 Tests for NULL values
970
971 If the value part is C<undef> then this is converted to SQL <IS NULL>
972
973     my %where  = (
974         user   => 'nwiger',
975         status => undef,
976     );
977
978 becomes:
979
980     $stmt = "WHERE user = ? AND status IS NULL";
981     @bind = ('nwiger');
982
983 To test if a column IS NOT NULL:
984
985     my %where  = (
986         user   => 'nwiger',
987         status => { '!=', undef },
988     );
989
990 =head2 Specific comparison operators
991
992 If you want to specify a different type of operator for your comparison,
993 you can use a hashref for a given column:
994
995     my %where  = (
996         user   => 'nwiger',
997         status => { '!=', 'completed' }
998     );
999
1000 Which would generate:
1001
1002     $stmt = "WHERE user = ? AND status != ?";
1003     @bind = ('nwiger', 'completed');
1004
1005 To test against multiple values, just enclose the values in an arrayref:
1006
1007     status => { '=', ['assigned', 'in-progress', 'pending'] };
1008
1009 Which would give you:
1010
1011     "WHERE status = ? OR status = ? OR status = ?"
1012
1013
1014 The hashref can also contain multiple pairs, in which case it is expanded
1015 into an C<AND> of its elements:
1016
1017     my %where  = (
1018         user   => 'nwiger',
1019         status => { '!=', 'completed', -not_like => 'pending%' }
1020     );
1021
1022     # Or more dynamically, like from a form
1023     $where{user} = 'nwiger';
1024     $where{status}{'!='} = 'completed';
1025     $where{status}{'-not_like'} = 'pending%';
1026
1027     # Both generate this
1028     $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
1029     @bind = ('nwiger', 'completed', 'pending%');
1030
1031
1032 To get an OR instead, you can combine it with the arrayref idea:
1033
1034     my %where => (
1035          user => 'nwiger',
1036          priority => [ { '=', 2 }, { '>', 5 } ]
1037     );
1038
1039 Which would generate:
1040
1041     $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
1042     @bind = ('2', '5', 'nwiger');
1043
1044 If you want to include literal SQL (with or without bind values), just use a
1045 scalar reference or array reference as the value:
1046
1047     my %where  = (
1048         date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
1049         date_expires => { '<' => \"now()" }
1050     );
1051
1052 Which would generate:
1053
1054     $stmt = "WHERE date_entered > "to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
1055     @bind = ('11/26/2008');
1056
1057
1058 =head2 Logic and nesting operators
1059
1060 In the example above,
1061 there is a subtle trap if you want to say something like
1062 this (notice the C<AND>):
1063
1064     WHERE priority != ? AND priority != ?
1065
1066 Because, in Perl you I<can't> do this:
1067
1068     priority => { '!=', 2, '!=', 1 }
1069
1070 As the second C<!=> key will obliterate the first. The solution
1071 is to use the special C<-modifier> form inside an arrayref:
1072
1073     priority => [ -and => {'!=', 2},
1074                           {'!=', 1} ]
1075
1076
1077 Normally, these would be joined by C<OR>, but the modifier tells it
1078 to use C<AND> instead. (Hint: You can use this in conjunction with the
1079 C<logic> option to C<new()> in order to change the way your queries
1080 work by default.) B<Important:> Note that the C<-modifier> goes
1081 B<INSIDE> the arrayref, as an extra first element. This will
1082 B<NOT> do what you think it might:
1083
1084     priority => -and => [{'!=', 2}, {'!=', 1}]   # WRONG!
1085
1086 Here is a quick list of equivalencies, since there is some overlap:
1087
1088     # Same
1089     status => {'!=', 'completed', 'not like', 'pending%' }
1090     status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
1091
1092     # Same
1093     status => {'=', ['assigned', 'in-progress']}
1094     status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
1095     status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
1096
1097
1098
1099 =head2 Special operators : IN, BETWEEN, etc.
1100
1101 You can also use the hashref format to compare a list of fields using the
1102 C<IN> comparison operator, by specifying the list as an arrayref:
1103
1104     my %where  = (
1105         status   => 'completed',
1106         reportid => { -in => [567, 2335, 2] }
1107     );
1108
1109 Which would generate:
1110
1111     $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
1112     @bind = ('completed', '567', '2335', '2');
1113
1114 The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
1115 the same way.
1116
1117 If the argument to C<-in> is an empty array, 'sqlfalse' is generated
1118 (by default : C<1=0>). Similarly, C<< -not_in => [] >> generates
1119 'sqltrue' (by default : C<1=1>).
1120
1121 In addition to the array you can supply a chunk of literal sql or
1122 literal sql with bind:
1123
1124     my %where = {
1125       customer => { -in => \[
1126         'SELECT cust_id FROM cust WHERE balance > ?',
1127         2000,
1128       ],
1129       status => { -in => \'SELECT status_codes FROM states' },
1130     };
1131
1132 would generate:
1133
1134     $stmt = "WHERE (
1135           customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
1136       AND status IN ( SELECT status_codes FROM states )
1137     )";
1138     @bind = ('2000');
1139
1140 Finally, if the argument to C<-in> is not a reference, it will be
1141 treated as a single-element array.
1142
1143 Another pair of operators is C<-between> and C<-not_between>,
1144 used with an arrayref of two values:
1145
1146     my %where  = (
1147         user   => 'nwiger',
1148         completion_date => {
1149            -not_between => ['2002-10-01', '2003-02-06']
1150         }
1151     );
1152
1153 Would give you:
1154
1155     WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
1156
1157 Just like with C<-in> all plausible combinations of literal SQL
1158 are possible:
1159
1160     my %where = {
1161       start0 => { -between => [ 1, 2 ] },
1162       start1 => { -between => \["? AND ?", 1, 2] },
1163       start2 => { -between => \"lower(x) AND upper(y)" },
1164       start3 => { -between => [
1165         \"lower(x)",
1166         \["upper(?)", 'stuff' ],
1167       ] },
1168     };
1169
1170 Would give you:
1171
1172     $stmt = "WHERE (
1173           ( start0 BETWEEN ? AND ?                )
1174       AND ( start1 BETWEEN ? AND ?                )
1175       AND ( start2 BETWEEN lower(x) AND upper(y)  )
1176       AND ( start3 BETWEEN lower(x) AND upper(?)  )
1177     )";
1178     @bind = (1, 2, 1, 2, 'stuff');
1179
1180
1181 These are the two builtin "special operators"; but the
1182 list can be expanded : see section L</"SPECIAL OPERATORS"> below.
1183
1184 =head2 Unary operators: bool
1185
1186 If you wish to test against boolean columns or functions within your
1187 database you can use the C<-bool> and C<-not_bool> operators. For
1188 example to test the column C<is_user> being true and the column
1189 C<is_enabled> being false you would use:-
1190
1191     my %where  = (
1192         -bool       => 'is_user',
1193         -not_bool   => 'is_enabled',
1194     );
1195
1196 Would give you:
1197
1198     WHERE is_user AND NOT is_enabled
1199
1200 If a more complex combination is required, testing more conditions,
1201 then you should use the and/or operators:-
1202
1203     my %where  = (
1204         -and           => [
1205             -bool      => 'one',
1206             -not_bool  => { two=> { -rlike => 'bar' } },
1207             -not_bool  => { three => [ { '=', 2 }, { '>', 5 } ] },
1208         ],
1209     );
1210
1211 Would give you:
1212
1213     WHERE
1214       one
1215         AND
1216       (NOT two RLIKE ?)
1217         AND
1218       (NOT ( three = ? OR three > ? ))
1219
1220
1221 =head2 Nested conditions, -and/-or prefixes
1222
1223 So far, we've seen how multiple conditions are joined with a top-level
1224 C<AND>.  We can change this by putting the different conditions we want in
1225 hashes and then putting those hashes in an array. For example:
1226
1227     my @where = (
1228         {
1229             user   => 'nwiger',
1230             status => { -like => ['pending%', 'dispatched'] },
1231         },
1232         {
1233             user   => 'robot',
1234             status => 'unassigned',
1235         }
1236     );
1237
1238 This data structure would create the following:
1239
1240     $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
1241                 OR ( user = ? AND status = ? ) )";
1242     @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
1243
1244
1245 Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
1246 to change the logic inside :
1247
1248     my @where = (
1249          -and => [
1250             user => 'nwiger',
1251             [
1252                 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
1253                 -or => { workhrs => {'<', 50}, geo => 'EURO' },
1254             ],
1255         ],
1256     );
1257
1258 That would yield:
1259
1260     WHERE ( user = ? AND (
1261                ( workhrs > ? AND geo = ? )
1262             OR ( workhrs < ? OR geo = ? )
1263           ) )
1264
1265 =head3 Algebraic inconsistency, for historical reasons
1266
1267 C<Important note>: when connecting several conditions, the C<-and->|C<-or>
1268 operator goes C<outside> of the nested structure; whereas when connecting
1269 several constraints on one column, the C<-and> operator goes
1270 C<inside> the arrayref. Here is an example combining both features :
1271
1272    my @where = (
1273      -and => [a => 1, b => 2],
1274      -or  => [c => 3, d => 4],
1275       e   => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
1276    )
1277
1278 yielding
1279
1280   WHERE ( (    ( a = ? AND b = ? )
1281             OR ( c = ? OR d = ? )
1282             OR ( e LIKE ? AND e LIKE ? ) ) )
1283
1284 This difference in syntax is unfortunate but must be preserved for
1285 historical reasons. So be careful : the two examples below would
1286 seem algebraically equivalent, but they are not
1287
1288   {col => [-and => {-like => 'foo%'}, {-like => '%bar'}]}
1289   # yields : WHERE ( ( col LIKE ? AND col LIKE ? ) )
1290
1291   [-and => {col => {-like => 'foo%'}, {col => {-like => '%bar'}}]]
1292   # yields : WHERE ( ( col LIKE ? OR col LIKE ? ) )
1293
1294
1295 =head2 Literal SQL and value type operators
1296
1297 The basic premise of SQL::Abstract is that in WHERE specifications the "left
1298 side" is a column name and the "right side" is a value (normally rendered as
1299 a placeholder). This holds true for both hashrefs and arrayref pairs as you
1300 see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
1301 alter this behavior. There are several ways of doing so.
1302
1303 =head3 -ident
1304
1305 This is a virtual operator that signals the string to its right side is an
1306 identifier (a column name) and not a value. For example to compare two
1307 columns you would write:
1308
1309     my %where = (
1310         priority => { '<', 2 },
1311         requestor => { -ident => 'submitter' },
1312     );
1313
1314 which creates:
1315
1316     $stmt = "WHERE priority < ? AND requestor = submitter";
1317     @bind = ('2');
1318
1319 If you are maintaining legacy code you may see a different construct as
1320 described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
1321 code.
1322
1323 =head3 -value
1324
1325 This is a virtual operator that signals that the construct to its right side
1326 is a value to be passed to DBI. This is for example necessary when you want
1327 to write a where clause against an array (for RDBMS that support such
1328 datatypes). For example:
1329
1330     my %where = (
1331         array => { -value => [1, 2, 3] }
1332     );
1333
1334 will result in:
1335
1336     $stmt = 'WHERE array = ?';
1337     @bind = ([1, 2, 3]);
1338
1339 Note that if you were to simply say:
1340
1341     my %where = (
1342         array => [1, 2, 3]
1343     );
1344
1345 the result would probably not be what you wanted:
1346
1347     $stmt = 'WHERE array = ? OR array = ? OR array = ?';
1348     @bind = (1, 2, 3);
1349
1350 =head3 Literal SQL
1351
1352 Finally, sometimes only literal SQL will do. To include a random snippet
1353 of SQL verbatim, you specify it as a scalar reference. Consider this only
1354 as a last resort. Usually there is a better way. For example:
1355
1356     my %where = (
1357         priority => { '<', 2 },
1358         requestor => { -in => \'(SELECT name FROM hitmen)' },
1359     );
1360
1361 Would create:
1362
1363     $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
1364     @bind = (2);
1365
1366 Note that in this example, you only get one bind parameter back, since
1367 the verbatim SQL is passed as part of the statement.
1368
1369 =head4 CAVEAT
1370
1371   Never use untrusted input as a literal SQL argument - this is a massive
1372   security risk (there is no way to check literal snippets for SQL
1373   injections and other nastyness). If you need to deal with untrusted input
1374   use literal SQL with placeholders as described next.
1375
1376 =head3 Literal SQL with placeholders and bind values (subqueries)
1377
1378 If the literal SQL to be inserted has placeholders and bind values,
1379 use a reference to an arrayref (yes this is a double reference --
1380 not so common, but perfectly legal Perl). For example, to find a date
1381 in Postgres you can use something like this:
1382
1383     my %where = (
1384        date_column => \[q/= date '2008-09-30' - ?::integer/, 10/]
1385     )
1386
1387 This would create:
1388
1389     $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
1390     @bind = ('10');
1391
1392 Note that you must pass the bind values in the same format as they are returned
1393 by L</where>. That means that if you set L</bindtype> to C<columns>, you must
1394 provide the bind values in the C<< [ column_meta => value ] >> format, where
1395 C<column_meta> is an opaque scalar value; most commonly the column name, but
1396 you can use any scalar value (including references and blessed references),
1397 L<SQL::Abstract> will simply pass it through intact. So if C<bindtype> is set
1398 to C<columns> the above example will look like:
1399
1400     my %where = (
1401        date_column => \[q/= date '2008-09-30' - ?::integer/, [ dummy => 10 ]/]
1402     )
1403
1404 Literal SQL is especially useful for nesting parenthesized clauses in the
1405 main SQL query. Here is a first example :
1406
1407   my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
1408                                100, "foo%");
1409   my %where = (
1410     foo => 1234,
1411     bar => \["IN ($sub_stmt)" => @sub_bind],
1412   );
1413
1414 This yields :
1415
1416   $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
1417                                              WHERE c2 < ? AND c3 LIKE ?))";
1418   @bind = (1234, 100, "foo%");
1419
1420 Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
1421 are expressed in the same way. Of course the C<$sub_stmt> and
1422 its associated bind values can be generated through a former call
1423 to C<select()> :
1424
1425   my ($sub_stmt, @sub_bind)
1426      = $sql->select("t1", "c1", {c2 => {"<" => 100},
1427                                  c3 => {-like => "foo%"}});
1428   my %where = (
1429     foo => 1234,
1430     bar => \["> ALL ($sub_stmt)" => @sub_bind],
1431   );
1432
1433 In the examples above, the subquery was used as an operator on a column;
1434 but the same principle also applies for a clause within the main C<%where>
1435 hash, like an EXISTS subquery :
1436
1437   my ($sub_stmt, @sub_bind)
1438      = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
1439   my %where = ( -and => [
1440     foo   => 1234,
1441     \["EXISTS ($sub_stmt)" => @sub_bind],
1442   ]);
1443
1444 which yields
1445
1446   $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
1447                                         WHERE c1 = ? AND c2 > t0.c0))";
1448   @bind = (1234, 1);
1449
1450
1451 Observe that the condition on C<c2> in the subquery refers to
1452 column C<t0.c0> of the main query : this is I<not> a bind
1453 value, so we have to express it through a scalar ref.
1454 Writing C<< c2 => {">" => "t0.c0"} >> would have generated
1455 C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
1456 what we wanted here.
1457
1458 Finally, here is an example where a subquery is used
1459 for expressing unary negation:
1460
1461   my ($sub_stmt, @sub_bind)
1462      = $sql->where({age => [{"<" => 10}, {">" => 20}]});
1463   $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
1464   my %where = (
1465         lname  => {like => '%son%'},
1466         \["NOT ($sub_stmt)" => @sub_bind],
1467     );
1468
1469 This yields
1470
1471   $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
1472   @bind = ('%son%', 10, 20)
1473
1474 =head3 Deprecated usage of Literal SQL
1475
1476 Below are some examples of archaic use of literal SQL. It is shown only as
1477 reference for those who deal with legacy code. Each example has a much
1478 better, cleaner and safer alternative that users should opt for in new code.
1479
1480 =over
1481
1482 =item *
1483
1484     my %where = ( requestor => \'IS NOT NULL' )
1485
1486     $stmt = "WHERE requestor IS NOT NULL"
1487
1488 This used to be the way of generating NULL comparisons, before the handling
1489 of C<undef> got formalized. For new code please use the superior syntax as
1490 described in L</Tests for NULL values>.
1491
1492 =item *
1493
1494     my %where = ( requestor => \'= submitter' )
1495
1496     $stmt = "WHERE requestor = submitter"
1497
1498 This used to be the only way to compare columns. Use the superior L</-ident>
1499 method for all new code. For example an identifier declared in such a way
1500 will be properly quoted if L</quote_char> is properly set, while the legacy
1501 form will remain as supplied.
1502
1503 =item *
1504
1505     my %where = ( is_ready  => \"", completed => { '>', '2012-12-21' } )
1506
1507     $stmt = "WHERE completed > ? AND is_ready"
1508     @bind = ('2012-12-21')
1509
1510 Using an empty string literal used to be the only way to express a boolean.
1511 For all new code please use the much more readable
1512 L<-bool|/Unary operators: bool> operator.
1513
1514 =back
1515
1516 =head2 Conclusion
1517
1518 These pages could go on for a while, since the nesting of the data
1519 structures this module can handle are pretty much unlimited (the
1520 module implements the C<WHERE> expansion as a recursive function
1521 internally). Your best bet is to "play around" with the module a
1522 little to see how the data structures behave, and choose the best
1523 format for your data based on that.
1524
1525 And of course, all the values above will probably be replaced with
1526 variables gotten from forms or the command line. After all, if you
1527 knew everything ahead of time, you wouldn't have to worry about
1528 dynamically-generating SQL and could just hardwire it into your
1529 script.
1530
1531 =head1 ORDER BY CLAUSES
1532
1533 Some functions take an order by clause. This can either be a scalar (just a
1534 column name,) a hash of C<< { -desc => 'col' } >> or C<< { -asc => 'col' } >>,
1535 or an array of either of the two previous forms. Examples:
1536
1537                Given            |         Will Generate
1538     ----------------------------------------------------------
1539                                 |
1540     \'colA DESC'                | ORDER BY colA DESC
1541                                 |
1542     'colA'                      | ORDER BY colA
1543                                 |
1544     [qw/colA colB/]             | ORDER BY colA, colB
1545                                 |
1546     {-asc  => 'colA'}           | ORDER BY colA ASC
1547                                 |
1548     {-desc => 'colB'}           | ORDER BY colB DESC
1549                                 |
1550     ['colA', {-asc => 'colB'}]  | ORDER BY colA, colB ASC
1551                                 |
1552     { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
1553                                 |
1554     [                           |
1555       { -asc => 'colA' },       | ORDER BY colA ASC, colB DESC,
1556       { -desc => [qw/colB/],    |          colC ASC, colD ASC
1557       { -asc => [qw/colC colD/],|
1558     ]                           |
1559     ===========================================================
1560
1561
1562
1563 =head1 SPECIAL OPERATORS
1564
1565   my $sqlmaker = SQL::Abstract->new(special_ops => [
1566      {
1567       regex => qr/.../,
1568       handler => sub {
1569         my ($self, $field, $op, $arg) = @_;
1570         ...
1571       },
1572      },
1573      {
1574       regex => qr/.../,
1575       handler => 'method_name',
1576      },
1577    ]);
1578
1579 A "special operator" is a SQL syntactic clause that can be
1580 applied to a field, instead of a usual binary operator.
1581 For example :
1582
1583    WHERE field IN (?, ?, ?)
1584    WHERE field BETWEEN ? AND ?
1585    WHERE MATCH(field) AGAINST (?, ?)
1586
1587 Special operators IN and BETWEEN are fairly standard and therefore
1588 are builtin within C<SQL::Abstract> (as the overridable methods
1589 C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
1590 like the MATCH .. AGAINST example above which is specific to MySQL,
1591 you can write your own operator handlers - supply a C<special_ops>
1592 argument to the C<new> method. That argument takes an arrayref of
1593 operator definitions; each operator definition is a hashref with two
1594 entries:
1595
1596 =over
1597
1598 =item regex
1599
1600 the regular expression to match the operator
1601
1602 =item handler
1603
1604 Either a coderef or a plain scalar method name. In both cases
1605 the expected return is C<< ($sql, @bind) >>.
1606
1607 When supplied with a method name, it is simply called on the
1608 L<SQL::Abstract/> object as:
1609
1610  $self->$method_name ($field, $op, $arg)
1611
1612  Where:
1613
1614   $op is the part that matched the handler regex
1615   $field is the LHS of the operator
1616   $arg is the RHS
1617
1618 When supplied with a coderef, it is called as:
1619
1620  $coderef->($self, $field, $op, $arg)
1621
1622
1623 =back
1624
1625 For example, here is an implementation
1626 of the MATCH .. AGAINST syntax for MySQL
1627
1628   my $sqlmaker = SQL::Abstract->new(special_ops => [
1629
1630     # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
1631     {regex => qr/^match$/i,
1632      handler => sub {
1633        my ($self, $field, $op, $arg) = @_;
1634        $arg = [$arg] if not ref $arg;
1635        my $label         = $self->_quote($field);
1636        my ($placeholder) = $self->_convert('?');
1637        my $placeholders  = join ", ", (($placeholder) x @$arg);
1638        my $sql           = $self->_sqlcase('match') . " ($label) "
1639                          . $self->_sqlcase('against') . " ($placeholders) ";
1640        my @bind = $self->_bindtype($field, @$arg);
1641        return ($sql, @bind);
1642        }
1643      },
1644
1645   ]);
1646
1647
1648 =head1 UNARY OPERATORS
1649
1650   my $sqlmaker = SQL::Abstract->new(unary_ops => [
1651      {
1652       regex => qr/.../,
1653       handler => sub {
1654         my ($self, $op, $arg) = @_;
1655         ...
1656       },
1657      },
1658      {
1659       regex => qr/.../,
1660       handler => 'method_name',
1661      },
1662    ]);
1663
1664 A "unary operator" is a SQL syntactic clause that can be
1665 applied to a field - the operator goes before the field
1666
1667 You can write your own operator handlers - supply a C<unary_ops>
1668 argument to the C<new> method. That argument takes an arrayref of
1669 operator definitions; each operator definition is a hashref with two
1670 entries:
1671
1672 =over
1673
1674 =item regex
1675
1676 the regular expression to match the operator
1677
1678 =item handler
1679
1680 Either a coderef or a plain scalar method name. In both cases
1681 the expected return is C<< $sql >>.
1682
1683 When supplied with a method name, it is simply called on the
1684 L<SQL::Abstract/> object as:
1685
1686  $self->$method_name ($op, $arg)
1687
1688  Where:
1689
1690   $op is the part that matched the handler regex
1691   $arg is the RHS or argument of the operator
1692
1693 When supplied with a coderef, it is called as:
1694
1695  $coderef->($self, $op, $arg)
1696
1697
1698 =back
1699
1700
1701 =head1 PERFORMANCE
1702
1703 Thanks to some benchmarking by Mark Stosberg, it turns out that
1704 this module is many orders of magnitude faster than using C<DBIx::Abstract>.
1705 I must admit this wasn't an intentional design issue, but it's a
1706 byproduct of the fact that you get to control your C<DBI> handles
1707 yourself.
1708
1709 To maximize performance, use a code snippet like the following:
1710
1711     # prepare a statement handle using the first row
1712     # and then reuse it for the rest of the rows
1713     my($sth, $stmt);
1714     for my $href (@array_of_hashrefs) {
1715         $stmt ||= $sql->insert('table', $href);
1716         $sth  ||= $dbh->prepare($stmt);
1717         $sth->execute($sql->values($href));
1718     }
1719
1720 The reason this works is because the keys in your C<$href> are sorted
1721 internally by B<SQL::Abstract>. Thus, as long as your data retains
1722 the same structure, you only have to generate the SQL the first time
1723 around. On subsequent queries, simply use the C<values> function provided
1724 by this module to return your values in the correct order.
1725
1726 However this depends on the values having the same type - if, for
1727 example, the values of a where clause may either have values
1728 (resulting in sql of the form C<column = ?> with a single bind
1729 value), or alternatively the values might be C<undef> (resulting in
1730 sql of the form C<column IS NULL> with no bind value) then the
1731 caching technique suggested will not work.
1732
1733 =head1 FORMBUILDER
1734
1735 If you use my C<CGI::FormBuilder> module at all, you'll hopefully
1736 really like this part (I do, at least). Building up a complex query
1737 can be as simple as the following:
1738
1739     #!/usr/bin/perl
1740
1741     use warnings;
1742     use strict;
1743
1744     use CGI::FormBuilder;
1745     use SQL::Abstract;
1746
1747     my $form = CGI::FormBuilder->new(...);
1748     my $sql  = SQL::Abstract->new;
1749
1750     if ($form->submitted) {
1751         my $field = $form->field;
1752         my $id = delete $field->{id};
1753         my($stmt, @bind) = $sql->update('table', $field, {id => $id});
1754     }
1755
1756 Of course, you would still have to connect using C<DBI> to run the
1757 query, but the point is that if you make your form look like your
1758 table, the actual query script can be extremely simplistic.
1759
1760 If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
1761 a fast interface to returning and formatting data. I frequently
1762 use these three modules together to write complex database query
1763 apps in under 50 lines.
1764
1765 =head1 REPO
1766
1767 =over
1768
1769 =item * gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
1770
1771 =item * git: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
1772
1773 =back
1774
1775 =head1 CHANGES
1776
1777 Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
1778 Great care has been taken to preserve the I<published> behavior
1779 documented in previous versions in the 1.* family; however,
1780 some features that were previously undocumented, or behaved
1781 differently from the documentation, had to be changed in order
1782 to clarify the semantics. Hence, client code that was relying
1783 on some dark areas of C<SQL::Abstract> v1.*
1784 B<might behave differently> in v1.50.
1785
1786 The main changes are :
1787
1788 =over
1789
1790 =item *
1791
1792 support for literal SQL through the C<< \ [$sql, bind] >> syntax.
1793
1794 =item *
1795
1796 support for the { operator => \"..." } construct (to embed literal SQL)
1797
1798 =item *
1799
1800 support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
1801
1802 =item *
1803
1804 optional support for L<array datatypes|/"Inserting and Updating Arrays">
1805
1806 =item *
1807
1808 defensive programming : check arguments
1809
1810 =item *
1811
1812 fixed bug with global logic, which was previously implemented
1813 through global variables yielding side-effects. Prior versions would
1814 interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
1815 as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
1816 Now this is interpreted
1817 as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
1818
1819
1820 =item *
1821
1822 fixed semantics of  _bindtype on array args
1823
1824 =item *
1825
1826 dropped the C<_anoncopy> of the %where tree. No longer necessary,
1827 we just avoid shifting arrays within that tree.
1828
1829 =item *
1830
1831 dropped the C<_modlogic> function
1832
1833 =back
1834
1835 =head1 ACKNOWLEDGEMENTS
1836
1837 There are a number of individuals that have really helped out with
1838 this module. Unfortunately, most of them submitted bugs via CPAN
1839 so I have no idea who they are! But the people I do know are:
1840
1841     Ash Berlin (order_by hash term support)
1842     Matt Trout (DBIx::Class support)
1843     Mark Stosberg (benchmarking)
1844     Chas Owens (initial "IN" operator support)
1845     Philip Collins (per-field SQL functions)
1846     Eric Kolve (hashref "AND" support)
1847     Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
1848     Dan Kubb (support for "quote_char" and "name_sep")
1849     Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
1850     Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
1851     Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
1852     Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
1853     Oliver Charles (support for "RETURNING" after "INSERT")
1854
1855 Thanks!
1856
1857 =head1 SEE ALSO
1858
1859 L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
1860
1861 =head1 AUTHOR
1862
1863 Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
1864
1865 This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
1866
1867 For support, your best bet is to try the C<DBIx::Class> users mailing list.
1868 While not an official support venue, C<DBIx::Class> makes heavy use of
1869 C<SQL::Abstract>, and as such list members there are very familiar with
1870 how to create queries.
1871
1872 =head1 LICENSE
1873
1874 This module is free software; you may copy this under the same
1875 terms as perl itself (either the GNU General Public License or
1876 the Artistic License)
1877
1878 =cut
1879