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