Deprecate emulate_limit() - can not be sanely supported by DQ
[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;
43use DBIx::Class::Exception;
e8fc51c7 44use namespace::clean;
b2b22cd6 45
6a247f33 46__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
47
3f5b99fe 48# for when I need a normalized l/r pair
49sub _quote_chars {
50 map
51 { defined $_ ? $_ : '' }
52 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
53 ;
54}
55
70c28808 56# FIXME when we bring in the storage weaklink, check its schema
57# weaklink and channel through $schema->throw_exception
58sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
59
b2b22cd6 60BEGIN {
2ea6032a 61 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
70c28808 62 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
b2b22cd6 63 no warnings qw/redefine/;
2ea6032a 64
65 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
66 my($func) = (caller(1))[3];
67 carp "[$func] Warning: ", @_;
68 };
69
70 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
71 my($func) = (caller(1))[3];
70c28808 72 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
2ea6032a 73 };
9c1700e3 74
75 # Current SQLA pollutes its namespace - clean for the time being
76 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
b2b22cd6 77}
6f4ddea1 78
e9657379 79# the "oh noes offset/top without limit" constant
fcb7fcbb 80# limited to 31 bits for sanity (and consistency,
81# since it may be handed to the like of sprintf %u)
82#
83# Also *some* builds of SQLite fail the test
84# some_column BETWEEN ? AND ?: 1, 4294967295
85# with the proper integer bind attrs
86#
6a247f33 87# Implemented as a method, since ::Storage::DBI also
88# refers to it (i.e. for the case of software_limit or
89# as the value to abuse with MSSQL ordered subqueries)
fcb7fcbb 90sub __max_int () { 0x7FFFFFFF };
e9657379 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
113 $fields = $self->_recurse_fields($fields);
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') {
81446c4f 234 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 235 }
236 elsif ($ref eq 'HASH') {
81446c4f 237 my %hash = %$fields; # shallow copy
83e09b5b 238
50136dd9 239 my $as = delete $hash{-as}; # if supplied
240
81446c4f 241 my ($func, $args, @toomany) = %hash;
242
243 # there should be only one pair
244 if (@toomany) {
70c28808 245 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 246 }
50136dd9 247
248 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
70c28808 249 $self->throw_exception (
50136dd9 250 'The select => { distinct => ... } syntax is not supported for multiple columns.'
251 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
252 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 253 );
6f4ddea1 254 }
83e09b5b 255
50136dd9 256 my $select = sprintf ('%s( %s )%s',
257 $self->_sqlcase($func),
258 $self->_recurse_fields($args),
259 $as
0491b597 260 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 261 : ''
262 );
263
83e09b5b 264 return $select;
6f4ddea1 265 }
266 # Is the second check absolutely necessary?
267 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 268 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
269 return $$fields->[0];
6f4ddea1 270 }
271 else {
70c28808 272 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 273 }
274}
275
a6b68a60 276
277# this used to be a part of _order_by but is broken out for clarity.
278# What we have been doing forever is hijacking the $order arg of
279# SQLA::select to pass in arbitrary pieces of data (first the group_by,
280# then pretty much the entire resultset attr-hash, as more and more
281# things in the SQLA space need to have mopre info about the $rs they
282# create SQL for. The alternative would be to keep expanding the
283# signature of _select with more and more positional parameters, which
284# is just gross. All hail SQLA2!
285sub _parse_rs_attrs {
1cbd3034 286 my ($self, $arg) = @_;
15827712 287
a6b68a60 288 my $sql = '';
1cbd3034 289
0542ec57 290 if ($arg->{group_by}) {
291 # horible horrible, waiting for refactor
292 local $self->{select_bind};
293 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
294 $sql .= $self->_sqlcase(' group by ') . $g;
295 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
296 }
a6b68a60 297 }
1cbd3034 298
a6b68a60 299 if (defined $arg->{having}) {
300 my ($frag, @bind) = $self->_recurse_where($arg->{having});
301 push(@{$self->{having_bind}}, @bind);
302 $sql .= $self->_sqlcase(' having ') . $frag;
303 }
15827712 304
a6b68a60 305 if (defined $arg->{order_by}) {
306 $sql .= $self->_order_by ($arg->{order_by});
307 }
15827712 308
a6b68a60 309 return $sql;
310}
311
312sub _order_by {
313 my ($self, $arg) = @_;
15827712 314
a6b68a60 315 # check that we are not called in legacy mode (order_by as 4th argument)
316 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
317 return $self->_parse_rs_attrs ($arg);
fde3719a 318 }
1cbd3034 319 else {
6a247f33 320 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 321 push @{$self->{order_bind}}, @bind;
1cbd3034 322 return $sql;
fd4cb60a 323 }
6f4ddea1 324}
325
326sub _table {
6a247f33 327# optimized due to hotttnesss
328# my ($self, $from) = @_;
329 if (my $ref = ref $_[1] ) {
330 if ($ref eq 'ARRAY') {
331 return $_[0]->_recurse_from(@{$_[1]});
332 }
333 elsif ($ref eq 'HASH') {
4c2b30d6 334 return $_[0]->_recurse_from($_[1]);
6a247f33 335 }
1bffc6b8 336 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
337 my ($sql, @bind) = @{ ${$_[1]} };
338 push @{$_[0]->{from_bind}}, @bind;
339 return $sql
340 }
6f4ddea1 341 }
6a247f33 342 return $_[0]->next::method ($_[1]);
6f4ddea1 343}
344
b8391c87 345sub _generate_join_clause {
346 my ($self, $join_type) = @_;
347
726c8f65 348 $join_type = $self->{_default_jointype}
349 if ! defined $join_type;
350
b8391c87 351 return sprintf ('%s JOIN ',
726c8f65 352 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 353 );
354}
355
6f4ddea1 356sub _recurse_from {
726c8f65 357 my $self = shift;
358
359 return join (' ', $self->_gen_from_blocks(@_) );
360}
361
362sub _gen_from_blocks {
363 my ($self, $from, @joins) = @_;
364
365 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 366
726c8f65 367 for (@joins) {
4c2b30d6 368 my ($to, $on) = @$_;
aa82ce29 369
6f4ddea1 370 # check whether a join type exists
6f4ddea1 371 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 372 my $join_type;
373 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
374 $join_type = $to_jt->{-join_type};
375 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 376 }
aa82ce29 377
726c8f65 378 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 379
380 if (ref $to eq 'ARRAY') {
726c8f65 381 push(@j, '(', $self->_recurse_from(@$to), ')');
382 }
383 else {
384 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 385 }
726c8f65 386
a697fa31 387 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 388 push(@j, ' ON ', $sql);
a697fa31 389 push @{$self->{from_bind}}, @bind;
726c8f65 390
391 push @fchunks, join '', @j;
6f4ddea1 392 }
726c8f65 393
394 return @fchunks;
6f4ddea1 395}
396
4c2b30d6 397sub _from_chunk_to_sql {
398 my ($self, $fromspec) = @_;
399
e8885a53 400 return join (' ', do {
401 if (! ref $fromspec) {
402 $self->_quote($fromspec);
403 }
404 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 405 $$fromspec;
e8885a53 406 }
407 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 408 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
409 $$fromspec->[0];
e8885a53 410 }
411 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 412 my ($as, $table, $toomuch) = ( map
413 { $_ => $fromspec->{$_} }
414 ( grep { $_ !~ /^\-/ } keys %$fromspec )
415 );
6f4ddea1 416
70c28808 417 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 418 if defined $toomuch;
6f4ddea1 419
4c2b30d6 420 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 421 }
422 else {
423 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
424 }
425 });
6f4ddea1 426}
427
428sub _join_condition {
429 my ($self, $cond) = @_;
4c2b30d6 430
a697fa31 431 # Backcompat for the old days when a plain hashref
432 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
433 # Once things settle we should start warning here so that
434 # folks unroll their hacks
435 if (
436 ref $cond eq 'HASH'
437 and
438 keys %$cond == 1
439 and
440 (keys %$cond)[0] =~ /\./
441 and
442 ! ref ( (values %$cond)[0] )
443 ) {
444 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 445 }
a697fa31 446 elsif ( ref $cond eq 'ARRAY' ) {
447 # do our own ORing so that the hashref-shim above is invoked
9aae3566 448 my @parts;
449 my @binds;
450 foreach my $c (@$cond) {
451 my ($sql, @bind) = $self->_join_condition($c);
452 push @binds, @bind;
453 push @parts, $sql;
454 }
455 return join(' OR ', @parts), @binds;
6f4ddea1 456 }
a697fa31 457
458 return $self->_recurse_where($cond);
6f4ddea1 459}
460
6f4ddea1 4611;
d5dedbd6 462
463=head1 AUTHORS
464
465See L<DBIx::Class/CONTRIBUTORS>.
466
467=head1 LICENSE
468
469You may distribute this code under the same terms as Perl itself.
470
471=cut