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