all tests pass
[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 DBIx::Class::Exception;
44 use namespace::clean;
45
46 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect storage/);
47
48 # for when I need a normalized l/r pair
49 sub _quote_chars {
50   map
51     { defined $_ ? $_ : '' }
52     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
53   ;
54 }
55
56 # FIXME when we bring in the storage weaklink, check its schema
57 # weaklink and channel through $schema->throw_exception
58 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
59
60 BEGIN {
61   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
62   # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
63   no warnings qw/redefine/;
64
65   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
66     my($func) = (caller(1))[3];
67     carp "[$func] Warning: ", @_;
68   };
69
70   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
71     my($func) = (caller(1))[3];
72     __PACKAGE__->throw_exception("[$func] Fatal: " . join ('',  @_));
73   };
74
75   # Current SQLA pollutes its namespace - clean for the time being
76   namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
77 }
78
79 # the "oh noes offset/top without limit" constant
80 # limited to 31 bits for sanity (and consistency,
81 # since it may be handed to the like of sprintf %u)
82 #
83 # Also *some* builds of SQLite fail the test
84 #   some_column BETWEEN ? AND ?: 1, 4294967295
85 # with the proper integer bind attrs
86 #
87 # Implemented as a method, since ::Storage::DBI also
88 # refers to it (i.e. for the case of software_limit or
89 # as the value to abuse with MSSQL ordered subqueries)
90 sub __max_int () { 0x7FFFFFFF };
91
92 # poor man's de-qualifier
93 sub _quote {
94   return undef if not defined $_[1];
95
96   my ($col) = ( $_[0]{_dequalify_idents} and ! ref $_[1] )
97     ? $_[1] =~ / ([^\.]+) $ /x
98     : $_[1]
99   ;
100
101   if (
102     $_[0]->{FROM}
103       and
104     $_[0]->storage
105       and
106     my $alias = ($_[0]->storage->_resolve_column_info($_[0]->{FROM}, [$col]) || {})->{$col}{sql_alias}
107   ) {
108     $col =~ s/[^\.]+$/$alias/;
109   }
110
111   $_[0]->next::method( $col );
112 }
113
114 sub _where_op_NEST {
115   carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
116       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
117   );
118
119   shift->next::method(@_);
120 }
121
122 # Handle limit-dialect selection
123 sub select {
124   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
125
126
127   local $self->{FROM} = $table;
128   $fields = $self->_recurse_fields($fields);
129
130   if (defined $offset) {
131     $self->throw_exception('A supplied offset must be a non-negative integer')
132       if ( $offset =~ /\D/ or $offset < 0 );
133   }
134   $offset ||= 0;
135
136   if (defined $limit) {
137     $self->throw_exception('A supplied limit must be a positive integer')
138       if ( $limit =~ /\D/ or $limit <= 0 );
139   }
140   elsif ($offset) {
141     $limit = $self->__max_int;
142   }
143
144
145   my ($sql, @bind);
146   if ($limit) {
147     # this is legacy code-flow from SQLA::Limit, it is not set in stone
148
149     ($sql, @bind) = $self->next::method ($table, $fields, $where);
150
151     my $limiter =
152       $self->can ('emulate_limit')  # also backcompat hook from SQLA::Limit
153         ||
154       do {
155         my $dialect = $self->limit_dialect
156           or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
157         $self->can ("_$dialect")
158           or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
159       }
160     ;
161
162     $sql = $self->$limiter (
163       $sql,
164       { %{$rs_attrs||{}}, _selector_sql => $fields },
165       $limit,
166       $offset
167     );
168   }
169   else {
170     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
171   }
172
173   push @{$self->{where_bind}}, @bind;
174
175 # this *must* be called, otherwise extra binds will remain in the sql-maker
176   my @all_bind = $self->_assemble_binds;
177
178   $sql .= $self->_lock_select ($rs_attrs->{for})
179     if $rs_attrs->{for};
180
181   return wantarray ? ($sql, @all_bind) : $sql;
182 }
183
184 sub _assemble_binds {
185   my $self = shift;
186   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
187 }
188
189 my $for_syntax = {
190   update => 'FOR UPDATE',
191   shared => 'FOR SHARE',
192 };
193 sub _lock_select {
194   my ($self, $type) = @_;
195
196   my $sql;
197   if (ref($type) eq 'SCALAR') {
198     $sql = "FOR $$type";
199   }
200   else {
201     $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
202   }
203
204   return " $sql";
205 }
206
207 # Handle default inserts
208 sub insert {
209 # optimized due to hotttnesss
210 #  my ($self, $table, $data, $options) = @_;
211
212   local $_[0]->{FROM} = $_[1];
213   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
214   # which is sadly understood only by MySQL. Change default behavior here,
215   # until SQLA2 comes with proper dialect support
216   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
217     my @bind;
218     my $sql = sprintf(
219       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
220     );
221
222     if ( ($_[3]||{})->{returning} ) {
223       my $s;
224       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
225       $sql .= $s;
226     }
227
228     return ($sql, @bind);
229   }
230
231   next::method(@_);
232 }
233
234 sub update {
235   local $_[0]->{FROM} = $_[1];
236
237   shift->next::method(@_);
238 }
239
240 sub delete {
241   local $_[0]->{FROM} = $_[1];
242
243   shift->next::method(@_);
244 }
245
246 sub _recurse_fields {
247   my ($self, $fields) = @_;
248   my $ref = ref $fields;
249   return $self->_quote($fields) unless $ref;
250   return $$fields if $ref eq 'SCALAR';
251
252   if ($ref eq 'ARRAY') {
253     return join(', ', map { $self->_recurse_fields($_) } @$fields);
254   }
255   elsif ($ref eq 'HASH') {
256     my %hash = %$fields;  # shallow copy
257
258     my $as = delete $hash{-as};   # if supplied
259
260     my ($func, $args, @toomany) = %hash;
261
262     # there should be only one pair
263     if (@toomany) {
264       $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
265     }
266
267     if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
268       $self->throw_exception (
269         'The select => { distinct => ... } syntax is not supported for multiple columns.'
270        .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
271        .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
272       );
273     }
274
275     my $select = sprintf ('%s( %s )%s',
276       $self->_sqlcase($func),
277       $self->_recurse_fields($args),
278       $as
279         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
280         : ''
281     );
282
283     return $select;
284   }
285   # Is the second check absolutely necessary?
286   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
287     push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
288     return $$fields->[0];
289   }
290   else {
291     $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
292   }
293 }
294
295
296 # this used to be a part of _order_by but is broken out for clarity.
297 # What we have been doing forever is hijacking the $order arg of
298 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
299 # then pretty much the entire resultset attr-hash, as more and more
300 # things in the SQLA space need to have mopre info about the $rs they
301 # create SQL for. The alternative would be to keep expanding the
302 # signature of _select with more and more positional parameters, which
303 # is just gross. All hail SQLA2!
304 sub _parse_rs_attrs {
305   my ($self, $arg) = @_;
306
307   my $sql = '';
308
309   if ($arg->{group_by}) {
310     # horible horrible, waiting for refactor
311     local $self->{select_bind};
312     if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
313       $sql .= $self->_sqlcase(' group by ') . $g;
314       push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
315     }
316   }
317
318   if (defined $arg->{having}) {
319     my ($frag, @bind) = $self->_recurse_where($arg->{having});
320     push(@{$self->{having_bind}}, @bind);
321     $sql .= $self->_sqlcase(' having ') . $frag;
322   }
323
324   if (defined $arg->{order_by}) {
325     $sql .= $self->_order_by ($arg->{order_by});
326   }
327
328   return $sql;
329 }
330
331 sub _order_by {
332   my ($self, $arg) = @_;
333
334   # check that we are not called in legacy mode (order_by as 4th argument)
335   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
336     return $self->_parse_rs_attrs ($arg);
337   }
338   else {
339     my ($sql, @bind) = $self->next::method($arg);
340     push @{$self->{order_bind}}, @bind;
341     return $sql;
342   }
343 }
344
345 sub _table {
346 # optimized due to hotttnesss
347 #  my ($self, $from) = @_;
348   if (my $ref = ref $_[1] ) {
349     if ($ref eq 'ARRAY') {
350       return $_[0]->_recurse_from(@{$_[1]});
351     }
352     elsif ($ref eq 'HASH') {
353       return $_[0]->_recurse_from($_[1]);
354     }
355     elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
356       my ($sql, @bind) = @{ ${$_[1]} };
357       push @{$_[0]->{from_bind}}, @bind;
358       return $sql
359     }
360   }
361   return $_[0]->next::method ($_[1]);
362 }
363
364 sub _generate_join_clause {
365     my ($self, $join_type) = @_;
366
367     $join_type = $self->{_default_jointype}
368       if ! defined $join_type;
369
370     return sprintf ('%s JOIN ',
371       $join_type ?  $self->_sqlcase($join_type) : ''
372     );
373 }
374
375 sub _recurse_from {
376   my $self = shift;
377
378   return join (' ', $self->_gen_from_blocks(@_) );
379 }
380
381 sub _gen_from_blocks {
382   my ($self, $from, @joins) = @_;
383
384   my @fchunks = $self->_from_chunk_to_sql($from);
385
386   for (@joins) {
387     my ($to, $on) = @$_;
388
389     # check whether a join type exists
390     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
391     my $join_type;
392     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
393       $join_type = $to_jt->{-join_type};
394       $join_type =~ s/^\s+ | \s+$//xg;
395     }
396
397     my @j = $self->_generate_join_clause( $join_type );
398
399     if (ref $to eq 'ARRAY') {
400       push(@j, '(', $self->_recurse_from(@$to), ')');
401     }
402     else {
403       push(@j, $self->_from_chunk_to_sql($to));
404     }
405
406     my ($sql, @bind) = $self->_join_condition($on);
407     push(@j, ' ON ', $sql);
408     push @{$self->{from_bind}}, @bind;
409
410     push @fchunks, join '', @j;
411   }
412
413   return @fchunks;
414 }
415
416 sub _from_chunk_to_sql {
417   my ($self, $fromspec) = @_;
418
419   return join (' ', do {
420     if (! ref $fromspec) {
421       $self->_quote($fromspec);
422     }
423     elsif (ref $fromspec eq 'SCALAR') {
424       $$fromspec;
425     }
426     elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
427       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
428       $$fromspec->[0];
429     }
430     elsif (ref $fromspec eq 'HASH') {
431       my ($as, $table, $toomuch) = ( map
432         { $_ => $fromspec->{$_} }
433         ( grep { $_ !~ /^\-/ } keys %$fromspec )
434       );
435
436       $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
437         if defined $toomuch;
438
439       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
440     }
441     else {
442       $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
443     }
444   });
445 }
446
447 sub _join_condition {
448   my ($self, $cond) = @_;
449
450   # Backcompat for the old days when a plain hashref
451   # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
452   # Once things settle we should start warning here so that
453   # folks unroll their hacks
454   if (
455     ref $cond eq 'HASH'
456       and
457     keys %$cond == 1
458       and
459     (keys %$cond)[0] =~ /\./
460       and
461     ! ref ( (values %$cond)[0] )
462   ) {
463     $cond = { keys %$cond => { -ident => values %$cond } }
464   }
465   elsif ( ref $cond eq 'ARRAY' ) {
466     # do our own ORing so that the hashref-shim above is invoked
467     my @parts;
468     my @binds;
469     foreach my $c (@$cond) {
470       my ($sql, @bind) = $self->_join_condition($c);
471       push @binds, @bind;
472       push @parts, $sql;
473     }
474     return join(' OR ', @parts), @binds;
475   }
476
477   return $self->_recurse_where($cond);
478 }
479
480 1;
481
482 =head1 AUTHORS
483
484 See L<DBIx::Class/CONTRIBUTORS>.
485
486 =head1 LICENSE
487
488 You may distribute this code under the same terms as Perl itself.
489
490 =cut