Add SQLMaker methods for matching and unquoting quoted identifiers
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
1 package DBIx::Class::SQLMaker;
2
3 use strict;
4 use warnings;
5
6 =head1 NAME
7
8 DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
9
10 =head1 DESCRIPTION
11
12 This module is a subclass of L<SQL::Abstract> and includes a number of
13 DBIC-specific workarounds, not yet suitable for inclusion into the
14 L<SQL::Abstract> core. It also provides all (and more than) the functionality
15 of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
16 more info.
17
18 Currently the enhancements to L<SQL::Abstract> are:
19
20 =over
21
22 =item * Support for C<JOIN> statements (via extended C<table/from> support)
23
24 =item * Support of functions in C<SELECT> lists
25
26 =item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
27
28 =item * Support of C<...FOR UPDATE> type of select statement modifiers
29
30 =back
31
32 =cut
33
34 use base qw/
35   DBIx::Class::SQLMaker::LimitDialects
36   SQL::Abstract
37   DBIx::Class
38 /;
39 use mro 'c3';
40
41 use Sub::Name 'subname';
42 use DBIx::Class::Carp;
43 use namespace::clean;
44
45 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
46
47 sub _quoting_enabled {
48   ( defined $_[0]->{quote_char} and length $_[0]->{quote_char} ) ? 1 : 0
49 }
50
51 # for when I need a normalized l/r pair
52 sub _quote_chars {
53
54   # in case we are called in the old !!$sm->_quote_chars fashion
55   return () if !wantarray and ( ! defined $_[0]->{quote_char} or ! length $_[0]->{quote_char} );
56
57   map
58     { defined $_ ? $_ : '' }
59     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
60   ;
61 }
62
63 sub _escape_char {
64   $_[0]->{escape_char} || ($_[0]->_quote_chars)[1] || '';
65 }
66
67 sub _unquote {
68   my ($self, $value) = @_;
69
70   return $value unless defined $value;
71
72   my ($l, $r, $e) = map { quotemeta $_ } $self->_quote_chars, $self->_escape_char;
73
74   # no quoting, all bets are off
75   return $value unless length $e;
76
77   my $re = $self->_quoted_ident_re($l, $r, $e);
78
79   if ($value =~ /\A$re\z/) {
80     $value =~ s/\A$l//;
81     $value =~ s/$r\z//;
82     $value =~ s/( $e [$e$r] )/substr($1, 1)/gex;
83     return $value;
84   }
85   else {
86     # not a quoted value, assume it's an identifier
87     return $value;
88   }
89 }
90
91 sub _quoted_ident_re {
92   my $self = shift;
93   my ($l, $r, $e) = @_ ? @_ : map { quotemeta $_ } $self->_quote_chars, $self->_escape_char;
94   return qr/ $l (?: [^$e$r] | $e [$e$r] )+ $r /x;
95 }
96
97 # FIXME when we bring in the storage weaklink, check its schema
98 # weaklink and channel through $schema->throw_exception
99 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
100
101 BEGIN {
102   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
103   # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
104   no warnings qw/redefine/;
105
106   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
107     my($func) = (caller(1))[3];
108     carp "[$func] Warning: ", @_;
109   };
110
111   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
112     my($func) = (caller(1))[3];
113     __PACKAGE__->throw_exception("[$func] Fatal: " . join ('',  @_));
114   };
115 }
116
117 # the "oh noes offset/top without limit" constant
118 # limited to 31 bits for sanity (and consistency,
119 # since it may be handed to the like of sprintf %u)
120 #
121 # Also *some* builds of SQLite fail the test
122 #   some_column BETWEEN ? AND ?: 1, 4294967295
123 # with the proper integer bind attrs
124 #
125 # Implemented as a method, since ::Storage::DBI also
126 # refers to it (i.e. for the case of software_limit or
127 # as the value to abuse with MSSQL ordered subqueries)
128 sub __max_int () { 0x7FFFFFFF };
129
130 # we ne longer need to check this - DBIC has ways of dealing with it
131 # specifically ::Storage::DBI::_resolve_bindattrs()
132 sub _assert_bindval_matches_bindtype () { 1 };
133
134 # poor man's de-qualifier
135 sub _quote {
136   $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
137     ? $_[1] =~ / ([^\.]+) $ /x
138     : $_[1]
139   );
140 }
141
142 sub _where_op_NEST {
143   carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
144       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
145   );
146
147   shift->next::method(@_);
148 }
149
150 # Handle limit-dialect selection
151 sub select {
152   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
153
154
155   ($fields, @{$self->{select_bind}}) = $self->_recurse_fields($fields);
156
157   if (defined $offset) {
158     $self->throw_exception('A supplied offset must be a non-negative integer')
159       if ( $offset =~ /\D/ or $offset < 0 );
160   }
161   $offset ||= 0;
162
163   if (defined $limit) {
164     $self->throw_exception('A supplied limit must be a positive integer')
165       if ( $limit =~ /\D/ or $limit <= 0 );
166   }
167   elsif ($offset) {
168     $limit = $self->__max_int;
169   }
170
171
172   my ($sql, @bind);
173   if ($limit) {
174     # this is legacy code-flow from SQLA::Limit, it is not set in stone
175
176     ($sql, @bind) = $self->next::method ($table, $fields, $where);
177
178     my $limiter;
179
180     if( $limiter = $self->can ('emulate_limit') ) {
181       carp_unique(
182         'Support for the legacy emulate_limit() mechanism inherited from '
183       . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
184       . 'DBIC transitions to Data::Query. If your code uses this type of '
185       . 'limit specification please file an RT and provide the source of '
186       . 'your emulate_limit() implementation, so an acceptable upgrade-path '
187       . 'can be devised'
188       );
189     }
190     else {
191       my $dialect = $self->limit_dialect
192         or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
193
194       $limiter = $self->can ("_$dialect")
195         or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
196     }
197
198     $sql = $self->$limiter (
199       $sql,
200       { %{$rs_attrs||{}}, _selector_sql => $fields },
201       $limit,
202       $offset
203     );
204   }
205   else {
206     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
207   }
208
209   push @{$self->{where_bind}}, @bind;
210
211 # this *must* be called, otherwise extra binds will remain in the sql-maker
212   my @all_bind = $self->_assemble_binds;
213
214   $sql .= $self->_lock_select ($rs_attrs->{for})
215     if $rs_attrs->{for};
216
217   return wantarray ? ($sql, @all_bind) : $sql;
218 }
219
220 sub _assemble_binds {
221   my $self = shift;
222   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
223 }
224
225 my $for_syntax = {
226   update => 'FOR UPDATE',
227   shared => 'FOR SHARE',
228 };
229 sub _lock_select {
230   my ($self, $type) = @_;
231
232   my $sql;
233   if (ref($type) eq 'SCALAR') {
234     $sql = "FOR $$type";
235   }
236   else {
237     $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
238   }
239
240   return " $sql";
241 }
242
243 # Handle default inserts
244 sub insert {
245 # optimized due to hotttnesss
246 #  my ($self, $table, $data, $options) = @_;
247
248   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
249   # which is sadly understood only by MySQL. Change default behavior here,
250   # until SQLA2 comes with proper dialect support
251   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
252     my @bind;
253     my $sql = sprintf(
254       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
255     );
256
257     if ( ($_[3]||{})->{returning} ) {
258       my $s;
259       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
260       $sql .= $s;
261     }
262
263     return ($sql, @bind);
264   }
265
266   next::method(@_);
267 }
268
269 sub _recurse_fields {
270   my ($self, $fields) = @_;
271   my $ref = ref $fields;
272   return $self->_quote($fields) unless $ref;
273   return $$fields if $ref eq 'SCALAR';
274
275   if ($ref eq 'ARRAY') {
276     my (@select, @bind);
277     for my $field (@$fields) {
278       my ($select, @new_bind) = $self->_recurse_fields($field);
279       push @select, $select;
280       push @bind, @new_bind;
281     }
282     return (join(', ', @select), @bind);
283   }
284   elsif ($ref eq 'HASH') {
285     my %hash = %$fields;  # shallow copy
286
287     my $as = delete $hash{-as};   # if supplied
288
289     my ($func, $rhs, @toomany) = %hash;
290
291     # there should be only one pair
292     if (@toomany) {
293       $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
294     }
295
296     if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
297       $self->throw_exception (
298         'The select => { distinct => ... } syntax is not supported for multiple columns.'
299        .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
300        .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
301       );
302     }
303
304     my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
305     my $select = sprintf ('%s( %s )%s',
306       $self->_sqlcase($func),
307       $rhs_sql,
308       $as
309         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
310         : ''
311     );
312
313     return ($select, @rhs_bind);
314   }
315   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
316     return @{$$fields};
317   }
318   else {
319     $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
320   }
321 }
322
323
324 # this used to be a part of _order_by but is broken out for clarity.
325 # What we have been doing forever is hijacking the $order arg of
326 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
327 # then pretty much the entire resultset attr-hash, as more and more
328 # things in the SQLA space need to have more info about the $rs they
329 # create SQL for. The alternative would be to keep expanding the
330 # signature of _select with more and more positional parameters, which
331 # is just gross. All hail SQLA2!
332 sub _parse_rs_attrs {
333   my ($self, $arg) = @_;
334
335   my $sql = '';
336
337   if ($arg->{group_by}) {
338     if ( my ($group_sql, @group_bind) = $self->_recurse_fields($arg->{group_by}) ) {
339       $sql .= $self->_sqlcase(' group by ') . $group_sql;
340       push @{$self->{group_bind}}, @group_bind;
341     }
342   }
343
344   if (defined $arg->{having}) {
345     my ($frag, @bind) = $self->_recurse_where($arg->{having});
346     push(@{$self->{having_bind}}, @bind);
347     $sql .= $self->_sqlcase(' having ') . $frag;
348   }
349
350   if (defined $arg->{order_by}) {
351     $sql .= $self->_order_by ($arg->{order_by});
352   }
353
354   return $sql;
355 }
356
357 sub _order_by {
358   my ($self, $arg) = @_;
359
360   # check that we are not called in legacy mode (order_by as 4th argument)
361   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
362     return $self->_parse_rs_attrs ($arg);
363   }
364   else {
365     my ($sql, @bind) = $self->next::method($arg);
366     push @{$self->{order_bind}}, @bind;
367     return $sql;
368   }
369 }
370
371 sub _split_order_chunk {
372   my ($self, $chunk) = @_;
373
374   # strip off sort modifiers, but always succeed, so $1 gets reset
375   $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
376
377   return (
378     $chunk,
379     ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
380   );
381 }
382
383 sub _table {
384 # optimized due to hotttnesss
385 #  my ($self, $from) = @_;
386   if (my $ref = ref $_[1] ) {
387     if ($ref eq 'ARRAY') {
388       return $_[0]->_recurse_from(@{$_[1]});
389     }
390     elsif ($ref eq 'HASH') {
391       return $_[0]->_recurse_from($_[1]);
392     }
393     elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
394       my ($sql, @bind) = @{ ${$_[1]} };
395       push @{$_[0]->{from_bind}}, @bind;
396       return $sql
397     }
398   }
399   return $_[0]->next::method ($_[1]);
400 }
401
402 sub _generate_join_clause {
403     my ($self, $join_type) = @_;
404
405     $join_type = $self->{_default_jointype}
406       if ! defined $join_type;
407
408     return sprintf ('%s JOIN ',
409       $join_type ?  $self->_sqlcase($join_type) : ''
410     );
411 }
412
413 sub _recurse_from {
414   my $self = shift;
415   return join (' ', $self->_gen_from_blocks(@_) );
416 }
417
418 sub _gen_from_blocks {
419   my ($self, $from, @joins) = @_;
420
421   my @fchunks = $self->_from_chunk_to_sql($from);
422
423   for (@joins) {
424     my ($to, $on) = @$_;
425
426     # check whether a join type exists
427     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
428     my $join_type;
429     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
430       $join_type = $to_jt->{-join_type};
431       $join_type =~ s/^\s+ | \s+$//xg;
432     }
433
434     my @j = $self->_generate_join_clause( $join_type );
435
436     if (ref $to eq 'ARRAY') {
437       push(@j, '(', $self->_recurse_from(@$to), ')');
438     }
439     else {
440       push(@j, $self->_from_chunk_to_sql($to));
441     }
442
443     my ($sql, @bind) = $self->_join_condition($on);
444     push(@j, ' ON ', $sql);
445     push @{$self->{from_bind}}, @bind;
446
447     push @fchunks, join '', @j;
448   }
449
450   return @fchunks;
451 }
452
453 sub _from_chunk_to_sql {
454   my ($self, $fromspec) = @_;
455
456   return join (' ', do {
457     if (! ref $fromspec) {
458       $self->_quote($fromspec);
459     }
460     elsif (ref $fromspec eq 'SCALAR') {
461       $$fromspec;
462     }
463     elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
464       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
465       $$fromspec->[0];
466     }
467     elsif (ref $fromspec eq 'HASH') {
468       my ($as, $table, $toomuch) = ( map
469         { $_ => $fromspec->{$_} }
470         ( grep { $_ !~ /^\-/ } keys %$fromspec )
471       );
472
473       $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
474         if defined $toomuch;
475
476       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
477     }
478     else {
479       $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
480     }
481   });
482 }
483
484 sub _join_condition {
485   my ($self, $cond) = @_;
486
487   # Backcompat for the old days when a plain hashref
488   # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
489   # Once things settle we should start warning here so that
490   # folks unroll their hacks
491   if (
492     ref $cond eq 'HASH'
493       and
494     keys %$cond == 1
495       and
496     (keys %$cond)[0] =~ /\./
497       and
498     ! ref ( (values %$cond)[0] )
499   ) {
500     $cond = { keys %$cond => { -ident => values %$cond } }
501   }
502   elsif ( ref $cond eq 'ARRAY' ) {
503     # do our own ORing so that the hashref-shim above is invoked
504     my @parts;
505     my @binds;
506     foreach my $c (@$cond) {
507       my ($sql, @bind) = $self->_join_condition($c);
508       push @binds, @bind;
509       push @parts, $sql;
510     }
511     return join(' OR ', @parts), @binds;
512   }
513
514   return $self->_recurse_where($cond);
515 }
516
517 # This is hideously ugly, but SQLA does not understand multicol IN expressions
518 # FIXME TEMPORARY - DQ should have native syntax for this
519 # moved here to raise API questions
520 #
521 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
522 sub _where_op_multicolumn_in {
523   my ($self, $lhs, $rhs) = @_;
524
525   if (! ref $lhs or ref $lhs eq 'ARRAY') {
526     my (@sql, @bind);
527     for (ref $lhs ? @$lhs : $lhs) {
528       if (! ref $_) {
529         push @sql, $self->_quote($_);
530       }
531       elsif (ref $_ eq 'SCALAR') {
532         push @sql, $$_;
533       }
534       elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
535         my ($s, @b) = @$$_;
536         push @sql, $s;
537         push @bind, @b;
538       }
539       else {
540         $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
541       }
542     }
543     $lhs = \[ join(', ', @sql), @bind];
544   }
545   elsif (ref $lhs eq 'SCALAR') {
546     $lhs = \[ $$lhs ];
547   }
548   elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
549     # noop
550   }
551   else {
552     $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
553   }
554
555   # is this proper...?
556   $rhs = \[ $self->_recurse_where($rhs) ];
557
558   for ($lhs, $rhs) {
559     $$_->[0] = "( $$_->[0] )"
560       unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
561   }
562
563   \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
564 }
565
566 1;
567
568 =head1 AUTHORS
569
570 See L<DBIx::Class/CONTRIBUTORS>.
571
572 =head1 LICENSE
573
574 You may distribute this code under the same terms as Perl itself.
575
576 =cut