The weird scan-for-binds-before-scan was obviated by a9e985b7
[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 = '';
1cbd3034 302
0542ec57 303 if ($arg->{group_by}) {
ad1d374e 304 if ( my ($group_sql, @group_bind) = $self->_recurse_fields($arg->{group_by}) ) {
305 $sql .= $self->_sqlcase(' group by ') . $group_sql;
306 push @{$self->{group_bind}}, @group_bind;
0542ec57 307 }
a6b68a60 308 }
1cbd3034 309
a6b68a60 310 if (defined $arg->{having}) {
311 my ($frag, @bind) = $self->_recurse_where($arg->{having});
312 push(@{$self->{having_bind}}, @bind);
313 $sql .= $self->_sqlcase(' having ') . $frag;
314 }
15827712 315
a6b68a60 316 if (defined $arg->{order_by}) {
317 $sql .= $self->_order_by ($arg->{order_by});
318 }
15827712 319
a6b68a60 320 return $sql;
321}
322
323sub _order_by {
324 my ($self, $arg) = @_;
15827712 325
a6b68a60 326 # check that we are not called in legacy mode (order_by as 4th argument)
327 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
328 return $self->_parse_rs_attrs ($arg);
fde3719a 329 }
1cbd3034 330 else {
6a247f33 331 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 332 push @{$self->{order_bind}}, @bind;
1cbd3034 333 return $sql;
fd4cb60a 334 }
6f4ddea1 335}
336
cb3e87f5 337sub _split_order_chunk {
338 my ($self, $chunk) = @_;
339
340 # strip off sort modifiers, but always succeed, so $1 gets reset
341 $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
342
343 return (
344 $chunk,
345 ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
346 );
347}
348
6f4ddea1 349sub _table {
6a247f33 350# optimized due to hotttnesss
351# my ($self, $from) = @_;
352 if (my $ref = ref $_[1] ) {
353 if ($ref eq 'ARRAY') {
354 return $_[0]->_recurse_from(@{$_[1]});
355 }
356 elsif ($ref eq 'HASH') {
4c2b30d6 357 return $_[0]->_recurse_from($_[1]);
6a247f33 358 }
1bffc6b8 359 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
360 my ($sql, @bind) = @{ ${$_[1]} };
361 push @{$_[0]->{from_bind}}, @bind;
362 return $sql
363 }
6f4ddea1 364 }
6a247f33 365 return $_[0]->next::method ($_[1]);
6f4ddea1 366}
367
b8391c87 368sub _generate_join_clause {
369 my ($self, $join_type) = @_;
370
726c8f65 371 $join_type = $self->{_default_jointype}
372 if ! defined $join_type;
373
b8391c87 374 return sprintf ('%s JOIN ',
726c8f65 375 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 376 );
377}
378
6f4ddea1 379sub _recurse_from {
726c8f65 380 my $self = shift;
726c8f65 381 return join (' ', $self->_gen_from_blocks(@_) );
382}
383
384sub _gen_from_blocks {
385 my ($self, $from, @joins) = @_;
386
387 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 388
726c8f65 389 for (@joins) {
4c2b30d6 390 my ($to, $on) = @$_;
aa82ce29 391
6f4ddea1 392 # check whether a join type exists
6f4ddea1 393 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 394 my $join_type;
395 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
396 $join_type = $to_jt->{-join_type};
397 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 398 }
aa82ce29 399
726c8f65 400 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 401
402 if (ref $to eq 'ARRAY') {
726c8f65 403 push(@j, '(', $self->_recurse_from(@$to), ')');
404 }
405 else {
406 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 407 }
726c8f65 408
a697fa31 409 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 410 push(@j, ' ON ', $sql);
a697fa31 411 push @{$self->{from_bind}}, @bind;
726c8f65 412
413 push @fchunks, join '', @j;
6f4ddea1 414 }
726c8f65 415
416 return @fchunks;
6f4ddea1 417}
418
4c2b30d6 419sub _from_chunk_to_sql {
420 my ($self, $fromspec) = @_;
421
e8885a53 422 return join (' ', do {
423 if (! ref $fromspec) {
424 $self->_quote($fromspec);
425 }
426 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 427 $$fromspec;
e8885a53 428 }
429 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 430 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
431 $$fromspec->[0];
e8885a53 432 }
433 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 434 my ($as, $table, $toomuch) = ( map
435 { $_ => $fromspec->{$_} }
436 ( grep { $_ !~ /^\-/ } keys %$fromspec )
437 );
6f4ddea1 438
70c28808 439 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 440 if defined $toomuch;
6f4ddea1 441
4c2b30d6 442 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 443 }
444 else {
445 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
446 }
447 });
6f4ddea1 448}
449
450sub _join_condition {
451 my ($self, $cond) = @_;
4c2b30d6 452
a697fa31 453 # Backcompat for the old days when a plain hashref
454 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
a697fa31 455 if (
456 ref $cond eq 'HASH'
457 and
458 keys %$cond == 1
459 and
460 (keys %$cond)[0] =~ /\./
461 and
462 ! ref ( (values %$cond)[0] )
463 ) {
1efc866d 464 carp_unique(
465 "ResultSet {from} structures with conditions not conforming to the "
466 . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
467 . "{from} altogether, or express the condition properly using the "
468 . "{ -ident => ... } operator"
469 );
a697fa31 470 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 471 }
a697fa31 472 elsif ( ref $cond eq 'ARRAY' ) {
473 # do our own ORing so that the hashref-shim above is invoked
9aae3566 474 my @parts;
475 my @binds;
476 foreach my $c (@$cond) {
477 my ($sql, @bind) = $self->_join_condition($c);
478 push @binds, @bind;
479 push @parts, $sql;
480 }
481 return join(' OR ', @parts), @binds;
6f4ddea1 482 }
a697fa31 483
484 return $self->_recurse_where($cond);
6f4ddea1 485}
486
66137dff 487# This is hideously ugly, but SQLA does not understand multicol IN expressions
488# FIXME TEMPORARY - DQ should have native syntax for this
489# moved here to raise API questions
490#
491# !!! EXPERIMENTAL API !!! WILL CHANGE !!!
492sub _where_op_multicolumn_in {
493 my ($self, $lhs, $rhs) = @_;
494
495 if (! ref $lhs or ref $lhs eq 'ARRAY') {
496 my (@sql, @bind);
497 for (ref $lhs ? @$lhs : $lhs) {
498 if (! ref $_) {
499 push @sql, $self->_quote($_);
500 }
501 elsif (ref $_ eq 'SCALAR') {
502 push @sql, $$_;
503 }
504 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
505 my ($s, @b) = @$$_;
506 push @sql, $s;
507 push @bind, @b;
508 }
509 else {
510 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
511 }
512 }
513 $lhs = \[ join(', ', @sql), @bind];
514 }
515 elsif (ref $lhs eq 'SCALAR') {
516 $lhs = \[ $$lhs ];
517 }
518 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
519 # noop
520 }
521 else {
522 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
523 }
524
525 # is this proper...?
526 $rhs = \[ $self->_recurse_where($rhs) ];
527
528 for ($lhs, $rhs) {
529 $$_->[0] = "( $$_->[0] )"
1d1ccc94 530 unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
66137dff 531 }
532
533 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
534}
535
a2bd3796 536=head1 FURTHER QUESTIONS?
d5dedbd6 537
a2bd3796 538Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
d5dedbd6 539
a2bd3796 540=head1 COPYRIGHT AND LICENSE
d5dedbd6 541
a2bd3796 542This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
543by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
544redistribute it and/or modify it under the same terms as the
545L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.
d5dedbd6 546
547=cut
a2bd3796 548
5491;