66b6c735de4f4af692ff06bac16c509a6b7ea0c5
[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 =item * The L</-ident> operator
31
32 =item * The L</-value> operator
33
34 =back
35
36 =cut
37
38 use base qw/
39   DBIx::Class::SQLMaker::LimitDialects
40   SQL::Abstract
41   DBIx::Class
42 /;
43 use mro 'c3';
44
45 use Sub::Name 'subname';
46 use DBIx::Class::Carp;
47 use DBIx::Class::Exception;
48 use namespace::clean;
49
50 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
51
52 # for when I need a normalized l/r pair
53 sub _quote_chars {
54   map
55     { defined $_ ? $_ : '' }
56     ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
57   ;
58 }
59
60 # FIXME when we bring in the storage weaklink, check its schema
61 # weaklink and channel through $schema->throw_exception
62 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
63
64 BEGIN {
65   # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
66   # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
67   no warnings qw/redefine/;
68
69   *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
70     my($func) = (caller(1))[3];
71     carp "[$func] Warning: ", @_;
72   };
73
74   *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
75     my($func) = (caller(1))[3];
76     __PACKAGE__->throw_exception("[$func] Fatal: " . join ('',  @_));
77   };
78
79   # Current SQLA pollutes its namespace - clean for the time being
80   namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
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 # poor man's de-qualifier
97 sub _quote {
98   $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
99     ? $_[1] =~ / ([^\.]+) $ /x
100     : $_[1]
101   );
102 }
103
104 sub new {
105   my $self = shift->next::method(@_);
106
107   # use the same coderefs, they are prepared to handle both cases
108   my @extra_dbic_syntax = (
109     { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
110     { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
111   );
112
113   push @{$self->{special_ops}}, @extra_dbic_syntax;
114   push @{$self->{unary_ops}}, @extra_dbic_syntax;
115
116   $self;
117 }
118
119 sub _where_op_IDENT {
120   my $self = shift;
121   my ($op, $rhs) = splice @_, -2;
122   if (ref $rhs) {
123     $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
124   }
125
126   # in case we are called as a top level special op (no '=')
127   my $lhs = shift;
128
129   $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
130
131   return $lhs
132     ? "$lhs = $rhs"
133     : $rhs
134   ;
135 }
136
137 sub _where_op_VALUE {
138   my $self = shift;
139   my ($op, $rhs) = splice @_, -2;
140
141   # in case we are called as a top level special op (no '=')
142   my $lhs = shift;
143
144   my @bind = [
145     ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
146     $rhs
147   ];
148
149   return $lhs
150     ? (
151       $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
152       @bind
153     )
154     : (
155       $self->_convert('?'),
156       @bind,
157     )
158   ;
159 }
160
161 sub _where_op_NEST {
162   carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
163       .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
164   );
165
166   shift->next::method(@_);
167 }
168
169 # Handle limit-dialect selection
170 sub select {
171   my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
172
173
174   $fields = $self->_recurse_fields($fields);
175
176   if (defined $offset) {
177     $self->throw_exception('A supplied offset must be a non-negative integer')
178       if ( $offset =~ /\D/ or $offset < 0 );
179   }
180   $offset ||= 0;
181
182   if (defined $limit) {
183     $self->throw_exception('A supplied limit must be a positive integer')
184       if ( $limit =~ /\D/ or $limit <= 0 );
185   }
186   elsif ($offset) {
187     $limit = $self->__max_int;
188   }
189
190
191   my ($sql, @bind);
192   if ($limit) {
193     # this is legacy code-flow from SQLA::Limit, it is not set in stone
194
195     ($sql, @bind) = $self->next::method ($table, $fields, $where);
196
197     my $limiter =
198       $self->can ('emulate_limit')  # also backcompat hook from SQLA::Limit
199         ||
200       do {
201         my $dialect = $self->limit_dialect
202           or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
203         $self->can ("_$dialect")
204           or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
205       }
206     ;
207
208     $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
209   }
210   else {
211     ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
212   }
213
214   push @{$self->{where_bind}}, @bind;
215
216 # this *must* be called, otherwise extra binds will remain in the sql-maker
217   my @all_bind = $self->_assemble_binds;
218
219   $sql .= $self->_lock_select ($rs_attrs->{for})
220     if $rs_attrs->{for};
221
222   return wantarray ? ($sql, @all_bind) : $sql;
223 }
224
225 sub _assemble_binds {
226   my $self = shift;
227   return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order limit/);
228 }
229
230 my $for_syntax = {
231   update => 'FOR UPDATE',
232   shared => 'FOR SHARE',
233 };
234 sub _lock_select {
235   my ($self, $type) = @_;
236   my $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
237   return " $sql";
238 }
239
240 # Handle default inserts
241 sub insert {
242 # optimized due to hotttnesss
243 #  my ($self, $table, $data, $options) = @_;
244
245   # SQLA will emit INSERT INTO $table ( ) VALUES ( )
246   # which is sadly understood only by MySQL. Change default behavior here,
247   # until SQLA2 comes with proper dialect support
248   if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
249     my @bind;
250     my $sql = sprintf(
251       'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
252     );
253
254     if ( ($_[3]||{})->{returning} ) {
255       my $s;
256       ($s, @bind) = $_[0]->_insert_returning ($_[3]);
257       $sql .= $s;
258     }
259
260     return ($sql, @bind);
261   }
262
263   next::method(@_);
264 }
265
266 sub _recurse_fields {
267   my ($self, $fields) = @_;
268   my $ref = ref $fields;
269   return $self->_quote($fields) unless $ref;
270   return $$fields if $ref eq 'SCALAR';
271
272   if ($ref eq 'ARRAY') {
273     return join(', ', map { $self->_recurse_fields($_) } @$fields);
274   }
275   elsif ($ref eq 'HASH') {
276     my %hash = %$fields;  # shallow copy
277
278     my $as = delete $hash{-as};   # if supplied
279
280     my ($func, $args, @toomany) = %hash;
281
282     # there should be only one pair
283     if (@toomany) {
284       $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
285     }
286
287     if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
288       $self->throw_exception (
289         'The select => { distinct => ... } syntax is not supported for multiple columns.'
290        .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
291        .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
292       );
293     }
294
295     my $select = sprintf ('%s( %s )%s',
296       $self->_sqlcase($func),
297       $self->_recurse_fields($args),
298       $as
299         ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
300         : ''
301     );
302
303     return $select;
304   }
305   # Is the second check absolutely necessary?
306   elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
307     push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
308     return $$fields->[0];
309   }
310   else {
311     $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
312   }
313 }
314
315
316 # this used to be a part of _order_by but is broken out for clarity.
317 # What we have been doing forever is hijacking the $order arg of
318 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
319 # then pretty much the entire resultset attr-hash, as more and more
320 # things in the SQLA space need to have mopre info about the $rs they
321 # create SQL for. The alternative would be to keep expanding the
322 # signature of _select with more and more positional parameters, which
323 # is just gross. All hail SQLA2!
324 sub _parse_rs_attrs {
325   my ($self, $arg) = @_;
326
327   my $sql = '';
328
329   if ($arg->{group_by}) {
330     # horible horrible, waiting for refactor
331     local $self->{select_bind};
332     if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
333       $sql .= $self->_sqlcase(' group by ') . $g;
334       push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
335     }
336   }
337
338   if (defined $arg->{having}) {
339     my ($frag, @bind) = $self->_recurse_where($arg->{having});
340     push(@{$self->{having_bind}}, @bind);
341     $sql .= $self->_sqlcase(' having ') . $frag;
342   }
343
344   if (defined $arg->{order_by}) {
345     $sql .= $self->_order_by ($arg->{order_by});
346   }
347
348   return $sql;
349 }
350
351 sub _order_by {
352   my ($self, $arg) = @_;
353
354   # check that we are not called in legacy mode (order_by as 4th argument)
355   if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
356     return $self->_parse_rs_attrs ($arg);
357   }
358   else {
359     my ($sql, @bind) = $self->next::method($arg);
360     push @{$self->{order_bind}}, @bind;
361     return $sql;
362   }
363 }
364
365 sub _table {
366 # optimized due to hotttnesss
367 #  my ($self, $from) = @_;
368   if (my $ref = ref $_[1] ) {
369     if ($ref eq 'ARRAY') {
370       return $_[0]->_recurse_from(@{$_[1]});
371     }
372     elsif ($ref eq 'HASH') {
373       return $_[0]->_recurse_from($_[1]);
374     }
375     elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
376       my ($sql, @bind) = @{ ${$_[1]} };
377       push @{$_[0]->{from_bind}}, @bind;
378       return $sql
379     }
380   }
381   return $_[0]->next::method ($_[1]);
382 }
383
384 sub _generate_join_clause {
385     my ($self, $join_type) = @_;
386
387     $join_type = $self->{_default_jointype}
388       if ! defined $join_type;
389
390     return sprintf ('%s JOIN ',
391       $join_type ?  $self->_sqlcase($join_type) : ''
392     );
393 }
394
395 sub _recurse_from {
396   my $self = shift;
397
398   return join (' ', $self->_gen_from_blocks(@_) );
399 }
400
401 sub _gen_from_blocks {
402   my ($self, $from, @joins) = @_;
403
404   my @fchunks = $self->_from_chunk_to_sql($from);
405
406   for (@joins) {
407     my ($to, $on) = @$_;
408
409     # check whether a join type exists
410     my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
411     my $join_type;
412     if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
413       $join_type = $to_jt->{-join_type};
414       $join_type =~ s/^\s+ | \s+$//xg;
415     }
416
417     my @j = $self->_generate_join_clause( $join_type );
418
419     if (ref $to eq 'ARRAY') {
420       push(@j, '(', $self->_recurse_from(@$to), ')');
421     }
422     else {
423       push(@j, $self->_from_chunk_to_sql($to));
424     }
425
426     my ($sql, @bind) = $self->_join_condition($on);
427     push(@j, ' ON ', $sql);
428     push @{$self->{from_bind}}, @bind;
429
430     push @fchunks, join '', @j;
431   }
432
433   return @fchunks;
434 }
435
436 sub _from_chunk_to_sql {
437   my ($self, $fromspec) = @_;
438
439   return join (' ', $self->_SWITCH_refkind($fromspec, {
440     SCALARREF => sub {
441       $$fromspec;
442     },
443     ARRAYREFREF => sub {
444       push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
445       $$fromspec->[0];
446     },
447     HASHREF => sub {
448       my ($as, $table, $toomuch) = ( map
449         { $_ => $fromspec->{$_} }
450         ( grep { $_ !~ /^\-/ } keys %$fromspec )
451       );
452
453       $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
454         if defined $toomuch;
455
456       ($self->_from_chunk_to_sql($table), $self->_quote($as) );
457     },
458     SCALAR => sub {
459       $self->_quote($fromspec);
460     },
461   }));
462 }
463
464 sub _join_condition {
465   my ($self, $cond) = @_;
466
467   # Backcompat for the old days when a plain hashref
468   # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
469   # Once things settle we should start warning here so that
470   # folks unroll their hacks
471   if (
472     ref $cond eq 'HASH'
473       and
474     keys %$cond == 1
475       and
476     (keys %$cond)[0] =~ /\./
477       and
478     ! ref ( (values %$cond)[0] )
479   ) {
480     $cond = { keys %$cond => { -ident => values %$cond } }
481   }
482   elsif ( ref $cond eq 'ARRAY' ) {
483     # do our own ORing so that the hashref-shim above is invoked
484     my @parts;
485     my @binds;
486     foreach my $c (@$cond) {
487       my ($sql, @bind) = $self->_join_condition($c);
488       push @binds, @bind;
489       push @parts, $sql;
490     }
491     return join(' OR ', @parts), @binds;
492   }
493
494   return $self->_recurse_where($cond);
495 }
496
497 1;
498
499 =head1 OPERATORS
500
501 =head2 -ident
502
503 Used to explicitly specify an SQL identifier. Takes a plain string as value
504 which is then invariably treated as a column name (and is being properly
505 quoted if quoting has been requested). Most useful for comparison of two
506 columns:
507
508     my %where = (
509         priority => { '<', 2 },
510         requestor => { -ident => 'submitter' }
511     );
512
513 which results in:
514
515     $stmt = 'WHERE "priority" < ? AND "requestor" = "submitter"';
516     @bind = ('2');
517
518 =head2 -value
519
520 The -value operator signals that the argument to the right is a raw bind value.
521 It will be passed straight to DBI, without invoking any of the SQL::Abstract
522 condition-parsing logic. This allows you to, for example, pass an array as a
523 column value for databases that support array datatypes, e.g.:
524
525     my %where = (
526         array => { -value => [1, 2, 3] }
527     );
528
529 which results in:
530
531     $stmt = 'WHERE array = ?';
532     @bind = ([1, 2, 3]);
533
534 =head1 AUTHORS
535
536 See L<DBIx::Class/CONTRIBUTORS>.
537
538 =head1 LICENSE
539
540 You may distribute this code under the same terms as Perl itself.
541
542 =cut