cleaner plugin registration
[scpubgit/Q-Branch.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 =back
31
32 =cut
33
34 use base qw/
35   DBIx::Class::SQLMaker::LimitDialects
36   SQL::Abstract
37   DBIx::Class
38 /;
39 use mro 'c3';
40
41 use Sub::Name 'subname';
42 use DBIx::Class::Carp;
43 use namespace::clean;
44
45 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
46
47 sub _quoting_enabled {
48   ( defined $_[0]->{quote_char} and length $_[0]->{quote_char} ) ? 1 : 0
49 }
50
51 # for when I need a normalized l/r pair
52 sub _quote_chars {
53
54   # in case we are called in the old !!$sm->_quote_chars fashion
55   return () if !wantarray and ( ! defined $_[0]->{quote_char} or ! length $_[0]->{quote_char} );
56
57   map
58     { defined $_ ? $_ : '' }
59     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
60   ;
61 }
62
63 # FIXME when we bring in the storage weaklink, check its schema
64 # weaklink and channel through $schema->throw_exception
65 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
66
67 BEGIN {
68   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
69   # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
70   no warnings qw/redefine/;
71
72   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
73     my($func) = (caller(1))[3];
74     carp "[$func] Warning: ", @_;
75   };
76
77   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
78     my($func) = (caller(1))[3];
79     __PACKAGE__->throw_exception("[$func] Fatal: " . join ('',  @_));
80   };
81 }
82
83 # the "oh noes offset/top without limit" constant
84 # limited to 31 bits for sanity (and consistency,
85 # since it may be handed to the like of sprintf %u)
86 #
87 # Also *some* builds of SQLite fail the test
88 #   some_column BETWEEN ? AND ?: 1, 4294967295
89 # with the proper integer bind attrs
90 #
91 # Implemented as a method, since ::Storage::DBI also
92 # refers to it (i.e. for the case of software_limit or
93 # as the value to abuse with MSSQL ordered subqueries)
94 sub __max_int () { 0x7FFFFFFF };
95
96 # we ne longer need to check this - DBIC has ways of dealing with it
97 # specifically ::Storage::DBI::_resolve_bindattrs()
98 sub _assert_bindval_matches_bindtype () { 1 };
99
100 # poor man's de-qualifier
101 sub _quote {
102   $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
103     ? $_[1] =~ / ([^\.]+) $ /x
104     : $_[1]
105   );
106 }
107
108 sub _where_op_NEST {
109   carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
110       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
111   );
112
113   shift->next::method(@_);
114 }
115
116 # Handle limit-dialect selection
117 sub select {
118   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
119
120
121   ($fields, @{$self->{select_bind}}) = $self->_recurse_fields($fields);
122
123   if (defined $offset) {
124     $self->throw_exception('A supplied offset must be a non-negative integer')
125       if ( $offset =~ /\D/ or $offset < 0 );
126   }
127   $offset ||= 0;
128
129   if (defined $limit) {
130     $self->throw_exception('A supplied limit must be a positive integer')
131       if ( $limit =~ /\D/ or $limit <= 0 );
132   }
133   elsif ($offset) {
134     $limit = $self->__max_int;
135   }
136
137
138   my ($sql, @bind);
139   if ($limit) {
140     # this is legacy code-flow from SQLA::Limit, it is not set in stone
141     ($sql, @bind) = $self->next::method ($table, $fields, $where);
142
143     my $limiter;
144
145     if( $limiter = $self->can ('emulate_limit') ) {
146       carp_unique(
147         'Support for the legacy emulate_limit() mechanism inherited from '
148       . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
149       . 'DBIC transitions to Data::Query. If your code uses this type of '
150       . 'limit specification please file an RT and provide the source of '
151       . 'your emulate_limit() implementation, so an acceptable upgrade-path '
152       . 'can be devised'
153       );
154     }
155     else {
156       my $dialect = $self->limit_dialect
157         or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
158
159       $limiter = $self->can ("_$dialect")
160         or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
161     }
162
163     $sql = $self->$limiter (
164       $sql,
165       { %{$rs_attrs||{}}, _selector_sql => $fields },
166       $limit,
167       $offset
168     );
169   }
170   else {
171     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
172   }
173
174   push @{$self->{where_bind}}, @bind;
175
176 # this *must* be called, otherwise extra binds will remain in the sql-maker
177   my @all_bind = $self->_assemble_binds;
178
179   $sql .= $self->_lock_select ($rs_attrs->{for})
180     if $rs_attrs->{for};
181
182   return wantarray ? ($sql, @all_bind) : $sql;
183 }
184
185 sub _assemble_binds {
186   my $self = shift;
187   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
188 }
189
190 my $for_syntax = {
191   update => 'FOR UPDATE',
192   shared => 'FOR SHARE',
193 };
194 sub _lock_select {
195   my ($self, $type) = @_;
196
197   my $sql;
198   if (ref($type) eq 'SCALAR') {
199     $sql = "FOR $$type";
200   }
201   else {
202     $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
203   }
204
205   return " $sql";
206 }
207
208 # Handle default inserts
209 sub insert {
210 # optimized due to hotttnesss
211 #  my ($self, $table, $data, $options) = @_;
212
213   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
214   # which is sadly understood only by MySQL. Change default behavior here,
215   # until SQLA2 comes with proper dialect support
216   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
217     my @bind;
218     my $sql = sprintf(
219       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
220     );
221
222     if ( ($_[3]||{})->{returning} ) {
223       my $s;
224       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
225       $sql .= $s;
226     }
227
228     return ($sql, @bind);
229   }
230
231   next::method(@_);
232 }
233
234 sub _recurse_fields {
235   my ($self, $fields) = @_;
236   my $ref = ref $fields;
237   return $self->_quote($fields) unless $ref;
238   return $$fields if $ref eq 'SCALAR';
239
240   if ($ref eq 'ARRAY') {
241     my (@select, @bind);
242     for my $field (@$fields) {
243       my ($select, @new_bind) = $self->_recurse_fields($field);
244       push @select, $select;
245       push @bind, @new_bind;
246     }
247     return (join(', ', @select), @bind);
248   }
249   elsif ($ref eq 'HASH') {
250     my %hash = %$fields;  # shallow copy
251
252     my $as = delete $hash{-as};   # if supplied
253
254     my ($func, $rhs, @toomany) = %hash;
255
256     # there should be only one pair
257     if (@toomany) {
258       $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
259     }
260
261     if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
262       $self->throw_exception (
263         'The select => { distinct => ... } syntax is not supported for multiple columns.'
264        .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
265        .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
266       );
267     }
268
269     my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
270     my $select = sprintf ('%s( %s )%s',
271       $self->_sqlcase($func),
272       $rhs_sql,
273       $as
274         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
275         : ''
276     );
277
278     return ($select, @rhs_bind);
279   }
280   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
281     return @{$$fields};
282   }
283   else {
284     $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
285   }
286 }
287
288
289 # this used to be a part of _order_by but is broken out for clarity.
290 # What we have been doing forever is hijacking the $order arg of
291 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
292 # then pretty much the entire resultset attr-hash, as more and more
293 # things in the SQLA space need to have more info about the $rs they
294 # create SQL for. The alternative would be to keep expanding the
295 # signature of _select with more and more positional parameters, which
296 # is just gross. All hail SQLA2!
297 sub _parse_rs_attrs {
298   my ($self, $arg) = @_;
299
300   my $sql = '';
301
302   if ($arg->{group_by}) {
303     if ( my ($group_sql, @group_bind) = $self->_recurse_fields($arg->{group_by}) ) {
304       $sql .= $self->_sqlcase(' group by ') . $group_sql;
305       push @{$self->{group_bind}}, @group_bind;
306     }
307   }
308
309   if (defined $arg->{having}) {
310     my ($frag, @bind) = $self->_recurse_where($arg->{having});
311     push(@{$self->{having_bind}}, @bind);
312     $sql .= $self->_sqlcase(' having ') . $frag;
313   }
314
315   if (defined $arg->{order_by}) {
316     $sql .= $self->_order_by ($arg->{order_by});
317   }
318
319   return $sql;
320 }
321
322 sub _order_by {
323   my ($self, $arg) = @_;
324
325   # check that we are not called in legacy mode (order_by as 4th argument)
326   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
327     return $self->_parse_rs_attrs ($arg);
328   }
329   else {
330     my ($sql, @bind) = $self->next::method($arg);
331     push @{$self->{order_bind}}, @bind;
332     return $sql;
333   }
334 }
335
336 sub _split_order_chunk {
337   my ($self, $chunk) = @_;
338
339   # strip off sort modifiers, but always succeed, so $1 gets reset
340   $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
341
342   return (
343     $chunk,
344     ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
345   );
346 }
347
348 sub _table {
349 # optimized due to hotttnesss
350 #  my ($self, $from) = @_;
351   if (my $ref = ref $_[1] ) {
352     if ($ref eq 'ARRAY') {
353       return $_[0]->_recurse_from(@{$_[1]});
354     }
355     elsif ($ref eq 'HASH') {
356       return $_[0]->_recurse_from($_[1]);
357     }
358     elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
359       my ($sql, @bind) = @{ ${$_[1]} };
360       push @{$_[0]->{from_bind}}, @bind;
361       return $sql
362     }
363   }
364   return $_[0]->next::method ($_[1]);
365 }
366
367 sub _generate_join_clause {
368     my ($self, $join_type) = @_;
369
370     $join_type = $self->{_default_jointype}
371       if ! defined $join_type;
372
373     return sprintf ('%s JOIN ',
374       $join_type ?  $self->_sqlcase($join_type) : ''
375     );
376 }
377
378 sub _recurse_from {
379   my $self = shift;
380   return join (' ', $self->_gen_from_blocks(@_) );
381 }
382
383 sub _gen_from_blocks {
384   my ($self, $from, @joins) = @_;
385
386   my @fchunks = $self->_from_chunk_to_sql($from);
387
388   for (@joins) {
389     my ($to, $on) = @$_;
390
391     # check whether a join type exists
392     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
393     my $join_type;
394     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
395       $join_type = $to_jt->{-join_type};
396       $join_type =~ s/^\s+ | \s+$//xg;
397     }
398
399     my @j = $self->_generate_join_clause( $join_type );
400
401     if (ref $to eq 'ARRAY') {
402       push(@j, '(', $self->_recurse_from(@$to), ')');
403     }
404     else {
405       push(@j, $self->_from_chunk_to_sql($to));
406     }
407
408     my ($sql, @bind) = $self->_join_condition($on);
409     push(@j, ' ON ', $sql);
410     push @{$self->{from_bind}}, @bind;
411
412     push @fchunks, join '', @j;
413   }
414
415   return @fchunks;
416 }
417
418 sub _from_chunk_to_sql {
419   my ($self, $fromspec) = @_;
420
421   return join (' ', do {
422     if (! ref $fromspec) {
423       $self->_quote($fromspec);
424     }
425     elsif (ref $fromspec eq 'SCALAR') {
426       $$fromspec;
427     }
428     elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
429       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
430       $$fromspec->[0];
431     }
432     elsif (ref $fromspec eq 'HASH') {
433       my ($as, $table, $toomuch) = ( map
434         { $_ => $fromspec->{$_} }
435         ( grep { $_ !~ /^\-/ } keys %$fromspec )
436       );
437
438       $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
439         if defined $toomuch;
440
441       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
442     }
443     else {
444       $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
445     }
446   });
447 }
448
449 sub _join_condition {
450   my ($self, $cond) = @_;
451
452   # Backcompat for the old days when a plain hashref
453   # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
454   if (
455     ref $cond eq 'HASH'
456       and
457     keys %$cond == 1
458       and
459     (keys %$cond)[0] =~ /\./
460       and
461     ! ref ( (values %$cond)[0] )
462   ) {
463     carp_unique(
464       "ResultSet {from} structures with conditions not conforming to the "
465     . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
466     . "{from} altogether, or express the condition properly using the "
467     . "{ -ident => ... } operator"
468     );
469     $cond = { keys %$cond => { -ident => values %$cond } }
470   }
471   elsif ( ref $cond eq 'ARRAY' ) {
472     # do our own ORing so that the hashref-shim above is invoked
473     my @parts;
474     my @binds;
475     foreach my $c (@$cond) {
476       my ($sql, @bind) = $self->_join_condition($c);
477       push @binds, @bind;
478       push @parts, $sql;
479     }
480     return join(' OR ', @parts), @binds;
481   }
482
483   return $self->_recurse_where($cond);
484 }
485
486 # This is hideously ugly, but SQLA does not understand multicol IN expressions
487 # FIXME TEMPORARY - DQ should have native syntax for this
488 # moved here to raise API questions
489 #
490 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
491 sub _where_op_multicolumn_in {
492   my ($self, $lhs, $rhs) = @_;
493
494   if (! ref $lhs or ref $lhs eq 'ARRAY') {
495     my (@sql, @bind);
496     for (ref $lhs ? @$lhs : $lhs) {
497       if (! ref $_) {
498         push @sql, $self->_quote($_);
499       }
500       elsif (ref $_ eq 'SCALAR') {
501         push @sql, $$_;
502       }
503       elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
504         my ($s, @b) = @$$_;
505         push @sql, $s;
506         push @bind, @b;
507       }
508       else {
509         $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
510       }
511     }
512     $lhs = \[ join(', ', @sql), @bind];
513   }
514   elsif (ref $lhs eq 'SCALAR') {
515     $lhs = \[ $$lhs ];
516   }
517   elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
518     # noop
519   }
520   else {
521     $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
522   }
523
524   # is this proper...?
525   $rhs = \[ $self->_recurse_where($rhs) ];
526
527   for ($lhs, $rhs) {
528     $$_->[0] = "( $$_->[0] )"
529       unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
530   }
531
532   \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
533 }
534
535 =head1 FURTHER QUESTIONS?
536
537 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
538
539 =head1 COPYRIGHT AND LICENSE
540
541 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
542 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
543 redistribute it and/or modify it under the same terms as the
544 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
545
546 =cut
547
548 1;