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