Fix unique constraint violations in Ordered.pm blanket movement (RT#79773)
[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
2bb4c37b 30=item * The L</-ident> operator
e6600283 31
2bb4c37b 32=item * The L</-value> operator
41519379 33
d5dedbd6 34=back
35
36=cut
6a247f33 37
38use base qw/
d5dedbd6 39 DBIx::Class::SQLMaker::LimitDialects
6a247f33 40 SQL::Abstract
70c28808 41 DBIx::Class
6a247f33 42/;
43use mro 'c3';
a697fa31 44
6298a324 45use Sub::Name 'subname';
70c28808 46use DBIx::Class::Carp;
47use DBIx::Class::Exception;
e8fc51c7 48use namespace::clean;
b2b22cd6 49
6a247f33 50__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
51
3f5b99fe 52# for when I need a normalized l/r pair
53sub _quote_chars {
54 map
55 { defined $_ ? $_ : '' }
56 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
57 ;
58}
59
70c28808 60# FIXME when we bring in the storage weaklink, check its schema
61# weaklink and channel through $schema->throw_exception
62sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
63
b2b22cd6 64BEGIN {
2ea6032a 65 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
70c28808 66 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
b2b22cd6 67 no warnings qw/redefine/;
2ea6032a 68
69 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
70 my($func) = (caller(1))[3];
71 carp "[$func] Warning: ", @_;
72 };
73
74 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
75 my($func) = (caller(1))[3];
70c28808 76 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
2ea6032a 77 };
9c1700e3 78
79 # Current SQLA pollutes its namespace - clean for the time being
80 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
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
e39f188a 96# poor man's de-qualifier
97sub _quote {
98 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
99 ? $_[1] =~ / ([^\.]+) $ /x
100 : $_[1]
101 );
102}
103
e6600283 104sub new {
105 my $self = shift->next::method(@_);
106
41519379 107 # use the same coderefs, they are prepared to handle both cases
108 my @extra_dbic_syntax = (
109 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
110 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
111 );
112
113 push @{$self->{special_ops}}, @extra_dbic_syntax;
114 push @{$self->{unary_ops}}, @extra_dbic_syntax;
e6600283 115
116 $self;
117}
118
119sub _where_op_IDENT {
120 my $self = shift;
121 my ($op, $rhs) = splice @_, -2;
122 if (ref $rhs) {
70c28808 123 $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
e6600283 124 }
125
41519379 126 # in case we are called as a top level special op (no '=')
e6600283 127 my $lhs = shift;
128
129 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
130
131 return $lhs
132 ? "$lhs = $rhs"
133 : $rhs
134 ;
135}
136
41519379 137sub _where_op_VALUE {
138 my $self = shift;
139 my ($op, $rhs) = splice @_, -2;
140
141 # in case we are called as a top level special op (no '=')
142 my $lhs = shift;
143
144 my @bind = [
70c28808 145 ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
41519379 146 $rhs
147 ];
148
149 return $lhs
150 ? (
151 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
152 @bind
153 )
154 : (
155 $self->_convert('?'),
156 @bind,
157 )
158 ;
159}
160
b1d821de 161sub _where_op_NEST {
70c28808 162 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
b1d821de 163 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
70c28808 164 );
b1d821de 165
166 shift->next::method(@_);
167}
168
6a247f33 169# Handle limit-dialect selection
6f4ddea1 170sub select {
6a247f33 171 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
172
173
174 $fields = $self->_recurse_fields($fields);
175
176 if (defined $offset) {
70c28808 177 $self->throw_exception('A supplied offset must be a non-negative integer')
6a247f33 178 if ( $offset =~ /\D/ or $offset < 0 );
179 }
180 $offset ||= 0;
1cbd3034 181
6a247f33 182 if (defined $limit) {
70c28808 183 $self->throw_exception('A supplied limit must be a positive integer')
6a247f33 184 if ( $limit =~ /\D/ or $limit <= 0 );
185 }
186 elsif ($offset) {
187 $limit = $self->__max_int;
6f4ddea1 188 }
c2b7c5dc 189
a6b68a60 190
6a247f33 191 my ($sql, @bind);
192 if ($limit) {
193 # this is legacy code-flow from SQLA::Limit, it is not set in stone
194
195 ($sql, @bind) = $self->next::method ($table, $fields, $where);
196
197 my $limiter =
198 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
199 ||
200 do {
201 my $dialect = $self->limit_dialect
70c28808 202 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
6a247f33 203 $self->can ("_$dialect")
70c28808 204 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 205 }
206 ;
207
f74d22e2 208 $sql = $self->$limiter (
209 $sql,
210 { %{$rs_attrs||{}}, _selector_sql => $fields },
211 $limit,
212 $offset
213 );
6a247f33 214 }
215 else {
216 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
217 }
218
49afd714 219 push @{$self->{where_bind}}, @bind;
583a0c65 220
221# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 222 my @all_bind = $self->_assemble_binds;
583a0c65 223
e5372da4 224 $sql .= $self->_lock_select ($rs_attrs->{for})
225 if $rs_attrs->{for};
226
49afd714 227 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 228}
229
230sub _assemble_binds {
231 my $self = shift;
8b31f62e 232 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
6f4ddea1 233}
234
e5372da4 235my $for_syntax = {
236 update => 'FOR UPDATE',
237 shared => 'FOR SHARE',
238};
239sub _lock_select {
240 my ($self, $type) = @_;
8249c09b 241
242 my $sql;
243 if (ref($type) eq 'SCALAR') {
244 $sql = "FOR $$type";
245 }
246 else {
247 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
248 }
249
e5372da4 250 return " $sql";
251}
252
6a247f33 253# Handle default inserts
6f4ddea1 254sub insert {
6a247f33 255# optimized due to hotttnesss
256# my ($self, $table, $data, $options) = @_;
7a72e5a5 257
258 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
259 # which is sadly understood only by MySQL. Change default behavior here,
260 # until SQLA2 comes with proper dialect support
6a247f33 261 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 262 my @bind;
20595c02 263 my $sql = sprintf(
264 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
265 );
28d28903 266
bf51641f 267 if ( ($_[3]||{})->{returning} ) {
268 my $s;
269 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
270 $sql .= $s;
28d28903 271 }
272
bf51641f 273 return ($sql, @bind);
7a72e5a5 274 }
275
6a247f33 276 next::method(@_);
6f4ddea1 277}
278
279sub _recurse_fields {
81446c4f 280 my ($self, $fields) = @_;
6f4ddea1 281 my $ref = ref $fields;
282 return $self->_quote($fields) unless $ref;
283 return $$fields if $ref eq 'SCALAR';
284
285 if ($ref eq 'ARRAY') {
81446c4f 286 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 287 }
288 elsif ($ref eq 'HASH') {
81446c4f 289 my %hash = %$fields; # shallow copy
83e09b5b 290
50136dd9 291 my $as = delete $hash{-as}; # if supplied
292
81446c4f 293 my ($func, $args, @toomany) = %hash;
294
295 # there should be only one pair
296 if (@toomany) {
70c28808 297 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 298 }
50136dd9 299
300 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
70c28808 301 $self->throw_exception (
50136dd9 302 'The select => { distinct => ... } syntax is not supported for multiple columns.'
303 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
304 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 305 );
6f4ddea1 306 }
83e09b5b 307
50136dd9 308 my $select = sprintf ('%s( %s )%s',
309 $self->_sqlcase($func),
310 $self->_recurse_fields($args),
311 $as
0491b597 312 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 313 : ''
314 );
315
83e09b5b 316 return $select;
6f4ddea1 317 }
318 # Is the second check absolutely necessary?
319 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 320 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
321 return $$fields->[0];
6f4ddea1 322 }
323 else {
70c28808 324 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 325 }
326}
327
a6b68a60 328
329# this used to be a part of _order_by but is broken out for clarity.
330# What we have been doing forever is hijacking the $order arg of
331# SQLA::select to pass in arbitrary pieces of data (first the group_by,
332# then pretty much the entire resultset attr-hash, as more and more
333# things in the SQLA space need to have mopre info about the $rs they
334# create SQL for. The alternative would be to keep expanding the
335# signature of _select with more and more positional parameters, which
336# is just gross. All hail SQLA2!
337sub _parse_rs_attrs {
1cbd3034 338 my ($self, $arg) = @_;
15827712 339
a6b68a60 340 my $sql = '';
1cbd3034 341
0542ec57 342 if ($arg->{group_by}) {
343 # horible horrible, waiting for refactor
344 local $self->{select_bind};
345 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
346 $sql .= $self->_sqlcase(' group by ') . $g;
347 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
348 }
a6b68a60 349 }
1cbd3034 350
a6b68a60 351 if (defined $arg->{having}) {
352 my ($frag, @bind) = $self->_recurse_where($arg->{having});
353 push(@{$self->{having_bind}}, @bind);
354 $sql .= $self->_sqlcase(' having ') . $frag;
355 }
15827712 356
a6b68a60 357 if (defined $arg->{order_by}) {
358 $sql .= $self->_order_by ($arg->{order_by});
359 }
15827712 360
a6b68a60 361 return $sql;
362}
363
364sub _order_by {
365 my ($self, $arg) = @_;
15827712 366
a6b68a60 367 # check that we are not called in legacy mode (order_by as 4th argument)
368 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
369 return $self->_parse_rs_attrs ($arg);
fde3719a 370 }
1cbd3034 371 else {
6a247f33 372 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 373 push @{$self->{order_bind}}, @bind;
1cbd3034 374 return $sql;
fd4cb60a 375 }
6f4ddea1 376}
377
378sub _table {
6a247f33 379# optimized due to hotttnesss
380# my ($self, $from) = @_;
381 if (my $ref = ref $_[1] ) {
382 if ($ref eq 'ARRAY') {
383 return $_[0]->_recurse_from(@{$_[1]});
384 }
385 elsif ($ref eq 'HASH') {
4c2b30d6 386 return $_[0]->_recurse_from($_[1]);
6a247f33 387 }
1bffc6b8 388 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
389 my ($sql, @bind) = @{ ${$_[1]} };
390 push @{$_[0]->{from_bind}}, @bind;
391 return $sql
392 }
6f4ddea1 393 }
6a247f33 394 return $_[0]->next::method ($_[1]);
6f4ddea1 395}
396
b8391c87 397sub _generate_join_clause {
398 my ($self, $join_type) = @_;
399
726c8f65 400 $join_type = $self->{_default_jointype}
401 if ! defined $join_type;
402
b8391c87 403 return sprintf ('%s JOIN ',
726c8f65 404 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 405 );
406}
407
6f4ddea1 408sub _recurse_from {
726c8f65 409 my $self = shift;
410
411 return join (' ', $self->_gen_from_blocks(@_) );
412}
413
414sub _gen_from_blocks {
415 my ($self, $from, @joins) = @_;
416
417 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 418
726c8f65 419 for (@joins) {
4c2b30d6 420 my ($to, $on) = @$_;
aa82ce29 421
6f4ddea1 422 # check whether a join type exists
6f4ddea1 423 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 424 my $join_type;
425 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
426 $join_type = $to_jt->{-join_type};
427 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 428 }
aa82ce29 429
726c8f65 430 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 431
432 if (ref $to eq 'ARRAY') {
726c8f65 433 push(@j, '(', $self->_recurse_from(@$to), ')');
434 }
435 else {
436 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 437 }
726c8f65 438
a697fa31 439 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 440 push(@j, ' ON ', $sql);
a697fa31 441 push @{$self->{from_bind}}, @bind;
726c8f65 442
443 push @fchunks, join '', @j;
6f4ddea1 444 }
726c8f65 445
446 return @fchunks;
6f4ddea1 447}
448
4c2b30d6 449sub _from_chunk_to_sql {
450 my ($self, $fromspec) = @_;
451
e8885a53 452 return join (' ', do {
453 if (! ref $fromspec) {
454 $self->_quote($fromspec);
455 }
456 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 457 $$fromspec;
e8885a53 458 }
459 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 460 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
461 $$fromspec->[0];
e8885a53 462 }
463 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 464 my ($as, $table, $toomuch) = ( map
465 { $_ => $fromspec->{$_} }
466 ( grep { $_ !~ /^\-/ } keys %$fromspec )
467 );
6f4ddea1 468
70c28808 469 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 470 if defined $toomuch;
6f4ddea1 471
4c2b30d6 472 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 473 }
474 else {
475 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
476 }
477 });
6f4ddea1 478}
479
480sub _join_condition {
481 my ($self, $cond) = @_;
4c2b30d6 482
a697fa31 483 # Backcompat for the old days when a plain hashref
484 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
485 # Once things settle we should start warning here so that
486 # folks unroll their hacks
487 if (
488 ref $cond eq 'HASH'
489 and
490 keys %$cond == 1
491 and
492 (keys %$cond)[0] =~ /\./
493 and
494 ! ref ( (values %$cond)[0] )
495 ) {
496 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 497 }
a697fa31 498 elsif ( ref $cond eq 'ARRAY' ) {
499 # do our own ORing so that the hashref-shim above is invoked
9aae3566 500 my @parts;
501 my @binds;
502 foreach my $c (@$cond) {
503 my ($sql, @bind) = $self->_join_condition($c);
504 push @binds, @bind;
505 push @parts, $sql;
506 }
507 return join(' OR ', @parts), @binds;
6f4ddea1 508 }
a697fa31 509
510 return $self->_recurse_where($cond);
6f4ddea1 511}
512
6f4ddea1 5131;
d5dedbd6 514
2bb4c37b 515=head1 OPERATORS
516
517=head2 -ident
518
519Used to explicitly specify an SQL identifier. Takes a plain string as value
520which is then invariably treated as a column name (and is being properly
521quoted if quoting has been requested). Most useful for comparison of two
522columns:
523
524 my %where = (
525 priority => { '<', 2 },
526 requestor => { -ident => 'submitter' }
527 );
528
529which results in:
530
531 $stmt = 'WHERE "priority" < ? AND "requestor" = "submitter"';
532 @bind = ('2');
533
534=head2 -value
535
536The -value operator signals that the argument to the right is a raw bind value.
537It will be passed straight to DBI, without invoking any of the SQL::Abstract
538condition-parsing logic. This allows you to, for example, pass an array as a
539column value for databases that support array datatypes, e.g.:
540
541 my %where = (
542 array => { -value => [1, 2, 3] }
543 );
544
545which results in:
546
547 $stmt = 'WHERE array = ?';
548 @bind = ([1, 2, 3]);
549
d5dedbd6 550=head1 AUTHORS
551
552See L<DBIx::Class/CONTRIBUTORS>.
553
554=head1 LICENSE
555
556You may distribute this code under the same terms as Perl itself.
557
558=cut