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