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