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