2ce72cfc31f81468dca81054e140ecdba2c26886
[dbsrgits/SQL-Abstract.git] / lib / SQL / Abstract / Converter.pm
1 package SQL::Abstract::Converter;
2
3 use Carp ();
4 use List::Util ();
5 use Scalar::Util ();
6 use Data::Query::Constants qw(
7   DQ_IDENTIFIER DQ_OPERATOR DQ_VALUE DQ_LITERAL DQ_JOIN DQ_SELECT DQ_ORDER
8   DQ_WHERE DQ_DELETE DQ_UPDATE DQ_INSERT
9 );
10 use Data::Query::ExprHelpers qw(perl_scalar_value);
11 use Moo;
12
13 has renderer_will_quote => (
14   is => 'ro'
15 );
16
17 has lower_case => (
18   is => 'ro' 
19 );
20
21 has default_logic => (
22   is => 'ro', coerce => sub { uc($_[0]) }, default => sub { 'OR' }
23 );
24
25 has bind_meta => (
26   is => 'ro', default => sub { 1 }
27 );
28
29 has cmp => (is => 'ro', default => sub { '=' });
30
31 has sqltrue => (is => 'ro', default => sub { '1=1' });
32 has sqlfalse => (is => 'ro', default => sub { '0=1' });
33
34 has special_ops => (is => 'ro', default => sub { [] });
35
36 # XXX documented but I don't current fail any tests not using it
37 has unary_ops => (is => 'ro', default => sub { [] });
38
39 has injection_guard => (
40   is => 'ro',
41   default => sub {
42     qr/
43       \;
44         |
45       ^ \s* go \s
46     /xmi;
47   }
48 );
49
50 has identifier_sep => (
51   is => 'ro', default => sub { '.' },
52 );
53
54 has always_quote => (is => 'ro', default => sub { 1 });
55
56 has convert => (is => 'ro');
57
58 has array_datatypes => (is => 'ro');
59
60 sub _literal_to_dq {
61   my ($self, $literal) = @_;
62   my @bind;
63   ($literal, @bind) = @$literal if ref($literal) eq 'ARRAY';
64   +{
65     type => DQ_LITERAL,
66     subtype => 'SQL',
67     literal => $literal,
68     (@bind ? (values => [ $self->_bind_to_dq(@bind) ]) : ()),
69   };
70 }
71
72 sub _bind_to_dq {
73   my ($self, @bind) = @_;
74   return unless @bind;
75   $self->bind_meta
76     ? do {
77         $self->_assert_bindval_matches_bindtype(@bind);
78         map perl_scalar_value(reverse @$_), @bind
79       }
80     : map perl_scalar_value($_), @bind
81 }
82
83 sub _value_to_dq {
84   my ($self, $value) = @_;
85   $self->_maybe_convert_dq(perl_scalar_value($value, our $Cur_Col_Meta));
86 }
87
88 sub _ident_to_dq {
89   my ($self, $ident) = @_;
90   $self->_assert_pass_injection_guard($ident)
91     unless $self->renderer_will_quote;
92   $self->_maybe_convert_dq({
93     type => DQ_IDENTIFIER,
94     elements => [ split /\Q${\$self->identifier_sep}/, $ident ],
95   });
96 }
97
98 sub _maybe_convert_dq {
99   my ($self, $dq) = @_;
100   if (my $c = $self->{where_convert}) {
101     +{
102        type => DQ_OPERATOR,
103        operator => { 'SQL.Naive' => 'apply' },
104        args => [
105          { type => DQ_IDENTIFIER, elements => [ $self->_sqlcase($c) ] },
106          $dq
107        ]
108      };
109   } else {
110     $dq;
111   }
112 }
113
114 sub _op_to_dq {
115   my ($self, $op, @args) = @_;
116   $self->_assert_pass_injection_guard($op);
117   +{
118     type => DQ_OPERATOR,
119     operator => { 'SQL.Naive' => $op },
120     args => \@args
121   };
122 }
123
124 sub _assert_pass_injection_guard {
125   if ($_[1] =~ $_[0]->{injection_guard}) {
126     my $class = ref $_[0];
127     die "Possible SQL injection attempt '$_[1]'. If this is indeed a part of the "
128      . "desired SQL use literal SQL ( \'...' or \[ '...' ] ) or supply your own "
129      . "{injection_guard} attribute to ${class}->new()"
130   }
131 }
132
133 sub _insert_to_dq {
134   my ($self, $table, $data, $options) = @_;
135   my (@names, @values);
136   if (ref($data) eq 'HASH') {
137     @names = sort keys %$data;
138     foreach my $k (@names) {
139       local our $Cur_Col_Meta = $k;
140       push @values, $self->_mutation_rhs_to_dq($data->{$k});
141     }
142   } elsif (ref($data) eq 'ARRAY') {
143     local our $Cur_Col_Meta;
144     @values = map $self->_mutation_rhs_to_dq($_), @$data;
145   } else {
146     die "Not handled yet";
147   }
148   my $returning;
149   if (my $r_source = $options->{returning}) {
150     $returning = [
151       map +(ref($_) ? $self->_expr_to_dq($_) : $self->_ident_to_dq($_)),
152         (ref($r_source) eq 'ARRAY' ? @$r_source : $r_source),
153     ];
154   }
155   +{
156     type => DQ_INSERT,
157     target => $self->_table_to_dq($table),
158     (@names ? (names => [ map $self->_ident_to_dq($_), @names ]) : ()),
159     values => [ \@values ],
160     ($returning ? (returning => $returning) : ()),
161   };
162 }
163
164 sub _mutation_rhs_to_dq {
165   my ($self, $v) = @_;
166   if (ref($v) eq 'ARRAY') {
167     if ($self->{array_datatypes}) {
168       return $self->_value_to_dq($v);
169     }
170     $v = \do { my $x = $v };
171   }
172   if (ref($v) eq 'HASH') {
173     my ($op, $arg, @rest) = %$v;
174
175     die 'Operator calls in update/insert must be in the form { -op => $arg }'
176       if (@rest or not $op =~ /^\-(.+)/);
177   }
178   return $self->_expr_to_dq($v);
179 }
180
181 sub _update_to_dq {
182   my ($self, $table, $data, $where) = @_;
183
184   die "Unsupported data type specified to \$sql->update"
185     unless ref $data eq 'HASH';
186
187   my @set;
188
189   foreach my $k (sort keys %$data) {
190     my $v = $data->{$k};
191     local our $Cur_Col_Meta = $k;
192     push @set, [ $self->_ident_to_dq($k), $self->_mutation_rhs_to_dq($v) ];
193   }
194
195   return +{
196     type => DQ_UPDATE,
197     target => $self->_table_to_dq($table),
198     set => \@set,
199     where => $self->_where_to_dq($where),
200   };
201 }
202
203 sub _source_to_dq {
204   my ($self, $table, undef, $where) = @_;
205
206   my $source_dq = $self->_table_to_dq($table);
207
208   if (my $where_dq = $self->_where_to_dq($where)) {
209     $source_dq = {
210       type => DQ_WHERE,
211       from => $source_dq,
212       where => $where_dq,
213     };
214   }
215
216   $source_dq;
217 }
218
219 sub _select_to_dq {
220   my $self = shift;
221   my ($table, $fields, $where, $order) = @_;
222
223   my $source_dq = $self->_source_to_dq(@_);
224
225   my $ordered_dq = do {
226     if ($order) {
227       $self->_order_by_to_dq($order, undef, $source_dq);
228     } else {
229       $source_dq
230     }
231   };
232
233   return $self->_select_list_to_dq($fields, $ordered_dq);
234 }
235
236 sub _select_list_to_dq {
237   my ($self, $fields, $from_dq) = @_;
238
239   $fields ||= '*';
240
241   return +{
242     type => DQ_SELECT,
243     select => [ $self->_select_field_list_to_dq($fields) ],
244     from => $from_dq,
245   };
246 }
247
248 sub _select_field_list_to_dq {
249   my ($self, $fields) = @_;
250   map $self->_select_field_to_dq($_),
251     ref($fields) eq 'ARRAY' ? @$fields : $fields;
252 }
253
254 sub _select_field_to_dq {
255   my ($self, $field) = @_;
256   ref($field)
257     ? $self->_literal_to_dq($$field)
258     : $self->_ident_to_dq($field)
259 }
260
261 sub _delete_to_dq {
262   my ($self, $table, $where) = @_;
263   +{
264     type => DQ_DELETE,
265     target => $self->_table_to_dq($table),
266     where => $self->_where_to_dq($where),
267   }
268 }
269
270 sub _where_to_dq {
271   my ($self, $where, $logic) = @_;
272
273   return undef unless defined($where);
274
275   # turn the convert misfeature on - only used in WHERE clauses
276   local $self->{where_convert} = $self->convert;
277
278   return $self->_expr_to_dq($where, $logic);
279 }
280
281 sub _expr_to_dq {
282   my ($self, $where, $logic) = @_;
283
284   if (ref($where) eq 'ARRAY') {
285     return $self->_expr_to_dq_ARRAYREF($where, $logic);
286   } elsif (ref($where) eq 'HASH') {
287     return $self->_expr_to_dq_HASHREF($where, $logic);
288   } elsif (
289     ref($where) eq 'SCALAR'
290     or (ref($where) eq 'REF' and ref($$where) eq 'ARRAY')
291   ) {
292     return $self->_literal_to_dq($$where);
293   } elsif (!ref($where) or Scalar::Util::blessed($where)) {
294     return $self->_value_to_dq($where);
295   }
296   die "Can't handle $where";
297 }
298
299 sub _expr_to_dq_ARRAYREF {
300   my ($self, $where, $logic) = @_;
301
302   $logic = uc($logic || $self->default_logic || 'OR');
303   $logic eq 'AND' or $logic eq 'OR' or die "unknown logic: $logic";
304
305   return unless @$where;
306
307   my ($first, @rest) = @$where;
308
309   return $self->_expr_to_dq($first) unless @rest;
310
311   my $first_dq = do {
312     if (!ref($first)) {
313       $self->_where_hashpair_to_dq($first => shift(@rest));
314     } else {
315       $self->_expr_to_dq($first);
316     }
317   };
318
319   return $self->_expr_to_dq_ARRAYREF(\@rest, $logic) unless $first_dq;
320
321   $self->_op_to_dq(
322     $logic, $first_dq, $self->_expr_to_dq_ARRAYREF(\@rest, $logic)
323   );
324 }
325
326 sub _expr_to_dq_HASHREF {
327   my ($self, $where, $logic) = @_;
328
329   $logic = uc($logic) if $logic;
330
331   my @dq = map {
332     $self->_where_hashpair_to_dq($_ => $where->{$_}, $logic)
333   } sort keys %$where;
334
335   return $dq[0] unless @dq > 1;
336
337   my $final = pop(@dq);
338
339   foreach my $dq (reverse @dq) {
340     $final = $self->_op_to_dq($logic||'AND', $dq, $final);
341   }
342
343   return $final;
344 }
345
346 sub _where_to_dq_SCALAR {
347   shift->_value_to_dq(@_);
348 }
349
350 sub _apply_to_dq {
351   my ($self, $op, $v) = @_;
352   my @args = map $self->_expr_to_dq($_), (ref($v) eq 'ARRAY' ? @$v : $v);
353
354   # Ok. Welcome to stupid compat code land. An SQLA expr that would in the
355   # absence of this piece of crazy render to:
356   #
357   #   A( B( C( x ) ) )
358   #
359   # such as
360   #
361   #   { -a => { -b => { -c => $x } } }
362   #
363   # actually needs to render to:
364   #
365   #   A( B( C x ) )
366   #
367   # because SQL sucks, and databases are hateful, and SQLA is Just That DWIM.
368   #
369   # However, we don't want to catch 'A(x)' and turn it into 'A x'
370   #
371   # So the way we deal with this is to go through all our arguments, and
372   # then if the argument is -also- an apply, i.e. at least 'B', we check
373   # its arguments - and if there's only one of them, and that isn't an apply,
374   # then we convert to the bareword form. The end result should be:
375   #
376   # A( x )                   -> A( x )
377   # A( B( x ) )              -> A( B x )
378   # A( B( C( x ) ) )         -> A( B( C x ) )
379   # A( B( x + y ) )          -> A( B( x + y ) )
380   # A( B( x, y ) )           -> A( B( x, y ) )
381   #
382   # If this turns out not to be quite right, please add additional tests
383   # to either 01generate.t or 02where.t *and* update this comment.
384
385   foreach my $arg (@args) {
386     if (
387       $arg->{type} eq DQ_OPERATOR and $arg->{operator}{'SQL.Naive'} eq 'apply'
388       and @{$arg->{args}} == 2 and $arg->{args}[1]{type} ne DQ_OPERATOR
389     ) {
390       $arg->{operator}{'SQL.Naive'} = (shift @{$arg->{args}})->{elements}->[0];
391     }
392   }
393   $self->_assert_pass_injection_guard($op);
394   return $self->_op_to_dq(
395     apply => $self->_ident_to_dq($op), @args
396   );
397 }
398
399 sub _where_hashpair_to_dq {
400   my ($self, $k, $v, $logic) = @_;
401
402   if ($k =~ /^-(.*)/s) {
403     my $op = uc($1);
404     if ($op eq 'AND' or $op eq 'OR') {
405       return $self->_expr_to_dq($v, $op);
406     } elsif ($op eq 'NEST') {
407       return $self->_expr_to_dq($v);
408     } elsif ($op eq 'NOT') {
409       return $self->_op_to_dq(NOT => $self->_expr_to_dq($v));
410     } elsif ($op eq 'BOOL') {
411       return ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v);
412     } elsif ($op eq 'NOT_BOOL') {
413       return $self->_op_to_dq(
414         NOT => ref($v) ? $self->_expr_to_dq($v) : $self->_ident_to_dq($v)
415       );
416     } elsif ($op eq 'IDENT') {
417       return $self->_ident_to_dq($v);
418     } elsif ($op eq 'VALUE') {
419       return $self->_value_to_dq($v);
420     } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+/) {
421       die "Use of [and|or|nest]_N modifiers is no longer supported";
422     } else {
423       return $self->_apply_to_dq($op, $v);
424     }
425   } else {
426     local our $Cur_Col_Meta = $k;
427     if (ref($v) eq 'ARRAY') {
428       if (!@$v) {
429         return $self->_literal_to_dq($self->{sqlfalse});
430       } elsif (defined($v->[0]) && $v->[0] =~ /-(and|or)/i) {
431         return $self->_expr_to_dq_ARRAYREF([
432           map +{ $k => $_ }, @{$v}[1..$#$v]
433         ], uc($1));
434       }
435       return $self->_expr_to_dq_ARRAYREF([
436         map +{ $k => $_ }, @$v
437       ], $logic);
438     } elsif (ref($v) eq 'SCALAR' or (ref($v) eq 'REF' and ref($$v) eq 'ARRAY')) {
439       return +{
440         type => DQ_LITERAL,
441         subtype => 'SQL',
442         parts => [ $self->_ident_to_dq($k), $self->_literal_to_dq($$v) ]
443       };
444     }
445     my ($op, $rhs) = do {
446       if (ref($v) eq 'HASH') {
447         if (keys %$v > 1) {
448           return $self->_expr_to_dq_ARRAYREF([
449             map +{ $k => { $_ => $v->{$_} } }, sort keys %$v
450           ], $logic||'AND');
451         }
452         my ($op, $value) = %$v;
453         s/^-//, s/_/ /g for $op;
454         if ($op =~ /^(and|or)$/i) {
455           return $self->_expr_to_dq({ $k => $value }, $op);
456         } elsif (
457           my $special_op = List::Util::first {$op =~ $_->{regex}}
458                              @{$self->{special_ops}}
459         ) {
460           return $self->_literal_to_dq(
461             [ $special_op->{handler}->($k, $op, $value) ]
462           );;
463         } elsif ($op =~ /^(?:AND|OR|NEST)_?\d+$/i) {
464           die "Use of [and|or|nest]_N modifiers is no longer supported";
465         }
466         (uc($op), $value);
467       } else {
468         ($self->{cmp}, $v);
469       }
470     };
471     if ($op eq 'BETWEEN' or $op eq 'IN' or $op eq 'NOT IN' or $op eq 'NOT BETWEEN') {
472       if (ref($rhs) ne 'ARRAY') {
473         if ($op =~ /IN$/) {
474           # have to add parens if none present because -in => \"SELECT ..."
475           # got documented. mst hates everything.
476           if (ref($rhs) eq 'SCALAR') {
477             my $x = $$rhs;
478             1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
479             $rhs = \$x;
480           } else {
481             my ($x, @rest) = @{$$rhs};
482             1 while ($x =~ s/\A\s*\((.*)\)\s*\Z/$1/s);
483             $rhs = \[ $x, @rest ];
484           }
485         }
486         return $self->_op_to_dq(
487           $op, $self->_ident_to_dq($k), $self->_literal_to_dq($$rhs)
488         );
489       }
490       return $self->_literal_to_dq($self->{sqlfalse}) unless @$rhs;
491       return $self->_op_to_dq(
492         $op, $self->_ident_to_dq($k), map $self->_expr_to_dq($_), @$rhs
493       )
494     } elsif ($op =~ s/^NOT (?!LIKE)//) {
495       return $self->_where_hashpair_to_dq(-not => { $k => { $op => $rhs } });
496     } elsif ($op eq 'IDENT') {
497       return $self->_op_to_dq(
498         $self->{cmp}, $self->_ident_to_dq($k), $self->_ident_to_dq($rhs)
499       );
500     } elsif ($op eq 'VALUE') {
501       return $self->_op_to_dq(
502         $self->{cmp}, $self->_ident_to_dq($k), $self->_value_to_dq($rhs)
503       );
504     } elsif (!defined($rhs)) {
505       my $null_op = do {
506         if ($op eq '=' or $op eq 'LIKE') {
507           'IS NULL'
508         } elsif ($op eq '!=') {
509           'IS NOT NULL'
510         } else {
511           die "Can't do undef -> NULL transform for operator ${op}";
512         }
513       };
514       return $self->_op_to_dq($null_op, $self->_ident_to_dq($k));
515     }
516     if (ref($rhs) eq 'ARRAY') {
517       if (!@$rhs) {
518         return $self->_literal_to_dq(
519           $op eq '!=' ? $self->{sqltrue} : $self->{sqlfalse}
520         );
521       } elsif (defined($rhs->[0]) and $rhs->[0] =~ /^-(and|or)$/i) {
522         return $self->_expr_to_dq_ARRAYREF([
523           map +{ $k => { $op => $_ } }, @{$rhs}[1..$#$rhs]
524         ], uc($1));
525       } elsif ($op =~ /^-(?:AND|OR|NEST)_?\d+/) {
526         die "Use of [and|or|nest]_N modifiers is no longer supported";
527       }
528       return $self->_expr_to_dq_ARRAYREF([
529         map +{ $k => { $op => $_ } }, @$rhs
530       ]);
531     }
532     return $self->_op_to_dq(
533       $op, $self->_ident_to_dq($k), $self->_expr_to_dq($rhs)
534     );
535   }
536 }
537
538 sub _order_by_to_dq {
539   my ($self, $arg, $dir, $from) = @_;
540
541   return unless $arg;
542
543   my $dq = {
544     type => DQ_ORDER,
545     ($dir ? (direction => $dir) : ()),
546     ($from ? (from => $from) : ()),
547   };
548
549   if (!ref($arg)) {
550     $dq->{by} = $self->_ident_to_dq($arg);
551   } elsif (ref($arg) eq 'ARRAY') {
552     return unless @$arg;
553     local our $Order_Inner unless our $Order_Recursing;
554     local $Order_Recursing = 1;
555     my ($outer, $inner);
556     foreach my $member (@$arg) {
557       local $Order_Inner;
558       my $next = $self->_order_by_to_dq($member, $dir, $from);
559       $outer ||= $next;
560       $inner->{from} = $next if $inner;
561       $inner = $Order_Inner || $next;
562     }
563     $Order_Inner = $inner;
564     return $outer;
565   } elsif (ref($arg) eq 'REF' and ref($$arg) eq 'ARRAY') {
566     $dq->{by} = $self->_literal_to_dq($$arg);
567   } elsif (ref($arg) eq 'SCALAR') {
568     $dq->{by} = $self->_literal_to_dq($$arg);
569   } elsif (ref($arg) eq 'HASH') {
570     my ($key, $val, @rest) = %$arg;
571
572     return unless $key;
573
574     if (@rest or not $key =~ /^-(desc|asc)/i) {
575       die "hash passed to _order_by must have exactly one key (-desc or -asc)";
576     }
577     my $dir = uc $1;
578     return $self->_order_by_to_dq($val, $dir, $from);
579   } else {
580     die "Can't handle $arg in _order_by_to_dq";
581   }
582   return $dq;
583 }
584
585 sub _table_to_dq {
586   my ($self, $from) = @_;
587   if (ref($from) eq 'ARRAY') {
588     die "Empty FROM list" unless my @f = @$from;
589     my $dq = $self->_table_to_dq(shift @f);
590     while (my $x = shift @f) {
591       $dq = {
592         type => DQ_JOIN,
593         join => [ $dq, $self->_table_to_dq($x) ]
594       };
595     }
596     $dq;
597   } elsif (ref($from) eq 'SCALAR' or (ref($from) eq 'REF')) {
598     $self->_literal_to_dq($$from);
599   } else {
600     $self->_ident_to_dq($from);
601   }
602 }
603
604 # And bindtype
605 sub _bindtype (@) {
606   #my ($self, $col, @vals) = @_;
607
608   #LDNOTE : changed original implementation below because it did not make
609   # sense when bindtype eq 'columns' and @vals > 1.
610 #  return $self->{bindtype} eq 'columns' ? [ $col, @vals ] : @vals;
611
612   # called often - tighten code
613   return $_[0]->bind_meta
614     ? map {[$_[1], $_]} @_[2 .. $#_]
615     : @_[2 .. $#_]
616   ;
617 }
618
619 # Dies if any element of @bind is not in [colname => value] format
620 # if bindtype is 'columns'.
621 sub _assert_bindval_matches_bindtype {
622 #  my ($self, @bind) = @_;
623   my $self = shift;
624   if ($self->bind_meta) {
625     for (@_) {
626       if (!defined $_ || ref($_) ne 'ARRAY' || @$_ != 2) {
627         die "bindtype 'columns' selected, you need to pass: [column_name => bind_value]"
628       }
629     }
630   }
631 }
632
633 # Fix SQL case, if so requested
634 sub _sqlcase {
635   return $_[0]->lower_case ? $_[1] : uc($_[1]);
636 }
637
638 1;