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 { |
58 | # reinstall the carp()/croak() functions imported into SQL::Abstract |
59 | # as Carp and Carp::Clan do not like each other much |
60 | no warnings qw/redefine/; |
61 | no strict qw/refs/; |
62 | for my $f (qw/carp croak/) { |
329d7385 |
63 | |
b2b22cd6 |
64 | my $orig = \&{"SQL::Abstract::$f"}; |
e8fc51c7 |
65 | my $clan_import = \&{$f}; |
6298a324 |
66 | *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" => |
8637bb24 |
67 | sub { |
d5dedbd6 |
68 | if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) { |
ff04fc51 |
69 | goto $clan_import; |
8637bb24 |
70 | } |
71 | else { |
72 | goto $orig; |
73 | } |
74 | }; |
b2b22cd6 |
75 | } |
76 | } |
6f4ddea1 |
77 | |
e9657379 |
78 | # the "oh noes offset/top without limit" constant |
6a247f33 |
79 | # limited to 32 bits for sanity (and consistency, |
80 | # since it is ultimately handed to sprintf %u) |
81 | # Implemented as a method, since ::Storage::DBI also |
82 | # refers to it (i.e. for the case of software_limit or |
83 | # as the value to abuse with MSSQL ordered subqueries) |
e9657379 |
84 | sub __max_int { 0xFFFFFFFF }; |
85 | |
e6600283 |
86 | sub new { |
87 | my $self = shift->next::method(@_); |
88 | |
41519379 |
89 | # use the same coderefs, they are prepared to handle both cases |
90 | my @extra_dbic_syntax = ( |
91 | { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' }, |
92 | { regex => qr/^ value $/xi, handler => '_where_op_VALUE' }, |
93 | ); |
94 | |
95 | push @{$self->{special_ops}}, @extra_dbic_syntax; |
96 | push @{$self->{unary_ops}}, @extra_dbic_syntax; |
e6600283 |
97 | |
98 | $self; |
99 | } |
100 | |
101 | sub _where_op_IDENT { |
102 | my $self = shift; |
103 | my ($op, $rhs) = splice @_, -2; |
104 | if (ref $rhs) { |
105 | croak "-$op takes a single scalar argument (a quotable identifier)"; |
106 | } |
107 | |
41519379 |
108 | # in case we are called as a top level special op (no '=') |
e6600283 |
109 | my $lhs = shift; |
110 | |
111 | $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs); |
112 | |
113 | return $lhs |
114 | ? "$lhs = $rhs" |
115 | : $rhs |
116 | ; |
117 | } |
118 | |
41519379 |
119 | sub _where_op_VALUE { |
120 | my $self = shift; |
121 | my ($op, $rhs) = splice @_, -2; |
122 | |
123 | # in case we are called as a top level special op (no '=') |
124 | my $lhs = shift; |
125 | |
126 | my @bind = [ |
127 | ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"), |
128 | $rhs |
129 | ]; |
130 | |
131 | return $lhs |
132 | ? ( |
133 | $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'), |
134 | @bind |
135 | ) |
136 | : ( |
137 | $self->_convert('?'), |
138 | @bind, |
139 | ) |
140 | ; |
141 | } |
142 | |
b1d821de |
143 | my $callsites_warned; |
144 | sub _where_op_NEST { |
145 | # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas) |
146 | my $callsite = do { |
147 | my $w; |
148 | local $SIG{__WARN__} = sub { $w = shift }; |
149 | carp; |
150 | $w |
151 | }; |
152 | |
153 | carp ("-nest in search conditions is deprecated, you most probably wanted:\n" |
154 | .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }| |
155 | ) unless $callsites_warned->{$callsite}++; |
156 | |
157 | shift->next::method(@_); |
158 | } |
159 | |
6a247f33 |
160 | # Handle limit-dialect selection |
6f4ddea1 |
161 | sub select { |
6a247f33 |
162 | my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_; |
163 | |
164 | |
165 | $fields = $self->_recurse_fields($fields); |
166 | |
167 | if (defined $offset) { |
168 | croak ('A supplied offset must be a non-negative integer') |
169 | if ( $offset =~ /\D/ or $offset < 0 ); |
170 | } |
171 | $offset ||= 0; |
1cbd3034 |
172 | |
6a247f33 |
173 | if (defined $limit) { |
174 | croak ('A supplied limit must be a positive integer') |
175 | if ( $limit =~ /\D/ or $limit <= 0 ); |
176 | } |
177 | elsif ($offset) { |
178 | $limit = $self->__max_int; |
6f4ddea1 |
179 | } |
c2b7c5dc |
180 | |
a6b68a60 |
181 | |
6a247f33 |
182 | my ($sql, @bind); |
183 | if ($limit) { |
184 | # this is legacy code-flow from SQLA::Limit, it is not set in stone |
185 | |
9aae3566 |
186 | ($sql, @bind) = $self->__overriden_select($table, $fields, $where); |
6a247f33 |
187 | |
188 | my $limiter = |
189 | $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit |
190 | || |
191 | do { |
192 | my $dialect = $self->limit_dialect |
193 | or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found"; |
194 | $self->can ("_$dialect") |
d5dedbd6 |
195 | or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'"); |
6a247f33 |
196 | } |
197 | ; |
198 | |
199 | $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset); |
200 | } |
201 | else { |
9aae3566 |
202 | ($sql, @bind) = $self->__overriden_select($table, $fields, $where, $rs_attrs); |
6a247f33 |
203 | } |
204 | |
49afd714 |
205 | push @{$self->{where_bind}}, @bind; |
583a0c65 |
206 | |
207 | # this *must* be called, otherwise extra binds will remain in the sql-maker |
49afd714 |
208 | my @all_bind = $self->_assemble_binds; |
583a0c65 |
209 | |
e5372da4 |
210 | $sql .= $self->_lock_select ($rs_attrs->{for}) |
211 | if $rs_attrs->{for}; |
212 | |
49afd714 |
213 | return wantarray ? ($sql, @all_bind) : $sql; |
583a0c65 |
214 | } |
215 | |
9aae3566 |
216 | sub __overriden_select { |
217 | my $self = shift; |
218 | my ($table, @bind) = $self->_table(shift); |
219 | my $fields = shift || '*'; |
220 | my $where = shift; |
221 | my $order = shift; |
222 | |
223 | my($where_sql, @morebind) = $self->where($where, $order); |
224 | push @bind, @morebind; |
225 | |
226 | my $f = (ref $fields eq 'ARRAY') ? join ', ', map { $self->_quote($_) } @$fields |
227 | : $fields; |
228 | my $sql = join(' ', $self->_sqlcase('select'), $f, |
229 | $self->_sqlcase('from'), $table) |
230 | . $where_sql; |
231 | |
232 | return wantarray ? ($sql, @bind) : $sql; |
233 | } |
234 | |
583a0c65 |
235 | sub _assemble_binds { |
236 | my $self = shift; |
0542ec57 |
237 | return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/); |
6f4ddea1 |
238 | } |
239 | |
e5372da4 |
240 | my $for_syntax = { |
241 | update => 'FOR UPDATE', |
242 | shared => 'FOR SHARE', |
243 | }; |
244 | sub _lock_select { |
245 | my ($self, $type) = @_; |
246 | my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested"; |
247 | return " $sql"; |
248 | } |
249 | |
6a247f33 |
250 | # Handle default inserts |
6f4ddea1 |
251 | sub insert { |
6a247f33 |
252 | # optimized due to hotttnesss |
253 | # my ($self, $table, $data, $options) = @_; |
7a72e5a5 |
254 | |
255 | # SQLA will emit INSERT INTO $table ( ) VALUES ( ) |
256 | # which is sadly understood only by MySQL. Change default behavior here, |
257 | # until SQLA2 comes with proper dialect support |
6a247f33 |
258 | if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) { |
bf51641f |
259 | my @bind; |
20595c02 |
260 | my $sql = sprintf( |
261 | 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1]) |
262 | ); |
28d28903 |
263 | |
bf51641f |
264 | if ( ($_[3]||{})->{returning} ) { |
265 | my $s; |
266 | ($s, @bind) = $_[0]->_insert_returning ($_[3]); |
267 | $sql .= $s; |
28d28903 |
268 | } |
269 | |
bf51641f |
270 | return ($sql, @bind); |
7a72e5a5 |
271 | } |
272 | |
6a247f33 |
273 | next::method(@_); |
6f4ddea1 |
274 | } |
275 | |
276 | sub _recurse_fields { |
81446c4f |
277 | my ($self, $fields) = @_; |
6f4ddea1 |
278 | my $ref = ref $fields; |
279 | return $self->_quote($fields) unless $ref; |
280 | return $$fields if $ref eq 'SCALAR'; |
281 | |
282 | if ($ref eq 'ARRAY') { |
81446c4f |
283 | return join(', ', map { $self->_recurse_fields($_) } @$fields); |
83e09b5b |
284 | } |
285 | elsif ($ref eq 'HASH') { |
81446c4f |
286 | my %hash = %$fields; # shallow copy |
83e09b5b |
287 | |
50136dd9 |
288 | my $as = delete $hash{-as}; # if supplied |
289 | |
81446c4f |
290 | my ($func, $args, @toomany) = %hash; |
291 | |
292 | # there should be only one pair |
293 | if (@toomany) { |
294 | croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ); |
295 | } |
50136dd9 |
296 | |
297 | if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) { |
298 | croak ( |
299 | 'The select => { distinct => ... } syntax is not supported for multiple columns.' |
300 | .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }' |
301 | .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }' |
83e09b5b |
302 | ); |
6f4ddea1 |
303 | } |
83e09b5b |
304 | |
50136dd9 |
305 | my $select = sprintf ('%s( %s )%s', |
306 | $self->_sqlcase($func), |
307 | $self->_recurse_fields($args), |
308 | $as |
0491b597 |
309 | ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) ) |
50136dd9 |
310 | : '' |
311 | ); |
312 | |
83e09b5b |
313 | return $select; |
6f4ddea1 |
314 | } |
315 | # Is the second check absolutely necessary? |
316 | elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) { |
4c2b30d6 |
317 | push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields]; |
318 | return $$fields->[0]; |
6f4ddea1 |
319 | } |
320 | else { |
e8fcf76f |
321 | croak($ref . qq{ unexpected in _recurse_fields()}) |
6f4ddea1 |
322 | } |
323 | } |
324 | |
a6b68a60 |
325 | |
326 | # this used to be a part of _order_by but is broken out for clarity. |
327 | # What we have been doing forever is hijacking the $order arg of |
328 | # SQLA::select to pass in arbitrary pieces of data (first the group_by, |
329 | # then pretty much the entire resultset attr-hash, as more and more |
330 | # things in the SQLA space need to have mopre info about the $rs they |
331 | # create SQL for. The alternative would be to keep expanding the |
332 | # signature of _select with more and more positional parameters, which |
333 | # is just gross. All hail SQLA2! |
334 | sub _parse_rs_attrs { |
1cbd3034 |
335 | my ($self, $arg) = @_; |
15827712 |
336 | |
a6b68a60 |
337 | my $sql = ''; |
1cbd3034 |
338 | |
0542ec57 |
339 | if ($arg->{group_by}) { |
340 | # horible horrible, waiting for refactor |
341 | local $self->{select_bind}; |
342 | if (my $g = $self->_recurse_fields($arg->{group_by}) ) { |
343 | $sql .= $self->_sqlcase(' group by ') . $g; |
344 | push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]}; |
345 | } |
a6b68a60 |
346 | } |
1cbd3034 |
347 | |
a6b68a60 |
348 | if (defined $arg->{having}) { |
349 | my ($frag, @bind) = $self->_recurse_where($arg->{having}); |
350 | push(@{$self->{having_bind}}, @bind); |
351 | $sql .= $self->_sqlcase(' having ') . $frag; |
352 | } |
15827712 |
353 | |
a6b68a60 |
354 | if (defined $arg->{order_by}) { |
355 | $sql .= $self->_order_by ($arg->{order_by}); |
356 | } |
15827712 |
357 | |
a6b68a60 |
358 | return $sql; |
359 | } |
360 | |
361 | sub _order_by { |
362 | my ($self, $arg) = @_; |
15827712 |
363 | |
a6b68a60 |
364 | # check that we are not called in legacy mode (order_by as 4th argument) |
365 | if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) { |
366 | return $self->_parse_rs_attrs ($arg); |
fde3719a |
367 | } |
1cbd3034 |
368 | else { |
6a247f33 |
369 | my ($sql, @bind) = $self->next::method($arg); |
a6b68a60 |
370 | push @{$self->{order_bind}}, @bind; |
1cbd3034 |
371 | return $sql; |
fd4cb60a |
372 | } |
6f4ddea1 |
373 | } |
374 | |
375 | sub _table { |
6a247f33 |
376 | # optimized due to hotttnesss |
377 | # my ($self, $from) = @_; |
378 | if (my $ref = ref $_[1] ) { |
379 | if ($ref eq 'ARRAY') { |
380 | return $_[0]->_recurse_from(@{$_[1]}); |
381 | } |
382 | elsif ($ref eq 'HASH') { |
4c2b30d6 |
383 | return $_[0]->_recurse_from($_[1]); |
6a247f33 |
384 | } |
6f4ddea1 |
385 | } |
6a247f33 |
386 | |
387 | return $_[0]->next::method ($_[1]); |
6f4ddea1 |
388 | } |
389 | |
b8391c87 |
390 | sub _generate_join_clause { |
391 | my ($self, $join_type) = @_; |
392 | |
393 | return sprintf ('%s JOIN ', |
4c2b30d6 |
394 | $join_type ? ' ' . $self->_sqlcase($join_type) : '' |
b8391c87 |
395 | ); |
396 | } |
397 | |
6f4ddea1 |
398 | sub _recurse_from { |
399 | my ($self, $from, @join) = @_; |
9aae3566 |
400 | my (@sqlf, @binds); |
4c2b30d6 |
401 | push @sqlf, $self->_from_chunk_to_sql($from); |
6f4ddea1 |
402 | |
4c2b30d6 |
403 | for (@join) { |
404 | my ($to, $on) = @$_; |
aa82ce29 |
405 | |
6f4ddea1 |
406 | # check whether a join type exists |
6f4ddea1 |
407 | my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to; |
aa82ce29 |
408 | my $join_type; |
409 | if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) { |
410 | $join_type = $to_jt->{-join_type}; |
411 | $join_type =~ s/^\s+ | \s+$//xg; |
6f4ddea1 |
412 | } |
aa82ce29 |
413 | |
de5f71ef |
414 | $join_type = $self->{_default_jointype} if not defined $join_type; |
aa82ce29 |
415 | |
b8391c87 |
416 | push @sqlf, $self->_generate_join_clause( $join_type ); |
6f4ddea1 |
417 | |
418 | if (ref $to eq 'ARRAY') { |
9aae3566 |
419 | my ($sql, @local_bind) = $self->_recurse_from(@$to); |
420 | push(@sqlf, '(', $sql , ')'); |
421 | push @binds, @local_bind; |
6f4ddea1 |
422 | } else { |
4c2b30d6 |
423 | push(@sqlf, $self->_from_chunk_to_sql($to)); |
6f4ddea1 |
424 | } |
9aae3566 |
425 | my ($sql, @local_bind) = $self->_join_condition($on); |
426 | push(@sqlf, ' ON ', $sql); |
427 | push @binds, @local_bind; |
6f4ddea1 |
428 | } |
9aae3566 |
429 | return join('', @sqlf), @binds; |
6f4ddea1 |
430 | } |
431 | |
4c2b30d6 |
432 | sub _from_chunk_to_sql { |
433 | my ($self, $fromspec) = @_; |
434 | |
435 | return join (' ', $self->_SWITCH_refkind($fromspec, { |
436 | SCALARREF => sub { |
437 | $$fromspec; |
438 | }, |
439 | ARRAYREFREF => sub { |
440 | push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec]; |
441 | $$fromspec->[0]; |
442 | }, |
443 | HASHREF => sub { |
444 | my ($as, $table, $toomuch) = ( map |
445 | { $_ => $fromspec->{$_} } |
446 | ( grep { $_ !~ /^\-/ } keys %$fromspec ) |
447 | ); |
6f4ddea1 |
448 | |
4c2b30d6 |
449 | croak "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" |
450 | if defined $toomuch; |
6f4ddea1 |
451 | |
4c2b30d6 |
452 | ($self->_from_chunk_to_sql($table), $self->_quote($as) ); |
453 | }, |
454 | SCALAR => sub { |
455 | $self->_quote($fromspec); |
456 | }, |
457 | })); |
6f4ddea1 |
458 | } |
459 | |
460 | sub _join_condition { |
461 | my ($self, $cond) = @_; |
4c2b30d6 |
462 | |
6f4ddea1 |
463 | if (ref $cond eq 'HASH') { |
464 | my %j; |
465 | for (keys %$cond) { |
466 | my $v = $cond->{$_}; |
467 | if (ref $v) { |
cf320fd7 |
468 | #croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'}) |
469 | # if ref($v) ne 'SCALAR'; |
6f4ddea1 |
470 | $j{$_} = $v; |
471 | } |
472 | else { |
473 | my $x = '= '.$self->_quote($v); $j{$_} = \$x; |
474 | } |
475 | }; |
9aae3566 |
476 | return $self->_recurse_where(\%j); |
6f4ddea1 |
477 | } elsif (ref $cond eq 'ARRAY') { |
9aae3566 |
478 | my @parts; |
479 | my @binds; |
480 | foreach my $c (@$cond) { |
481 | my ($sql, @bind) = $self->_join_condition($c); |
482 | push @binds, @bind; |
483 | push @parts, $sql; |
484 | } |
485 | return join(' OR ', @parts), @binds; |
6f4ddea1 |
486 | } else { |
b48d3b4e |
487 | croak "Can't handle this yet!"; |
6f4ddea1 |
488 | } |
489 | } |
490 | |
6f4ddea1 |
491 | 1; |
d5dedbd6 |
492 | |
493 | =head1 AUTHORS |
494 | |
495 | See L<DBIx::Class/CONTRIBUTORS>. |
496 | |
497 | =head1 LICENSE |
498 | |
499 | You may distribute this code under the same terms as Perl itself. |
500 | |
501 | =cut |