Some cleanups around loading/use of DBIx::Class::Exception (no func. changes)
[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
e39f188a 88# poor man's de-qualifier
89sub _quote {
90 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
91 ? $_[1] =~ / ([^\.]+) $ /x
92 : $_[1]
93 );
94}
95
b1d821de 96sub _where_op_NEST {
70c28808 97 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
b1d821de 98 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
70c28808 99 );
b1d821de 100
101 shift->next::method(@_);
102}
103
6a247f33 104# Handle limit-dialect selection
6f4ddea1 105sub select {
6a247f33 106 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
107
108
109 $fields = $self->_recurse_fields($fields);
110
111 if (defined $offset) {
70c28808 112 $self->throw_exception('A supplied offset must be a non-negative integer')
6a247f33 113 if ( $offset =~ /\D/ or $offset < 0 );
114 }
115 $offset ||= 0;
1cbd3034 116
6a247f33 117 if (defined $limit) {
70c28808 118 $self->throw_exception('A supplied limit must be a positive integer')
6a247f33 119 if ( $limit =~ /\D/ or $limit <= 0 );
120 }
121 elsif ($offset) {
122 $limit = $self->__max_int;
6f4ddea1 123 }
c2b7c5dc 124
a6b68a60 125
6a247f33 126 my ($sql, @bind);
127 if ($limit) {
128 # this is legacy code-flow from SQLA::Limit, it is not set in stone
129
130 ($sql, @bind) = $self->next::method ($table, $fields, $where);
131
67341081 132 my $limiter;
133
134 if( $limiter = $self->can ('emulate_limit') ) {
135 carp_unique(
136 'Support for the legacy emulate_limit() mechanism inherited from '
137 . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
138 . 'DBIC transitions to Data::Query. If your code uses this type of '
139 . 'limit specification please file an RT and provide the source of '
140 . 'your emulate_limit() implementation, so an acceptable upgrade-path '
141 . 'can be devised'
142 );
143 }
144 else {
145 my $dialect = $self->limit_dialect
146 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
147
148 $limiter = $self->can ("_$dialect")
149 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
150 }
6a247f33 151
f74d22e2 152 $sql = $self->$limiter (
153 $sql,
154 { %{$rs_attrs||{}}, _selector_sql => $fields },
155 $limit,
156 $offset
157 );
6a247f33 158 }
159 else {
160 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
161 }
162
49afd714 163 push @{$self->{where_bind}}, @bind;
583a0c65 164
165# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 166 my @all_bind = $self->_assemble_binds;
583a0c65 167
e5372da4 168 $sql .= $self->_lock_select ($rs_attrs->{for})
169 if $rs_attrs->{for};
170
49afd714 171 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 172}
173
174sub _assemble_binds {
175 my $self = shift;
8b31f62e 176 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
6f4ddea1 177}
178
e5372da4 179my $for_syntax = {
180 update => 'FOR UPDATE',
181 shared => 'FOR SHARE',
182};
183sub _lock_select {
184 my ($self, $type) = @_;
8249c09b 185
186 my $sql;
187 if (ref($type) eq 'SCALAR') {
188 $sql = "FOR $$type";
189 }
190 else {
191 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
192 }
193
e5372da4 194 return " $sql";
195}
196
6a247f33 197# Handle default inserts
6f4ddea1 198sub insert {
6a247f33 199# optimized due to hotttnesss
200# my ($self, $table, $data, $options) = @_;
7a72e5a5 201
202 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
203 # which is sadly understood only by MySQL. Change default behavior here,
204 # until SQLA2 comes with proper dialect support
6a247f33 205 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 206 my @bind;
20595c02 207 my $sql = sprintf(
208 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
209 );
28d28903 210
bf51641f 211 if ( ($_[3]||{})->{returning} ) {
212 my $s;
213 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
214 $sql .= $s;
28d28903 215 }
216
bf51641f 217 return ($sql, @bind);
7a72e5a5 218 }
219
6a247f33 220 next::method(@_);
6f4ddea1 221}
222
223sub _recurse_fields {
81446c4f 224 my ($self, $fields) = @_;
6f4ddea1 225 my $ref = ref $fields;
226 return $self->_quote($fields) unless $ref;
227 return $$fields if $ref eq 'SCALAR';
228
229 if ($ref eq 'ARRAY') {
81446c4f 230 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 231 }
232 elsif ($ref eq 'HASH') {
81446c4f 233 my %hash = %$fields; # shallow copy
83e09b5b 234
50136dd9 235 my $as = delete $hash{-as}; # if supplied
236
81446c4f 237 my ($func, $args, @toomany) = %hash;
238
239 # there should be only one pair
240 if (@toomany) {
70c28808 241 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 242 }
50136dd9 243
244 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
70c28808 245 $self->throw_exception (
50136dd9 246 'The select => { distinct => ... } syntax is not supported for multiple columns.'
247 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
248 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 249 );
6f4ddea1 250 }
83e09b5b 251
50136dd9 252 my $select = sprintf ('%s( %s )%s',
253 $self->_sqlcase($func),
254 $self->_recurse_fields($args),
255 $as
0491b597 256 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 257 : ''
258 );
259
83e09b5b 260 return $select;
6f4ddea1 261 }
262 # Is the second check absolutely necessary?
263 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 264 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
265 return $$fields->[0];
6f4ddea1 266 }
267 else {
70c28808 268 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 269 }
270}
271
a6b68a60 272
273# this used to be a part of _order_by but is broken out for clarity.
274# What we have been doing forever is hijacking the $order arg of
275# SQLA::select to pass in arbitrary pieces of data (first the group_by,
276# then pretty much the entire resultset attr-hash, as more and more
277# things in the SQLA space need to have mopre info about the $rs they
278# create SQL for. The alternative would be to keep expanding the
279# signature of _select with more and more positional parameters, which
280# is just gross. All hail SQLA2!
281sub _parse_rs_attrs {
1cbd3034 282 my ($self, $arg) = @_;
15827712 283
a6b68a60 284 my $sql = '';
1cbd3034 285
0542ec57 286 if ($arg->{group_by}) {
287 # horible horrible, waiting for refactor
288 local $self->{select_bind};
289 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
290 $sql .= $self->_sqlcase(' group by ') . $g;
291 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
292 }
a6b68a60 293 }
1cbd3034 294
a6b68a60 295 if (defined $arg->{having}) {
296 my ($frag, @bind) = $self->_recurse_where($arg->{having});
297 push(@{$self->{having_bind}}, @bind);
298 $sql .= $self->_sqlcase(' having ') . $frag;
299 }
15827712 300
a6b68a60 301 if (defined $arg->{order_by}) {
302 $sql .= $self->_order_by ($arg->{order_by});
303 }
15827712 304
a6b68a60 305 return $sql;
306}
307
308sub _order_by {
309 my ($self, $arg) = @_;
15827712 310
a6b68a60 311 # check that we are not called in legacy mode (order_by as 4th argument)
312 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
313 return $self->_parse_rs_attrs ($arg);
fde3719a 314 }
1cbd3034 315 else {
6a247f33 316 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 317 push @{$self->{order_bind}}, @bind;
1cbd3034 318 return $sql;
fd4cb60a 319 }
6f4ddea1 320}
321
322sub _table {
6a247f33 323# optimized due to hotttnesss
324# my ($self, $from) = @_;
325 if (my $ref = ref $_[1] ) {
326 if ($ref eq 'ARRAY') {
327 return $_[0]->_recurse_from(@{$_[1]});
328 }
329 elsif ($ref eq 'HASH') {
4c2b30d6 330 return $_[0]->_recurse_from($_[1]);
6a247f33 331 }
1bffc6b8 332 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
333 my ($sql, @bind) = @{ ${$_[1]} };
334 push @{$_[0]->{from_bind}}, @bind;
335 return $sql
336 }
6f4ddea1 337 }
6a247f33 338 return $_[0]->next::method ($_[1]);
6f4ddea1 339}
340
b8391c87 341sub _generate_join_clause {
342 my ($self, $join_type) = @_;
343
726c8f65 344 $join_type = $self->{_default_jointype}
345 if ! defined $join_type;
346
b8391c87 347 return sprintf ('%s JOIN ',
726c8f65 348 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 349 );
350}
351
6f4ddea1 352sub _recurse_from {
726c8f65 353 my $self = shift;
354
355 return join (' ', $self->_gen_from_blocks(@_) );
356}
357
358sub _gen_from_blocks {
359 my ($self, $from, @joins) = @_;
360
361 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 362
726c8f65 363 for (@joins) {
4c2b30d6 364 my ($to, $on) = @$_;
aa82ce29 365
6f4ddea1 366 # check whether a join type exists
6f4ddea1 367 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 368 my $join_type;
369 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
370 $join_type = $to_jt->{-join_type};
371 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 372 }
aa82ce29 373
726c8f65 374 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 375
376 if (ref $to eq 'ARRAY') {
726c8f65 377 push(@j, '(', $self->_recurse_from(@$to), ')');
378 }
379 else {
380 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 381 }
726c8f65 382
a697fa31 383 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 384 push(@j, ' ON ', $sql);
a697fa31 385 push @{$self->{from_bind}}, @bind;
726c8f65 386
387 push @fchunks, join '', @j;
6f4ddea1 388 }
726c8f65 389
390 return @fchunks;
6f4ddea1 391}
392
4c2b30d6 393sub _from_chunk_to_sql {
394 my ($self, $fromspec) = @_;
395
e8885a53 396 return join (' ', do {
397 if (! ref $fromspec) {
398 $self->_quote($fromspec);
399 }
400 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 401 $$fromspec;
e8885a53 402 }
403 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 404 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
405 $$fromspec->[0];
e8885a53 406 }
407 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 408 my ($as, $table, $toomuch) = ( map
409 { $_ => $fromspec->{$_} }
410 ( grep { $_ !~ /^\-/ } keys %$fromspec )
411 );
6f4ddea1 412
70c28808 413 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 414 if defined $toomuch;
6f4ddea1 415
4c2b30d6 416 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 417 }
418 else {
419 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
420 }
421 });
6f4ddea1 422}
423
424sub _join_condition {
425 my ($self, $cond) = @_;
4c2b30d6 426
a697fa31 427 # Backcompat for the old days when a plain hashref
428 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
429 # Once things settle we should start warning here so that
430 # folks unroll their hacks
431 if (
432 ref $cond eq 'HASH'
433 and
434 keys %$cond == 1
435 and
436 (keys %$cond)[0] =~ /\./
437 and
438 ! ref ( (values %$cond)[0] )
439 ) {
440 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 441 }
a697fa31 442 elsif ( ref $cond eq 'ARRAY' ) {
443 # do our own ORing so that the hashref-shim above is invoked
9aae3566 444 my @parts;
445 my @binds;
446 foreach my $c (@$cond) {
447 my ($sql, @bind) = $self->_join_condition($c);
448 push @binds, @bind;
449 push @parts, $sql;
450 }
451 return join(' OR ', @parts), @binds;
6f4ddea1 452 }
a697fa31 453
454 return $self->_recurse_where($cond);
6f4ddea1 455}
456
66137dff 457# This is hideously ugly, but SQLA does not understand multicol IN expressions
458# FIXME TEMPORARY - DQ should have native syntax for this
459# moved here to raise API questions
460#
461# !!! EXPERIMENTAL API !!! WILL CHANGE !!!
462sub _where_op_multicolumn_in {
463 my ($self, $lhs, $rhs) = @_;
464
465 if (! ref $lhs or ref $lhs eq 'ARRAY') {
466 my (@sql, @bind);
467 for (ref $lhs ? @$lhs : $lhs) {
468 if (! ref $_) {
469 push @sql, $self->_quote($_);
470 }
471 elsif (ref $_ eq 'SCALAR') {
472 push @sql, $$_;
473 }
474 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
475 my ($s, @b) = @$$_;
476 push @sql, $s;
477 push @bind, @b;
478 }
479 else {
480 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
481 }
482 }
483 $lhs = \[ join(', ', @sql), @bind];
484 }
485 elsif (ref $lhs eq 'SCALAR') {
486 $lhs = \[ $$lhs ];
487 }
488 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
489 # noop
490 }
491 else {
492 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
493 }
494
495 # is this proper...?
496 $rhs = \[ $self->_recurse_where($rhs) ];
497
498 for ($lhs, $rhs) {
499 $$_->[0] = "( $$_->[0] )"
500 unless $$_->[0] =~ /^ \s* \( .* \) \s* ^/xs;
501 }
502
503 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
504}
505
6f4ddea1 5061;
d5dedbd6 507
508=head1 AUTHORS
509
510See L<DBIx::Class/CONTRIBUTORS>.
511
512=head1 LICENSE
513
514You may distribute this code under the same terms as Perl itself.
515
516=cut