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