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