-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathAbstract.pm
More file actions
3314 lines (2478 loc) · 95.3 KB
/
Abstract.pm
File metadata and controls
3314 lines (2478 loc) · 95.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package SQL::Abstract; # see doc at end of file
use strict;
use warnings;
use Carp ();
use List::Util ();
use Scalar::Util ();
use Exporter 'import';
our @EXPORT_OK = qw(is_plain_value is_literal_value);
BEGIN {
if ($] < 5.009_005) {
require MRO::Compat;
}
else {
require mro;
}
*SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION = $ENV{SQLA_ISVALUE_IGNORE_AUTOGENERATED_STRINGIFICATION}
? sub () { 0 }
: sub () { 1 }
;
}
#======================================================================
# GLOBALS
#======================================================================
our $VERSION = '1.86';
# This would confuse some packagers
$VERSION = eval $VERSION if $VERSION =~ /_/; # numify for warning-free dev releases
our $AUTOLOAD;
# special operators (-in, -between). May be extended/overridden by user.
# See section WHERE: BUILTIN SPECIAL OPERATORS below for implementation
my @BUILTIN_SPECIAL_OPS = (
{regex => qr/^ (?: not \s )? between $/ix, handler => '_where_field_BETWEEN'},
{regex => qr/^ (?: not \s )? in $/ix, handler => '_where_field_IN'},
{regex => qr/^ ident $/ix, handler => '_where_op_IDENT'},
{regex => qr/^ value $/ix, handler => '_where_op_VALUE'},
{regex => qr/^ is (?: \s+ not )? $/ix, handler => '_where_field_IS'},
);
# unaryish operators - key maps to handler
my @BUILTIN_UNARY_OPS = (
# the digits are backcompat stuff
{ regex => qr/^ and (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
{ regex => qr/^ or (?: [_\s]? \d+ )? $/xi, handler => '_where_op_ANDOR' },
{ regex => qr/^ nest (?: [_\s]? \d+ )? $/xi, handler => '_where_op_NEST' },
{ regex => qr/^ (?: not \s )? bool $/xi, handler => '_where_op_BOOL' },
{ regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
{ regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
);
#======================================================================
# DEBUGGING AND ERROR REPORTING
#======================================================================
sub _debug {
return unless $_[0]->{debug}; shift; # a little faster
my $func = (caller(1))[3];
warn "[$func] ", @_, "\n";
}
sub belch (@) {
my($func) = (caller(1))[3];
Carp::carp "[$func] Warning: ", @_;
}
sub puke (@) {
my($func) = (caller(1))[3];
Carp::croak "[$func] Fatal: ", @_;
}
sub is_literal_value ($) {
ref $_[0] eq 'SCALAR' ? [ ${$_[0]} ]
: ( ref $_[0] eq 'REF' and ref ${$_[0]} eq 'ARRAY' ) ? [ @${ $_[0] } ]
: undef;
}
# FIXME XSify - this can be done so much more efficiently
sub is_plain_value ($) {
no strict 'refs';
! length ref $_[0] ? \($_[0])
: (
ref $_[0] eq 'HASH' and keys %{$_[0]} == 1
and
exists $_[0]->{-value}
) ? \($_[0]->{-value})
: (
# reuse @_ for even moar speedz
defined ( $_[1] = Scalar::Util::blessed $_[0] )
and
# deliberately not using Devel::OverloadInfo - the checks we are
# intersted in are much more limited than the fullblown thing, and
# this is a very hot piece of code
(
# simply using ->can('(""') can leave behind stub methods that
# break actually using the overload later (see L<perldiag/Stub
# found while resolving method "%s" overloading "%s" in package
# "%s"> and the source of overload::mycan())
#
# either has stringification which DBI SHOULD prefer out of the box
grep { *{ (qq[${_}::(""]) }{CODE} } @{ $_[2] = mro::get_linear_isa( $_[1] ) }
or
# has nummification or boolification, AND fallback is *not* disabled
(
SQL::Abstract::_ENV_::DETECT_AUTOGENERATED_STRINGIFICATION
and
(
grep { *{"${_}::(0+"}{CODE} } @{$_[2]}
or
grep { *{"${_}::(bool"}{CODE} } @{$_[2]}
)
and
(
# no fallback specified at all
! ( ($_[3]) = grep { *{"${_}::()"}{CODE} } @{$_[2]} )
or
# fallback explicitly undef
! defined ${"$_[3]::()"}
or
# explicitly true
!! ${"$_[3]::()"}
)
)
)
) ? \($_[0])
: undef;
}
#======================================================================
# NEW
#======================================================================
sub new {
my $self = shift;
my $class = ref($self) || $self;
my %opt = (ref $_[0] eq 'HASH') ? %{$_[0]} : @_;
# choose our case by keeping an option around
delete $opt{case} if $opt{case} && $opt{case} ne 'lower';
# default logic for interpreting arrayrefs
$opt{logic} = $opt{logic} ? uc $opt{logic} : 'OR';
# how to return bind vars
$opt{bindtype} ||= 'normal';
# default comparison is "=", but can be overridden
$opt{cmp} ||= '=';
# try to recognize which are the 'equality' and 'inequality' ops
# (temporary quickfix (in 2007), should go through a more seasoned API)
$opt{equality_op} = qr/^( \Q$opt{cmp}\E | \= )$/ix;
$opt{inequality_op} = qr/^( != | <> )$/ix;
$opt{like_op} = qr/^ (is\s+)? r?like $/xi;
$opt{not_like_op} = qr/^ (is\s+)? not \s+ r?like $/xi;
# SQL booleans
$opt{sqltrue} ||= '1=1';
$opt{sqlfalse} ||= '0=1';
# special operators
$opt{special_ops} ||= [];
# regexes are applied in order, thus push after user-defines
push @{$opt{special_ops}}, @BUILTIN_SPECIAL_OPS;
# unary operators
$opt{unary_ops} ||= [];
push @{$opt{unary_ops}}, @BUILTIN_UNARY_OPS;
# rudimentary sanity-check for user supplied bits treated as functions/operators
# If a purported function matches this regular expression, an exception is thrown.
# Literal SQL is *NOT* subject to this check, only functions (and column names
# when quoting is not in effect)
# FIXME
# need to guard against ()'s in column names too, but this will break tons of
# hacks... ideas anyone?
$opt{injection_guard} ||= qr/
\;
|
^ \s* go \s
/xmi;
return bless \%opt, $class;
}
sub _assert_pass_injection_guard {
if ($_[1] =~ $_[0]->{injection_guard}) {
my $class = ref $_[0];
puke "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
. "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
. "{injection_guard} attribute to ${class}->new()"
}
}
#======================================================================
# INSERT methods
#======================================================================
sub insert {
my $self = shift;
my $table = $self->_table(shift);
my $data = shift || return;
my $options = shift;
my $method = $self->_METHOD_FOR_refkind("_insert", $data);
my ($sql, @bind) = $self->$method($data);
$sql = join " ", $self->_sqlcase('insert into'), $table, $sql;
if ($options->{returning}) {
my ($s, @b) = $self->_insert_returning($options);
$sql .= $s;
push @bind, @b;
}
return wantarray ? ($sql, @bind) : $sql;
}
# So that subclasses can override INSERT ... RETURNING separately from
# UPDATE and DELETE (e.g. DBIx::Class::SQLMaker::Oracle does this)
sub _insert_returning { shift->_returning(@_) }
sub _returning {
my ($self, $options) = @_;
my $f = $options->{returning};
my $fieldlist = $self->_SWITCH_refkind($f, {
ARRAYREF => sub {join ', ', map { $self->_quote($_) } @$f;},
SCALAR => sub {$self->_quote($f)},
SCALARREF => sub {$$f},
});
return $self->_sqlcase(' returning ') . $fieldlist;
}
sub _insert_HASHREF { # explicit list of fields and then values
my ($self, $data) = @_;
my @fields = sort keys %$data;
my ($sql, @bind) = $self->_insert_values($data);
# assemble SQL
$_ = $self->_quote($_) foreach @fields;
$sql = "( ".join(", ", @fields).") ".$sql;
return ($sql, @bind);
}
sub _insert_ARRAYREF { # just generate values(?,?) part (no list of fields)
my ($self, $data) = @_;
# no names (arrayref) so can't generate bindtype
$self->{bindtype} ne 'columns'
or belch "can't do 'columns' bindtype when called with arrayref";
my (@values, @all_bind);
foreach my $value (@$data) {
my ($values, @bind) = $self->_insert_value(undef, $value);
push @values, $values;
push @all_bind, @bind;
}
my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
return ($sql, @all_bind);
}
sub _insert_ARRAYREFREF { # literal SQL with bind
my ($self, $data) = @_;
my ($sql, @bind) = @${$data};
$self->_assert_bindval_matches_bindtype(@bind);
return ($sql, @bind);
}
sub _insert_SCALARREF { # literal SQL without bind
my ($self, $data) = @_;
return ($$data);
}
sub _insert_values {
my ($self, $data) = @_;
my (@values, @all_bind);
foreach my $column (sort keys %$data) {
my ($values, @bind) = $self->_insert_value($column, $data->{$column});
push @values, $values;
push @all_bind, @bind;
}
my $sql = $self->_sqlcase('values')." ( ".join(", ", @values)." )";
return ($sql, @all_bind);
}
sub _insert_value {
my ($self, $column, $v) = @_;
my (@values, @all_bind);
$self->_SWITCH_refkind($v, {
ARRAYREF => sub {
if ($self->{array_datatypes}) { # if array datatype are activated
push @values, '?';
push @all_bind, $self->_bindtype($column, $v);
}
else { # else literal SQL with bind
my ($sql, @bind) = @$v;
$self->_assert_bindval_matches_bindtype(@bind);
push @values, $sql;
push @all_bind, @bind;
}
},
ARRAYREFREF => sub { # literal SQL with bind
my ($sql, @bind) = @${$v};
$self->_assert_bindval_matches_bindtype(@bind);
push @values, $sql;
push @all_bind, @bind;
},
# THINK: anything useful to do with a HASHREF ?
HASHREF => sub { # (nothing, but old SQLA passed it through)
#TODO in SQLA >= 2.0 it will die instead
belch "HASH ref as bind value in insert is not supported";
push @values, '?';
push @all_bind, $self->_bindtype($column, $v);
},
SCALARREF => sub { # literal SQL without bind
push @values, $$v;
},
SCALAR_or_UNDEF => sub {
push @values, '?';
push @all_bind, $self->_bindtype($column, $v);
},
});
my $sql = join(", ", @values);
return ($sql, @all_bind);
}
#======================================================================
# UPDATE methods
#======================================================================
sub update {
my $self = shift;
my $table = $self->_table(shift);
my $data = shift || return;
my $where = shift;
my $options = shift;
# first build the 'SET' part of the sql statement
puke "Unsupported data type specified to \$sql->update"
unless ref $data eq 'HASH';
my ($sql, @all_bind) = $self->_update_set_values($data);
$sql = $self->_sqlcase('update ') . $table . $self->_sqlcase(' set ')
. $sql;
if ($where) {
my($where_sql, @where_bind) = $self->where($where);
$sql .= $where_sql;
push @all_bind, @where_bind;
}
if ($options->{returning}) {
my ($returning_sql, @returning_bind) = $self->_update_returning($options);
$sql .= $returning_sql;
push @all_bind, @returning_bind;
}
return wantarray ? ($sql, @all_bind) : $sql;
}
sub _update_set_values {
my ($self, $data) = @_;
my (@set, @all_bind);
for my $k (sort keys %$data) {
my $v = $data->{$k};
my $r = ref $v;
my $label = $self->_quote($k);
$self->_SWITCH_refkind($v, {
ARRAYREF => sub {
if ($self->{array_datatypes}) { # array datatype
push @set, "$label = ?";
push @all_bind, $self->_bindtype($k, $v);
}
else { # literal SQL with bind
my ($sql, @bind) = @$v;
$self->_assert_bindval_matches_bindtype(@bind);
push @set, "$label = $sql";
push @all_bind, @bind;
}
},
ARRAYREFREF => sub { # literal SQL with bind
my ($sql, @bind) = @${$v};
$self->_assert_bindval_matches_bindtype(@bind);
push @set, "$label = $sql";
push @all_bind, @bind;
},
SCALARREF => sub { # literal SQL without bind
push @set, "$label = $$v";
},
HASHREF => sub {
my ($op, $arg, @rest) = %$v;
puke 'Operator calls in update must be in the form { -op => $arg }'
if (@rest or not $op =~ /^\-(.+)/);
local $self->{_nested_func_lhs} = $k;
my ($sql, @bind) = $self->_where_unary_op($1, $arg);
push @set, "$label = $sql";
push @all_bind, @bind;
},
SCALAR_or_UNDEF => sub {
push @set, "$label = ?";
push @all_bind, $self->_bindtype($k, $v);
},
});
}
# generate sql
my $sql = join ', ', @set;
return ($sql, @all_bind);
}
# So that subclasses can override UPDATE ... RETURNING separately from
# INSERT and DELETE
sub _update_returning { shift->_returning(@_) }
#======================================================================
# SELECT
#======================================================================
sub select {
my $self = shift;
my $table = $self->_table(shift);
my $fields = shift || '*';
my $where = shift;
my $order = shift;
my ($fields_sql, @bind) = $self->_select_fields($fields);
my ($where_sql, @where_bind) = $self->where($where, $order);
push @bind, @where_bind;
my $sql = join(' ', $self->_sqlcase('select'), $fields_sql,
$self->_sqlcase('from'), $table)
. $where_sql;
return wantarray ? ($sql, @bind) : $sql;
}
sub _select_fields {
my ($self, $fields) = @_;
return ref $fields eq 'ARRAY' ? join ', ', map { $self->_quote($_) } @$fields
: $fields;
}
#======================================================================
# DELETE
#======================================================================
sub delete {
my $self = shift;
my $table = $self->_table(shift);
my $where = shift;
my $options = shift;
my($where_sql, @bind) = $self->where($where);
my $sql = $self->_sqlcase('delete from ') . $table . $where_sql;
if ($options->{returning}) {
my ($returning_sql, @returning_bind) = $self->_delete_returning($options);
$sql .= $returning_sql;
push @bind, @returning_bind;
}
return wantarray ? ($sql, @bind) : $sql;
}
# So that subclasses can override DELETE ... RETURNING separately from
# INSERT and UPDATE
sub _delete_returning { shift->_returning(@_) }
#======================================================================
# WHERE: entry point
#======================================================================
# Finally, a separate routine just to handle WHERE clauses
sub where {
my ($self, $where, $order) = @_;
# where ?
my ($sql, @bind) = $self->_recurse_where($where);
$sql = (defined $sql and length $sql) ? $self->_sqlcase(' where ') . "( $sql )" : '';
# order by?
if ($order) {
my ($order_sql, @order_bind) = $self->_order_by($order);
$sql .= $order_sql;
push @bind, @order_bind;
}
return wantarray ? ($sql, @bind) : $sql;
}
sub _recurse_where {
my ($self, $where, $logic) = @_;
# dispatch on appropriate method according to refkind of $where
my $method = $self->_METHOD_FOR_refkind("_where", $where);
my ($sql, @bind) = $self->$method($where, $logic);
# DBIx::Class used to call _recurse_where in scalar context
# something else might too...
if (wantarray) {
return ($sql, @bind);
}
else {
belch "Calling _recurse_where in scalar context is deprecated and will go away before 2.0";
return $sql;
}
}
#======================================================================
# WHERE: top-level ARRAYREF
#======================================================================
sub _where_ARRAYREF {
my ($self, $where, $logic) = @_;
$logic = uc($logic || $self->{logic});
$logic eq 'AND' or $logic eq 'OR' or puke "unknown logic: $logic";
my @clauses = @$where;
my (@sql_clauses, @all_bind);
# need to use while() so can shift() for pairs
while (@clauses) {
my $el = shift @clauses;
$el = undef if (defined $el and ! length $el);
# switch according to kind of $el and get corresponding ($sql, @bind)
my ($sql, @bind) = $self->_SWITCH_refkind($el, {
# skip empty elements, otherwise get invalid trailing AND stuff
ARRAYREF => sub {$self->_recurse_where($el) if @$el},
ARRAYREFREF => sub {
my ($s, @b) = @$$el;
$self->_assert_bindval_matches_bindtype(@b);
($s, @b);
},
HASHREF => sub {$self->_recurse_where($el, 'and') if %$el},
SCALARREF => sub { ($$el); },
SCALAR => sub {
# top-level arrayref with scalars, recurse in pairs
$self->_recurse_where({$el => shift(@clauses)})
},
UNDEF => sub {puke "Supplying an empty left hand side argument is not supported in array-pairs" },
});
if ($sql) {
push @sql_clauses, $sql;
push @all_bind, @bind;
}
}
return $self->_join_sql_clauses($logic, \@sql_clauses, \@all_bind);
}
#======================================================================
# WHERE: top-level ARRAYREFREF
#======================================================================
sub _where_ARRAYREFREF {
my ($self, $where) = @_;
my ($sql, @bind) = @$$where;
$self->_assert_bindval_matches_bindtype(@bind);
return ($sql, @bind);
}
#======================================================================
# WHERE: top-level HASHREF
#======================================================================
sub _where_HASHREF {
my ($self, $where) = @_;
my (@sql_clauses, @all_bind);
for my $k (sort keys %$where) {
my $v = $where->{$k};
# ($k => $v) is either a special unary op or a regular hashpair
my ($sql, @bind) = do {
if ($k =~ /^-./) {
# put the operator in canonical form
my $op = $k;
$op = substr $op, 1; # remove initial dash
$op =~ s/^\s+|\s+$//g;# remove leading/trailing space
$op =~ s/\s+/ /g; # compress whitespace
# so that -not_foo works correctly
$op =~ s/^not_/NOT /i;
$self->_debug("Unary OP(-$op) within hashref, recursing...");
my ($s, @b) = $self->_where_unary_op($op, $v);
# top level vs nested
# we assume that handled unary ops will take care of their ()s
$s = "($s)" unless (
List::Util::first {$op =~ $_->{regex}} @{$self->{unary_ops}}
or
( defined $self->{_nested_func_lhs} and $self->{_nested_func_lhs} eq $k )
);
($s, @b);
}
else {
if (! length $k) {
if (is_literal_value ($v) ) {
belch 'Hash-pairs consisting of an empty string with a literal are deprecated, and will be removed in 2.0: use -and => [ $literal ] instead';
}
else {
puke "Supplying an empty left hand side argument is not supported in hash-pairs";
}
}
my $method = $self->_METHOD_FOR_refkind("_where_hashpair", $v);
$self->$method($k, $v);
}
};
push @sql_clauses, $sql;
push @all_bind, @bind;
}
return $self->_join_sql_clauses('and', \@sql_clauses, \@all_bind);
}
sub _where_unary_op {
my ($self, $op, $rhs) = @_;
# top level special ops are illegal in general
# this includes the -ident/-value ops (dual purpose unary and special)
puke "Illegal use of top-level '-$op'"
if ! defined $self->{_nested_func_lhs} and List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}};
if (my $op_entry = List::Util::first { $op =~ $_->{regex} } @{$self->{unary_ops}}) {
my $handler = $op_entry->{handler};
if (not ref $handler) {
if ($op =~ s/ [_\s]? \d+ $//x ) {
belch 'Use of [and|or|nest]_N modifiers is deprecated and will be removed in SQLA v2.0. '
. "You probably wanted ...-and => [ -$op => COND1, -$op => COND2 ... ]";
}
return $self->$handler($op, $rhs);
}
elsif (ref $handler eq 'CODE') {
return $handler->($self, $op, $rhs);
}
else {
puke "Illegal handler for operator $op - expecting a method name or a coderef";
}
}
$self->_debug("Generic unary OP: $op - recursing as function");
$self->_assert_pass_injection_guard($op);
my ($sql, @bind) = $self->_SWITCH_refkind($rhs, {
SCALAR => sub {
puke "Illegal use of top-level '-$op'"
unless defined $self->{_nested_func_lhs};
return (
$self->_convert('?'),
$self->_bindtype($self->{_nested_func_lhs}, $rhs)
);
},
FALLBACK => sub {
$self->_recurse_where($rhs)
},
});
$sql = sprintf('%s %s',
$self->_sqlcase($op),
$sql,
);
return ($sql, @bind);
}
sub _where_op_ANDOR {
my ($self, $op, $v) = @_;
$self->_SWITCH_refkind($v, {
ARRAYREF => sub {
return $self->_where_ARRAYREF($v, $op);
},
HASHREF => sub {
return ($op =~ /^or/i)
? $self->_where_ARRAYREF([ map { $_ => $v->{$_} } (sort keys %$v) ], $op)
: $self->_where_HASHREF($v);
},
SCALARREF => sub {
puke "-$op => \\\$scalar makes little sense, use " .
($op =~ /^or/i
? '[ \$scalar, \%rest_of_conditions ] instead'
: '-and => [ \$scalar, \%rest_of_conditions ] instead'
);
},
ARRAYREFREF => sub {
puke "-$op => \\[...] makes little sense, use " .
($op =~ /^or/i
? '[ \[...], \%rest_of_conditions ] instead'
: '-and => [ \[...], \%rest_of_conditions ] instead'
);
},
SCALAR => sub { # permissively interpreted as SQL
puke "-$op => \$value makes little sense, use -bool => \$value instead";
},
UNDEF => sub {
puke "-$op => undef not supported";
},
});
}
sub _where_op_NEST {
my ($self, $op, $v) = @_;
$self->_SWITCH_refkind($v, {
SCALAR => sub { # permissively interpreted as SQL
belch "literal SQL should be -nest => \\'scalar' "
. "instead of -nest => 'scalar' ";
return ($v);
},
UNDEF => sub {
puke "-$op => undef not supported";
},
FALLBACK => sub {
$self->_recurse_where($v);
},
});
}
sub _where_op_BOOL {
my ($self, $op, $v) = @_;
my ($s, @b) = $self->_SWITCH_refkind($v, {
SCALAR => sub { # interpreted as SQL column
$self->_convert($self->_quote($v));
},
UNDEF => sub {
puke "-$op => undef not supported";
},
FALLBACK => sub {
$self->_recurse_where($v);
},
});
$s = "(NOT $s)" if $op =~ /^not/i;
($s, @b);
}
sub _where_op_IDENT {
my $self = shift;
my ($op, $rhs) = splice @_, -2;
if (! defined $rhs or length ref $rhs) {
puke "-$op requires a single plain scalar argument (a quotable identifier)";
}
# in case we are called as a top level special op (no '=')
my $lhs = shift;
$_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
return $lhs
? "$lhs = $rhs"
: $rhs
;
}
sub _where_op_VALUE {
my $self = shift;
my ($op, $rhs) = splice @_, -2;
# in case we are called as a top level special op (no '=')
my $lhs = shift;
# special-case NULL
if (! defined $rhs) {
return defined $lhs
? $self->_convert($self->_quote($lhs)) . ' IS NULL'
: undef
;
}
my @bind =
$self->_bindtype(
(defined $lhs ? $lhs : $self->{_nested_func_lhs}),
$rhs,
)
;
return $lhs
? (
$self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
@bind
)
: (
$self->_convert('?'),
@bind,
)
;
}
sub _where_hashpair_ARRAYREF {
my ($self, $k, $v) = @_;
if (@$v) {
my @v = @$v; # need copy because of shift below
$self->_debug("ARRAY($k) means distribute over elements");
# put apart first element if it is an operator (-and, -or)
my $op = (
(defined $v[0] && $v[0] =~ /^ - (?: AND|OR ) $/ix)
? shift @v
: ''
);
my @distributed = map { {$k => $_} } @v;
if ($op) {
$self->_debug("OP($op) reinjected into the distributed array");
unshift @distributed, $op;
}
my $logic = $op ? substr($op, 1) : '';
return $self->_recurse_where(\@distributed, $logic);
}
else {
$self->_debug("empty ARRAY($k) means 0=1");
return ($self->{sqlfalse});
}
}
sub _where_hashpair_HASHREF {
my ($self, $k, $v, $logic) = @_;
$logic ||= 'and';
local $self->{_nested_func_lhs} = defined $self->{_nested_func_lhs}
? $self->{_nested_func_lhs}
: $k
;
my ($all_sql, @all_bind);
for my $orig_op (sort keys %$v) {
my $val = $v->{$orig_op};
# put the operator in canonical form
my $op = $orig_op;
# FIXME - we need to phase out dash-less ops
$op =~ s/^-//; # remove possible initial dash
$op =~ s/^\s+|\s+$//g;# remove leading/trailing space
$op =~ s/\s+/ /g; # compress whitespace
$self->_assert_pass_injection_guard($op);
# fixup is_not
$op =~ s/^is_not/IS NOT/i;
# so that -not_foo works correctly
$op =~ s/^not_/NOT /i;
# another retarded special case: foo => { $op => { -value => undef } }
if (ref $val eq 'HASH' and keys %$val == 1 and exists $val->{-value} and ! defined $val->{-value} ) {
$val = undef;
}
my ($sql, @bind);
# CASE: col-value logic modifiers
if ($orig_op =~ /^ \- (and|or) $/xi) {
($sql, @bind) = $self->_where_hashpair_HASHREF($k, $val, $1);
}
# CASE: special operators like -in or -between
elsif (my $special_op = List::Util::first { $op =~ $_->{regex} } @{$self->{special_ops}}) {
my $handler = $special_op->{handler};
if (! $handler) {
puke "No handler supplied for special operator $orig_op";
}
elsif (not ref $handler) {
($sql, @bind) = $self->$handler($k, $op, $val);
}
elsif (ref $handler eq 'CODE') {
($sql, @bind) = $handler->($self, $k, $op, $val);
}
else {
puke "Illegal handler for special operator $orig_op - expecting a method name or a coderef";
}
}
else {
$self->_SWITCH_refkind($val, {
ARRAYREF => sub { # CASE: col => {op => \@vals}
($sql, @bind) = $self->_where_field_op_ARRAYREF($k, $op, $val);
},
ARRAYREFREF => sub { # CASE: col => {op => \[$sql, @bind]} (literal SQL with bind)
my ($sub_sql, @sub_bind) = @$$val;
$self->_assert_bindval_matches_bindtype(@sub_bind);
$sql = join ' ', $self->_convert($self->_quote($k)),
$self->_sqlcase($op),
$sub_sql;
@bind = @sub_bind;
},
UNDEF => sub { # CASE: col => {op => undef} : sql "IS (NOT)? NULL"
my $is =
$op =~ /^not$/i ? 'is not' # legacy
: $op =~ $self->{equality_op} ? 'is'
: $op =~ $self->{like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is'
: $op =~ $self->{inequality_op} ? 'is not'
: $op =~ $self->{not_like_op} ? belch("Supplying an undefined argument to '@{[ uc $op]}' is deprecated") && 'is not'
: puke "unexpected operator '$orig_op' with undef operand";
$sql = $self->_quote($k) . $self->_sqlcase(" $is null");
},
FALLBACK => sub { # CASE: col => {op/func => $stuff}
($sql, @bind) = $self->_where_unary_op($op, $val);
$sql = join(' ',
$self->_convert($self->_quote($k)),
$self->{_nested_func_lhs} eq $k ? $sql : "($sql)", # top level vs nested
);
},
});
}
($all_sql) = (defined $all_sql and $all_sql) ? $self->_join_sql_clauses($logic, [$all_sql, $sql], []) : $sql;
push @all_bind, @bind;
}
return ($all_sql, @all_bind);