fe07e28201dfb61d51a04f5adc806331003f4c80
[dbsrgits/DBIx-Class.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
142     ($sql, @bind) = $self->next::method ($table, $fields, $where);
143
144     my $limiter;
145
146     if( $limiter = $self->can ('emulate_limit') ) {
147       carp_unique(
148         'Support for the legacy emulate_limit() mechanism inherited from '
149       . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
150       . 'DBIC transitions to Data::Query. If your code uses this type of '
151       . 'limit specification please file an RT and provide the source of '
152       . 'your emulate_limit() implementation, so an acceptable upgrade-path '
153       . 'can be devised'
154       );
155     }
156     else {
157       my $dialect = $self->limit_dialect
158         or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
159
160       $limiter = $self->can ("_$dialect")
161         or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
162     }
163
164     $sql = $self->$limiter (
165       $sql,
166       { %{$rs_attrs||{}}, _selector_sql => $fields },
167       $limit,
168       $offset
169     );
170   }
171   else {
172     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
173   }
174
175   push @{$self->{where_bind}}, @bind;
176
177 # this *must* be called, otherwise extra binds will remain in the sql-maker
178   my @all_bind = $self->_assemble_binds;
179
180   $sql .= $self->_lock_select ($rs_attrs->{for})
181     if $rs_attrs->{for};
182
183   return wantarray ? ($sql, @all_bind) : $sql;
184 }
185
186 sub _assemble_binds {
187   my $self = shift;
188   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
189 }
190
191 my $for_syntax = {
192   update => 'FOR UPDATE',
193   shared => 'FOR SHARE',
194 };
195 sub _lock_select {
196   my ($self, $type) = @_;
197
198   my $sql;
199   if (ref($type) eq 'SCALAR') {
200     $sql = "FOR $$type";
201   }
202   else {
203     $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
204   }
205
206   return " $sql";
207 }
208
209 # Handle default inserts
210 sub insert {
211 # optimized due to hotttnesss
212 #  my ($self, $table, $data, $options) = @_;
213
214   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
215   # which is sadly understood only by MySQL. Change default behavior here,
216   # until SQLA2 comes with proper dialect support
217   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
218     my @bind;
219     my $sql = sprintf(
220       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
221     );
222
223     if ( ($_[3]||{})->{returning} ) {
224       my $s;
225       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
226       $sql .= $s;
227     }
228
229     return ($sql, @bind);
230   }
231
232   next::method(@_);
233 }
234
235 sub _recurse_fields {
236   my ($self, $fields) = @_;
237   my $ref = ref $fields;
238   return $self->_quote($fields) unless $ref;
239   return $$fields if $ref eq 'SCALAR';
240
241   if ($ref eq 'ARRAY') {
242     my (@select, @bind);
243     for my $field (@$fields) {
244       my ($select, @new_bind) = $self->_recurse_fields($field);
245       push @select, $select;
246       push @bind, @new_bind;
247     }
248     return (join(', ', @select), @bind);
249   }
250   elsif ($ref eq 'HASH') {
251     my %hash = %$fields;  # shallow copy
252
253     my $as = delete $hash{-as};   # if supplied
254
255     my ($func, $rhs, @toomany) = %hash;
256
257     # there should be only one pair
258     if (@toomany) {
259       $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
260     }
261
262     if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
263       $self->throw_exception (
264         'The select => { distinct => ... } syntax is not supported for multiple columns.'
265        .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
266        .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
267       );
268     }
269
270     my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
271     my $select = sprintf ('%s( %s )%s',
272       $self->_sqlcase($func),
273       $rhs_sql,
274       $as
275         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
276         : ''
277     );
278
279     return ($select, @rhs_bind);
280   }
281   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
282     return @{$$fields};
283   }
284   else {
285     $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
286   }
287 }
288
289
290 # this used to be a part of _order_by but is broken out for clarity.
291 # What we have been doing forever is hijacking the $order arg of
292 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
293 # then pretty much the entire resultset attr-hash, as more and more
294 # things in the SQLA space need to have more info about the $rs they
295 # create SQL for. The alternative would be to keep expanding the
296 # signature of _select with more and more positional parameters, which
297 # is just gross. All hail SQLA2!
298 sub _parse_rs_attrs {
299   my ($self, $arg) = @_;
300
301   my $sql = '';
302   my @sqlbind;
303
304   if (
305     $arg->{group_by}
306       and
307     @sqlbind = $self->_recurse_fields($arg->{group_by})
308   ) {
309     $sql .= $self->_sqlcase(' group by ') . shift @sqlbind;
310     push @{$self->{group_bind}}, @sqlbind;
311   }
312
313   if (
314     $arg->{having}
315       and
316     @sqlbind = $self->_recurse_where($arg->{having})
317   ) {
318     $sql .= $self->_sqlcase(' having ') . shift @sqlbind;
319     push(@{$self->{having_bind}}, @sqlbind);
320   }
321
322   if ($arg->{order_by}) {
323     # unlike the 2 above, _order_by injects into @{...bind...} for us
324     $sql .= $self->_order_by ($arg->{order_by});
325   }
326
327   return $sql;
328 }
329
330 sub _order_by {
331   my ($self, $arg) = @_;
332
333   # check that we are not called in legacy mode (order_by as 4th argument)
334   (
335     ref $arg eq 'HASH'
336       and
337     not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg
338   )
339     ? $self->_parse_rs_attrs ($arg)
340     : do {
341       my ($sql, @bind) = $self->next::method($arg);
342       push @{$self->{order_bind}}, @bind;
343       $sql; # RV
344     }
345   ;
346 }
347
348 sub _split_order_chunk {
349   my ($self, $chunk) = @_;
350
351   # strip off sort modifiers, but always succeed, so $1 gets reset
352   $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
353
354   return (
355     $chunk,
356     ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
357   );
358 }
359
360 sub _table {
361 # optimized due to hotttnesss
362 #  my ($self, $from) = @_;
363   if (my $ref = ref $_[1] ) {
364     if ($ref eq 'ARRAY') {
365       return $_[0]->_recurse_from(@{$_[1]});
366     }
367     elsif ($ref eq 'HASH') {
368       return $_[0]->_recurse_from($_[1]);
369     }
370     elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
371       my ($sql, @bind) = @{ ${$_[1]} };
372       push @{$_[0]->{from_bind}}, @bind;
373       return $sql
374     }
375   }
376   return $_[0]->next::method ($_[1]);
377 }
378
379 sub _generate_join_clause {
380     my ($self, $join_type) = @_;
381
382     $join_type = $self->{_default_jointype}
383       if ! defined $join_type;
384
385     return sprintf ('%s JOIN ',
386       $join_type ?  $self->_sqlcase($join_type) : ''
387     );
388 }
389
390 sub _recurse_from {
391   my $self = shift;
392   return join (' ', $self->_gen_from_blocks(@_) );
393 }
394
395 sub _gen_from_blocks {
396   my ($self, $from, @joins) = @_;
397
398   my @fchunks = $self->_from_chunk_to_sql($from);
399
400   for (@joins) {
401     my ($to, $on) = @$_;
402
403     # check whether a join type exists
404     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
405     my $join_type;
406     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
407       $join_type = $to_jt->{-join_type};
408       $join_type =~ s/^\s+ | \s+$//xg;
409     }
410
411     my @j = $self->_generate_join_clause( $join_type );
412
413     if (ref $to eq 'ARRAY') {
414       push(@j, '(', $self->_recurse_from(@$to), ')');
415     }
416     else {
417       push(@j, $self->_from_chunk_to_sql($to));
418     }
419
420     my ($sql, @bind) = $self->_join_condition($on);
421     push(@j, ' ON ', $sql);
422     push @{$self->{from_bind}}, @bind;
423
424     push @fchunks, join '', @j;
425   }
426
427   return @fchunks;
428 }
429
430 sub _from_chunk_to_sql {
431   my ($self, $fromspec) = @_;
432
433   return join (' ', do {
434     if (! ref $fromspec) {
435       $self->_quote($fromspec);
436     }
437     elsif (ref $fromspec eq 'SCALAR') {
438       $$fromspec;
439     }
440     elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
441       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
442       $$fromspec->[0];
443     }
444     elsif (ref $fromspec eq 'HASH') {
445       my ($as, $table, $toomuch) = ( map
446         { $_ => $fromspec->{$_} }
447         ( grep { $_ !~ /^\-/ } keys %$fromspec )
448       );
449
450       $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
451         if defined $toomuch;
452
453       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
454     }
455     else {
456       $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
457     }
458   });
459 }
460
461 sub _join_condition {
462   my ($self, $cond) = @_;
463
464   # Backcompat for the old days when a plain hashref
465   # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
466   if (
467     ref $cond eq 'HASH'
468       and
469     keys %$cond == 1
470       and
471     (keys %$cond)[0] =~ /\./
472       and
473     ! ref ( (values %$cond)[0] )
474   ) {
475     carp_unique(
476       "ResultSet {from} structures with conditions not conforming to the "
477     . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
478     . "{from} altogether, or express the condition properly using the "
479     . "{ -ident => ... } operator"
480     );
481     $cond = { keys %$cond => { -ident => values %$cond } }
482   }
483   elsif ( ref $cond eq 'ARRAY' ) {
484     # do our own ORing so that the hashref-shim above is invoked
485     my @parts;
486     my @binds;
487     foreach my $c (@$cond) {
488       my ($sql, @bind) = $self->_join_condition($c);
489       push @binds, @bind;
490       push @parts, $sql;
491     }
492     return join(' OR ', @parts), @binds;
493   }
494
495   return $self->_recurse_where($cond);
496 }
497
498 # This is hideously ugly, but SQLA does not understand multicol IN expressions
499 # FIXME TEMPORARY - DQ should have native syntax for this
500 # moved here to raise API questions
501 #
502 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
503 sub _where_op_multicolumn_in {
504   my ($self, $lhs, $rhs) = @_;
505
506   if (! ref $lhs or ref $lhs eq 'ARRAY') {
507     my (@sql, @bind);
508     for (ref $lhs ? @$lhs : $lhs) {
509       if (! ref $_) {
510         push @sql, $self->_quote($_);
511       }
512       elsif (ref $_ eq 'SCALAR') {
513         push @sql, $$_;
514       }
515       elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
516         my ($s, @b) = @$$_;
517         push @sql, $s;
518         push @bind, @b;
519       }
520       else {
521         $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
522       }
523     }
524     $lhs = \[ join(', ', @sql), @bind];
525   }
526   elsif (ref $lhs eq 'SCALAR') {
527     $lhs = \[ $$lhs ];
528   }
529   elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
530     # noop
531   }
532   else {
533     $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
534   }
535
536   # is this proper...?
537   $rhs = \[ $self->_recurse_where($rhs) ];
538
539   for ($lhs, $rhs) {
540     $$_->[0] = "( $$_->[0] )"
541       unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
542   }
543
544   \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
545 }
546
547 =head1 FURTHER QUESTIONS?
548
549 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
550
551 =head1 COPYRIGHT AND LICENSE
552
553 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
554 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
555 redistribute it and/or modify it under the same terms as the
556 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
557
558 =cut
559
560 1;