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