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