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