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