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