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 |
38 | Class::Accessor::Grouped |
39 | /; |
40 | use mro 'c3'; |
e3764383 |
41 | use strict; |
42 | use warnings; |
6298a324 |
43 | use Sub::Name 'subname'; |
ac322978 |
44 | use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/; |
e8fc51c7 |
45 | use namespace::clean; |
b2b22cd6 |
46 | |
6a247f33 |
47 | __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/); |
48 | |
3f5b99fe |
49 | # for when I need a normalized l/r pair |
50 | sub _quote_chars { |
51 | map |
52 | { defined $_ ? $_ : '' } |
53 | ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) ) |
54 | ; |
55 | } |
56 | |
b2b22cd6 |
57 | BEGIN { |
2ea6032a |
58 | # reinstall the belch()/puke() functions of SQL::Abstract with custom versions |
59 | # that use Carp::Clan instead of plain Carp (they do not like each other much) |
b2b22cd6 |
60 | no warnings qw/redefine/; |
2ea6032a |
61 | |
62 | *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) { |
63 | my($func) = (caller(1))[3]; |
64 | carp "[$func] Warning: ", @_; |
65 | }; |
66 | |
67 | *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) { |
68 | my($func) = (caller(1))[3]; |
69 | croak "[$func] Fatal: ", @_; |
70 | }; |
9c1700e3 |
71 | |
72 | # Current SQLA pollutes its namespace - clean for the time being |
73 | namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/); |
b2b22cd6 |
74 | } |
6f4ddea1 |
75 | |
e9657379 |
76 | # the "oh noes offset/top without limit" constant |
6a247f33 |
77 | # limited to 32 bits for sanity (and consistency, |
78 | # since it is ultimately handed to sprintf %u) |
79 | # Implemented as a method, since ::Storage::DBI also |
80 | # refers to it (i.e. for the case of software_limit or |
81 | # as the value to abuse with MSSQL ordered subqueries) |
e9657379 |
82 | sub __max_int { 0xFFFFFFFF }; |
83 | |
e6600283 |
84 | sub new { |
85 | my $self = shift->next::method(@_); |
86 | |
41519379 |
87 | # use the same coderefs, they are prepared to handle both cases |
88 | my @extra_dbic_syntax = ( |
89 | { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' }, |
90 | { regex => qr/^ value $/xi, handler => '_where_op_VALUE' }, |
91 | ); |
92 | |
93 | push @{$self->{special_ops}}, @extra_dbic_syntax; |
94 | push @{$self->{unary_ops}}, @extra_dbic_syntax; |
e6600283 |
95 | |
96 | $self; |
97 | } |
98 | |
99 | sub _where_op_IDENT { |
100 | my $self = shift; |
101 | my ($op, $rhs) = splice @_, -2; |
102 | if (ref $rhs) { |
103 | croak "-$op takes a single scalar argument (a quotable identifier)"; |
104 | } |
105 | |
41519379 |
106 | # in case we are called as a top level special op (no '=') |
e6600283 |
107 | my $lhs = shift; |
108 | |
109 | $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs); |
110 | |
111 | return $lhs |
112 | ? "$lhs = $rhs" |
113 | : $rhs |
114 | ; |
115 | } |
116 | |
41519379 |
117 | sub _where_op_VALUE { |
118 | my $self = shift; |
119 | my ($op, $rhs) = splice @_, -2; |
120 | |
121 | # in case we are called as a top level special op (no '=') |
122 | my $lhs = shift; |
123 | |
124 | my @bind = [ |
125 | ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"), |
126 | $rhs |
127 | ]; |
128 | |
129 | return $lhs |
130 | ? ( |
131 | $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'), |
132 | @bind |
133 | ) |
134 | : ( |
135 | $self->_convert('?'), |
136 | @bind, |
137 | ) |
138 | ; |
139 | } |
140 | |
b1d821de |
141 | my $callsites_warned; |
142 | sub _where_op_NEST { |
143 | # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas) |
144 | my $callsite = do { |
145 | my $w; |
146 | local $SIG{__WARN__} = sub { $w = shift }; |
147 | carp; |
148 | $w |
149 | }; |
150 | |
151 | carp ("-nest in search conditions is deprecated, you most probably wanted:\n" |
152 | .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }| |
153 | ) unless $callsites_warned->{$callsite}++; |
154 | |
155 | shift->next::method(@_); |
156 | } |
157 | |
6a247f33 |
158 | # Handle limit-dialect selection |
6f4ddea1 |
159 | sub select { |
6a247f33 |
160 | my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_; |
161 | |
162 | |
163 | $fields = $self->_recurse_fields($fields); |
164 | |
165 | if (defined $offset) { |
166 | croak ('A supplied offset must be a non-negative integer') |
167 | if ( $offset =~ /\D/ or $offset < 0 ); |
168 | } |
169 | $offset ||= 0; |
1cbd3034 |
170 | |
6a247f33 |
171 | if (defined $limit) { |
172 | croak ('A supplied limit must be a positive integer') |
173 | if ( $limit =~ /\D/ or $limit <= 0 ); |
174 | } |
175 | elsif ($offset) { |
176 | $limit = $self->__max_int; |
6f4ddea1 |
177 | } |
c2b7c5dc |
178 | |
a6b68a60 |
179 | |
6a247f33 |
180 | my ($sql, @bind); |
181 | if ($limit) { |
182 | # this is legacy code-flow from SQLA::Limit, it is not set in stone |
183 | |
184 | ($sql, @bind) = $self->next::method ($table, $fields, $where); |
185 | |
186 | my $limiter = |
187 | $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit |
188 | || |
189 | do { |
190 | my $dialect = $self->limit_dialect |
191 | or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found"; |
192 | $self->can ("_$dialect") |
d5dedbd6 |
193 | or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'"); |
6a247f33 |
194 | } |
195 | ; |
196 | |
197 | $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset); |
198 | } |
199 | else { |
200 | ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs); |
201 | } |
202 | |
49afd714 |
203 | push @{$self->{where_bind}}, @bind; |
583a0c65 |
204 | |
205 | # this *must* be called, otherwise extra binds will remain in the sql-maker |
49afd714 |
206 | my @all_bind = $self->_assemble_binds; |
583a0c65 |
207 | |
e5372da4 |
208 | $sql .= $self->_lock_select ($rs_attrs->{for}) |
209 | if $rs_attrs->{for}; |
210 | |
49afd714 |
211 | return wantarray ? ($sql, @all_bind) : $sql; |
583a0c65 |
212 | } |
213 | |
214 | sub _assemble_binds { |
215 | my $self = shift; |
0542ec57 |
216 | return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/); |
6f4ddea1 |
217 | } |
218 | |
e5372da4 |
219 | my $for_syntax = { |
220 | update => 'FOR UPDATE', |
221 | shared => 'FOR SHARE', |
222 | }; |
223 | sub _lock_select { |
224 | my ($self, $type) = @_; |
225 | my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested"; |
226 | return " $sql"; |
227 | } |
228 | |
6a247f33 |
229 | # Handle default inserts |
6f4ddea1 |
230 | sub insert { |
6a247f33 |
231 | # optimized due to hotttnesss |
232 | # my ($self, $table, $data, $options) = @_; |
7a72e5a5 |
233 | |
234 | # SQLA will emit INSERT INTO $table ( ) VALUES ( ) |
235 | # which is sadly understood only by MySQL. Change default behavior here, |
236 | # until SQLA2 comes with proper dialect support |
6a247f33 |
237 | if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) { |
bf51641f |
238 | my @bind; |
20595c02 |
239 | my $sql = sprintf( |
240 | 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1]) |
241 | ); |
28d28903 |
242 | |
bf51641f |
243 | if ( ($_[3]||{})->{returning} ) { |
244 | my $s; |
245 | ($s, @bind) = $_[0]->_insert_returning ($_[3]); |
246 | $sql .= $s; |
28d28903 |
247 | } |
248 | |
bf51641f |
249 | return ($sql, @bind); |
7a72e5a5 |
250 | } |
251 | |
6a247f33 |
252 | next::method(@_); |
6f4ddea1 |
253 | } |
254 | |
255 | sub _recurse_fields { |
81446c4f |
256 | my ($self, $fields) = @_; |
6f4ddea1 |
257 | my $ref = ref $fields; |
258 | return $self->_quote($fields) unless $ref; |
259 | return $$fields if $ref eq 'SCALAR'; |
260 | |
261 | if ($ref eq 'ARRAY') { |
81446c4f |
262 | return join(', ', map { $self->_recurse_fields($_) } @$fields); |
83e09b5b |
263 | } |
264 | elsif ($ref eq 'HASH') { |
81446c4f |
265 | my %hash = %$fields; # shallow copy |
83e09b5b |
266 | |
50136dd9 |
267 | my $as = delete $hash{-as}; # if supplied |
268 | |
81446c4f |
269 | my ($func, $args, @toomany) = %hash; |
270 | |
271 | # there should be only one pair |
272 | if (@toomany) { |
273 | croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ); |
274 | } |
50136dd9 |
275 | |
276 | if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) { |
277 | croak ( |
278 | 'The select => { distinct => ... } syntax is not supported for multiple columns.' |
279 | .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }' |
280 | .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }' |
83e09b5b |
281 | ); |
6f4ddea1 |
282 | } |
83e09b5b |
283 | |
50136dd9 |
284 | my $select = sprintf ('%s( %s )%s', |
285 | $self->_sqlcase($func), |
286 | $self->_recurse_fields($args), |
287 | $as |
0491b597 |
288 | ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) ) |
50136dd9 |
289 | : '' |
290 | ); |
291 | |
83e09b5b |
292 | return $select; |
6f4ddea1 |
293 | } |
294 | # Is the second check absolutely necessary? |
295 | elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) { |
4c2b30d6 |
296 | push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields]; |
297 | return $$fields->[0]; |
6f4ddea1 |
298 | } |
299 | else { |
e8fcf76f |
300 | croak($ref . qq{ unexpected in _recurse_fields()}) |
6f4ddea1 |
301 | } |
302 | } |
303 | |
a6b68a60 |
304 | |
305 | # this used to be a part of _order_by but is broken out for clarity. |
306 | # What we have been doing forever is hijacking the $order arg of |
307 | # SQLA::select to pass in arbitrary pieces of data (first the group_by, |
308 | # then pretty much the entire resultset attr-hash, as more and more |
309 | # things in the SQLA space need to have mopre info about the $rs they |
310 | # create SQL for. The alternative would be to keep expanding the |
311 | # signature of _select with more and more positional parameters, which |
312 | # is just gross. All hail SQLA2! |
313 | sub _parse_rs_attrs { |
1cbd3034 |
314 | my ($self, $arg) = @_; |
15827712 |
315 | |
a6b68a60 |
316 | my $sql = ''; |
1cbd3034 |
317 | |
0542ec57 |
318 | if ($arg->{group_by}) { |
319 | # horible horrible, waiting for refactor |
320 | local $self->{select_bind}; |
321 | if (my $g = $self->_recurse_fields($arg->{group_by}) ) { |
322 | $sql .= $self->_sqlcase(' group by ') . $g; |
323 | push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]}; |
324 | } |
a6b68a60 |
325 | } |
1cbd3034 |
326 | |
a6b68a60 |
327 | if (defined $arg->{having}) { |
328 | my ($frag, @bind) = $self->_recurse_where($arg->{having}); |
329 | push(@{$self->{having_bind}}, @bind); |
330 | $sql .= $self->_sqlcase(' having ') . $frag; |
331 | } |
15827712 |
332 | |
a6b68a60 |
333 | if (defined $arg->{order_by}) { |
334 | $sql .= $self->_order_by ($arg->{order_by}); |
335 | } |
15827712 |
336 | |
a6b68a60 |
337 | return $sql; |
338 | } |
339 | |
340 | sub _order_by { |
341 | my ($self, $arg) = @_; |
15827712 |
342 | |
a6b68a60 |
343 | # check that we are not called in legacy mode (order_by as 4th argument) |
344 | if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) { |
345 | return $self->_parse_rs_attrs ($arg); |
fde3719a |
346 | } |
1cbd3034 |
347 | else { |
6a247f33 |
348 | my ($sql, @bind) = $self->next::method($arg); |
a6b68a60 |
349 | push @{$self->{order_bind}}, @bind; |
1cbd3034 |
350 | return $sql; |
fd4cb60a |
351 | } |
6f4ddea1 |
352 | } |
353 | |
354 | sub _table { |
6a247f33 |
355 | # optimized due to hotttnesss |
356 | # my ($self, $from) = @_; |
357 | if (my $ref = ref $_[1] ) { |
358 | if ($ref eq 'ARRAY') { |
359 | return $_[0]->_recurse_from(@{$_[1]}); |
360 | } |
361 | elsif ($ref eq 'HASH') { |
4c2b30d6 |
362 | return $_[0]->_recurse_from($_[1]); |
6a247f33 |
363 | } |
6f4ddea1 |
364 | } |
6a247f33 |
365 | |
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 | |
4c2b30d6 |
424 | croak "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" |
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) { |
e8fcf76f |
443 | croak (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 { |
b48d3b4e |
455 | croak "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 |