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