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