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