08acbb2e5df5e21f25de2394eeaac23c1892f59f
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
1 package DBIx::Class::SQLMaker;
2
3 =head1 NAME
4
5 DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
6
7 =head1 DESCRIPTION
8
9 This module is a subclass of L<SQL::Abstract> and includes a number of
10 DBIC-specific workarounds, not yet suitable for inclusion into the
11 L<SQL::Abstract> core. It also provides all (and more than) the functionality
12 of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
13 more info.
14
15 Currently the enhancements to L<SQL::Abstract> are:
16
17 =over
18
19 =item * Support for C<JOIN> statements (via extended C<table/from> support)
20
21 =item * Support of functions in C<SELECT> lists
22
23 =item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
24
25 =item * Support of C<...FOR UPDATE> type of select statement modifiers
26
27 =item * The -ident operator
28
29 =item * The -value operator
30
31 =back
32
33 =cut
34
35 use base qw/
36   DBIx::Class::SQLMaker::LimitDialects
37   SQL::Abstract
38   Class::Accessor::Grouped
39 /;
40 use mro 'c3';
41 use strict;
42 use warnings;
43 use Sub::Name 'subname';
44 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
45 use namespace::clean;
46
47 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
48
49 # for when I need a normalized l/r pair
50 sub _quote_chars {
51   map
52     { defined $_ ? $_ : '' }
53     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
54   ;
55 }
56
57 BEGIN {
58   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
59   # that use Carp::Clan instead of plain Carp (they do not like each other much)
60   no warnings qw/redefine/;
61
62   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
63     my($func) = (caller(1))[3];
64     carp "[$func] Warning: ", @_;
65   };
66
67   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
68     my($func) = (caller(1))[3];
69     croak "[$func] Fatal: ", @_;
70   };
71
72   # Current SQLA pollutes its namespace - clean for the time being
73   namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
74 }
75
76 # the "oh noes offset/top without limit" constant
77 # limited to 32 bits for sanity (and consistency,
78 # since it is ultimately handed to sprintf %u)
79 # Implemented as a method, since ::Storage::DBI also
80 # refers to it (i.e. for the case of software_limit or
81 # as the value to abuse with MSSQL ordered subqueries)
82 sub __max_int { 0xFFFFFFFF };
83
84 sub new {
85   my $self = shift->next::method(@_);
86
87   # use the same coderefs, they are prepared to handle both cases
88   my @extra_dbic_syntax = (
89     { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
90     { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
91   );
92
93   push @{$self->{special_ops}}, @extra_dbic_syntax;
94   push @{$self->{unary_ops}}, @extra_dbic_syntax;
95
96   $self;
97 }
98
99 sub _where_op_IDENT {
100   my $self = shift;
101   my ($op, $rhs) = splice @_, -2;
102   if (ref $rhs) {
103     croak "-$op takes a single scalar argument (a quotable identifier)";
104   }
105
106   # in case we are called as a top level special op (no '=')
107   my $lhs = shift;
108
109   $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
110
111   return $lhs
112     ? "$lhs = $rhs"
113     : $rhs
114   ;
115 }
116
117 sub _where_op_VALUE {
118   my $self = shift;
119   my ($op, $rhs) = splice @_, -2;
120
121   # in case we are called as a top level special op (no '=')
122   my $lhs = shift;
123
124   my @bind = [
125     ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"),
126     $rhs
127   ];
128
129   return $lhs
130     ? (
131       $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
132       @bind
133     )
134     : (
135       $self->_convert('?'),
136       @bind,
137     )
138   ;
139 }
140
141 my $callsites_warned;
142 sub _where_op_NEST {
143   # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
144   my $callsite = do {
145     my $w;
146     local $SIG{__WARN__} = sub { $w = shift };
147     carp;
148     $w
149   };
150
151   carp ("-nest in search conditions is deprecated, you most probably wanted:\n"
152       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
153   ) unless $callsites_warned->{$callsite}++;
154
155   shift->next::method(@_);
156 }
157
158 # Handle limit-dialect selection
159 sub select {
160   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
161
162
163   $fields = $self->_recurse_fields($fields);
164
165   if (defined $offset) {
166     croak ('A supplied offset must be a non-negative integer')
167       if ( $offset =~ /\D/ or $offset < 0 );
168   }
169   $offset ||= 0;
170
171   if (defined $limit) {
172     croak ('A supplied limit must be a positive integer')
173       if ( $limit =~ /\D/ or $limit <= 0 );
174   }
175   elsif ($offset) {
176     $limit = $self->__max_int;
177   }
178
179
180   my ($sql, @bind);
181   if ($limit) {
182     # this is legacy code-flow from SQLA::Limit, it is not set in stone
183
184     ($sql, @bind) = $self->next::method ($table, $fields, $where);
185
186     my $limiter =
187       $self->can ('emulate_limit')  # also backcompat hook from SQLA::Limit
188         ||
189       do {
190         my $dialect = $self->limit_dialect
191           or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
192         $self->can ("_$dialect")
193           or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
194       }
195     ;
196
197     $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
198   }
199   else {
200     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
201   }
202
203   push @{$self->{where_bind}}, @bind;
204
205 # this *must* be called, otherwise extra binds will remain in the sql-maker
206   my @all_bind = $self->_assemble_binds;
207
208   $sql .= $self->_lock_select ($rs_attrs->{for})
209     if $rs_attrs->{for};
210
211   return wantarray ? ($sql, @all_bind) : $sql;
212 }
213
214 sub _assemble_binds {
215   my $self = shift;
216   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
217 }
218
219 my $for_syntax = {
220   update => 'FOR UPDATE',
221   shared => 'FOR SHARE',
222 };
223 sub _lock_select {
224   my ($self, $type) = @_;
225   my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
226   return " $sql";
227 }
228
229 # Handle default inserts
230 sub insert {
231 # optimized due to hotttnesss
232 #  my ($self, $table, $data, $options) = @_;
233
234   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
235   # which is sadly understood only by MySQL. Change default behavior here,
236   # until SQLA2 comes with proper dialect support
237   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
238     my @bind;
239     my $sql = sprintf(
240       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
241     );
242
243     if ( ($_[3]||{})->{returning} ) {
244       my $s;
245       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
246       $sql .= $s;
247     }
248
249     return ($sql, @bind);
250   }
251
252   next::method(@_);
253 }
254
255 sub _recurse_fields {
256   my ($self, $fields) = @_;
257   my $ref = ref $fields;
258   return $self->_quote($fields) unless $ref;
259   return $$fields if $ref eq 'SCALAR';
260
261   if ($ref eq 'ARRAY') {
262     return join(', ', map { $self->_recurse_fields($_) } @$fields);
263   }
264   elsif ($ref eq 'HASH') {
265     my %hash = %$fields;  # shallow copy
266
267     my $as = delete $hash{-as};   # if supplied
268
269     my ($func, $args, @toomany) = %hash;
270
271     # there should be only one pair
272     if (@toomany) {
273       croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
274     }
275
276     if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
277       croak (
278         'The select => { distinct => ... } syntax is not supported for multiple columns.'
279        .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
280        .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
281       );
282     }
283
284     my $select = sprintf ('%s( %s )%s',
285       $self->_sqlcase($func),
286       $self->_recurse_fields($args),
287       $as
288         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
289         : ''
290     );
291
292     return $select;
293   }
294   # Is the second check absolutely necessary?
295   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
296     push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
297     return $$fields->[0];
298   }
299   else {
300     croak($ref . qq{ unexpected in _recurse_fields()})
301   }
302 }
303
304
305 # this used to be a part of _order_by but is broken out for clarity.
306 # What we have been doing forever is hijacking the $order arg of
307 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
308 # then pretty much the entire resultset attr-hash, as more and more
309 # things in the SQLA space need to have mopre info about the $rs they
310 # create SQL for. The alternative would be to keep expanding the
311 # signature of _select with more and more positional parameters, which
312 # is just gross. All hail SQLA2!
313 sub _parse_rs_attrs {
314   my ($self, $arg) = @_;
315
316   my $sql = '';
317
318   if ($arg->{group_by}) {
319     # horible horrible, waiting for refactor
320     local $self->{select_bind};
321     if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
322       $sql .= $self->_sqlcase(' group by ') . $g;
323       push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
324     }
325   }
326
327   if (defined $arg->{having}) {
328     my ($frag, @bind) = $self->_recurse_where($arg->{having});
329     push(@{$self->{having_bind}}, @bind);
330     $sql .= $self->_sqlcase(' having ') . $frag;
331   }
332
333   if (defined $arg->{order_by}) {
334     $sql .= $self->_order_by ($arg->{order_by});
335   }
336
337   return $sql;
338 }
339
340 sub _order_by {
341   my ($self, $arg) = @_;
342
343   # check that we are not called in legacy mode (order_by as 4th argument)
344   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
345     return $self->_parse_rs_attrs ($arg);
346   }
347   else {
348     my ($sql, @bind) = $self->next::method($arg);
349     push @{$self->{order_bind}}, @bind;
350     return $sql;
351   }
352 }
353
354 sub _table {
355 # optimized due to hotttnesss
356 #  my ($self, $from) = @_;
357   if (my $ref = ref $_[1] ) {
358     if ($ref eq 'ARRAY') {
359       return $_[0]->_recurse_from(@{$_[1]});
360     }
361     elsif ($ref eq 'HASH') {
362       return $_[0]->_recurse_from($_[1]);
363     }
364   }
365
366   return $_[0]->next::method ($_[1]);
367 }
368
369 sub _generate_join_clause {
370     my ($self, $join_type) = @_;
371
372     return sprintf ('%s JOIN ',
373       $join_type ?  ' ' . $self->_sqlcase($join_type) : ''
374     );
375 }
376
377 sub _recurse_from {
378   my ($self, $from, @join) = @_;
379   my @sqlf;
380   push @sqlf, $self->_from_chunk_to_sql($from);
381
382   for (@join) {
383     my ($to, $on) = @$_;
384
385     # check whether a join type exists
386     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
387     my $join_type;
388     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
389       $join_type = $to_jt->{-join_type};
390       $join_type =~ s/^\s+ | \s+$//xg;
391     }
392
393     $join_type = $self->{_default_jointype} if not defined $join_type;
394
395     push @sqlf, $self->_generate_join_clause( $join_type );
396
397     if (ref $to eq 'ARRAY') {
398       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
399     } else {
400       push(@sqlf, $self->_from_chunk_to_sql($to));
401     }
402     push(@sqlf, ' ON ', $self->_join_condition($on));
403   }
404   return join('', @sqlf);
405 }
406
407 sub _from_chunk_to_sql {
408   my ($self, $fromspec) = @_;
409
410   return join (' ', $self->_SWITCH_refkind($fromspec, {
411     SCALARREF => sub {
412       $$fromspec;
413     },
414     ARRAYREFREF => sub {
415       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
416       $$fromspec->[0];
417     },
418     HASHREF => sub {
419       my ($as, $table, $toomuch) = ( map
420         { $_ => $fromspec->{$_} }
421         ( grep { $_ !~ /^\-/ } keys %$fromspec )
422       );
423
424       croak "Only one table/as pair expected in from-spec but an exra '$toomuch' key present"
425         if defined $toomuch;
426
427       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
428     },
429     SCALAR => sub {
430       $self->_quote($fromspec);
431     },
432   }));
433 }
434
435 sub _join_condition {
436   my ($self, $cond) = @_;
437
438   if (ref $cond eq 'HASH') {
439     my %j;
440     for (keys %$cond) {
441       my $v = $cond->{$_};
442       if (ref $v) {
443         croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
444             if ref($v) ne 'SCALAR';
445         $j{$_} = $v;
446       }
447       else {
448         my $x = '= '.$self->_quote($v); $j{$_} = \$x;
449       }
450     };
451     return scalar($self->_recurse_where(\%j));
452   } elsif (ref $cond eq 'ARRAY') {
453     return join(' OR ', map { $self->_join_condition($_) } @$cond);
454   } else {
455     croak "Can't handle this yet!";
456   }
457 }
458
459 1;
460
461 =head1 AUTHORS
462
463 See L<DBIx::Class/CONTRIBUTORS>.
464
465 =head1 LICENSE
466
467 You may distribute this code under the same terms as Perl itself.
468
469 =cut