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