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