move and/or expansion to non-hashpair
[scpubgit/Q-Branch.git] / lib / SQL / Abstract.pm
CommitLineData
96449e8e 1package SQL::Abstract; # see doc at end of file
2
96449e8e 3use strict;
4use warnings;
9d9d5bd6 5use Carp ();
312d830b 6use List::Util ();
7use Scalar::Util ();
96449e8e 8
0da0fe34 9use Exporter 'import';
10our @EXPORT_OK = qw(is_plain_value is_literal_value);
11
12BEGIN {
13 if ($] < 5.009_005) {
14 require MRO::Compat;
15 }
16 else {
17 require mro;
18 }
843a94b5 19
20 *SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
21 ? sub () { 0 }
22 : sub () { 1 }
23 ;
0da0fe34 24}
25
96449e8e 26#======================================================================
27# GLOBALS
28#======================================================================
29
dc6afcf8 30our $VERSION = '1.86';
7479e27e 31
22f1a437 32# This would confuse some packagers
c520207b 33$VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
96449e8e 34
35our $AUTOLOAD;
36
37# special operators (-in, -between). May be extended/overridden by user.
38# See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
39my @BUILTIN_SPECIAL_OPS = (
f663e672 40 {regex => qr/^ (?: not \s )? between $/ix, handler => sub { die "NOPE" }},
41 {regex => qr/^ (?: not \s )? in $/ix, handler => sub { die "NOPE" }},
87c8e45b 42 {regex => qr/^ is (?: \s+ not )? $/ix, handler => sub { die "NOPE" }},
96449e8e 43);
44
45#======================================================================
46# DEBUGGING AND ERROR REPORTING
47#======================================================================
48
49sub _debug {
50 return unless $_[0]->{debug}; shift; # a little faster
51 my $func = (caller(1))[3];
52 warn "[$func] ", @_, "\n";
53}
54
55sub belch (@) {
56 my($func) = (caller(1))[3];
9d9d5bd6 57 Carp::carp "[$func] Warning: ", @_;
96449e8e 58}
59
60sub puke (@) {
61 my($func) = (caller(1))[3];
9d9d5bd6 62 Carp::croak "[$func] Fatal: ", @_;
96449e8e 63}
64
0da0fe34 65sub is_literal_value ($) {
66 ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
67 : ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
0da0fe34 68 : undef;
69}
70
71# FIXME XSify - this can be done so much more efficiently
72sub is_plain_value ($) {
73 no strict 'refs';
966200cc 74 ! length ref $_[0] ? \($_[0])
0da0fe34 75 : (
76 ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
77 and
78 exists $_[0]->{-value}
966200cc 79 ) ? \($_[0]->{-value})
0da0fe34 80 : (
a1c9e0ff 81 # reuse @_ for even moar speedz
82 defined ( $_[1] = Scalar::Util::blessed $_[0] )
0da0fe34 83 and
84 # deliberately not using Devel::OverloadInfo - the checks we are
85 # intersted in are much more limited than the fullblown thing, and
86 # this is a very hot piece of code
87 (
e8d729d4 88 # simply using ->can('(""') can leave behind stub methods that
89 # break actually using the overload later (see L<perldiag/Stub
90 # found while resolving method "%s" overloading "%s" in package
91 # "%s"> and the source of overload::mycan())
44e54b41 92 #
0da0fe34 93 # either has stringification which DBI SHOULD prefer out of the box
a1c9e0ff 94 grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
0da0fe34 95 or
20e178a8 96 # has nummification or boolification, AND fallback is *not* disabled
0da0fe34 97 (
843a94b5 98 SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
99 and
20e178a8 100 (
101 grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
102 or
103 grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
104 )
0da0fe34 105 and
106 (
107 # no fallback specified at all
a1c9e0ff 108 ! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
0da0fe34 109 or
110 # fallback explicitly undef
a1c9e0ff 111 ! defined ${"$_[3]::()"}
0da0fe34 112 or
113 # explicitly true
a1c9e0ff 114 !! ${"$_[3]::()"}
0da0fe34 115 )
116 )
117 )
966200cc 118 ) ? \($_[0])
0da0fe34 119 : undef;
120}
121
122
96449e8e 123
124#======================================================================
125# NEW
126#======================================================================
127
128sub new {
129 my $self = shift;
130 my $class = ref($self) || $self;
131 my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
132
133 # choose our case by keeping an option around
134 delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
135
136 # default logic for interpreting arrayrefs
ef559da3 137 $opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
96449e8e 138
139 # how to return bind vars
96449e8e 140 $opt{bindtype} ||= 'normal';
141
142 # default comparison is "=", but can be overridden
143 $opt{cmp} ||= '=';
144
3af02ccb 145 # try to recognize which are the 'equality' and 'inequality' ops
3cdadcbe 146 # (temporary quickfix (in 2007), should go through a more seasoned API)
147 $opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
148 $opt{inequality_op} = qr/^( != | <> )$/ix;
149
150 $opt{like_op} = qr/^ (is\s+)? r?like $/xi;
151 $opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
96449e8e 152
153 # SQL booleans
154 $opt{sqltrue} ||= '1=1';
155 $opt{sqlfalse} ||= '0=1';
156
9d48860e 157 # special operators
30af97c5 158 $opt{special_ops} ||= [];
159
b6251592 160 # regexes are applied in order, thus push after user-defines
96449e8e 161 push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
162
cf06e9dc 163 if ($class->isa('DBIx::Class::SQLMaker')) {
dd1d0dbf 164 push @{$opt{special_ops}}, our $DBIC_Compat_Op ||= {
165 regex => qr/^(?:ident|value)$/i, handler => sub { die "NOPE" }
166 };
cf06e9dc 167 $opt{is_dbic_sqlmaker} = 1;
dd1d0dbf 168 }
169
9d48860e 170 # unary operators
59f23b3d 171 $opt{unary_ops} ||= [];
59f23b3d 172
3af02ccb 173 # rudimentary sanity-check for user supplied bits treated as functions/operators
b6251592 174 # If a purported function matches this regular expression, an exception is thrown.
175 # Literal SQL is *NOT* subject to this check, only functions (and column names
176 # when quoting is not in effect)
96449e8e 177
b6251592 178 # FIXME
179 # need to guard against ()'s in column names too, but this will break tons of
180 # hacks... ideas anyone?
181 $opt{injection_guard} ||= qr/
182 \;
183 |
184 ^ \s* go \s
185 /xmi;
96449e8e 186
21225d32 187 $opt{render} = {
188 (map +("-$_", "_render_$_"), qw(op func bind ident literal list)),
189 %{$opt{render}||{}}
b07681b1 190 };
191
ec19b759 192 $opt{expand_unary} = {};
193
767b62e4 194 $opt{expand} = {
195 '-ident' => '_expand_ident',
196 '-fffvalue' => sub { +{ -bind => [ our $Cur_Col_Meta, $_[2] ] } },
197 };
198
b6251592 199 return bless \%opt, $class;
200}
96449e8e 201
e175845b 202sub sqltrue { +{ -literal => [ $_[0]->{sqltrue} ] } }
203sub sqlfalse { +{ -literal => [ $_[0]->{sqlfalse} ] } }
170e6c33 204
205sub _assert_pass_injection_guard {
206 if ($_[1] =~ $_[0]->{injection_guard}) {
207 my $class = ref $_[0];
208 puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
209 . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
210 . "{injection_guard} attribute to ${class}->new()"
211 }
212}
213
214
96449e8e 215#======================================================================
216# INSERT methods
217#======================================================================
218
219sub insert {
02288357 220 my $self = shift;
221 my $table = $self->_table(shift);
222 my $data = shift || return;
223 my $options = shift;
96449e8e 224
225 my $method = $self->_METHOD_FOR_refkind("_insert", $data);
02288357 226 my ($sql, @bind) = $self->$method($data);
96449e8e 227 $sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
02288357 228
e82e648a 229 if ($options->{returning}) {
ca4f826a 230 my ($s, @b) = $self->_insert_returning($options);
e82e648a 231 $sql .= $s;
232 push @bind, @b;
02288357 233 }
234
96449e8e 235 return wantarray ? ($sql, @bind) : $sql;
236}
237
60f3fd3f 238# So that subclasses can override INSERT ... RETURNING separately from
239# UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
b17a3ece 240sub _insert_returning { shift->_returning(@_) }
241
95904db5 242sub _returning {
e82e648a 243 my ($self, $options) = @_;
6b1fe79d 244
e82e648a 245 my $f = $options->{returning};
246
79d310f2 247 my ($sql, @bind) = $self->render_aqt(
ff96fdd4 248 $self->_expand_maybe_list_expr($f, undef, -ident)
249 );
250 return wantarray
251 ? $self->_sqlcase(' returning ') . $sql
252 : ($self->_sqlcase(' returning ').$sql, @bind);
6b1fe79d 253}
254
96449e8e 255sub _insert_HASHREF { # explicit list of fields and then values
256 my ($self, $data) = @_;
257
258 my @fields = sort keys %$data;
259
fe3ae272 260 my ($sql, @bind) = $self->_insert_values($data);
96449e8e 261
262 # assemble SQL
263 $_ = $self->_quote($_) foreach @fields;
264 $sql = "( ".join(", ", @fields).") ".$sql;
265
266 return ($sql, @bind);
267}
268
269sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
270 my ($self, $data) = @_;
271
272 # no names (arrayref) so can't generate bindtype
273 $self->{bindtype} ne 'columns'
274 or belch "can't do 'columns' bindtype when called with arrayref";
275
19b6ccce 276 my (@values, @all_bind);
277 foreach my $value (@$data) {
278 my ($values, @bind) = $self->_insert_value(undef, $value);
279 push @values, $values;
280 push @all_bind, @bind;
281 }
282 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
283 return ($sql, @all_bind);
fe3ae272 284}
285
286sub _insert_ARRAYREFREF { # literal SQL with bind
287 my ($self, $data) = @_;
288
289 my ($sql, @bind) = @${$data};
290 $self->_assert_bindval_matches_bindtype(@bind);
291
292 return ($sql, @bind);
293}
294
295
296sub _insert_SCALARREF { # literal SQL without bind
297 my ($self, $data) = @_;
298
299 return ($$data);
300}
301
302sub _insert_values {
303 my ($self, $data) = @_;
304
96449e8e 305 my (@values, @all_bind);
fe3ae272 306 foreach my $column (sort keys %$data) {
19b6ccce 307 my ($values, @bind) = $self->_insert_value($column, $data->{$column});
308 push @values, $values;
309 push @all_bind, @bind;
310 }
311 my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
312 return ($sql, @all_bind);
313}
96449e8e 314
19b6ccce 315sub _insert_value {
316 my ($self, $column, $v) = @_;
96449e8e 317
79d310f2 318 return $self->render_aqt(
720ca4f7 319 $self->_expand_insert_value($column, $v)
320 );
321}
96449e8e 322
720ca4f7 323sub _expand_insert_value {
324 my ($self, $column, $v) = @_;
96449e8e 325
720ca4f7 326 if (ref($v) eq 'ARRAY') {
327 if ($self->{array_datatypes}) {
328 return +{ -bind => [ $column, $v ] };
329 }
330 my ($sql, @bind) = @$v;
331 $self->_assert_bindval_matches_bindtype(@bind);
332 return +{ -literal => $v };
333 }
334 if (ref($v) eq 'HASH') {
335 if (grep !/^-/, keys %$v) {
336 belch "HASH ref as bind value in insert is not supported";
337 return +{ -bind => [ $column, $v ] };
338 }
339 }
340 if (!defined($v)) {
341 return +{ -bind => [ $column, undef ] };
342 }
343 local our $Cur_Col_Meta = $column;
79d310f2 344 return $self->expand_expr($v);
96449e8e 345}
346
347
96449e8e 348
349#======================================================================
350# UPDATE methods
351#======================================================================
352
353
354sub update {
95904db5 355 my $self = shift;
356 my $table = $self->_table(shift);
357 my $data = shift || return;
358 my $where = shift;
359 my $options = shift;
96449e8e 360
361 # first build the 'SET' part of the sql statement
96449e8e 362 puke "Unsupported data type specified to \$sql->update"
363 unless ref $data eq 'HASH';
364
9ade906e 365 my ($sql, @all_bind) = $self->_update_set_values($data);
a9e94508 366 $sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
9ade906e 367 . $sql;
368
369 if ($where) {
370 my($where_sql, @where_bind) = $self->where($where);
371 $sql .= $where_sql;
372 push @all_bind, @where_bind;
373 }
374
375 if ($options->{returning}) {
376 my ($returning_sql, @returning_bind) = $self->_update_returning($options);
377 $sql .= $returning_sql;
378 push @all_bind, @returning_bind;
379 }
380
381 return wantarray ? ($sql, @all_bind) : $sql;
382}
383
384sub _update_set_values {
385 my ($self, $data) = @_;
386
79d310f2 387 return $self->render_aqt(
89690da2 388 $self->_expand_update_set_values($data),
389 );
390}
96449e8e 391
89690da2 392sub _expand_update_set_values {
393 my ($self, $data) = @_;
394 $self->_expand_maybe_list_expr( [
395 map {
396 my ($k, $set) = @$_;
c4ed66f4 397 $set = { -bind => $_ } unless defined $set;
9103bd14 398 +{ -op => [ '=', $self->_expand_ident(-ident => $k), $set ] };
89690da2 399 }
400 map {
401 my $k = $_;
402 my $v = $data->{$k};
403 (ref($v) eq 'ARRAY'
404 ? ($self->{array_datatypes}
405 ? [ $k, +{ -bind => [ $k, $v ] } ]
406 : [ $k, +{ -literal => $v } ])
407 : do {
408 local our $Cur_Col_Meta = $k;
409 [ $k, $self->_expand_expr($v) ]
410 }
411 );
412 } sort keys %$data
413 ] );
96449e8e 414}
415
60f3fd3f 416# So that subclasses can override UPDATE ... RETURNING separately from
417# INSERT and DELETE
20bb2ad5 418sub _update_returning { shift->_returning(@_) }
96449e8e 419
420
421
422#======================================================================
423# SELECT
424#======================================================================
425
426
427sub select {
428 my $self = shift;
429 my $table = $self->_table(shift);
430 my $fields = shift || '*';
431 my $where = shift;
432 my $order = shift;
433
daa4ccdd 434 my ($fields_sql, @bind) = $self->_select_fields($fields);
96449e8e 435
daa4ccdd 436 my ($where_sql, @where_bind) = $self->where($where, $order);
437 push @bind, @where_bind;
438
439 my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
96449e8e 440 $self->_sqlcase('from'), $table)
441 . $where_sql;
442
9d48860e 443 return wantarray ? ($sql, @bind) : $sql;
96449e8e 444}
445
daa4ccdd 446sub _select_fields {
447 my ($self, $fields) = @_;
de63ce57 448 return $fields unless ref($fields);
79d310f2 449 return $self->render_aqt(
27592e2b 450 $self->_expand_maybe_list_expr($fields, undef, '-ident')
451 );
daa4ccdd 452}
453
96449e8e 454#======================================================================
455# DELETE
456#======================================================================
457
458
459sub delete {
85327cd5 460 my $self = shift;
461 my $table = $self->_table(shift);
462 my $where = shift;
463 my $options = shift;
96449e8e 464
465 my($where_sql, @bind) = $self->where($where);
a9e94508 466 my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
96449e8e 467
85327cd5 468 if ($options->{returning}) {
ca4f826a 469 my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
85327cd5 470 $sql .= $returning_sql;
471 push @bind, @returning_bind;
472 }
473
9d48860e 474 return wantarray ? ($sql, @bind) : $sql;
96449e8e 475}
476
60f3fd3f 477# So that subclasses can override DELETE ... RETURNING separately from
478# INSERT and UPDATE
85327cd5 479sub _delete_returning { shift->_returning(@_) }
480
481
96449e8e 482
483#======================================================================
484# WHERE: entry point
485#======================================================================
486
487
488
489# Finally, a separate routine just to handle WHERE clauses
490sub where {
491 my ($self, $where, $order) = @_;
492
7ad12721 493 local $self->{convert_where} = $self->{convert};
494
96449e8e 495 # where ?
e175845b 496 my ($sql, @bind) = defined($where)
497 ? $self->_recurse_where($where)
498 : (undef);
417dd15e 499 $sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
96449e8e 500
501 # order by?
502 if ($order) {
26fe4d30 503 my ($order_sql, @order_bind) = $self->_order_by($order);
504 $sql .= $order_sql;
505 push @bind, @order_bind;
96449e8e 506 }
507
9d48860e 508 return wantarray ? ($sql, @bind) : $sql;
96449e8e 509}
510
79d310f2 511sub expand_expr {
54d3140f 512 my ($self, $expr, $default_scalar_to) = @_;
513 local our $Default_Scalar_To = $default_scalar_to if $default_scalar_to;
7d93797d 514 $self->_expand_expr($expr);
79d310f2 515}
516
517sub render_aqt {
518 my ($self, $aqt) = @_;
519 my ($k, $v, @rest) = %$aqt;
520 die "No" if @rest;
21225d32 521 if (my $meth = $self->{render}{$k}) {
79d310f2 522 return $self->$meth($v);
523 }
524 die "notreached: $k";
525}
526
6082a464 527sub render_expr {
528 my ($self, $expr) = @_;
529 $self->render_aqt($self->expand_expr($expr));
530}
531
a2cd381d 532sub _expand_expr {
c7aeb9f5 533 my ($self, $expr, $logic) = @_;
3ae10d16 534 our $Expand_Depth ||= 0; local $Expand_Depth = $Expand_Depth + 1;
252518da 535 return undef unless defined($expr);
59588695 536 if (ref($expr) eq 'HASH') {
767b62e4 537 return undef unless my $kc = keys %$expr;
538 if ($kc > 1) {
59588695 539 $logic ||= 'and';
77617257 540 return +{ -op => [
541 $logic,
767b62e4 542 map $self->_expand_expr({ $_ => $expr->{$_} }, $logic),
59588695 543 sort keys %$expr
544 ] };
545 }
767b62e4 546 my ($key, $value) = %$expr;
547 if (my $exp = $self->{expand}{$key}) {
548 $self->$exp($key, $value);
549 }
550 return $self->_expand_expr_hashpair($key, $value, $logic);
a2cd381d 551 }
08264f40 552 if (ref($expr) eq 'ARRAY') {
99a65fa8 553 my $logic = lc($logic || $self->{logic});
08264f40 554 $logic eq 'and' or $logic eq 'or' or puke "unknown logic: $logic";
555
1c0c0f41 556 my @expr = grep {
557 (ref($_) eq 'ARRAY' and @$_)
558 or (ref($_) eq 'HASH' and %$_)
559 or 1
560 } @$expr;
08264f40 561
562 my @res;
563
564 while (my ($el) = splice @expr, 0, 1) {
565 puke "Supplying an empty left hand side argument is not supported in array-pairs"
566 unless defined($el) and length($el);
567 my $elref = ref($el);
568 if (!$elref) {
dd1d0dbf 569 local $Expand_Depth = 0;
f4082f8b 570 push(@res, grep defined, $self->_expand_expr({ $el, shift(@expr) }));
08264f40 571 } elsif ($elref eq 'ARRAY') {
f4082f8b 572 push(@res, grep defined, $self->_expand_expr($el)) if @$el;
ec857800 573 } elsif (my $l = is_literal_value($el)) {
574 push @res, { -literal => $l };
08264f40 575 } elsif ($elref eq 'HASH') {
dd1d0dbf 576 local $Expand_Depth = 0;
f4082f8b 577 push @res, grep defined, $self->_expand_expr($el) if %$el;
08264f40 578 } else {
da4a0964 579 die "notreached";
08264f40 580 }
581 }
767b62e4 582 # ???
583 # return $res[0] if @res == 1;
2143604f 584 return { -op => [ $logic, @res ] };
08264f40 585 }
ca3da680 586 if (my $literal = is_literal_value($expr)) {
587 return +{ -literal => $literal };
588 }
99a65fa8 589 if (!ref($expr) or Scalar::Util::blessed($expr)) {
c7aeb9f5 590 if (my $d = our $Default_Scalar_To) {
a332e2cb 591 return $self->_expand_expr({ $d => $expr });
2558b622 592 }
99a65fa8 593 if (my $m = our $Cur_Col_Meta) {
594 return +{ -bind => [ $m, $expr ] };
595 }
a332e2cb 596 return +{ -bind => [ undef, $expr ] };
252518da 597 }
252518da 598 die "notreached";
a2cd381d 599}
96449e8e 600
59588695 601sub _expand_expr_hashpair {
602 my ($self, $k, $v, $logic) = @_;
d13725da 603 unless (defined($k) and length($k)) {
2d64004f 604 if (defined($k) and my $literal = is_literal_value($v)) {
d13725da 605 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
2d64004f 606 return { -literal => $literal };
d13725da 607 }
608 puke "Supplying an empty left hand side argument is not supported";
609 }
ef071fad 610 if ($k =~ /^-/) {
99a65fa8 611 $self->_assert_pass_injection_guard($k =~ /^-(.*)$/s);
612 if ($k =~ s/ [_\s]? \d+ $//x ) {
613 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
614 . "You probably wanted ...-and => [ $k => COND1, $k => COND2 ... ]";
615 }
ef071fad 616 if ($k eq '-nest') {
0fc68377 617 # DBIx::Class requires a nest warning to be emitted once but the private
618 # method it overrode to do so no longer exists
cf06e9dc 619 if ($self->{is_dbic_sqlmaker}) {
620 unless (our $Nest_Warned) {
0fc68377 621 belch(
622 "-nest in search conditions is deprecated, you most probably wanted:\n"
623 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
624 );
625 $Nest_Warned = 1;
626 }
627 }
ef071fad 628 return $self->_expand_expr($v);
629 }
6ab1562a 630 if ($k eq '-bool') {
631 if (ref($v)) {
632 return $self->_expand_expr($v);
633 }
634 puke "-bool => undef not supported" unless defined($v);
944f2c7b 635 return $self->_expand_ident(-ident => $v);
6ab1562a 636 }
99a65fa8 637 if ($k eq '-not') {
0c7e3af0 638 return { -op => [ 'not', $self->_expand_expr($v) ] };
99a65fa8 639 }
ce3bc4b0 640 if (my ($rest) = $k =~/^-not[_ ](.*)$/) {
0c7e3af0 641 return +{ -op => [
642 'not',
767b62e4 643 $self->_expand_expr({ "-${rest}", $v }, $logic)
0c7e3af0 644 ] };
ce3bc4b0 645 }
99a65fa8 646 if (my ($logic) = $k =~ /^-(and|or)$/i) {
dd2d5bf7 647 if (ref($v) eq 'HASH') {
648 return $self->_expand_expr($v, $logic);
649 }
99a65fa8 650 if (ref($v) eq 'ARRAY') {
651 return $self->_expand_expr($v, $logic);
652 }
dd2d5bf7 653 }
99a65fa8 654 {
655 my $op = $k;
656 $op =~ s/^-// if length($op) > 1;
ddc44894 657
99a65fa8 658 # top level special ops are illegal in general
3ae10d16 659 # note that, arguably, if it makes no sense at top level, it also
660 # makes no sense on the other side of an = sign or similar but DBIC
661 # gets disappointingly upset if I disallow it
662 if (
663 (our $Expand_Depth) == 1
664 and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}
665 ) {
666 puke "Illegal use of top-level '-$op'"
667 }
96a8d74a 668 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
669 return { -op => [ $op, $v ] };
670 }
99a65fa8 671 }
a332e2cb 672 if ($k eq '-value') {
673 return +{ -bind => [ our $Cur_Col_Meta, $v ] };
99a65fa8 674 }
767b62e4 675# if ($k eq '-ident') {
676# return $self->_expand_ident(-ident => $v);
677# }
ec19b759 678 if (my $custom = $self->{expand_unary}{$k}) {
679 return $self->$custom($v);
680 }
21225d32 681 if ($self->{render}{$k}) {
99a65fa8 682 return { $k => $v };
d13725da 683 }
711892b1 684 if (
685 ref($v) eq 'HASH'
686 and keys %$v == 1
687 and (keys %$v)[0] =~ /^-/
688 ) {
689 my ($func) = $k =~ /^-(.*)$/;
3ae10d16 690 if (List::Util::first { $func =~ $_->{regex} } @{$self->{special_ops}}) {
691 return +{ -op => [ $func, $self->_expand_expr($v) ] };
692 }
711892b1 693 return +{ -func => [ $func, $self->_expand_expr($v) ] };
694 }
695 if (!ref($v) or is_literal_value($v)) {
99a65fa8 696 return +{ -op => [ $k =~ /^-(.*)$/, $self->_expand_expr($v) ] };
59588695 697 }
99a65fa8 698 }
699 if (
700 !defined($v)
701 or (
702 ref($v) eq 'HASH'
703 and exists $v->{-value}
704 and not defined $v->{-value}
705 )
706 ) {
213209dd 707 return $self->_expand_expr({ $k => { $self->{cmp} => undef } });
99a65fa8 708 }
709 if (!ref($v) or Scalar::Util::blessed($v)) {
ec19b759 710 my $d = our $Default_Scalar_To;
99a65fa8 711 return +{
712 -op => [
713 $self->{cmp},
944f2c7b 714 $self->_expand_ident(-ident => $k),
7d93797d 715 ($d
716 ? $self->_expand_expr($d => $v)
717 : { -bind => [ $k, $v ] }
718 )
99a65fa8 719 ]
720 };
721 }
722 if (ref($v) eq 'HASH') {
723 if (keys %$v > 1) {
e175845b 724 return { -op => [
725 'and',
5e75aa04 726 map $self->_expand_expr({ $k => { $_ => $v->{$_} } }),
99a65fa8 727 sort keys %$v
728 ] };
729 }
b18a95e4 730 return undef unless keys %$v;
99a65fa8 731 my ($vk, $vv) = %$v;
d455dcf1 732 my $op = join ' ', split '_', (map lc, $vk =~ /^-?(.*)$/)[0];
733 $self->_assert_pass_injection_guard($op);
734 if ($op =~ s/ [_\s]? \d+ $//x ) {
99a65fa8 735 belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
d455dcf1 736 . "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
99a65fa8 737 }
d455dcf1 738 if ($op =~ /^(?:not )?between$/) {
99a65fa8 739 local our $Cur_Col_Meta = $k;
740 my @rhs = map $self->_expand_expr($_),
741 ref($vv) eq 'ARRAY' ? @$vv : $vv;
742 unless (
743 (@rhs == 1 and ref($rhs[0]) eq 'HASH' and $rhs[0]->{-literal})
744 or
745 (@rhs == 2 and defined($rhs[0]) and defined($rhs[1]))
746 ) {
d455dcf1 747 puke "Operator '${\uc($op)}' requires either an arrayref with two defined values or expressions, or a single literal scalarref/arrayref-ref";
b5b18861 748 }
99a65fa8 749 return +{ -op => [
d455dcf1 750 $op,
944f2c7b 751 $self->_expand_ident(-ident => $k),
99a65fa8 752 @rhs
753 ] }
754 }
d455dcf1 755 if ($op =~ /^(?:not )?in$/) {
99a65fa8 756 if (my $literal = is_literal_value($vv)) {
757 my ($sql, @bind) = @$literal;
758 my $opened_sql = $self->_open_outer_paren($sql);
10d07c4e 759 return +{ -op => [
d455dcf1 760 $op, $self->_expand_ident(-ident => $k),
99a65fa8 761 [ { -literal => [ $opened_sql, @bind ] } ]
10d07c4e 762 ] };
763 }
99a65fa8 764 my $undef_err =
765 'SQL::Abstract before v1.75 used to generate incorrect SQL when the '
d455dcf1 766 . "-${\uc($op)} operator was given an undef-containing list: !!!AUDIT YOUR CODE "
99a65fa8 767 . 'AND DATA!!! (the upcoming Data::Query-based version of SQL::Abstract '
768 . 'will emit the logically correct SQL instead of raising this exception)'
769 ;
d455dcf1 770 puke("Argument passed to the '${\uc($op)}' operator can not be undefined")
99a65fa8 771 if !defined($vv);
772 my @rhs = map $self->_expand_expr($_),
773 map { ref($_) ? $_ : { -bind => [ $k, $_ ] } }
774 map { defined($_) ? $_: puke($undef_err) }
775 (ref($vv) eq 'ARRAY' ? @$vv : $vv);
d455dcf1 776 return $self->${\($op =~ /^not/ ? 'sqltrue' : 'sqlfalse')} unless @rhs;
99a65fa8 777
778 return +{ -op => [
d455dcf1 779 $op,
944f2c7b 780 $self->_expand_ident(-ident => $k),
99a65fa8 781 \@rhs
782 ] };
783 }
d455dcf1 784 if ($op eq 'ident') {
02b8fe35 785 if (! defined $vv or (ref($vv) and ref($vv) eq 'ARRAY')) {
d455dcf1 786 puke "-$op requires a single plain scalar argument (a quotable identifier) or an arrayref of identifier parts";
f7778474 787 }
99a65fa8 788 return +{ -op => [
789 $self->{cmp},
de8d04fb 790 $self->_expand_ident(-ident => $k),
791 $self->_expand_ident(-ident => $vv),
99a65fa8 792 ] };
793 }
d455dcf1 794 if ($op eq 'value') {
99a65fa8 795 return $self->_expand_expr_hashpair($k, undef) unless defined($vv);
796 return +{ -op => [
797 $self->{cmp},
de8d04fb 798 $self->_expand_ident(-ident => $k),
99a65fa8 799 { -bind => [ $k, $vv ] }
800 ] };
801 }
d455dcf1 802 if ($op =~ /^is(?: not)?$/) {
803 puke "$op can only take undef as argument"
99a65fa8 804 if defined($vv)
805 and not (
806 ref($vv) eq 'HASH'
807 and exists($vv->{-value})
808 and !defined($vv->{-value})
809 );
d455dcf1 810 return +{ -op => [ $op.' null', $self->_expand_ident(-ident => $k) ] };
99a65fa8 811 }
d455dcf1 812 if ($op =~ /^(and|or)$/) {
99a65fa8 813 if (ref($vv) eq 'HASH') {
e62fe58a 814 return +{ -op => [
d455dcf1 815 $op,
ff1b554a 816 map $self->_expand_expr({ $k, { $_ => $vv->{$_} } }),
99a65fa8 817 sort keys %$vv
7d7868d1 818 ] };
819 }
e28d9b13 820 }
d455dcf1 821 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
822 return { -op => [ $op, $self->_expand_ident(-ident => $k), $vv ] };
7dbe1183 823 }
d455dcf1 824 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
96a8d74a 825 return { -op => [
826 $self->{cmp},
de8d04fb 827 $self->_expand_ident(-ident => $k),
d455dcf1 828 { -op => [ $op, $vv ] }
96a8d74a 829 ] };
830 }
99a65fa8 831 if (ref($vv) eq 'ARRAY') {
832 my ($logic, @values) = (
833 (defined($vv->[0]) and $vv->[0] =~ /^-(and|or)$/i)
834 ? @$vv
835 : (-or => @$vv)
836 );
837 if (
d455dcf1 838 $op =~ $self->{inequality_op}
839 or $op =~ $self->{not_like_op}
99a65fa8 840 ) {
841 if (lc($logic) eq '-or' and @values > 1) {
d455dcf1 842 belch "A multi-element arrayref as an argument to the inequality op '${\uc($op)}' "
99a65fa8 843 . 'is technically equivalent to an always-true 1=1 (you probably wanted '
844 . "to say ...{ \$inequality_op => [ -and => \@values ] }... instead)"
845 ;
846 }
ef071fad 847 }
b3cb13e8 848 unless (@values) {
849 # try to DWIM on equality operators
b3cb13e8 850 return
e175845b 851 $op =~ $self->{equality_op} ? $self->sqlfalse
852 : $op =~ $self->{like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqlfalse
853 : $op =~ $self->{inequality_op} ? $self->sqltrue
854 : $op =~ $self->{not_like_op} ? belch("Supplying an empty arrayref to '@{[ uc $op]}' is deprecated") && $self->sqltrue
b3cb13e8 855 : puke "operator '$op' applied on an empty array (field '$k')";
856 }
63c97a0b 857 return +{ -op => [
858 $logic =~ /^-(.*)$/,
99a65fa8 859 map $self->_expand_expr_hashpair($k => { $vk => $_ }),
860 @values
861 ] };
862 }
863 if (
864 !defined($vv)
865 or (
866 ref($vv) eq 'HASH'
867 and exists $vv->{-value}
868 and not defined $vv->{-value}
869 )
870 ) {
99a65fa8 871 my $is =
872 $op =~ /^not$/i ? 'is not' # legacy
873 : $op =~ $self->{equality_op} ? 'is'
874 : $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
875 : $op =~ $self->{inequality_op} ? 'is not'
876 : $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
877 : puke "unexpected operator '$op' with undef operand";
de8d04fb 878 return +{ -op => [ $is.' null', $self->_expand_ident(-ident => $k) ] };
99a65fa8 879 }
880 local our $Cur_Col_Meta = $k;
881 return +{ -op => [
d455dcf1 882 $op,
883 $self->_expand_ident(-ident => $k),
884 $self->_expand_expr($vv)
99a65fa8 885 ] };
886 }
887 if (ref($v) eq 'ARRAY') {
e175845b 888 return $self->sqlfalse unless @$v;
99a65fa8 889 $self->_debug("ARRAY($k) means distribute over elements");
890 my $this_logic = (
891 $v->[0] =~ /^-((?:and|or))$/i
892 ? ($v = [ @{$v}[1..$#$v] ], $1)
893 : ($self->{logic} || 'or')
894 );
cba28f66 895 return +{ -op => [
896 $this_logic,
897 map $self->_expand_expr({ $k => $_ }, $this_logic), @$v
898 ] };
99a65fa8 899 }
900 if (my $literal = is_literal_value($v)) {
901 unless (length $k) {
902 belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
903 return \$literal;
904 }
905 my ($sql, @bind) = @$literal;
906 if ($self->{bindtype} eq 'columns') {
907 for (@bind) {
6fb2bd90 908 $self->_assert_bindval_matches_bindtype($_);
aa8d7bdb 909 }
331e2209 910 }
99a65fa8 911 return +{ -literal => [ $self->_quote($k).' '.$sql, @bind ] };
331e2209 912 }
99a65fa8 913 die "notreached";
59588695 914}
915
9103bd14 916sub _expand_ident {
917 my ($self, undef, $body) = @_;
918 my @parts = map split(/\Q${\($self->{name_sep}||'.')}\E/, $_),
919 ref($body) ? @$body : $body;
944f2c7b 920 return { -ident => $parts[-1] } if $self->{_dequalify_idents};
921 unless ($self->{quote_char}) {
922 $self->_assert_pass_injection_guard($_) for @parts;
923 }
9103bd14 924 return +{ -ident => \@parts };
925}
926
96449e8e 927sub _recurse_where {
928 my ($self, $where, $logic) = @_;
929
5492d4c2 930 # Special case: top level simple string treated as literal
931
932 my $where_exp = (ref($where)
ae56a156 933 ? $self->_expand_expr($where, $logic)
5492d4c2 934 : { -literal => [ $where ] });
e175845b 935
e3e27543 936 # dispatch expanded expression
311b2151 937
79d310f2 938 my ($sql, @bind) = defined($where_exp) ? $self->render_aqt($where_exp) : (undef);
abe1a491 939 # DBIx::Class used to call _recurse_where in scalar context
940 # something else might too...
941 if (wantarray) {
942 return ($sql, @bind);
943 }
944 else {
945 belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
946 return $sql;
947 }
96449e8e 948}
949
181dcebf 950sub _render_ident {
951 my ($self, $ident) = @_;
cc422895 952
9cf28dfb 953 return $self->_convert($self->_quote($ident));
cc422895 954}
955
c452734e 956my %unop_postfix = map +($_ => 1),
957 'is null', 'is not null',
958 'asc', 'desc',
959;
d13725da 960
b5b18861 961my %special = (
962 (map +($_ => do {
963 my $op = $_;
964 sub {
965 my ($self, $args) = @_;
966 my ($left, $low, $high) = @$args;
967 my ($rhsql, @rhbind) = do {
968 if (@$args == 2) {
969 puke "Single arg to between must be a literal"
970 unless $low->{-literal};
971 @{$low->{-literal}}
972 } else {
79d310f2 973 my ($l, $h) = map [ $self->render_aqt($_) ], $low, $high;
b5b18861 974 (join(' ', $l->[0], $self->_sqlcase('and'), $h->[0]),
975 @{$l}[1..$#$l], @{$h}[1..$#$h])
976 }
977 };
79d310f2 978 my ($lhsql, @lhbind) = $self->render_aqt($left);
b5b18861 979 return (
980 join(' ', '(', $lhsql, $self->_sqlcase($op), $rhsql, ')'),
981 @lhbind, @rhbind
982 );
983 }
984 }), 'between', 'not between'),
10d07c4e 985 (map +($_ => do {
986 my $op = $_;
987 sub {
988 my ($self, $args) = @_;
989 my ($lhs, $rhs) = @$args;
990 my @in_bind;
991 my @in_sql = map {
79d310f2 992 my ($sql, @bind) = $self->render_aqt($_);
10d07c4e 993 push @in_bind, @bind;
994 $sql;
995 } @$rhs;
79d310f2 996 my ($lhsql, @lbind) = $self->render_aqt($lhs);
10d07c4e 997 return (
998 $lhsql.' '.$self->_sqlcase($op).' ( '
999 .join(', ', @in_sql)
1000 .' )',
1001 @lbind, @in_bind
1002 );
1003 }
1004 }), 'in', 'not in'),
b5b18861 1005);
1006
181dcebf 1007sub _render_op {
1008 my ($self, $v) = @_;
d13725da 1009 my ($op, @args) = @$v;
1010 $op =~ s/^-// if length($op) > 1;
cba28f66 1011 $op = lc($op);
b5b18861 1012 if (my $h = $special{$op}) {
1013 return $self->$h(\@args);
1014 }
3ae10d16 1015 my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
1016 if ($us and @args > 1) {
99a65fa8 1017 puke "Special op '${op}' requires first value to be identifier"
7d93797d 1018 unless my ($ident) = map $_->{-ident}, grep ref($_) eq 'HASH', $args[0];
1019 my $k = join(($self->{name_sep}||'.'), @$ident);
dd1d0dbf 1020 local our $Expand_Depth = 1;
99a65fa8 1021 return $self->${\($us->{handler})}($k, $op, $args[1]);
1022 }
96a8d74a 1023 if (my $us = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
1024 return $self->${\($us->{handler})}($op, $args[0]);
1025 }
99a65fa8 1026 my $final_op = $op =~ /^(?:is|not)_/ ? join(' ', split '_', $op) : $op;
2143604f 1027 if (@args == 1 and $op !~ /^(and|or)$/) {
79d310f2 1028 my ($expr_sql, @bind) = $self->render_aqt($args[0]);
d13725da 1029 my $op_sql = $self->_sqlcase($final_op);
1030 my $final_sql = (
1031 $unop_postfix{lc($final_op)}
1032 ? "${expr_sql} ${op_sql}"
1033 : "${op_sql} ${expr_sql}"
1034 );
3ae10d16 1035 return (($op eq 'not' || $us ? '('.$final_sql.')' : $final_sql), @bind);
16d9289c 1036 } else {
79d310f2 1037 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @args;
1c0c0f41 1038 return '' unless @parts;
230812fc 1039 my $is_andor = !!($op =~ /^(and|or)$/);
1040 return @{$parts[0]} if $is_andor and @parts == 1;
1041 my ($final_sql) = map +($is_andor ? "( ${_} )" : $_), join(
352d74bc 1042 ' '.$self->_sqlcase($final_op).' ',
77617257 1043 map $_->[0], @parts
1044 );
99a65fa8 1045 return (
77617257 1046 $final_sql,
16d9289c 1047 map @{$_}[1..$#$_], @parts
99a65fa8 1048 );
d13725da 1049 }
1050 die "unhandled";
1051}
1052
352d74bc 1053sub _render_list {
1054 my ($self, $list) = @_;
79d310f2 1055 my @parts = grep length($_->[0]), map [ $self->render_aqt($_) ], @$list;
352d74bc 1056 return join(', ', map $_->[0], @parts), map @{$_}[1..$#$_], @parts;
1057}
1058
181dcebf 1059sub _render_func {
1060 my ($self, $rest) = @_;
711892b1 1061 my ($func, @args) = @$rest;
1062 my @arg_sql;
1063 my @bind = map {
1064 my @x = @$_;
1065 push @arg_sql, shift @x;
1066 @x
79d310f2 1067 } map [ $self->render_aqt($_) ], @args;
711892b1 1068 return ($self->_sqlcase($func).'('.join(', ', @arg_sql).')', @bind);
1069}
1070
181dcebf 1071sub _render_bind {
1072 my ($self, $bind) = @_;
d13725da 1073 return ($self->_convert('?'), $self->_bindtype(@$bind));
1074}
1075
181dcebf 1076sub _render_literal {
1077 my ($self, $literal) = @_;
465d43fd 1078 $self->_assert_bindval_matches_bindtype(@{$literal}[1..$#$literal]);
aa8d7bdb 1079 return @$literal;
1080}
1081
4a1f01a3 1082# Some databases (SQLite) treat col IN (1, 2) different from
1083# col IN ( (1, 2) ). Use this to strip all outer parens while
1084# adding them back in the corresponding method
1085sub _open_outer_paren {
1086 my ($self, $sql) = @_;
a5f91feb 1087
ca4f826a 1088 while (my ($inner) = $sql =~ /^ \s* \( (.*) \) \s* $/xs) {
a5f91feb 1089
1090 # there are closing parens inside, need the heavy duty machinery
1091 # to reevaluate the extraction starting from $sql (full reevaluation)
ca4f826a 1092 if ($inner =~ /\)/) {
a5f91feb 1093 require Text::Balanced;
1094
1095 my (undef, $remainder) = do {
1096 # idiotic design - writes to $@ but *DOES NOT* throw exceptions
1097 local $@;
ca4f826a 1098 Text::Balanced::extract_bracketed($sql, '()', qr/\s*/);
a5f91feb 1099 };
1100
1101 # the entire expression needs to be a balanced bracketed thing
1102 # (after an extract no remainder sans trailing space)
1103 last if defined $remainder and $remainder =~ /\S/;
1104 }
1105
1106 $sql = $inner;
1107 }
1108
1109 $sql;
4a1f01a3 1110}
1111
96449e8e 1112
96449e8e 1113#======================================================================
1114# ORDER BY
1115#======================================================================
1116
33177570 1117sub _expand_order_by {
96449e8e 1118 my ($self, $arg) = @_;
1119
33177570 1120 return unless defined($arg) and not (ref($arg) eq 'ARRAY' and !@$arg);
2b6158af 1121
4325df6a 1122 my $expander = sub {
1123 my ($self, $dir, $expr) = @_;
52ca537e 1124 my @to_expand = ref($expr) eq 'ARRAY' ? @$expr : $expr;
1125 foreach my $arg (@to_expand) {
1126 if (
1127 ref($arg) eq 'HASH'
1128 and keys %$arg > 1
1129 and grep /^-(asc|desc)$/, keys %$arg
1130 ) {
1131 puke "ordering direction hash passed to order by must have exactly one key (-asc or -desc)";
1132 }
1133 }
4325df6a 1134 my @exp = map +(defined($dir) ? { -op => [ $dir => $_ ] } : $_),
79d310f2 1135 map $self->expand_expr($_, -ident),
74156ee9 1136 map ref($_) eq 'ARRAY' ? @$_ : $_, @to_expand;
352d74bc 1137 return (@exp > 1 ? { -list => \@exp } : $exp[0]);
4325df6a 1138 };
18c743c8 1139
ec19b759 1140 local @{$self->{expand_unary}}{qw(-asc -desc)} = (
1141 sub { shift->$expander(asc => @_) },
1142 sub { shift->$expander(desc => @_) },
1143 );
f267b646 1144
33177570 1145 return $self->$expander(undef, $arg);
1146}
1147
1148sub _order_by {
1149 my ($self, $arg) = @_;
1150
1151 return '' unless defined(my $expanded = $self->_expand_order_by($arg));
4325df6a 1152
79d310f2 1153 my ($sql, @bind) = $self->render_aqt($expanded);
4325df6a 1154
13cd9220 1155 return '' unless length($sql);
1156
4325df6a 1157 my $final_sql = $self->_sqlcase(' order by ').$sql;
1158
1159 return wantarray ? ($final_sql, @bind) : $final_sql;
f267b646 1160}
1161
2e3cc357 1162# _order_by no longer needs to call this so doesn't but DBIC uses it.
1163
33177570 1164sub _order_by_chunks {
1165 my ($self, $arg) = @_;
1166
1167 return () unless defined(my $expanded = $self->_expand_order_by($arg));
1168
2e3cc357 1169 return $self->_chunkify_order_by($expanded);
1170}
1171
1172sub _chunkify_order_by {
1173 my ($self, $expanded) = @_;
1b630cfe 1174
79d310f2 1175 return grep length, $self->render_aqt($expanded)
1b630cfe 1176 if $expanded->{-ident} or @{$expanded->{-literal}||[]} == 1;
1177
33177570 1178 for ($expanded) {
352d74bc 1179 if (ref() eq 'HASH' and my $l = $_->{-list}) {
1180 return map $self->_chunkify_order_by($_), @$l;
33177570 1181 }
79d310f2 1182 return [ $self->render_aqt($_) ];
33177570 1183 }
1184}
1185
96449e8e 1186#======================================================================
1187# DATASOURCE (FOR NOW, JUST PLAIN TABLE OR LIST OF TABLES)
1188#======================================================================
1189
1190sub _table {
1191 my $self = shift;
1192 my $from = shift;
79d310f2 1193 ($self->render_aqt(
8476c6a3 1194 $self->_expand_maybe_list_expr($from, undef, -ident)
7ad12721 1195 ))[0];
96449e8e 1196}
1197
1198
1199#======================================================================
1200# UTILITY FUNCTIONS
1201#======================================================================
1202
8476c6a3 1203sub _expand_maybe_list_expr {
1204 my ($self, $expr, $logic, $default) = @_;
bba04f52 1205 my $e = do {
1206 if (ref($expr) eq 'ARRAY') {
352d74bc 1207 return { -list => [
4ee3313d 1208 map $self->expand_expr($_, $default), @$expr
bba04f52 1209 ] } if @$expr > 1;
1210 $expr->[0]
1211 } else {
1212 $expr
1213 }
1214 };
4ee3313d 1215 return $self->expand_expr($e, $default);
8476c6a3 1216}
1217
955e77ca 1218# highly optimized, as it's called way too often
96449e8e 1219sub _quote {
955e77ca 1220 # my ($self, $label) = @_;
96449e8e 1221
955e77ca 1222 return '' unless defined $_[1];
955e77ca 1223 return ${$_[1]} if ref($_[1]) eq 'SCALAR';
d3162b5c 1224 puke 'Identifier cannot be hashref' if ref($_[1]) eq 'HASH';
96449e8e 1225
d3162b5c 1226 unless ($_[0]->{quote_char}) {
1227 if (ref($_[1]) eq 'ARRAY') {
1228 return join($_[0]->{name_sep}||'.', @{$_[1]});
1229 } else {
1230 $_[0]->_assert_pass_injection_guard($_[1]);
1231 return $_[1];
1232 }
1233 }
96449e8e 1234
07d7c35c 1235 my $qref = ref $_[0]->{quote_char};
439834d3 1236 my ($l, $r) =
1237 !$qref ? ($_[0]->{quote_char}, $_[0]->{quote_char})
1238 : ($qref eq 'ARRAY') ? @{$_[0]->{quote_char}}
1239 : puke "Unsupported quote_char format: $_[0]->{quote_char}";
1240
46be4313 1241 my $esc = $_[0]->{escape_char} || $r;
96449e8e 1242
07d7c35c 1243 # parts containing * are naturally unquoted
d3162b5c 1244 return join(
1245 $_[0]->{name_sep}||'',
1246 map +(
1247 $_ eq '*'
1248 ? $_
1249 : do { (my $n = $_) =~ s/(\Q$esc\E|\Q$r\E)/$esc$1/g; $l . $n . $r }
1250 ),
1251 (ref($_[1]) eq 'ARRAY'
1252 ? @{$_[1]}
1253 : (
1254 $_[0]->{name_sep}
1255 ? split (/\Q$_[0]->{name_sep}\E/, $_[1] )
1256 : $_[1]
1257 )
1258 )
955e77ca 1259 );
96449e8e 1260}
1261
1262
1263# Conversion, if applicable
d7c862e0 1264sub _convert {
07d7c35c 1265 #my ($self, $arg) = @_;
7ad12721 1266 if ($_[0]->{convert_where}) {
1267 return $_[0]->_sqlcase($_[0]->{convert_where}) .'(' . $_[1] . ')';
96449e8e 1268 }
07d7c35c 1269 return $_[1];
96449e8e 1270}
1271
1272# And bindtype
d7c862e0 1273sub _bindtype {
07d7c35c 1274 #my ($self, $col, @vals) = @_;
07d7c35c 1275 # called often - tighten code
1276 return $_[0]->{bindtype} eq 'columns'
1277 ? map {[$_[1], $_]} @_[2 .. $#_]
1278 : @_[2 .. $#_]
1279 ;
96449e8e 1280}
1281
fe3ae272 1282# Dies if any element of @bind is not in [colname => value] format
1283# if bindtype is 'columns'.
1284sub _assert_bindval_matches_bindtype {
c94a6c93 1285# my ($self, @bind) = @_;
1286 my $self = shift;
fe3ae272 1287 if ($self->{bindtype} eq 'columns') {
c94a6c93 1288 for (@_) {
1289 if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
3a06278c 1290 puke "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
fe3ae272 1291 }
1292 }
1293 }
1294}
1295
96449e8e 1296sub _join_sql_clauses {
1297 my ($self, $logic, $clauses_aref, $bind_aref) = @_;
1298
1299 if (@$clauses_aref > 1) {
1300 my $join = " " . $self->_sqlcase($logic) . " ";
1301 my $sql = '( ' . join($join, @$clauses_aref) . ' )';
1302 return ($sql, @$bind_aref);
1303 }
1304 elsif (@$clauses_aref) {
1305 return ($clauses_aref->[0], @$bind_aref); # no parentheses
1306 }
1307 else {
1308 return (); # if no SQL, ignore @$bind_aref
1309 }
1310}
1311
1312
1313# Fix SQL case, if so requested
1314sub _sqlcase {
96449e8e 1315 # LDNOTE: if $self->{case} is true, then it contains 'lower', so we
1316 # don't touch the argument ... crooked logic, but let's not change it!
07d7c35c 1317 return $_[0]->{case} ? $_[1] : uc($_[1]);
96449e8e 1318}
1319
1320
1321#======================================================================
1322# DISPATCHING FROM REFKIND
1323#======================================================================
1324
1325sub _refkind {
1326 my ($self, $data) = @_;
96449e8e 1327
955e77ca 1328 return 'UNDEF' unless defined $data;
1329
1330 # blessed objects are treated like scalars
1331 my $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1332
1333 return 'SCALAR' unless $ref;
1334
1335 my $n_steps = 1;
1336 while ($ref eq 'REF') {
96449e8e 1337 $data = $$data;
955e77ca 1338 $ref = (Scalar::Util::blessed $data) ? '' : ref $data;
1339 $n_steps++ if $ref;
96449e8e 1340 }
1341
848556bc 1342 return ($ref||'SCALAR') . ('REF' x $n_steps);
96449e8e 1343}
1344
1345sub _try_refkind {
1346 my ($self, $data) = @_;
1347 my @try = ($self->_refkind($data));
1348 push @try, 'SCALAR_or_UNDEF' if $try[0] eq 'SCALAR' || $try[0] eq 'UNDEF';
1349 push @try, 'FALLBACK';
955e77ca 1350 return \@try;
96449e8e 1351}
1352
1353sub _METHOD_FOR_refkind {
1354 my ($self, $meth_prefix, $data) = @_;
f39eaa60 1355
1356 my $method;
955e77ca 1357 for (@{$self->_try_refkind($data)}) {
f39eaa60 1358 $method = $self->can($meth_prefix."_".$_)
1359 and last;
1360 }
1361
1362 return $method || puke "cannot dispatch on '$meth_prefix' for ".$self->_refkind($data);
96449e8e 1363}
1364
1365
1366sub _SWITCH_refkind {
1367 my ($self, $data, $dispatch_table) = @_;
1368
f39eaa60 1369 my $coderef;
955e77ca 1370 for (@{$self->_try_refkind($data)}) {
f39eaa60 1371 $coderef = $dispatch_table->{$_}
1372 and last;
1373 }
1374
1375 puke "no dispatch entry for ".$self->_refkind($data)
1376 unless $coderef;
1377
96449e8e 1378 $coderef->();
1379}
1380
1381
1382
1383
1384#======================================================================
1385# VALUES, GENERATE, AUTOLOAD
1386#======================================================================
1387
1388# LDNOTE: original code from nwiger, didn't touch code in that section
1389# I feel the AUTOLOAD stuff should not be the default, it should
1390# only be activated on explicit demand by user.
1391
1392sub values {
1393 my $self = shift;
1394 my $data = shift || return;
1395 puke "Argument to ", __PACKAGE__, "->values must be a \\%hash"
1396 unless ref $data eq 'HASH';
bab725ce 1397
1398 my @all_bind;
ca4f826a 1399 foreach my $k (sort keys %$data) {
bab725ce 1400 my $v = $data->{$k};
1401 $self->_SWITCH_refkind($v, {
9d48860e 1402 ARRAYREF => sub {
bab725ce 1403 if ($self->{array_datatypes}) { # array datatype
1404 push @all_bind, $self->_bindtype($k, $v);
1405 }
1406 else { # literal SQL with bind
1407 my ($sql, @bind) = @$v;
1408 $self->_assert_bindval_matches_bindtype(@bind);
1409 push @all_bind, @bind;
1410 }
1411 },
1412 ARRAYREFREF => sub { # literal SQL with bind
1413 my ($sql, @bind) = @${$v};
1414 $self->_assert_bindval_matches_bindtype(@bind);
1415 push @all_bind, @bind;
1416 },
1417 SCALARREF => sub { # literal SQL without bind
1418 },
1419 SCALAR_or_UNDEF => sub {
1420 push @all_bind, $self->_bindtype($k, $v);
1421 },
1422 });
1423 }
1424
1425 return @all_bind;
96449e8e 1426}
1427
1428sub generate {
1429 my $self = shift;
1430
1431 my(@sql, @sqlq, @sqlv);
1432
1433 for (@_) {
1434 my $ref = ref $_;
1435 if ($ref eq 'HASH') {
1436 for my $k (sort keys %$_) {
1437 my $v = $_->{$k};
1438 my $r = ref $v;
1439 my $label = $self->_quote($k);
1440 if ($r eq 'ARRAY') {
fe3ae272 1441 # literal SQL with bind
1442 my ($sql, @bind) = @$v;
1443 $self->_assert_bindval_matches_bindtype(@bind);
96449e8e 1444 push @sqlq, "$label = $sql";
fe3ae272 1445 push @sqlv, @bind;
96449e8e 1446 } elsif ($r eq 'SCALAR') {
fe3ae272 1447 # literal SQL without bind
96449e8e 1448 push @sqlq, "$label = $$v";
9d48860e 1449 } else {
96449e8e 1450 push @sqlq, "$label = ?";
1451 push @sqlv, $self->_bindtype($k, $v);
1452 }
1453 }
1454 push @sql, $self->_sqlcase('set'), join ', ', @sqlq;
1455 } elsif ($ref eq 'ARRAY') {
1456 # unlike insert(), assume these are ONLY the column names, i.e. for SQL
1457 for my $v (@$_) {
1458 my $r = ref $v;
fe3ae272 1459 if ($r eq 'ARRAY') { # literal SQL with bind
1460 my ($sql, @bind) = @$v;
1461 $self->_assert_bindval_matches_bindtype(@bind);
1462 push @sqlq, $sql;
1463 push @sqlv, @bind;
1464 } elsif ($r eq 'SCALAR') { # literal SQL without bind
96449e8e 1465 # embedded literal SQL
1466 push @sqlq, $$v;
9d48860e 1467 } else {
96449e8e 1468 push @sqlq, '?';
1469 push @sqlv, $v;
1470 }
1471 }
1472 push @sql, '(' . join(', ', @sqlq) . ')';
1473 } elsif ($ref eq 'SCALAR') {
1474 # literal SQL
1475 push @sql, $$_;
1476 } else {
1477 # strings get case twiddled
1478 push @sql, $self->_sqlcase($_);
1479 }
1480 }
1481
1482 my $sql = join ' ', @sql;
1483
1484 # this is pretty tricky
1485 # if ask for an array, return ($stmt, @bind)
1486 # otherwise, s/?/shift @sqlv/ to put it inline
1487 if (wantarray) {
1488 return ($sql, @sqlv);
1489 } else {
1490 1 while $sql =~ s/\?/my $d = shift(@sqlv);
1491 ref $d ? $d->[1] : $d/e;
1492 return $sql;
1493 }
1494}
1495
1496
1497sub DESTROY { 1 }
1498
1499sub AUTOLOAD {
1500 # This allows us to check for a local, then _form, attr
1501 my $self = shift;
1502 my($name) = $AUTOLOAD =~ /.*::(.+)/;
1503 return $self->generate($name, @_);
1504}
1505
15061;
1507
1508
1509
1510__END__
32eab2da 1511
1512=head1 NAME
1513
1514SQL::Abstract - Generate SQL from Perl data structures
1515
1516=head1 SYNOPSIS
1517
1518 use SQL::Abstract;
1519
1520 my $sql = SQL::Abstract->new;
1521
85783f3c 1522 my($stmt, @bind) = $sql->select($source, \@fields, \%where, $order);
32eab2da 1523
1524 my($stmt, @bind) = $sql->insert($table, \%fieldvals || \@values);
1525
1526 my($stmt, @bind) = $sql->update($table, \%fieldvals, \%where);
1527
1528 my($stmt, @bind) = $sql->delete($table, \%where);
1529
1530 # Then, use these in your DBI statements
1531 my $sth = $dbh->prepare($stmt);
1532 $sth->execute(@bind);
1533
1534 # Just generate the WHERE clause
85783f3c 1535 my($stmt, @bind) = $sql->where(\%where, $order);
32eab2da 1536
1537 # Return values in the same order, for hashed queries
1538 # See PERFORMANCE section for more details
1539 my @bind = $sql->values(\%fieldvals);
1540
1541=head1 DESCRIPTION
1542
1543This module was inspired by the excellent L<DBIx::Abstract>.
1544However, in using that module I found that what I really wanted
1545to do was generate SQL, but still retain complete control over my
1546statement handles and use the DBI interface. So, I set out to
1547create an abstract SQL generation module.
1548
1549While based on the concepts used by L<DBIx::Abstract>, there are
1550several important differences, especially when it comes to WHERE
1551clauses. I have modified the concepts used to make the SQL easier
1552to generate from Perl data structures and, IMO, more intuitive.
1553The underlying idea is for this module to do what you mean, based
1554on the data structures you provide it. The big advantage is that
1555you don't have to modify your code every time your data changes,
1556as this module figures it out.
1557
1558To begin with, an SQL INSERT is as easy as just specifying a hash
1559of C<key=value> pairs:
1560
1561 my %data = (
1562 name => 'Jimbo Bobson',
1563 phone => '123-456-7890',
1564 address => '42 Sister Lane',
1565 city => 'St. Louis',
1566 state => 'Louisiana',
1567 );
1568
1569The SQL can then be generated with this:
1570
1571 my($stmt, @bind) = $sql->insert('people', \%data);
1572
1573Which would give you something like this:
1574
1575 $stmt = "INSERT INTO people
1576 (address, city, name, phone, state)
1577 VALUES (?, ?, ?, ?, ?)";
1578 @bind = ('42 Sister Lane', 'St. Louis', 'Jimbo Bobson',
1579 '123-456-7890', 'Louisiana');
1580
1581These are then used directly in your DBI code:
1582
1583 my $sth = $dbh->prepare($stmt);
1584 $sth->execute(@bind);
1585
96449e8e 1586=head2 Inserting and Updating Arrays
1587
1588If your database has array types (like for example Postgres),
1589activate the special option C<< array_datatypes => 1 >>
9d48860e 1590when creating the C<SQL::Abstract> object.
96449e8e 1591Then you may use an arrayref to insert and update database array types:
1592
1593 my $sql = SQL::Abstract->new(array_datatypes => 1);
1594 my %data = (
1595 planets => [qw/Mercury Venus Earth Mars/]
1596 );
9d48860e 1597
96449e8e 1598 my($stmt, @bind) = $sql->insert('solar_system', \%data);
1599
1600This results in:
1601
1602 $stmt = "INSERT INTO solar_system (planets) VALUES (?)"
1603
1604 @bind = (['Mercury', 'Venus', 'Earth', 'Mars']);
1605
1606
1607=head2 Inserting and Updating SQL
1608
1609In order to apply SQL functions to elements of your C<%data> you may
1610specify a reference to an arrayref for the given hash value. For example,
1611if you need to execute the Oracle C<to_date> function on a value, you can
1612say something like this:
32eab2da 1613
1614 my %data = (
1615 name => 'Bill',
3ae1c5e2 1616 date_entered => \[ "to_date(?,'MM/DD/YYYY')", "03/02/2003" ],
9d48860e 1617 );
32eab2da 1618
1619The first value in the array is the actual SQL. Any other values are
1620optional and would be included in the bind values array. This gives
1621you:
1622
1623 my($stmt, @bind) = $sql->insert('people', \%data);
1624
9d48860e 1625 $stmt = "INSERT INTO people (name, date_entered)
32eab2da 1626 VALUES (?, to_date(?,'MM/DD/YYYY'))";
1627 @bind = ('Bill', '03/02/2003');
1628
1629An UPDATE is just as easy, all you change is the name of the function:
1630
1631 my($stmt, @bind) = $sql->update('people', \%data);
1632
1633Notice that your C<%data> isn't touched; the module will generate
1634the appropriately quirky SQL for you automatically. Usually you'll
1635want to specify a WHERE clause for your UPDATE, though, which is
1636where handling C<%where> hashes comes in handy...
1637
96449e8e 1638=head2 Complex where statements
1639
32eab2da 1640This module can generate pretty complicated WHERE statements
1641easily. For example, simple C<key=value> pairs are taken to mean
1642equality, and if you want to see if a field is within a set
1643of values, you can use an arrayref. Let's say we wanted to
1644SELECT some data based on this criteria:
1645
1646 my %where = (
1647 requestor => 'inna',
1648 worker => ['nwiger', 'rcwe', 'sfz'],
1649 status => { '!=', 'completed' }
1650 );
1651
1652 my($stmt, @bind) = $sql->select('tickets', '*', \%where);
1653
1654The above would give you something like this:
1655
1656 $stmt = "SELECT * FROM tickets WHERE
1657 ( requestor = ? ) AND ( status != ? )
1658 AND ( worker = ? OR worker = ? OR worker = ? )";
1659 @bind = ('inna', 'completed', 'nwiger', 'rcwe', 'sfz');
1660
1661Which you could then use in DBI code like so:
1662
1663 my $sth = $dbh->prepare($stmt);
1664 $sth->execute(@bind);
1665
1666Easy, eh?
1667
0da0fe34 1668=head1 METHODS
32eab2da 1669
13cc86af 1670The methods are simple. There's one for every major SQL operation,
32eab2da 1671and a constructor you use first. The arguments are specified in a
13cc86af 1672similar order for each method (table, then fields, then a where
32eab2da 1673clause) to try and simplify things.
1674
32eab2da 1675=head2 new(option => 'value')
1676
1677The C<new()> function takes a list of options and values, and returns
1678a new B<SQL::Abstract> object which can then be used to generate SQL
1679through the methods below. The options accepted are:
1680
1681=over
1682
1683=item case
1684
1685If set to 'lower', then SQL will be generated in all lowercase. By
1686default SQL is generated in "textbook" case meaning something like:
1687
1688 SELECT a_field FROM a_table WHERE some_field LIKE '%someval%'
1689
96449e8e 1690Any setting other than 'lower' is ignored.
1691
32eab2da 1692=item cmp
1693
1694This determines what the default comparison operator is. By default
1695it is C<=>, meaning that a hash like this:
1696
1697 %where = (name => 'nwiger', email => 'nate@wiger.org');
1698
1699Will generate SQL like this:
1700
1701 WHERE name = 'nwiger' AND email = 'nate@wiger.org'
1702
1703However, you may want loose comparisons by default, so if you set
1704C<cmp> to C<like> you would get SQL such as:
1705
1706 WHERE name like 'nwiger' AND email like 'nate@wiger.org'
1707
3af02ccb 1708You can also override the comparison on an individual basis - see
32eab2da 1709the huge section on L</"WHERE CLAUSES"> at the bottom.
1710
96449e8e 1711=item sqltrue, sqlfalse
1712
1713Expressions for inserting boolean values within SQL statements.
6e0c6552 1714By default these are C<1=1> and C<1=0>. They are used
1715by the special operators C<-in> and C<-not_in> for generating
1716correct SQL even when the argument is an empty array (see below).
96449e8e 1717
32eab2da 1718=item logic
1719
1720This determines the default logical operator for multiple WHERE
7cac25e6 1721statements in arrays or hashes. If absent, the default logic is "or"
1722for arrays, and "and" for hashes. This means that a WHERE
32eab2da 1723array of the form:
1724
1725 @where = (
9d48860e 1726 event_date => {'>=', '2/13/99'},
1727 event_date => {'<=', '4/24/03'},
32eab2da 1728 );
1729
7cac25e6 1730will generate SQL like this:
32eab2da 1731
1732 WHERE event_date >= '2/13/99' OR event_date <= '4/24/03'
1733
1734This is probably not what you want given this query, though (look
1735at the dates). To change the "OR" to an "AND", simply specify:
1736
1737 my $sql = SQL::Abstract->new(logic => 'and');
1738
1739Which will change the above C<WHERE> to:
1740
1741 WHERE event_date >= '2/13/99' AND event_date <= '4/24/03'
1742
96449e8e 1743The logic can also be changed locally by inserting
be21dde3 1744a modifier in front of an arrayref:
96449e8e 1745
9d48860e 1746 @where = (-and => [event_date => {'>=', '2/13/99'},
7cac25e6 1747 event_date => {'<=', '4/24/03'} ]);
96449e8e 1748
1749See the L</"WHERE CLAUSES"> section for explanations.
1750
32eab2da 1751=item convert
1752
1753This will automatically convert comparisons using the specified SQL
1754function for both column and value. This is mostly used with an argument
1755of C<upper> or C<lower>, so that the SQL will have the effect of
1756case-insensitive "searches". For example, this:
1757
1758 $sql = SQL::Abstract->new(convert => 'upper');
1759 %where = (keywords => 'MaKe iT CAse inSeNSItive');
1760
1761Will turn out the following SQL:
1762
1763 WHERE upper(keywords) like upper('MaKe iT CAse inSeNSItive')
1764
1765The conversion can be C<upper()>, C<lower()>, or any other SQL function
1766that can be applied symmetrically to fields (actually B<SQL::Abstract> does
1767not validate this option; it will just pass through what you specify verbatim).
1768
1769=item bindtype
1770
1771This is a kludge because many databases suck. For example, you can't
1772just bind values using DBI's C<execute()> for Oracle C<CLOB> or C<BLOB> fields.
1773Instead, you have to use C<bind_param()>:
1774
1775 $sth->bind_param(1, 'reg data');
1776 $sth->bind_param(2, $lots, {ora_type => ORA_CLOB});
1777
1778The problem is, B<SQL::Abstract> will normally just return a C<@bind> array,
1779which loses track of which field each slot refers to. Fear not.
1780
1781If you specify C<bindtype> in new, you can determine how C<@bind> is returned.
1782Currently, you can specify either C<normal> (default) or C<columns>. If you
1783specify C<columns>, you will get an array that looks like this:
1784
1785 my $sql = SQL::Abstract->new(bindtype => 'columns');
1786 my($stmt, @bind) = $sql->insert(...);
1787
1788 @bind = (
1789 [ 'column1', 'value1' ],
1790 [ 'column2', 'value2' ],
1791 [ 'column3', 'value3' ],
1792 );
1793
1794You can then iterate through this manually, using DBI's C<bind_param()>.
e3f9dff4 1795
32eab2da 1796 $sth->prepare($stmt);
1797 my $i = 1;
1798 for (@bind) {
1799 my($col, $data) = @$_;
1800 if ($col eq 'details' || $col eq 'comments') {
1801 $sth->bind_param($i, $data, {ora_type => ORA_CLOB});
1802 } elsif ($col eq 'image') {
1803 $sth->bind_param($i, $data, {ora_type => ORA_BLOB});
1804 } else {
1805 $sth->bind_param($i, $data);
1806 }
1807 $i++;
1808 }
1809 $sth->execute; # execute without @bind now
1810
1811Now, why would you still use B<SQL::Abstract> if you have to do this crap?
1812Basically, the advantage is still that you don't have to care which fields
1813are or are not included. You could wrap that above C<for> loop in a simple
1814sub called C<bind_fields()> or something and reuse it repeatedly. You still
1815get a layer of abstraction over manual SQL specification.
1816
3ae1c5e2 1817Note that if you set L</bindtype> to C<columns>, the C<\[ $sql, @bind ]>
deb148a2 1818construct (see L</Literal SQL with placeholders and bind values (subqueries)>)
1819will expect the bind values in this format.
1820
32eab2da 1821=item quote_char
1822
1823This is the character that a table or column name will be quoted
9d48860e 1824with. By default this is an empty string, but you could set it to
32eab2da 1825the character C<`>, to generate SQL like this:
1826
1827 SELECT `a_field` FROM `a_table` WHERE `some_field` LIKE '%someval%'
1828
96449e8e 1829Alternatively, you can supply an array ref of two items, the first being the left
1830hand quote character, and the second the right hand quote character. For
1831example, you could supply C<['[',']']> for SQL Server 2000 compliant quotes
1832that generates SQL like this:
1833
1834 SELECT [a_field] FROM [a_table] WHERE [some_field] LIKE '%someval%'
1835
9d48860e 1836Quoting is useful if you have tables or columns names that are reserved
96449e8e 1837words in your database's SQL dialect.
32eab2da 1838
46be4313 1839=item escape_char
1840
1841This is the character that will be used to escape L</quote_char>s appearing
1842in an identifier before it has been quoted.
1843
80790166 1844The parameter default in case of a single L</quote_char> character is the quote
46be4313 1845character itself.
1846
1847When opening-closing-style quoting is used (L</quote_char> is an arrayref)
9de2bd86 1848this parameter defaults to the B<closing (right)> L</quote_char>. Occurrences
46be4313 1849of the B<opening (left)> L</quote_char> within the identifier are currently left
1850untouched. The default for opening-closing-style quotes may change in future
1851versions, thus you are B<strongly encouraged> to specify the escape character
1852explicitly.
1853
32eab2da 1854=item name_sep
1855
1856This is the character that separates a table and column name. It is
1857necessary to specify this when the C<quote_char> option is selected,
1858so that tables and column names can be individually quoted like this:
1859
1860 SELECT `table`.`one_field` FROM `table` WHERE `table`.`other_field` = 1
1861
b6251592 1862=item injection_guard
1863
1864A regular expression C<qr/.../> that is applied to any C<-function> and unquoted
1865column name specified in a query structure. This is a safety mechanism to avoid
1866injection attacks when mishandling user input e.g.:
1867
1868 my %condition_as_column_value_pairs = get_values_from_user();
1869 $sqla->select( ... , \%condition_as_column_value_pairs );
1870
1871If the expression matches an exception is thrown. Note that literal SQL
1872supplied via C<\'...'> or C<\['...']> is B<not> checked in any way.
1873
1874Defaults to checking for C<;> and the C<GO> keyword (TransactSQL)
1875
96449e8e 1876=item array_datatypes
32eab2da 1877
9d48860e 1878When this option is true, arrayrefs in INSERT or UPDATE are
1879interpreted as array datatypes and are passed directly
96449e8e 1880to the DBI layer.
1881When this option is false, arrayrefs are interpreted
1882as literal SQL, just like refs to arrayrefs
1883(but this behavior is for backwards compatibility; when writing
1884new queries, use the "reference to arrayref" syntax
1885for literal SQL).
32eab2da 1886
32eab2da 1887
96449e8e 1888=item special_ops
32eab2da 1889
9d48860e 1890Takes a reference to a list of "special operators"
96449e8e 1891to extend the syntax understood by L<SQL::Abstract>.
1892See section L</"SPECIAL OPERATORS"> for details.
32eab2da 1893
59f23b3d 1894=item unary_ops
1895
9d48860e 1896Takes a reference to a list of "unary operators"
59f23b3d 1897to extend the syntax understood by L<SQL::Abstract>.
1898See section L</"UNARY OPERATORS"> for details.
1899
32eab2da 1900
32eab2da 1901
96449e8e 1902=back
32eab2da 1903
02288357 1904=head2 insert($table, \@values || \%fieldvals, \%options)
32eab2da 1905
1906This is the simplest function. You simply give it a table name
1907and either an arrayref of values or hashref of field/value pairs.
1908It returns an SQL INSERT statement and a list of bind values.
96449e8e 1909See the sections on L</"Inserting and Updating Arrays"> and
1910L</"Inserting and Updating SQL"> for information on how to insert
1911with those data types.
32eab2da 1912
02288357 1913The optional C<\%options> hash reference may contain additional
1914options to generate the insert SQL. Currently supported options
1915are:
1916
1917=over 4
1918
1919=item returning
1920
1921Takes either a scalar of raw SQL fields, or an array reference of
1922field names, and adds on an SQL C<RETURNING> statement at the end.
1923This allows you to return data generated by the insert statement
1924(such as row IDs) without performing another C<SELECT> statement.
1925Note, however, this is not part of the SQL standard and may not
1926be supported by all database engines.
1927
1928=back
1929
95904db5 1930=head2 update($table, \%fieldvals, \%where, \%options)
32eab2da 1931
1932This takes a table, hashref of field/value pairs, and an optional
86298391 1933hashref L<WHERE clause|/WHERE CLAUSES>. It returns an SQL UPDATE function and a list
32eab2da 1934of bind values.
96449e8e 1935See the sections on L</"Inserting and Updating Arrays"> and
1936L</"Inserting and Updating SQL"> for information on how to insert
1937with those data types.
32eab2da 1938
95904db5 1939The optional C<\%options> hash reference may contain additional
1940options to generate the update SQL. Currently supported options
1941are:
1942
1943=over 4
1944
1945=item returning
1946
1947See the C<returning> option to
1948L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
1949
1950=back
1951
96449e8e 1952=head2 select($source, $fields, $where, $order)
32eab2da 1953
9d48860e 1954This returns a SQL SELECT statement and associated list of bind values, as
be21dde3 1955specified by the arguments:
32eab2da 1956
96449e8e 1957=over
32eab2da 1958
96449e8e 1959=item $source
32eab2da 1960
9d48860e 1961Specification of the 'FROM' part of the statement.
96449e8e 1962The argument can be either a plain scalar (interpreted as a table
1963name, will be quoted), or an arrayref (interpreted as a list
1964of table names, joined by commas, quoted), or a scalarref
063097a3 1965(literal SQL, not quoted).
32eab2da 1966
96449e8e 1967=item $fields
32eab2da 1968
9d48860e 1969Specification of the list of fields to retrieve from
96449e8e 1970the source.
1971The argument can be either an arrayref (interpreted as a list
9d48860e 1972of field names, will be joined by commas and quoted), or a
96449e8e 1973plain scalar (literal SQL, not quoted).
521647e7 1974Please observe that this API is not as flexible as that of
1975the first argument C<$source>, for backwards compatibility reasons.
32eab2da 1976
96449e8e 1977=item $where
32eab2da 1978
96449e8e 1979Optional argument to specify the WHERE part of the query.
1980The argument is most often a hashref, but can also be
9d48860e 1981an arrayref or plain scalar --
96449e8e 1982see section L<WHERE clause|/"WHERE CLAUSES"> for details.
32eab2da 1983
96449e8e 1984=item $order
32eab2da 1985
96449e8e 1986Optional argument to specify the ORDER BY part of the query.
9d48860e 1987The argument can be a scalar, a hashref or an arrayref
96449e8e 1988-- see section L<ORDER BY clause|/"ORDER BY CLAUSES">
1989for details.
32eab2da 1990
96449e8e 1991=back
32eab2da 1992
32eab2da 1993
85327cd5 1994=head2 delete($table, \%where, \%options)
32eab2da 1995
86298391 1996This takes a table name and optional hashref L<WHERE clause|/WHERE CLAUSES>.
32eab2da 1997It returns an SQL DELETE statement and list of bind values.
1998
85327cd5 1999The optional C<\%options> hash reference may contain additional
2000options to generate the delete SQL. Currently supported options
2001are:
2002
2003=over 4
2004
2005=item returning
2006
2007See the C<returning> option to
2008L<insert|/insert($table, \@values || \%fieldvals, \%options)>.
2009
2010=back
2011
85783f3c 2012=head2 where(\%where, $order)
32eab2da 2013
2014This is used to generate just the WHERE clause. For example,
2015if you have an arbitrary data structure and know what the
2016rest of your SQL is going to look like, but want an easy way
2017to produce a WHERE clause, use this. It returns an SQL WHERE
2018clause and list of bind values.
2019
32eab2da 2020
2021=head2 values(\%data)
2022
2023This just returns the values from the hash C<%data>, in the same
2024order that would be returned from any of the other above queries.
2025Using this allows you to markedly speed up your queries if you
2026are affecting lots of rows. See below under the L</"PERFORMANCE"> section.
2027
32eab2da 2028=head2 generate($any, 'number', $of, \@data, $struct, \%types)
2029
2030Warning: This is an experimental method and subject to change.
2031
2032This returns arbitrarily generated SQL. It's a really basic shortcut.
2033It will return two different things, depending on return context:
2034
2035 my($stmt, @bind) = $sql->generate('create table', \$table, \@fields);
2036 my $stmt_and_val = $sql->generate('create table', \$table, \@fields);
2037
2038These would return the following:
2039
2040 # First calling form
2041 $stmt = "CREATE TABLE test (?, ?)";
2042 @bind = (field1, field2);
2043
2044 # Second calling form
2045 $stmt_and_val = "CREATE TABLE test (field1, field2)";
2046
2047Depending on what you're trying to do, it's up to you to choose the correct
2048format. In this example, the second form is what you would want.
2049
2050By the same token:
2051
2052 $sql->generate('alter session', { nls_date_format => 'MM/YY' });
2053
2054Might give you:
2055
2056 ALTER SESSION SET nls_date_format = 'MM/YY'
2057
2058You get the idea. Strings get their case twiddled, but everything
2059else remains verbatim.
2060
0da0fe34 2061=head1 EXPORTABLE FUNCTIONS
2062
2063=head2 is_plain_value
2064
2065Determines if the supplied argument is a plain value as understood by this
2066module:
2067
2068=over
2069
2070=item * The value is C<undef>
2071
2072=item * The value is a non-reference
2073
2074=item * The value is an object with stringification overloading
2075
2076=item * The value is of the form C<< { -value => $anything } >>
2077
2078=back
2079
9de2bd86 2080On failure returns C<undef>, on success returns a B<scalar> reference
966200cc 2081to the original supplied argument.
0da0fe34 2082
843a94b5 2083=over
2084
2085=item * Note
2086
2087The stringification overloading detection is rather advanced: it takes
2088into consideration not only the presence of a C<""> overload, but if that
2089fails also checks for enabled
2090L<autogenerated versions of C<"">|overload/Magic Autogeneration>, based
2091on either C<0+> or C<bool>.
2092
2093Unfortunately testing in the field indicates that this
2094detection B<< may tickle a latent bug in perl versions before 5.018 >>,
2095but only when very large numbers of stringifying objects are involved.
2096At the time of writing ( Sep 2014 ) there is no clear explanation of
2097the direct cause, nor is there a manageably small test case that reliably
2098reproduces the problem.
2099
2100If you encounter any of the following exceptions in B<random places within
2101your application stack> - this module may be to blame:
2102
2103 Operation "ne": no method found,
2104 left argument in overloaded package <something>,
2105 right argument in overloaded package <something>
2106
2107or perhaps even
2108
2109 Stub found while resolving method "???" overloading """" in package <something>
2110
2111If you fall victim to the above - please attempt to reduce the problem
2112to something that could be sent to the L<SQL::Abstract developers
1f490ae4 2113|DBIx::Class/GETTING HELP/SUPPORT>
843a94b5 2114(either publicly or privately). As a workaround in the meantime you can
2115set C<$ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}> to a true
2116value, which will most likely eliminate your problem (at the expense of
2117not being able to properly detect exotic forms of stringification).
2118
2119This notice and environment variable will be removed in a future version,
2120as soon as the underlying problem is found and a reliable workaround is
2121devised.
2122
2123=back
2124
0da0fe34 2125=head2 is_literal_value
2126
2127Determines if the supplied argument is a literal value as understood by this
2128module:
2129
2130=over
2131
2132=item * C<\$sql_string>
2133
2134=item * C<\[ $sql_string, @bind_values ]>
2135
0da0fe34 2136=back
2137
9de2bd86 2138On failure returns C<undef>, on success returns an B<array> reference
966200cc 2139containing the unpacked version of the supplied literal SQL and bind values.
0da0fe34 2140
32eab2da 2141=head1 WHERE CLAUSES
2142
96449e8e 2143=head2 Introduction
2144
32eab2da 2145This module uses a variation on the idea from L<DBIx::Abstract>. It
2146is B<NOT>, repeat I<not> 100% compatible. B<The main logic of this
2147module is that things in arrays are OR'ed, and things in hashes
2148are AND'ed.>
2149
2150The easiest way to explain is to show lots of examples. After
2151each C<%where> hash shown, it is assumed you used:
2152
2153 my($stmt, @bind) = $sql->where(\%where);
2154
2155However, note that the C<%where> hash can be used directly in any
2156of the other functions as well, as described above.
2157
96449e8e 2158=head2 Key-value pairs
2159
32eab2da 2160So, let's get started. To begin, a simple hash:
2161
2162 my %where = (
2163 user => 'nwiger',
2164 status => 'completed'
2165 );
2166
2167Is converted to SQL C<key = val> statements:
2168
2169 $stmt = "WHERE user = ? AND status = ?";
2170 @bind = ('nwiger', 'completed');
2171
2172One common thing I end up doing is having a list of values that
2173a field can be in. To do this, simply specify a list inside of
2174an arrayref:
2175
2176 my %where = (
2177 user => 'nwiger',
2178 status => ['assigned', 'in-progress', 'pending'];
2179 );
2180
2181This simple code will create the following:
9d48860e 2182
32eab2da 2183 $stmt = "WHERE user = ? AND ( status = ? OR status = ? OR status = ? )";
2184 @bind = ('nwiger', 'assigned', 'in-progress', 'pending');
2185
9d48860e 2186A field associated to an empty arrayref will be considered a
7cac25e6 2187logical false and will generate 0=1.
8a68b5be 2188
b864ba9b 2189=head2 Tests for NULL values
2190
2191If the value part is C<undef> then this is converted to SQL <IS NULL>
2192
2193 my %where = (
2194 user => 'nwiger',
2195 status => undef,
2196 );
2197
2198becomes:
2199
2200 $stmt = "WHERE user = ? AND status IS NULL";
2201 @bind = ('nwiger');
2202
e9614080 2203To test if a column IS NOT NULL:
2204
2205 my %where = (
2206 user => 'nwiger',
2207 status => { '!=', undef },
2208 );
cc422895 2209
6e0c6552 2210=head2 Specific comparison operators
96449e8e 2211
32eab2da 2212If you want to specify a different type of operator for your comparison,
2213you can use a hashref for a given column:
2214
2215 my %where = (
2216 user => 'nwiger',
2217 status => { '!=', 'completed' }
2218 );
2219
2220Which would generate:
2221
2222 $stmt = "WHERE user = ? AND status != ?";
2223 @bind = ('nwiger', 'completed');
2224
2225To test against multiple values, just enclose the values in an arrayref:
2226
96449e8e 2227 status => { '=', ['assigned', 'in-progress', 'pending'] };
2228
f2d5020d 2229Which would give you:
96449e8e 2230
2231 "WHERE status = ? OR status = ? OR status = ?"
2232
2233
2234The hashref can also contain multiple pairs, in which case it is expanded
32eab2da 2235into an C<AND> of its elements:
2236
2237 my %where = (
2238 user => 'nwiger',
2239 status => { '!=', 'completed', -not_like => 'pending%' }
2240 );
2241
2242 # Or more dynamically, like from a form
2243 $where{user} = 'nwiger';
2244 $where{status}{'!='} = 'completed';
2245 $where{status}{'-not_like'} = 'pending%';
2246
2247 # Both generate this
2248 $stmt = "WHERE user = ? AND status != ? AND status NOT LIKE ?";
2249 @bind = ('nwiger', 'completed', 'pending%');
2250
96449e8e 2251
32eab2da 2252To get an OR instead, you can combine it with the arrayref idea:
2253
2254 my %where => (
2255 user => 'nwiger',
1a6f2a03 2256 priority => [ { '=', 2 }, { '>', 5 } ]
32eab2da 2257 );
2258
2259Which would generate:
2260
1a6f2a03 2261 $stmt = "WHERE ( priority = ? OR priority > ? ) AND user = ?";
2262 @bind = ('2', '5', 'nwiger');
32eab2da 2263
44b9e502 2264If you want to include literal SQL (with or without bind values), just use a
13cc86af 2265scalar reference or reference to an arrayref as the value:
44b9e502 2266
2267 my %where = (
2268 date_entered => { '>' => \["to_date(?, 'MM/DD/YYYY')", "11/26/2008"] },
2269 date_expires => { '<' => \"now()" }
2270 );
2271
2272Which would generate:
2273
13cc86af 2274 $stmt = "WHERE date_entered > to_date(?, 'MM/DD/YYYY') AND date_expires < now()";
44b9e502 2275 @bind = ('11/26/2008');
2276
96449e8e 2277
2278=head2 Logic and nesting operators
2279
2280In the example above,
2281there is a subtle trap if you want to say something like
32eab2da 2282this (notice the C<AND>):
2283
2284 WHERE priority != ? AND priority != ?
2285
2286Because, in Perl you I<can't> do this:
2287
13cc86af 2288 priority => { '!=' => 2, '!=' => 1 }
32eab2da 2289
2290As the second C<!=> key will obliterate the first. The solution
2291is to use the special C<-modifier> form inside an arrayref:
2292
9d48860e 2293 priority => [ -and => {'!=', 2},
96449e8e 2294 {'!=', 1} ]
2295
32eab2da 2296
2297Normally, these would be joined by C<OR>, but the modifier tells it
2298to use C<AND> instead. (Hint: You can use this in conjunction with the
2299C<logic> option to C<new()> in order to change the way your queries
2300work by default.) B<Important:> Note that the C<-modifier> goes
2301B<INSIDE> the arrayref, as an extra first element. This will
2302B<NOT> do what you think it might:
2303
2304 priority => -and => [{'!=', 2}, {'!=', 1}] # WRONG!
2305
2306Here is a quick list of equivalencies, since there is some overlap:
2307
2308 # Same
2309 status => {'!=', 'completed', 'not like', 'pending%' }
2310 status => [ -and => {'!=', 'completed'}, {'not like', 'pending%'}]
2311
2312 # Same
2313 status => {'=', ['assigned', 'in-progress']}
2314 status => [ -or => {'=', 'assigned'}, {'=', 'in-progress'}]
2315 status => [ {'=', 'assigned'}, {'=', 'in-progress'} ]
2316
e3f9dff4 2317
2318
be21dde3 2319=head2 Special operators: IN, BETWEEN, etc.
96449e8e 2320
32eab2da 2321You can also use the hashref format to compare a list of fields using the
2322C<IN> comparison operator, by specifying the list as an arrayref:
2323
2324 my %where = (
2325 status => 'completed',
2326 reportid => { -in => [567, 2335, 2] }
2327 );
2328
2329Which would generate:
2330
2331 $stmt = "WHERE status = ? AND reportid IN (?,?,?)";
2332 @bind = ('completed', '567', '2335', '2');
2333
9d48860e 2334The reverse operator C<-not_in> generates SQL C<NOT IN> and is used in
96449e8e 2335the same way.
2336
6e0c6552 2337If the argument to C<-in> is an empty array, 'sqlfalse' is generated
be21dde3 2338(by default: C<1=0>). Similarly, C<< -not_in => [] >> generates
2339'sqltrue' (by default: C<1=1>).
6e0c6552 2340
e41c3bdd 2341In addition to the array you can supply a chunk of literal sql or
2342literal sql with bind:
6e0c6552 2343
e41c3bdd 2344 my %where = {
2345 customer => { -in => \[
2346 'SELECT cust_id FROM cust WHERE balance > ?',
2347 2000,
2348 ],
2349 status => { -in => \'SELECT status_codes FROM states' },
2350 };
6e0c6552 2351
e41c3bdd 2352would generate:
2353
2354 $stmt = "WHERE (
2355 customer IN ( SELECT cust_id FROM cust WHERE balance > ? )
2356 AND status IN ( SELECT status_codes FROM states )
2357 )";
2358 @bind = ('2000');
2359
0dfd2442 2360Finally, if the argument to C<-in> is not a reference, it will be
2361treated as a single-element array.
e41c3bdd 2362
2363Another pair of operators is C<-between> and C<-not_between>,
96449e8e 2364used with an arrayref of two values:
32eab2da 2365
2366 my %where = (
2367 user => 'nwiger',
2368 completion_date => {
2369 -not_between => ['2002-10-01', '2003-02-06']
2370 }
2371 );
2372
2373Would give you:
2374
2375 WHERE user = ? AND completion_date NOT BETWEEN ( ? AND ? )
2376
e41c3bdd 2377Just like with C<-in> all plausible combinations of literal SQL
2378are possible:
2379
2380 my %where = {
2381 start0 => { -between => [ 1, 2 ] },
2382 start1 => { -between => \["? AND ?", 1, 2] },
2383 start2 => { -between => \"lower(x) AND upper(y)" },
9d48860e 2384 start3 => { -between => [
e41c3bdd 2385 \"lower(x)",
2386 \["upper(?)", 'stuff' ],
2387 ] },
2388 };
2389
2390Would give you:
2391
2392 $stmt = "WHERE (
2393 ( start0 BETWEEN ? AND ? )
2394 AND ( start1 BETWEEN ? AND ? )
2395 AND ( start2 BETWEEN lower(x) AND upper(y) )
2396 AND ( start3 BETWEEN lower(x) AND upper(?) )
2397 )";
2398 @bind = (1, 2, 1, 2, 'stuff');
2399
2400
9d48860e 2401These are the two builtin "special operators"; but the
be21dde3 2402list can be expanded: see section L</"SPECIAL OPERATORS"> below.
96449e8e 2403
59f23b3d 2404=head2 Unary operators: bool
97a920ef 2405
2406If you wish to test against boolean columns or functions within your
2407database you can use the C<-bool> and C<-not_bool> operators. For
2408example to test the column C<is_user> being true and the column
827bb0eb 2409C<is_enabled> being false you would use:-
97a920ef 2410
2411 my %where = (
2412 -bool => 'is_user',
2413 -not_bool => 'is_enabled',
2414 );
2415
2416Would give you:
2417
277b5d3f 2418 WHERE is_user AND NOT is_enabled
97a920ef 2419
0b604e9d 2420If a more complex combination is required, testing more conditions,
2421then you should use the and/or operators:-
2422
2423 my %where = (
2424 -and => [
2425 -bool => 'one',
23401b81 2426 -not_bool => { two=> { -rlike => 'bar' } },
2427 -not_bool => { three => [ { '=', 2 }, { '>', 5 } ] },
0b604e9d 2428 ],
2429 );
2430
2431Would give you:
2432
23401b81 2433 WHERE
2434 one
2435 AND
2436 (NOT two RLIKE ?)
2437 AND
2438 (NOT ( three = ? OR three > ? ))
97a920ef 2439
2440
107b72f1 2441=head2 Nested conditions, -and/-or prefixes
96449e8e 2442
32eab2da 2443So far, we've seen how multiple conditions are joined with a top-level
2444C<AND>. We can change this by putting the different conditions we want in
2445hashes and then putting those hashes in an array. For example:
2446
2447 my @where = (
2448 {
2449 user => 'nwiger',
2450 status => { -like => ['pending%', 'dispatched'] },
2451 },
2452 {
2453 user => 'robot',
2454 status => 'unassigned',
2455 }
2456 );
2457
2458This data structure would create the following:
2459
2460 $stmt = "WHERE ( user = ? AND ( status LIKE ? OR status LIKE ? ) )
2461 OR ( user = ? AND status = ? ) )";
2462 @bind = ('nwiger', 'pending', 'dispatched', 'robot', 'unassigned');
2463
107b72f1 2464
48d9f5f8 2465Clauses in hashrefs or arrayrefs can be prefixed with an C<-and> or C<-or>
be21dde3 2466to change the logic inside:
32eab2da 2467
2468 my @where = (
2469 -and => [
2470 user => 'nwiger',
48d9f5f8 2471 [
2472 -and => [ workhrs => {'>', 20}, geo => 'ASIA' ],
2473 -or => { workhrs => {'<', 50}, geo => 'EURO' },
32eab2da 2474 ],
2475 ],
2476 );
2477
2478That would yield:
2479
13cc86af 2480 $stmt = "WHERE ( user = ?
2481 AND ( ( workhrs > ? AND geo = ? )
2482 OR ( workhrs < ? OR geo = ? ) ) )";
2483 @bind = ('nwiger', '20', 'ASIA', '50', 'EURO');
107b72f1 2484
cc422895 2485=head3 Algebraic inconsistency, for historical reasons
107b72f1 2486
7cac25e6 2487C<Important note>: when connecting several conditions, the C<-and->|C<-or>
2488operator goes C<outside> of the nested structure; whereas when connecting
2489several constraints on one column, the C<-and> operator goes
be21dde3 2490C<inside> the arrayref. Here is an example combining both features:
7cac25e6 2491
2492 my @where = (
2493 -and => [a => 1, b => 2],
2494 -or => [c => 3, d => 4],
2495 e => [-and => {-like => 'foo%'}, {-like => '%bar'} ]
2496 )
2497
2498yielding
2499
9d48860e 2500 WHERE ( ( ( a = ? AND b = ? )
2501 OR ( c = ? OR d = ? )
7cac25e6 2502 OR ( e LIKE ? AND e LIKE ? ) ) )
2503
107b72f1 2504This difference in syntax is unfortunate but must be preserved for
be21dde3 2505historical reasons. So be careful: the two examples below would
107b72f1 2506seem algebraically equivalent, but they are not
2507
a948b1fe 2508 { col => [ -and =>
2509 { -like => 'foo%' },
2510 { -like => '%bar' },
2511 ] }
be21dde3 2512 # yields: WHERE ( ( col LIKE ? AND col LIKE ? ) )
107b72f1 2513
a948b1fe 2514 [ -and =>
2515 { col => { -like => 'foo%' } },
2516 { col => { -like => '%bar' } },
2517 ]
be21dde3 2518 # yields: WHERE ( ( col LIKE ? OR col LIKE ? ) )
107b72f1 2519
7cac25e6 2520
cc422895 2521=head2 Literal SQL and value type operators
96449e8e 2522
cc422895 2523The basic premise of SQL::Abstract is that in WHERE specifications the "left
2524side" is a column name and the "right side" is a value (normally rendered as
2525a placeholder). This holds true for both hashrefs and arrayref pairs as you
2526see in the L</WHERE CLAUSES> examples above. Sometimes it is necessary to
2527alter this behavior. There are several ways of doing so.
e9614080 2528
cc422895 2529=head3 -ident
2530
2531This is a virtual operator that signals the string to its right side is an
2532identifier (a column name) and not a value. For example to compare two
2533columns you would write:
32eab2da 2534
e9614080 2535 my %where = (
2536 priority => { '<', 2 },
cc422895 2537 requestor => { -ident => 'submitter' },
e9614080 2538 );
2539
2540which creates:
2541
2542 $stmt = "WHERE priority < ? AND requestor = submitter";
2543 @bind = ('2');
2544
cc422895 2545If you are maintaining legacy code you may see a different construct as
2546described in L</Deprecated usage of Literal SQL>, please use C<-ident> in new
2547code.
2548
2549=head3 -value
e9614080 2550
cc422895 2551This is a virtual operator that signals that the construct to its right side
2552is a value to be passed to DBI. This is for example necessary when you want
2553to write a where clause against an array (for RDBMS that support such
2554datatypes). For example:
e9614080 2555
32eab2da 2556 my %where = (
cc422895 2557 array => { -value => [1, 2, 3] }
32eab2da 2558 );
2559
cc422895 2560will result in:
32eab2da 2561
cc422895 2562 $stmt = 'WHERE array = ?';
2563 @bind = ([1, 2, 3]);
32eab2da 2564
cc422895 2565Note that if you were to simply say:
32eab2da 2566
2567 my %where = (
cc422895 2568 array => [1, 2, 3]
32eab2da 2569 );
2570
3af02ccb 2571the result would probably not be what you wanted:
cc422895 2572
2573 $stmt = 'WHERE array = ? OR array = ? OR array = ?';
2574 @bind = (1, 2, 3);
2575
2576=head3 Literal SQL
96449e8e 2577
cc422895 2578Finally, sometimes only literal SQL will do. To include a random snippet
2579of SQL verbatim, you specify it as a scalar reference. Consider this only
2580as a last resort. Usually there is a better way. For example:
96449e8e 2581
2582 my %where = (
cc422895 2583 priority => { '<', 2 },
2584 requestor => { -in => \'(SELECT name FROM hitmen)' },
96449e8e 2585 );
2586
cc422895 2587Would create:
96449e8e 2588
cc422895 2589 $stmt = "WHERE priority < ? AND requestor IN (SELECT name FROM hitmen)"
2590 @bind = (2);
2591
2592Note that in this example, you only get one bind parameter back, since
2593the verbatim SQL is passed as part of the statement.
2594
2595=head4 CAVEAT
2596
2597 Never use untrusted input as a literal SQL argument - this is a massive
2598 security risk (there is no way to check literal snippets for SQL
2599 injections and other nastyness). If you need to deal with untrusted input
2600 use literal SQL with placeholders as described next.
96449e8e 2601
cc422895 2602=head3 Literal SQL with placeholders and bind values (subqueries)
96449e8e 2603
2604If the literal SQL to be inserted has placeholders and bind values,
2605use a reference to an arrayref (yes this is a double reference --
2606not so common, but perfectly legal Perl). For example, to find a date
2607in Postgres you can use something like this:
2608
2609 my %where = (
3ae1c5e2 2610 date_column => \[ "= date '2008-09-30' - ?::integer", 10 ]
96449e8e 2611 )
2612
2613This would create:
2614
d2a8fe1a 2615 $stmt = "WHERE ( date_column = date '2008-09-30' - ?::integer )"
96449e8e 2616 @bind = ('10');
2617
deb148a2 2618Note that you must pass the bind values in the same format as they are returned
85783f3c 2619by L<where|/where(\%where, $order)>. This means that if you set L</bindtype>
1f490ae4 2620to C<columns>, you must provide the bind values in the
2621C<< [ column_meta => value ] >> format, where C<column_meta> is an opaque
2622scalar value; most commonly the column name, but you can use any scalar value
2623(including references and blessed references), L<SQL::Abstract> will simply
2624pass it through intact. So if C<bindtype> is set to C<columns> the above
2625example will look like:
deb148a2 2626
2627 my %where = (
3ae1c5e2 2628 date_column => \[ "= date '2008-09-30' - ?::integer", [ {} => 10 ] ]
deb148a2 2629 )
96449e8e 2630
2631Literal SQL is especially useful for nesting parenthesized clauses in the
be21dde3 2632main SQL query. Here is a first example:
96449e8e 2633
2634 my ($sub_stmt, @sub_bind) = ("SELECT c1 FROM t1 WHERE c2 < ? AND c3 LIKE ?",
2635 100, "foo%");
2636 my %where = (
2637 foo => 1234,
2638 bar => \["IN ($sub_stmt)" => @sub_bind],
2639 );
2640
be21dde3 2641This yields:
96449e8e 2642
9d48860e 2643 $stmt = "WHERE (foo = ? AND bar IN (SELECT c1 FROM t1
96449e8e 2644 WHERE c2 < ? AND c3 LIKE ?))";
2645 @bind = (1234, 100, "foo%");
2646
9d48860e 2647Other subquery operators, like for example C<"E<gt> ALL"> or C<"NOT IN">,
96449e8e 2648are expressed in the same way. Of course the C<$sub_stmt> and
9d48860e 2649its associated bind values can be generated through a former call
96449e8e 2650to C<select()> :
2651
2652 my ($sub_stmt, @sub_bind)
9d48860e 2653 = $sql->select("t1", "c1", {c2 => {"<" => 100},
96449e8e 2654 c3 => {-like => "foo%"}});
2655 my %where = (
2656 foo => 1234,
2657 bar => \["> ALL ($sub_stmt)" => @sub_bind],
2658 );
2659
2660In the examples above, the subquery was used as an operator on a column;
9d48860e 2661but the same principle also applies for a clause within the main C<%where>
be21dde3 2662hash, like an EXISTS subquery:
96449e8e 2663
9d48860e 2664 my ($sub_stmt, @sub_bind)
96449e8e 2665 = $sql->select("t1", "*", {c1 => 1, c2 => \"> t0.c0"});
48d9f5f8 2666 my %where = ( -and => [
96449e8e 2667 foo => 1234,
48d9f5f8 2668 \["EXISTS ($sub_stmt)" => @sub_bind],
2669 ]);
96449e8e 2670
2671which yields
2672
9d48860e 2673 $stmt = "WHERE (foo = ? AND EXISTS (SELECT * FROM t1
96449e8e 2674 WHERE c1 = ? AND c2 > t0.c0))";
2675 @bind = (1234, 1);
2676
2677
9d48860e 2678Observe that the condition on C<c2> in the subquery refers to
be21dde3 2679column C<t0.c0> of the main query: this is I<not> a bind
9d48860e 2680value, so we have to express it through a scalar ref.
96449e8e 2681Writing C<< c2 => {">" => "t0.c0"} >> would have generated
2682C<< c2 > ? >> with bind value C<"t0.c0"> ... not exactly
2683what we wanted here.
2684
96449e8e 2685Finally, here is an example where a subquery is used
2686for expressing unary negation:
2687
9d48860e 2688 my ($sub_stmt, @sub_bind)
96449e8e 2689 = $sql->where({age => [{"<" => 10}, {">" => 20}]});
2690 $sub_stmt =~ s/^ where //i; # don't want "WHERE" in the subclause
2691 my %where = (
2692 lname => {like => '%son%'},
48d9f5f8 2693 \["NOT ($sub_stmt)" => @sub_bind],
96449e8e 2694 );
2695
2696This yields
2697
2698 $stmt = "lname LIKE ? AND NOT ( age < ? OR age > ? )"
2699 @bind = ('%son%', 10, 20)
2700
cc422895 2701=head3 Deprecated usage of Literal SQL
2702
2703Below are some examples of archaic use of literal SQL. It is shown only as
2704reference for those who deal with legacy code. Each example has a much
2705better, cleaner and safer alternative that users should opt for in new code.
2706
2707=over
2708
2709=item *
2710
2711 my %where = ( requestor => \'IS NOT NULL' )
2712
2713 $stmt = "WHERE requestor IS NOT NULL"
2714
2715This used to be the way of generating NULL comparisons, before the handling
2716of C<undef> got formalized. For new code please use the superior syntax as
2717described in L</Tests for NULL values>.
96449e8e 2718
cc422895 2719=item *
2720
2721 my %where = ( requestor => \'= submitter' )
2722
2723 $stmt = "WHERE requestor = submitter"
2724
2725This used to be the only way to compare columns. Use the superior L</-ident>
2726method for all new code. For example an identifier declared in such a way
2727will be properly quoted if L</quote_char> is properly set, while the legacy
2728form will remain as supplied.
2729
2730=item *
2731
2732 my %where = ( is_ready => \"", completed => { '>', '2012-12-21' } )
2733
2734 $stmt = "WHERE completed > ? AND is_ready"
2735 @bind = ('2012-12-21')
2736
2737Using an empty string literal used to be the only way to express a boolean.
2738For all new code please use the much more readable
2739L<-bool|/Unary operators: bool> operator.
2740
2741=back
96449e8e 2742
2743=head2 Conclusion
2744
32eab2da 2745These pages could go on for a while, since the nesting of the data
2746structures this module can handle are pretty much unlimited (the
2747module implements the C<WHERE> expansion as a recursive function
2748internally). Your best bet is to "play around" with the module a
2749little to see how the data structures behave, and choose the best
2750format for your data based on that.
2751
2752And of course, all the values above will probably be replaced with
2753variables gotten from forms or the command line. After all, if you
2754knew everything ahead of time, you wouldn't have to worry about
2755dynamically-generating SQL and could just hardwire it into your
2756script.
2757
86298391 2758=head1 ORDER BY CLAUSES
2759
9d48860e 2760Some functions take an order by clause. This can either be a scalar (just a
18710f60 2761column name), a hashref of C<< { -desc => 'col' } >> or C<< { -asc => 'col' }
2762>>, a scalarref, an arrayref-ref, or an arrayref of any of the previous
2763forms. Examples:
1cfa1db3 2764
8c15b421 2765 Given | Will Generate
18710f60 2766 ---------------------------------------------------------------
8c15b421 2767 |
2768 'colA' | ORDER BY colA
2769 |
2770 [qw/colA colB/] | ORDER BY colA, colB
2771 |
2772 {-asc => 'colA'} | ORDER BY colA ASC
2773 |
2774 {-desc => 'colB'} | ORDER BY colB DESC
2775 |
2776 ['colA', {-asc => 'colB'}] | ORDER BY colA, colB ASC
2777 |
2778 { -asc => [qw/colA colB/] } | ORDER BY colA ASC, colB ASC
2779 |
2780 \'colA DESC' | ORDER BY colA DESC
2781 |
2782 \[ 'FUNC(colA, ?)', $x ] | ORDER BY FUNC(colA, ?)
2783 | /* ...with $x bound to ? */
2784 |
bd805d85 2785 [ | ORDER BY
2786 { -asc => 'colA' }, | colA ASC,
2787 { -desc => [qw/colB/] }, | colB DESC,
2788 { -asc => [qw/colC colD/] },| colC ASC, colD ASC,
2789 \'colE DESC', | colE DESC,
2790 \[ 'FUNC(colF, ?)', $x ], | FUNC(colF, ?)
2791 ] | /* ...with $x bound to ? */
18710f60 2792 ===============================================================
86298391 2793
96449e8e 2794
2795
2796=head1 SPECIAL OPERATORS
2797
e3f9dff4 2798 my $sqlmaker = SQL::Abstract->new(special_ops => [
3a2e1a5e 2799 {
2800 regex => qr/.../,
e3f9dff4 2801 handler => sub {
2802 my ($self, $field, $op, $arg) = @_;
2803 ...
3a2e1a5e 2804 },
2805 },
2806 {
2807 regex => qr/.../,
2808 handler => 'method_name',
e3f9dff4 2809 },
2810 ]);
2811
9d48860e 2812A "special operator" is a SQL syntactic clause that can be
e3f9dff4 2813applied to a field, instead of a usual binary operator.
be21dde3 2814For example:
e3f9dff4 2815
2816 WHERE field IN (?, ?, ?)
2817 WHERE field BETWEEN ? AND ?
2818 WHERE MATCH(field) AGAINST (?, ?)
96449e8e 2819
e3f9dff4 2820Special operators IN and BETWEEN are fairly standard and therefore
3a2e1a5e 2821are builtin within C<SQL::Abstract> (as the overridable methods
2822C<_where_field_IN> and C<_where_field_BETWEEN>). For other operators,
2823like the MATCH .. AGAINST example above which is specific to MySQL,
2824you can write your own operator handlers - supply a C<special_ops>
2825argument to the C<new> method. That argument takes an arrayref of
2826operator definitions; each operator definition is a hashref with two
2827entries:
96449e8e 2828
e3f9dff4 2829=over
2830
2831=item regex
2832
2833the regular expression to match the operator
96449e8e 2834
e3f9dff4 2835=item handler
2836
3a2e1a5e 2837Either a coderef or a plain scalar method name. In both cases
2838the expected return is C<< ($sql, @bind) >>.
2839
2840When supplied with a method name, it is simply called on the
13cc86af 2841L<SQL::Abstract> object as:
3a2e1a5e 2842
ca4f826a 2843 $self->$method_name($field, $op, $arg)
3a2e1a5e 2844
2845 Where:
2846
3a2e1a5e 2847 $field is the LHS of the operator
13cc86af 2848 $op is the part that matched the handler regex
3a2e1a5e 2849 $arg is the RHS
2850
2851When supplied with a coderef, it is called as:
2852
2853 $coderef->($self, $field, $op, $arg)
2854
e3f9dff4 2855
2856=back
2857
9d48860e 2858For example, here is an implementation
e3f9dff4 2859of the MATCH .. AGAINST syntax for MySQL
2860
2861 my $sqlmaker = SQL::Abstract->new(special_ops => [
9d48860e 2862
e3f9dff4 2863 # special op for MySql MATCH (field) AGAINST(word1, word2, ...)
9d48860e 2864 {regex => qr/^match$/i,
e3f9dff4 2865 handler => sub {
2866 my ($self, $field, $op, $arg) = @_;
2867 $arg = [$arg] if not ref $arg;
2868 my $label = $self->_quote($field);
2869 my ($placeholder) = $self->_convert('?');
2870 my $placeholders = join ", ", (($placeholder) x @$arg);
2871 my $sql = $self->_sqlcase('match') . " ($label) "
2872 . $self->_sqlcase('against') . " ($placeholders) ";
2873 my @bind = $self->_bindtype($field, @$arg);
2874 return ($sql, @bind);
2875 }
2876 },
9d48860e 2877
e3f9dff4 2878 ]);
96449e8e 2879
2880
59f23b3d 2881=head1 UNARY OPERATORS
2882
112b5232 2883 my $sqlmaker = SQL::Abstract->new(unary_ops => [
59f23b3d 2884 {
2885 regex => qr/.../,
2886 handler => sub {
2887 my ($self, $op, $arg) = @_;
2888 ...
2889 },
2890 },
2891 {
2892 regex => qr/.../,
2893 handler => 'method_name',
2894 },
2895 ]);
2896
9d48860e 2897A "unary operator" is a SQL syntactic clause that can be
59f23b3d 2898applied to a field - the operator goes before the field
2899
2900You can write your own operator handlers - supply a C<unary_ops>
2901argument to the C<new> method. That argument takes an arrayref of
2902operator definitions; each operator definition is a hashref with two
2903entries:
2904
2905=over
2906
2907=item regex
2908
2909the regular expression to match the operator
2910
2911=item handler
2912
2913Either a coderef or a plain scalar method name. In both cases
2914the expected return is C<< $sql >>.
2915
2916When supplied with a method name, it is simply called on the
13cc86af 2917L<SQL::Abstract> object as:
59f23b3d 2918
ca4f826a 2919 $self->$method_name($op, $arg)
59f23b3d 2920
2921 Where:
2922
2923 $op is the part that matched the handler regex
2924 $arg is the RHS or argument of the operator
2925
2926When supplied with a coderef, it is called as:
2927
2928 $coderef->($self, $op, $arg)
2929
2930
2931=back
2932
2933
32eab2da 2934=head1 PERFORMANCE
2935
2936Thanks to some benchmarking by Mark Stosberg, it turns out that
2937this module is many orders of magnitude faster than using C<DBIx::Abstract>.
2938I must admit this wasn't an intentional design issue, but it's a
2939byproduct of the fact that you get to control your C<DBI> handles
2940yourself.
2941
2942To maximize performance, use a code snippet like the following:
2943
2944 # prepare a statement handle using the first row
2945 # and then reuse it for the rest of the rows
2946 my($sth, $stmt);
2947 for my $href (@array_of_hashrefs) {
2948 $stmt ||= $sql->insert('table', $href);
2949 $sth ||= $dbh->prepare($stmt);
2950 $sth->execute($sql->values($href));
2951 }
2952
2953The reason this works is because the keys in your C<$href> are sorted
2954internally by B<SQL::Abstract>. Thus, as long as your data retains
2955the same structure, you only have to generate the SQL the first time
2956around. On subsequent queries, simply use the C<values> function provided
2957by this module to return your values in the correct order.
2958
b864ba9b 2959However this depends on the values having the same type - if, for
2960example, the values of a where clause may either have values
2961(resulting in sql of the form C<column = ?> with a single bind
2962value), or alternatively the values might be C<undef> (resulting in
2963sql of the form C<column IS NULL> with no bind value) then the
2964caching technique suggested will not work.
96449e8e 2965
32eab2da 2966=head1 FORMBUILDER
2967
2968If you use my C<CGI::FormBuilder> module at all, you'll hopefully
2969really like this part (I do, at least). Building up a complex query
2970can be as simple as the following:
2971
2972 #!/usr/bin/perl
2973
46dc2f3e 2974 use warnings;
2975 use strict;
2976
32eab2da 2977 use CGI::FormBuilder;
2978 use SQL::Abstract;
2979
2980 my $form = CGI::FormBuilder->new(...);
2981 my $sql = SQL::Abstract->new;
2982
2983 if ($form->submitted) {
2984 my $field = $form->field;
2985 my $id = delete $field->{id};
2986 my($stmt, @bind) = $sql->update('table', $field, {id => $id});
2987 }
2988
2989Of course, you would still have to connect using C<DBI> to run the
2990query, but the point is that if you make your form look like your
2991table, the actual query script can be extremely simplistic.
2992
2993If you're B<REALLY> lazy (I am), check out C<HTML::QuickTable> for
9d48860e 2994a fast interface to returning and formatting data. I frequently
32eab2da 2995use these three modules together to write complex database query
2996apps in under 50 lines.
2997
af733667 2998=head1 HOW TO CONTRIBUTE
2999
3000Contributions are always welcome, in all usable forms (we especially
3001welcome documentation improvements). The delivery methods include git-
3002or unified-diff formatted patches, GitHub pull requests, or plain bug
3003reports either via RT or the Mailing list. Contributors are generally
3004granted full access to the official repository after their first several
3005patches pass successful review.
3006
3007This project is maintained in a git repository. The code and related tools are
3008accessible at the following locations:
d8cc1792 3009
3010=over
3011
af733667 3012=item * Official repo: L<git://git.shadowcat.co.uk/dbsrgits/SQL-Abstract.git>
3013
3014=item * Official gitweb: L<http://git.shadowcat.co.uk/gitweb/gitweb.cgi?p=dbsrgits/SQL-Abstract.git>
3015
3016=item * GitHub mirror: L<https://github.com/dbsrgits/sql-abstract>
d8cc1792 3017
af733667 3018=item * Authorized committers: L<ssh://dbsrgits@git.shadowcat.co.uk/SQL-Abstract.git>
d8cc1792 3019
3020=back
32eab2da 3021
96449e8e 3022=head1 CHANGES
3023
3024Version 1.50 was a major internal refactoring of C<SQL::Abstract>.
3025Great care has been taken to preserve the I<published> behavior
3026documented in previous versions in the 1.* family; however,
9d48860e 3027some features that were previously undocumented, or behaved
96449e8e 3028differently from the documentation, had to be changed in order
3029to clarify the semantics. Hence, client code that was relying
9d48860e 3030on some dark areas of C<SQL::Abstract> v1.*
96449e8e 3031B<might behave differently> in v1.50.
32eab2da 3032
be21dde3 3033The main changes are:
d2a8fe1a 3034
96449e8e 3035=over
32eab2da 3036
9d48860e 3037=item *
32eab2da 3038
3ae1c5e2 3039support for literal SQL through the C<< \ [ $sql, @bind ] >> syntax.
96449e8e 3040
3041=item *
3042
145fbfc8 3043support for the { operator => \"..." } construct (to embed literal SQL)
3044
3045=item *
3046
9c37b9c0 3047support for the { operator => \["...", @bind] } construct (to embed literal SQL with bind values)
3048
3049=item *
3050
96449e8e 3051optional support for L<array datatypes|/"Inserting and Updating Arrays">
3052
9d48860e 3053=item *
96449e8e 3054
be21dde3 3055defensive programming: check arguments
96449e8e 3056
3057=item *
3058
3059fixed bug with global logic, which was previously implemented
7cac25e6 3060through global variables yielding side-effects. Prior versions would
96449e8e 3061interpret C<< [ {cond1, cond2}, [cond3, cond4] ] >>
3062as C<< "(cond1 AND cond2) OR (cond3 AND cond4)" >>.
3063Now this is interpreted
3064as C<< "(cond1 AND cond2) OR (cond3 OR cond4)" >>.
3065
96449e8e 3066
3067=item *
3068
3069fixed semantics of _bindtype on array args
3070
9d48860e 3071=item *
96449e8e 3072
3073dropped the C<_anoncopy> of the %where tree. No longer necessary,
3074we just avoid shifting arrays within that tree.
3075
3076=item *
3077
3078dropped the C<_modlogic> function
3079
3080=back
32eab2da 3081
32eab2da 3082=head1 ACKNOWLEDGEMENTS
3083
3084There are a number of individuals that have really helped out with
3085this module. Unfortunately, most of them submitted bugs via CPAN
3086so I have no idea who they are! But the people I do know are:
3087
9d48860e 3088 Ash Berlin (order_by hash term support)
b643abe1 3089 Matt Trout (DBIx::Class support)
32eab2da 3090 Mark Stosberg (benchmarking)
3091 Chas Owens (initial "IN" operator support)
3092 Philip Collins (per-field SQL functions)
3093 Eric Kolve (hashref "AND" support)
3094 Mike Fragassi (enhancements to "BETWEEN" and "LIKE")
3095 Dan Kubb (support for "quote_char" and "name_sep")
f5aab26e 3096 Guillermo Roditi (patch to cleanup "IN" and "BETWEEN", fix and tests for _order_by)
48d9f5f8 3097 Laurent Dami (internal refactoring, extensible list of special operators, literal SQL)
dbdf7648 3098 Norbert Buchmuller (support for literal SQL in hashpair, misc. fixes & tests)
e96c510a 3099 Peter Rabbitson (rewrite of SQLA::Test, misc. fixes & tests)
02288357 3100 Oliver Charles (support for "RETURNING" after "INSERT")
32eab2da 3101
3102Thanks!
3103
32eab2da 3104=head1 SEE ALSO
3105
86298391 3106L<DBIx::Class>, L<DBIx::Abstract>, L<CGI::FormBuilder>, L<HTML::QuickTable>.
32eab2da 3107
32eab2da 3108=head1 AUTHOR
3109
b643abe1 3110Copyright (c) 2001-2007 Nathan Wiger <nwiger@cpan.org>. All Rights Reserved.
3111
3112This module is actively maintained by Matt Trout <mst@shadowcatsystems.co.uk>
32eab2da 3113
abe72f94 3114For support, your best bet is to try the C<DBIx::Class> users mailing list.
3115While not an official support venue, C<DBIx::Class> makes heavy use of
3116C<SQL::Abstract>, and as such list members there are very familiar with
3117how to create queries.
3118
0d067ded 3119=head1 LICENSE
3120
d988ab87 3121This module is free software; you may copy this under the same
3122terms as perl itself (either the GNU General Public License or
3123the Artistic License)
32eab2da 3124
3125=cut