Commit | Line | Data |
d5dedbd6 |
1 | package DBIx::Class::SQLMaker; |
6f4ddea1 |
2 | |
a697fa31 |
3 | use strict; |
4 | use warnings; |
5 | |
d5dedbd6 |
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 |
6a247f33 |
33 | |
34 | use base qw/ |
d5dedbd6 |
35 | DBIx::Class::SQLMaker::LimitDialects |
6a247f33 |
36 | SQL::Abstract |
70c28808 |
37 | DBIx::Class |
6a247f33 |
38 | /; |
39 | use mro 'c3'; |
a697fa31 |
40 | |
6298a324 |
41 | use Sub::Name 'subname'; |
70c28808 |
42 | use DBIx::Class::Carp; |
43 | use DBIx::Class::Exception; |
e8fc51c7 |
44 | use namespace::clean; |
b2b22cd6 |
45 | |
6a247f33 |
46 | __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/); |
47 | |
3f5b99fe |
48 | # for when I need a normalized l/r pair |
49 | sub _quote_chars { |
50 | map |
51 | { defined $_ ? $_ : '' } |
52 | ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) ) |
53 | ; |
54 | } |
55 | |
70c28808 |
56 | # FIXME when we bring in the storage weaklink, check its schema |
57 | # weaklink and channel through $schema->throw_exception |
58 | sub throw_exception { DBIx::Class::Exception->throw($_[1]) } |
59 | |
b2b22cd6 |
60 | BEGIN { |
2ea6032a |
61 | # reinstall the belch()/puke() functions of SQL::Abstract with custom versions |
70c28808 |
62 | # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp |
b2b22cd6 |
63 | no warnings qw/redefine/; |
2ea6032a |
64 | |
65 | *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) { |
66 | my($func) = (caller(1))[3]; |
67 | carp "[$func] Warning: ", @_; |
68 | }; |
69 | |
70 | *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) { |
71 | my($func) = (caller(1))[3]; |
70c28808 |
72 | __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_)); |
2ea6032a |
73 | }; |
b2b22cd6 |
74 | } |
6f4ddea1 |
75 | |
e9657379 |
76 | # the "oh noes offset/top without limit" constant |
fcb7fcbb |
77 | # limited to 31 bits for sanity (and consistency, |
78 | # since it may be handed to the like of sprintf %u) |
79 | # |
80 | # Also *some* builds of SQLite fail the test |
81 | # some_column BETWEEN ? AND ?: 1, 4294967295 |
82 | # with the proper integer bind attrs |
83 | # |
6a247f33 |
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) |
fcb7fcbb |
87 | sub __max_int () { 0x7FFFFFFF }; |
e9657379 |
88 | |
e39f188a |
89 | # poor man's de-qualifier |
90 | sub _quote { |
91 | $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] ) |
92 | ? $_[1] =~ / ([^\.]+) $ /x |
93 | : $_[1] |
94 | ); |
95 | } |
96 | |
b1d821de |
97 | sub _where_op_NEST { |
70c28808 |
98 | carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n" |
b1d821de |
99 | .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }| |
70c28808 |
100 | ); |
b1d821de |
101 | |
102 | shift->next::method(@_); |
103 | } |
104 | |
6a247f33 |
105 | # Handle limit-dialect selection |
6f4ddea1 |
106 | sub select { |
6a247f33 |
107 | my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_; |
108 | |
109 | |
110 | $fields = $self->_recurse_fields($fields); |
111 | |
112 | if (defined $offset) { |
70c28808 |
113 | $self->throw_exception('A supplied offset must be a non-negative integer') |
6a247f33 |
114 | if ( $offset =~ /\D/ or $offset < 0 ); |
115 | } |
116 | $offset ||= 0; |
1cbd3034 |
117 | |
6a247f33 |
118 | if (defined $limit) { |
70c28808 |
119 | $self->throw_exception('A supplied limit must be a positive integer') |
6a247f33 |
120 | if ( $limit =~ /\D/ or $limit <= 0 ); |
121 | } |
122 | elsif ($offset) { |
123 | $limit = $self->__max_int; |
6f4ddea1 |
124 | } |
c2b7c5dc |
125 | |
a6b68a60 |
126 | |
6a247f33 |
127 | my ($sql, @bind); |
128 | if ($limit) { |
129 | # this is legacy code-flow from SQLA::Limit, it is not set in stone |
130 | |
131 | ($sql, @bind) = $self->next::method ($table, $fields, $where); |
132 | |
67341081 |
133 | my $limiter; |
134 | |
135 | if( $limiter = $self->can ('emulate_limit') ) { |
136 | carp_unique( |
137 | 'Support for the legacy emulate_limit() mechanism inherited from ' |
138 | . 'SQL::Abstract::Limit has been deprecated, and will be removed when ' |
139 | . 'DBIC transitions to Data::Query. If your code uses this type of ' |
140 | . 'limit specification please file an RT and provide the source of ' |
141 | . 'your emulate_limit() implementation, so an acceptable upgrade-path ' |
142 | . 'can be devised' |
143 | ); |
144 | } |
145 | else { |
146 | my $dialect = $self->limit_dialect |
147 | or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" ); |
148 | |
149 | $limiter = $self->can ("_$dialect") |
150 | or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'"); |
151 | } |
6a247f33 |
152 | |
f74d22e2 |
153 | $sql = $self->$limiter ( |
154 | $sql, |
155 | { %{$rs_attrs||{}}, _selector_sql => $fields }, |
156 | $limit, |
157 | $offset |
158 | ); |
6a247f33 |
159 | } |
160 | else { |
161 | ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs); |
162 | } |
163 | |
49afd714 |
164 | push @{$self->{where_bind}}, @bind; |
583a0c65 |
165 | |
166 | # this *must* be called, otherwise extra binds will remain in the sql-maker |
49afd714 |
167 | my @all_bind = $self->_assemble_binds; |
583a0c65 |
168 | |
e5372da4 |
169 | $sql .= $self->_lock_select ($rs_attrs->{for}) |
170 | if $rs_attrs->{for}; |
171 | |
49afd714 |
172 | return wantarray ? ($sql, @all_bind) : $sql; |
583a0c65 |
173 | } |
174 | |
175 | sub _assemble_binds { |
176 | my $self = shift; |
8b31f62e |
177 | return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/); |
6f4ddea1 |
178 | } |
179 | |
e5372da4 |
180 | my $for_syntax = { |
181 | update => 'FOR UPDATE', |
182 | shared => 'FOR SHARE', |
183 | }; |
184 | sub _lock_select { |
185 | my ($self, $type) = @_; |
8249c09b |
186 | |
187 | my $sql; |
188 | if (ref($type) eq 'SCALAR') { |
189 | $sql = "FOR $$type"; |
190 | } |
191 | else { |
192 | $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" ); |
193 | } |
194 | |
e5372da4 |
195 | return " $sql"; |
196 | } |
197 | |
6a247f33 |
198 | # Handle default inserts |
6f4ddea1 |
199 | sub insert { |
6a247f33 |
200 | # optimized due to hotttnesss |
201 | # my ($self, $table, $data, $options) = @_; |
7a72e5a5 |
202 | |
203 | # SQLA will emit INSERT INTO $table ( ) VALUES ( ) |
204 | # which is sadly understood only by MySQL. Change default behavior here, |
205 | # until SQLA2 comes with proper dialect support |
6a247f33 |
206 | if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) { |
bf51641f |
207 | my @bind; |
20595c02 |
208 | my $sql = sprintf( |
209 | 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1]) |
210 | ); |
28d28903 |
211 | |
bf51641f |
212 | if ( ($_[3]||{})->{returning} ) { |
213 | my $s; |
214 | ($s, @bind) = $_[0]->_insert_returning ($_[3]); |
215 | $sql .= $s; |
28d28903 |
216 | } |
217 | |
bf51641f |
218 | return ($sql, @bind); |
7a72e5a5 |
219 | } |
220 | |
6a247f33 |
221 | next::method(@_); |
6f4ddea1 |
222 | } |
223 | |
224 | sub _recurse_fields { |
81446c4f |
225 | my ($self, $fields) = @_; |
6f4ddea1 |
226 | my $ref = ref $fields; |
227 | return $self->_quote($fields) unless $ref; |
228 | return $$fields if $ref eq 'SCALAR'; |
229 | |
230 | if ($ref eq 'ARRAY') { |
81446c4f |
231 | return join(', ', map { $self->_recurse_fields($_) } @$fields); |
83e09b5b |
232 | } |
233 | elsif ($ref eq 'HASH') { |
81446c4f |
234 | my %hash = %$fields; # shallow copy |
83e09b5b |
235 | |
50136dd9 |
236 | my $as = delete $hash{-as}; # if supplied |
237 | |
81446c4f |
238 | my ($func, $args, @toomany) = %hash; |
239 | |
240 | # there should be only one pair |
241 | if (@toomany) { |
70c28808 |
242 | $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) ); |
81446c4f |
243 | } |
50136dd9 |
244 | |
245 | if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) { |
70c28808 |
246 | $self->throw_exception ( |
50136dd9 |
247 | 'The select => { distinct => ... } syntax is not supported for multiple columns.' |
248 | .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }' |
249 | .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }' |
83e09b5b |
250 | ); |
6f4ddea1 |
251 | } |
83e09b5b |
252 | |
50136dd9 |
253 | my $select = sprintf ('%s( %s )%s', |
254 | $self->_sqlcase($func), |
255 | $self->_recurse_fields($args), |
256 | $as |
0491b597 |
257 | ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) ) |
50136dd9 |
258 | : '' |
259 | ); |
260 | |
83e09b5b |
261 | return $select; |
6f4ddea1 |
262 | } |
263 | # Is the second check absolutely necessary? |
264 | elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) { |
4c2b30d6 |
265 | push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields]; |
266 | return $$fields->[0]; |
6f4ddea1 |
267 | } |
268 | else { |
70c28808 |
269 | $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} ); |
6f4ddea1 |
270 | } |
271 | } |
272 | |
a6b68a60 |
273 | |
274 | # this used to be a part of _order_by but is broken out for clarity. |
275 | # What we have been doing forever is hijacking the $order arg of |
276 | # SQLA::select to pass in arbitrary pieces of data (first the group_by, |
277 | # then pretty much the entire resultset attr-hash, as more and more |
278 | # things in the SQLA space need to have mopre info about the $rs they |
279 | # create SQL for. The alternative would be to keep expanding the |
280 | # signature of _select with more and more positional parameters, which |
281 | # is just gross. All hail SQLA2! |
282 | sub _parse_rs_attrs { |
1cbd3034 |
283 | my ($self, $arg) = @_; |
15827712 |
284 | |
a6b68a60 |
285 | my $sql = ''; |
1cbd3034 |
286 | |
0542ec57 |
287 | if ($arg->{group_by}) { |
288 | # horible horrible, waiting for refactor |
289 | local $self->{select_bind}; |
290 | if (my $g = $self->_recurse_fields($arg->{group_by}) ) { |
291 | $sql .= $self->_sqlcase(' group by ') . $g; |
292 | push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]}; |
293 | } |
a6b68a60 |
294 | } |
1cbd3034 |
295 | |
a6b68a60 |
296 | if (defined $arg->{having}) { |
297 | my ($frag, @bind) = $self->_recurse_where($arg->{having}); |
298 | push(@{$self->{having_bind}}, @bind); |
299 | $sql .= $self->_sqlcase(' having ') . $frag; |
300 | } |
15827712 |
301 | |
a6b68a60 |
302 | if (defined $arg->{order_by}) { |
303 | $sql .= $self->_order_by ($arg->{order_by}); |
304 | } |
15827712 |
305 | |
a6b68a60 |
306 | return $sql; |
307 | } |
308 | |
309 | sub _order_by { |
310 | my ($self, $arg) = @_; |
15827712 |
311 | |
a6b68a60 |
312 | # check that we are not called in legacy mode (order_by as 4th argument) |
313 | if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) { |
314 | return $self->_parse_rs_attrs ($arg); |
fde3719a |
315 | } |
1cbd3034 |
316 | else { |
6a247f33 |
317 | my ($sql, @bind) = $self->next::method($arg); |
a6b68a60 |
318 | push @{$self->{order_bind}}, @bind; |
1cbd3034 |
319 | return $sql; |
fd4cb60a |
320 | } |
6f4ddea1 |
321 | } |
322 | |
323 | sub _table { |
6a247f33 |
324 | # optimized due to hotttnesss |
325 | # my ($self, $from) = @_; |
326 | if (my $ref = ref $_[1] ) { |
327 | if ($ref eq 'ARRAY') { |
328 | return $_[0]->_recurse_from(@{$_[1]}); |
329 | } |
330 | elsif ($ref eq 'HASH') { |
4c2b30d6 |
331 | return $_[0]->_recurse_from($_[1]); |
6a247f33 |
332 | } |
1bffc6b8 |
333 | elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') { |
334 | my ($sql, @bind) = @{ ${$_[1]} }; |
335 | push @{$_[0]->{from_bind}}, @bind; |
336 | return $sql |
337 | } |
6f4ddea1 |
338 | } |
6a247f33 |
339 | return $_[0]->next::method ($_[1]); |
6f4ddea1 |
340 | } |
341 | |
b8391c87 |
342 | sub _generate_join_clause { |
343 | my ($self, $join_type) = @_; |
344 | |
726c8f65 |
345 | $join_type = $self->{_default_jointype} |
346 | if ! defined $join_type; |
347 | |
b8391c87 |
348 | return sprintf ('%s JOIN ', |
726c8f65 |
349 | $join_type ? $self->_sqlcase($join_type) : '' |
b8391c87 |
350 | ); |
351 | } |
352 | |
6f4ddea1 |
353 | sub _recurse_from { |
726c8f65 |
354 | my $self = shift; |
355 | |
356 | return join (' ', $self->_gen_from_blocks(@_) ); |
357 | } |
358 | |
359 | sub _gen_from_blocks { |
360 | my ($self, $from, @joins) = @_; |
361 | |
362 | my @fchunks = $self->_from_chunk_to_sql($from); |
6f4ddea1 |
363 | |
726c8f65 |
364 | for (@joins) { |
4c2b30d6 |
365 | my ($to, $on) = @$_; |
aa82ce29 |
366 | |
6f4ddea1 |
367 | # check whether a join type exists |
6f4ddea1 |
368 | my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to; |
aa82ce29 |
369 | my $join_type; |
370 | if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) { |
371 | $join_type = $to_jt->{-join_type}; |
372 | $join_type =~ s/^\s+ | \s+$//xg; |
6f4ddea1 |
373 | } |
aa82ce29 |
374 | |
726c8f65 |
375 | my @j = $self->_generate_join_clause( $join_type ); |
6f4ddea1 |
376 | |
377 | if (ref $to eq 'ARRAY') { |
726c8f65 |
378 | push(@j, '(', $self->_recurse_from(@$to), ')'); |
379 | } |
380 | else { |
381 | push(@j, $self->_from_chunk_to_sql($to)); |
6f4ddea1 |
382 | } |
726c8f65 |
383 | |
a697fa31 |
384 | my ($sql, @bind) = $self->_join_condition($on); |
b4e9f590 |
385 | push(@j, ' ON ', $sql); |
a697fa31 |
386 | push @{$self->{from_bind}}, @bind; |
726c8f65 |
387 | |
388 | push @fchunks, join '', @j; |
6f4ddea1 |
389 | } |
726c8f65 |
390 | |
391 | return @fchunks; |
6f4ddea1 |
392 | } |
393 | |
4c2b30d6 |
394 | sub _from_chunk_to_sql { |
395 | my ($self, $fromspec) = @_; |
396 | |
e8885a53 |
397 | return join (' ', do { |
398 | if (! ref $fromspec) { |
399 | $self->_quote($fromspec); |
400 | } |
401 | elsif (ref $fromspec eq 'SCALAR') { |
4c2b30d6 |
402 | $$fromspec; |
e8885a53 |
403 | } |
404 | elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') { |
4c2b30d6 |
405 | push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec]; |
406 | $$fromspec->[0]; |
e8885a53 |
407 | } |
408 | elsif (ref $fromspec eq 'HASH') { |
4c2b30d6 |
409 | my ($as, $table, $toomuch) = ( map |
410 | { $_ => $fromspec->{$_} } |
411 | ( grep { $_ !~ /^\-/ } keys %$fromspec ) |
412 | ); |
6f4ddea1 |
413 | |
70c28808 |
414 | $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" ) |
4c2b30d6 |
415 | if defined $toomuch; |
6f4ddea1 |
416 | |
4c2b30d6 |
417 | ($self->_from_chunk_to_sql($table), $self->_quote($as) ); |
e8885a53 |
418 | } |
419 | else { |
420 | $self->throw_exception('Unsupported from refkind: ' . ref $fromspec ); |
421 | } |
422 | }); |
6f4ddea1 |
423 | } |
424 | |
425 | sub _join_condition { |
426 | my ($self, $cond) = @_; |
4c2b30d6 |
427 | |
a697fa31 |
428 | # Backcompat for the old days when a plain hashref |
429 | # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2 |
430 | # Once things settle we should start warning here so that |
431 | # folks unroll their hacks |
432 | if ( |
433 | ref $cond eq 'HASH' |
434 | and |
435 | keys %$cond == 1 |
436 | and |
437 | (keys %$cond)[0] =~ /\./ |
438 | and |
439 | ! ref ( (values %$cond)[0] ) |
440 | ) { |
441 | $cond = { keys %$cond => { -ident => values %$cond } } |
6f4ddea1 |
442 | } |
a697fa31 |
443 | elsif ( ref $cond eq 'ARRAY' ) { |
444 | # do our own ORing so that the hashref-shim above is invoked |
9aae3566 |
445 | my @parts; |
446 | my @binds; |
447 | foreach my $c (@$cond) { |
448 | my ($sql, @bind) = $self->_join_condition($c); |
449 | push @binds, @bind; |
450 | push @parts, $sql; |
451 | } |
452 | return join(' OR ', @parts), @binds; |
6f4ddea1 |
453 | } |
a697fa31 |
454 | |
455 | return $self->_recurse_where($cond); |
6f4ddea1 |
456 | } |
457 | |
6f4ddea1 |
458 | 1; |
d5dedbd6 |
459 | |
460 | =head1 AUTHORS |
461 | |
462 | See L<DBIx::Class/CONTRIBUTORS>. |
463 | |
464 | =head1 LICENSE |
465 | |
466 | You may distribute this code under the same terms as Perl itself. |
467 | |
468 | =cut |