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