Even more aggressive streamline of SQL scanning in _resolve_aliastypes
[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
30=back
31
32=cut
6a247f33 33
34use base qw/
d5dedbd6 35 DBIx::Class::SQLMaker::LimitDialects
6a247f33 36 SQL::Abstract
70c28808 37 DBIx::Class
6a247f33 38/;
39use mro 'c3';
a697fa31 40
6298a324 41use Sub::Name 'subname';
70c28808 42use DBIx::Class::Carp;
e8fc51c7 43use namespace::clean;
b2b22cd6 44
6a247f33 45__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
46
111364b3 47sub _quoting_enabled {
48 ( defined $_[0]->{quote_char} and length $_[0]->{quote_char} ) ? 1 : 0
49}
50
3f5b99fe 51# for when I need a normalized l/r pair
52sub _quote_chars {
111364b3 53
54 # in case we are called in the old !!$sm->_quote_chars fashion
55 return () if !wantarray and ( ! defined $_[0]->{quote_char} or ! length $_[0]->{quote_char} );
56
3f5b99fe 57 map
58 { defined $_ ? $_ : '' }
59 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
60 ;
61}
62
70c28808 63# FIXME when we bring in the storage weaklink, check its schema
64# weaklink and channel through $schema->throw_exception
65sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
66
b2b22cd6 67BEGIN {
2ea6032a 68 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
70c28808 69 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
b2b22cd6 70 no warnings qw/redefine/;
2ea6032a 71
72 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
73 my($func) = (caller(1))[3];
74 carp "[$func] Warning: ", @_;
75 };
76
77 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
78 my($func) = (caller(1))[3];
70c28808 79 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
2ea6032a 80 };
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
1b5ddf23 96# we ne longer need to check this - DBIC has ways of dealing with it
97# specifically ::Storage::DBI::_resolve_bindattrs()
98sub _assert_bindval_matches_bindtype () { 1 };
99
e39f188a 100# poor man's de-qualifier
101sub _quote {
102 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
103 ? $_[1] =~ / ([^\.]+) $ /x
104 : $_[1]
105 );
106}
107
b1d821de 108sub _where_op_NEST {
70c28808 109 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
b1d821de 110 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
70c28808 111 );
b1d821de 112
113 shift->next::method(@_);
114}
115
6a247f33 116# Handle limit-dialect selection
6f4ddea1 117sub select {
6a247f33 118 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
119
120
ad1d374e 121 ($fields, @{$self->{select_bind}}) = $self->_recurse_fields($fields);
6a247f33 122
123 if (defined $offset) {
70c28808 124 $self->throw_exception('A supplied offset must be a non-negative integer')
6a247f33 125 if ( $offset =~ /\D/ or $offset < 0 );
126 }
127 $offset ||= 0;
1cbd3034 128
6a247f33 129 if (defined $limit) {
70c28808 130 $self->throw_exception('A supplied limit must be a positive integer')
6a247f33 131 if ( $limit =~ /\D/ or $limit <= 0 );
132 }
133 elsif ($offset) {
134 $limit = $self->__max_int;
6f4ddea1 135 }
c2b7c5dc 136
a6b68a60 137
6a247f33 138 my ($sql, @bind);
139 if ($limit) {
140 # this is legacy code-flow from SQLA::Limit, it is not set in stone
141
142 ($sql, @bind) = $self->next::method ($table, $fields, $where);
143
67341081 144 my $limiter;
145
146 if( $limiter = $self->can ('emulate_limit') ) {
147 carp_unique(
148 'Support for the legacy emulate_limit() mechanism inherited from '
149 . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
150 . 'DBIC transitions to Data::Query. If your code uses this type of '
151 . 'limit specification please file an RT and provide the source of '
152 . 'your emulate_limit() implementation, so an acceptable upgrade-path '
153 . 'can be devised'
154 );
155 }
156 else {
157 my $dialect = $self->limit_dialect
158 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
159
160 $limiter = $self->can ("_$dialect")
161 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
162 }
6a247f33 163
f74d22e2 164 $sql = $self->$limiter (
165 $sql,
166 { %{$rs_attrs||{}}, _selector_sql => $fields },
167 $limit,
168 $offset
169 );
6a247f33 170 }
171 else {
172 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
173 }
174
49afd714 175 push @{$self->{where_bind}}, @bind;
583a0c65 176
177# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 178 my @all_bind = $self->_assemble_binds;
583a0c65 179
e5372da4 180 $sql .= $self->_lock_select ($rs_attrs->{for})
181 if $rs_attrs->{for};
182
49afd714 183 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 184}
185
186sub _assemble_binds {
187 my $self = shift;
8b31f62e 188 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
6f4ddea1 189}
190
e5372da4 191my $for_syntax = {
192 update => 'FOR UPDATE',
193 shared => 'FOR SHARE',
194};
195sub _lock_select {
196 my ($self, $type) = @_;
8249c09b 197
198 my $sql;
199 if (ref($type) eq 'SCALAR') {
200 $sql = "FOR $$type";
201 }
202 else {
203 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
204 }
205
e5372da4 206 return " $sql";
207}
208
6a247f33 209# Handle default inserts
6f4ddea1 210sub insert {
6a247f33 211# optimized due to hotttnesss
212# my ($self, $table, $data, $options) = @_;
7a72e5a5 213
214 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
215 # which is sadly understood only by MySQL. Change default behavior here,
216 # until SQLA2 comes with proper dialect support
6a247f33 217 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 218 my @bind;
20595c02 219 my $sql = sprintf(
220 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
221 );
28d28903 222
bf51641f 223 if ( ($_[3]||{})->{returning} ) {
224 my $s;
225 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
226 $sql .= $s;
28d28903 227 }
228
bf51641f 229 return ($sql, @bind);
7a72e5a5 230 }
231
6a247f33 232 next::method(@_);
6f4ddea1 233}
234
235sub _recurse_fields {
81446c4f 236 my ($self, $fields) = @_;
6f4ddea1 237 my $ref = ref $fields;
238 return $self->_quote($fields) unless $ref;
239 return $$fields if $ref eq 'SCALAR';
240
241 if ($ref eq 'ARRAY') {
ad1d374e 242 my (@select, @bind);
243 for my $field (@$fields) {
244 my ($select, @new_bind) = $self->_recurse_fields($field);
245 push @select, $select;
246 push @bind, @new_bind;
247 }
248 return (join(', ', @select), @bind);
83e09b5b 249 }
250 elsif ($ref eq 'HASH') {
81446c4f 251 my %hash = %$fields; # shallow copy
83e09b5b 252
50136dd9 253 my $as = delete $hash{-as}; # if supplied
254
ad1d374e 255 my ($func, $rhs, @toomany) = %hash;
81446c4f 256
257 # there should be only one pair
258 if (@toomany) {
70c28808 259 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 260 }
50136dd9 261
ad1d374e 262 if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
70c28808 263 $self->throw_exception (
50136dd9 264 'The select => { distinct => ... } syntax is not supported for multiple columns.'
ad1d374e 265 .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
266 .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
83e09b5b 267 );
6f4ddea1 268 }
83e09b5b 269
ad1d374e 270 my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
50136dd9 271 my $select = sprintf ('%s( %s )%s',
272 $self->_sqlcase($func),
ad1d374e 273 $rhs_sql,
50136dd9 274 $as
0491b597 275 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 276 : ''
277 );
278
ad1d374e 279 return ($select, @rhs_bind);
6f4ddea1 280 }
6f4ddea1 281 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
ad1d374e 282 return @{$$fields};
6f4ddea1 283 }
284 else {
70c28808 285 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 286 }
287}
288
a6b68a60 289
290# this used to be a part of _order_by but is broken out for clarity.
291# What we have been doing forever is hijacking the $order arg of
292# SQLA::select to pass in arbitrary pieces of data (first the group_by,
293# then pretty much the entire resultset attr-hash, as more and more
4a0eed52 294# things in the SQLA space need to have more info about the $rs they
a6b68a60 295# create SQL for. The alternative would be to keep expanding the
296# signature of _select with more and more positional parameters, which
297# is just gross. All hail SQLA2!
298sub _parse_rs_attrs {
1cbd3034 299 my ($self, $arg) = @_;
15827712 300
a6b68a60 301 my $sql = '';
71b788fb 302 my @sqlbind;
303
304 if (
305 $arg->{group_by}
306 and
307 @sqlbind = $self->_recurse_fields($arg->{group_by})
308 ) {
309 $sql .= $self->_sqlcase(' group by ') . shift @sqlbind;
310 push @{$self->{group_bind}}, @sqlbind;
a6b68a60 311 }
1cbd3034 312
71b788fb 313 if (
314 $arg->{having}
315 and
316 @sqlbind = $self->_recurse_where($arg->{having})
317 ) {
318 $sql .= $self->_sqlcase(' having ') . shift @sqlbind;
319 push(@{$self->{having_bind}}, @sqlbind);
a6b68a60 320 }
15827712 321
71b788fb 322 if ($arg->{order_by}) {
323 # unlike the 2 above, _order_by injects into @{...bind...} for us
a6b68a60 324 $sql .= $self->_order_by ($arg->{order_by});
325 }
15827712 326
a6b68a60 327 return $sql;
328}
329
330sub _order_by {
331 my ($self, $arg) = @_;
15827712 332
a6b68a60 333 # check that we are not called in legacy mode (order_by as 4th argument)
71b788fb 334 (
335 ref $arg eq 'HASH'
336 and
337 not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg
338 )
339 ? $self->_parse_rs_attrs ($arg)
340 : do {
341 my ($sql, @bind) = $self->next::method($arg);
342 push @{$self->{order_bind}}, @bind;
343 $sql; # RV
344 }
345 ;
6f4ddea1 346}
347
cb3e87f5 348sub _split_order_chunk {
349 my ($self, $chunk) = @_;
350
351 # strip off sort modifiers, but always succeed, so $1 gets reset
352 $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
353
354 return (
355 $chunk,
356 ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
357 );
358}
359
6f4ddea1 360sub _table {
6a247f33 361# optimized due to hotttnesss
362# my ($self, $from) = @_;
363 if (my $ref = ref $_[1] ) {
364 if ($ref eq 'ARRAY') {
365 return $_[0]->_recurse_from(@{$_[1]});
366 }
367 elsif ($ref eq 'HASH') {
4c2b30d6 368 return $_[0]->_recurse_from($_[1]);
6a247f33 369 }
1bffc6b8 370 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
371 my ($sql, @bind) = @{ ${$_[1]} };
372 push @{$_[0]->{from_bind}}, @bind;
373 return $sql
374 }
6f4ddea1 375 }
6a247f33 376 return $_[0]->next::method ($_[1]);
6f4ddea1 377}
378
b8391c87 379sub _generate_join_clause {
380 my ($self, $join_type) = @_;
381
726c8f65 382 $join_type = $self->{_default_jointype}
383 if ! defined $join_type;
384
b8391c87 385 return sprintf ('%s JOIN ',
726c8f65 386 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 387 );
388}
389
6f4ddea1 390sub _recurse_from {
726c8f65 391 my $self = shift;
726c8f65 392 return join (' ', $self->_gen_from_blocks(@_) );
393}
394
395sub _gen_from_blocks {
396 my ($self, $from, @joins) = @_;
397
398 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 399
726c8f65 400 for (@joins) {
4c2b30d6 401 my ($to, $on) = @$_;
aa82ce29 402
6f4ddea1 403 # check whether a join type exists
6f4ddea1 404 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 405 my $join_type;
406 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
407 $join_type = $to_jt->{-join_type};
408 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 409 }
aa82ce29 410
726c8f65 411 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 412
413 if (ref $to eq 'ARRAY') {
726c8f65 414 push(@j, '(', $self->_recurse_from(@$to), ')');
415 }
416 else {
417 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 418 }
726c8f65 419
a697fa31 420 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 421 push(@j, ' ON ', $sql);
a697fa31 422 push @{$self->{from_bind}}, @bind;
726c8f65 423
424 push @fchunks, join '', @j;
6f4ddea1 425 }
726c8f65 426
427 return @fchunks;
6f4ddea1 428}
429
4c2b30d6 430sub _from_chunk_to_sql {
431 my ($self, $fromspec) = @_;
432
e8885a53 433 return join (' ', do {
434 if (! ref $fromspec) {
435 $self->_quote($fromspec);
436 }
437 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 438 $$fromspec;
e8885a53 439 }
440 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 441 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
442 $$fromspec->[0];
e8885a53 443 }
444 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 445 my ($as, $table, $toomuch) = ( map
446 { $_ => $fromspec->{$_} }
447 ( grep { $_ !~ /^\-/ } keys %$fromspec )
448 );
6f4ddea1 449
70c28808 450 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 451 if defined $toomuch;
6f4ddea1 452
4c2b30d6 453 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 454 }
455 else {
456 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
457 }
458 });
6f4ddea1 459}
460
461sub _join_condition {
462 my ($self, $cond) = @_;
4c2b30d6 463
a697fa31 464 # Backcompat for the old days when a plain hashref
465 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
a697fa31 466 if (
467 ref $cond eq 'HASH'
468 and
469 keys %$cond == 1
470 and
471 (keys %$cond)[0] =~ /\./
472 and
473 ! ref ( (values %$cond)[0] )
474 ) {
1efc866d 475 carp_unique(
476 "ResultSet {from} structures with conditions not conforming to the "
477 . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
478 . "{from} altogether, or express the condition properly using the "
479 . "{ -ident => ... } operator"
480 );
a697fa31 481 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 482 }
a697fa31 483 elsif ( ref $cond eq 'ARRAY' ) {
484 # do our own ORing so that the hashref-shim above is invoked
9aae3566 485 my @parts;
486 my @binds;
487 foreach my $c (@$cond) {
488 my ($sql, @bind) = $self->_join_condition($c);
489 push @binds, @bind;
490 push @parts, $sql;
491 }
492 return join(' OR ', @parts), @binds;
6f4ddea1 493 }
a697fa31 494
495 return $self->_recurse_where($cond);
6f4ddea1 496}
497
66137dff 498# This is hideously ugly, but SQLA does not understand multicol IN expressions
499# FIXME TEMPORARY - DQ should have native syntax for this
500# moved here to raise API questions
501#
502# !!! EXPERIMENTAL API !!! WILL CHANGE !!!
503sub _where_op_multicolumn_in {
504 my ($self, $lhs, $rhs) = @_;
505
506 if (! ref $lhs or ref $lhs eq 'ARRAY') {
507 my (@sql, @bind);
508 for (ref $lhs ? @$lhs : $lhs) {
509 if (! ref $_) {
510 push @sql, $self->_quote($_);
511 }
512 elsif (ref $_ eq 'SCALAR') {
513 push @sql, $$_;
514 }
515 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
516 my ($s, @b) = @$$_;
517 push @sql, $s;
518 push @bind, @b;
519 }
520 else {
521 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
522 }
523 }
524 $lhs = \[ join(', ', @sql), @bind];
525 }
526 elsif (ref $lhs eq 'SCALAR') {
527 $lhs = \[ $$lhs ];
528 }
529 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
530 # noop
531 }
532 else {
533 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
534 }
535
536 # is this proper...?
537 $rhs = \[ $self->_recurse_where($rhs) ];
538
539 for ($lhs, $rhs) {
540 $$_->[0] = "( $$_->[0] )"
1d1ccc94 541 unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
66137dff 542 }
543
544 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
545}
546
a2bd3796 547=head1 FURTHER QUESTIONS?
d5dedbd6 548
a2bd3796 549Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
d5dedbd6 550
a2bd3796 551=head1 COPYRIGHT AND LICENSE
d5dedbd6 552
a2bd3796 553This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
554by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
555redistribute it and/or modify it under the same terms as the
556L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
d5dedbd6 557
558=cut
a2bd3796 559
5601;