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