f43aa0b0abb19719d595b8ffcd6c0560ecbbacc3
[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 =back
28
29 =cut
30
31 use base qw/
32   DBIx::Class::SQLMaker::LimitDialects
33   SQL::Abstract
34   Class::Accessor::Grouped
35 /;
36 use mro 'c3';
37 use strict;
38 use warnings;
39 use Sub::Name 'subname';
40 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
41 use namespace::clean;
42
43 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
44
45 # for when I need a normalized l/r pair
46 sub _quote_chars {
47   map
48     { defined $_ ? $_ : '' }
49     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
50   ;
51 }
52
53 BEGIN {
54   # reinstall the carp()/croak() functions imported into SQL::Abstract
55   # as Carp and Carp::Clan do not like each other much
56   no warnings qw/redefine/;
57   no strict qw/refs/;
58   for my $f (qw/carp croak/) {
59
60     my $orig = \&{"SQL::Abstract::$f"};
61     my $clan_import = \&{$f};
62     *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
63       sub {
64         if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) {
65           goto $clan_import;
66         }
67         else {
68           goto $orig;
69         }
70       };
71   }
72 }
73
74 # the "oh noes offset/top without limit" constant
75 # limited to 32 bits for sanity (and consistency,
76 # since it is ultimately handed to sprintf %u)
77 # Implemented as a method, since ::Storage::DBI also
78 # refers to it (i.e. for the case of software_limit or
79 # as the value to abuse with MSSQL ordered subqueries)
80 sub __max_int { 0xFFFFFFFF };
81
82 # Handle limit-dialect selection
83 sub select {
84   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
85
86
87   $fields = $self->_recurse_fields($fields);
88
89   if (defined $offset) {
90     croak ('A supplied offset must be a non-negative integer')
91       if ( $offset =~ /\D/ or $offset < 0 );
92   }
93   $offset ||= 0;
94
95   if (defined $limit) {
96     croak ('A supplied limit must be a positive integer')
97       if ( $limit =~ /\D/ or $limit <= 0 );
98   }
99   elsif ($offset) {
100     $limit = $self->__max_int;
101   }
102
103
104   my ($sql, @bind);
105   if ($limit) {
106     # this is legacy code-flow from SQLA::Limit, it is not set in stone
107
108     ($sql, @bind) = $self->next::method ($table, $fields, $where);
109
110     my $limiter =
111       $self->can ('emulate_limit')  # also backcompat hook from SQLA::Limit
112         ||
113       do {
114         my $dialect = $self->limit_dialect
115           or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
116         $self->can ("_$dialect")
117           or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
118       }
119     ;
120
121     $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
122   }
123   else {
124     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
125   }
126
127   push @{$self->{where_bind}}, @bind;
128
129 # this *must* be called, otherwise extra binds will remain in the sql-maker
130   my @all_bind = $self->_assemble_binds;
131
132   $sql .= $self->_lock_select ($rs_attrs->{for})
133     if $rs_attrs->{for};
134
135   return wantarray ? ($sql, @all_bind) : $sql;
136 }
137
138 sub _assemble_binds {
139   my $self = shift;
140   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
141 }
142
143 my $for_syntax = {
144   update => 'FOR UPDATE',
145   shared => 'FOR SHARE',
146 };
147 sub _lock_select {
148   my ($self, $type) = @_;
149   my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
150   return " $sql";
151 }
152
153 # Handle default inserts
154 sub insert {
155 # optimized due to hotttnesss
156 #  my ($self, $table, $data, $options) = @_;
157
158   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
159   # which is sadly understood only by MySQL. Change default behavior here,
160   # until SQLA2 comes with proper dialect support
161   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
162     my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
163
164     if (my $ret = ($_[3]||{})->{returning} ) {
165       $sql .= $_[0]->_insert_returning ($ret);
166     }
167
168     return $sql;
169   }
170
171   next::method(@_);
172 }
173
174 sub _recurse_fields {
175   my ($self, $fields) = @_;
176   my $ref = ref $fields;
177   return $self->_quote($fields) unless $ref;
178   return $$fields if $ref eq 'SCALAR';
179
180   if ($ref eq 'ARRAY') {
181     return join(', ', map { $self->_recurse_fields($_) } @$fields);
182   }
183   elsif ($ref eq 'HASH') {
184     my %hash = %$fields;  # shallow copy
185
186     my $as = delete $hash{-as};   # if supplied
187
188     my ($func, $args, @toomany) = %hash;
189
190     # there should be only one pair
191     if (@toomany) {
192       croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
193     }
194
195     if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
196       croak (
197         'The select => { distinct => ... } syntax is not supported for multiple columns.'
198        .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
199        .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
200       );
201     }
202
203     my $select = sprintf ('%s( %s )%s',
204       $self->_sqlcase($func),
205       $self->_recurse_fields($args),
206       $as
207         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
208         : ''
209     );
210
211     return $select;
212   }
213   # Is the second check absolutely necessary?
214   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
215     return $self->_fold_sqlbind( $fields );
216   }
217   else {
218     croak($ref . qq{ unexpected in _recurse_fields()})
219   }
220 }
221
222
223 # this used to be a part of _order_by but is broken out for clarity.
224 # What we have been doing forever is hijacking the $order arg of
225 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
226 # then pretty much the entire resultset attr-hash, as more and more
227 # things in the SQLA space need to have mopre info about the $rs they
228 # create SQL for. The alternative would be to keep expanding the
229 # signature of _select with more and more positional parameters, which
230 # is just gross. All hail SQLA2!
231 sub _parse_rs_attrs {
232   my ($self, $arg) = @_;
233
234   my $sql = '';
235
236   if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
237     $sql .= $self->_sqlcase(' group by ') . $g;
238   }
239
240   if (defined $arg->{having}) {
241     my ($frag, @bind) = $self->_recurse_where($arg->{having});
242     push(@{$self->{having_bind}}, @bind);
243     $sql .= $self->_sqlcase(' having ') . $frag;
244   }
245
246   if (defined $arg->{order_by}) {
247     $sql .= $self->_order_by ($arg->{order_by});
248   }
249
250   return $sql;
251 }
252
253 sub _order_by {
254   my ($self, $arg) = @_;
255
256   # check that we are not called in legacy mode (order_by as 4th argument)
257   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
258     return $self->_parse_rs_attrs ($arg);
259   }
260   else {
261     my ($sql, @bind) = $self->next::method($arg);
262     push @{$self->{order_bind}}, @bind;
263     return $sql;
264   }
265 }
266
267 sub _table {
268 # optimized due to hotttnesss
269 #  my ($self, $from) = @_;
270   if (my $ref = ref $_[1] ) {
271     if ($ref eq 'ARRAY') {
272       return $_[0]->_recurse_from(@{$_[1]});
273     }
274     elsif ($ref eq 'HASH') {
275       return $_[0]->_make_as($_[1]);
276     }
277   }
278
279   return $_[0]->next::method ($_[1]);
280 }
281
282 sub _generate_join_clause {
283     my ($self, $join_type) = @_;
284
285     return sprintf ('%s JOIN ',
286       $join_type ?  ' ' . uc($join_type) : ''
287     );
288 }
289
290 sub _recurse_from {
291   my ($self, $from, @join) = @_;
292   my @sqlf;
293   push(@sqlf, $self->_make_as($from));
294   foreach my $j (@join) {
295     my ($to, $on) = @$j;
296
297
298     # check whether a join type exists
299     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
300     my $join_type;
301     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
302       $join_type = $to_jt->{-join_type};
303       $join_type =~ s/^\s+ | \s+$//xg;
304     }
305
306     $join_type = $self->{_default_jointype} if not defined $join_type;
307
308     push @sqlf, $self->_generate_join_clause( $join_type );
309
310     if (ref $to eq 'ARRAY') {
311       push(@sqlf, '(', $self->_recurse_from(@$to), ')');
312     } else {
313       push(@sqlf, $self->_make_as($to));
314     }
315     push(@sqlf, ' ON ', $self->_join_condition($on));
316   }
317   return join('', @sqlf);
318 }
319
320 sub _fold_sqlbind {
321   my ($self, $sqlbind) = @_;
322
323   my @sqlbind = @$$sqlbind; # copy
324   my $sql = shift @sqlbind;
325   push @{$self->{from_bind}}, @sqlbind;
326
327   return $sql;
328 }
329
330 sub _make_as {
331   my ($self, $from) = @_;
332   return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
333                         : ref $_ eq 'REF'    ? $self->_fold_sqlbind($_)
334                         : $self->_quote($_))
335                        } reverse each %{$self->_skip_options($from)});
336 }
337
338 sub _skip_options {
339   my ($self, $hash) = @_;
340   my $clean_hash = {};
341   $clean_hash->{$_} = $hash->{$_}
342     for grep {!/^-/} keys %$hash;
343   return $clean_hash;
344 }
345
346 sub _join_condition {
347   my ($self, $cond) = @_;
348   if (ref $cond eq 'HASH') {
349     my %j;
350     for (keys %$cond) {
351       my $v = $cond->{$_};
352       if (ref $v) {
353         croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
354             if ref($v) ne 'SCALAR';
355         $j{$_} = $v;
356       }
357       else {
358         my $x = '= '.$self->_quote($v); $j{$_} = \$x;
359       }
360     };
361     return scalar($self->_recurse_where(\%j));
362   } elsif (ref $cond eq 'ARRAY') {
363     return join(' OR ', map { $self->_join_condition($_) } @$cond);
364   } else {
365     croak "Can't handle this yet!";
366   }
367 }
368
369 1;
370
371 =head1 AUTHORS
372
373 See L<DBIx::Class/CONTRIBUTORS>.
374
375 =head1 LICENSE
376
377 You may distribute this code under the same terms as Perl itself.
378
379 =cut