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