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