Merge 'trunk' into 'handle_all_storage_methods_in_replicated'
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLAHacks.pm
CommitLineData
6f4ddea1 1package # Hide from PAUSE
855c6fd0 2 DBIx::Class::SQLAHacks;
6f4ddea1 3
998373c2 4# This module is a subclass of SQL::Abstract::Limit and includes a number
5# of DBIC-specific workarounds, not yet suitable for inclusion into the
6# SQLA core
7
6f4ddea1 8use base qw/SQL::Abstract::Limit/;
e3764383 9use strict;
10use warnings;
b2b22cd6 11use Carp::Clan qw/^DBIx::Class|^SQL::Abstract/;
8637bb24 12use Sub::Name();
b2b22cd6 13
14BEGIN {
15 # reinstall the carp()/croak() functions imported into SQL::Abstract
16 # as Carp and Carp::Clan do not like each other much
17 no warnings qw/redefine/;
18 no strict qw/refs/;
19 for my $f (qw/carp croak/) {
329d7385 20
b2b22cd6 21 my $orig = \&{"SQL::Abstract::$f"};
8637bb24 22 *{"SQL::Abstract::$f"} = Sub::Name::subname "SQL::Abstract::$f" =>
23 sub {
24 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
25 __PACKAGE__->can($f)->(@_);
26 }
27 else {
28 goto $orig;
29 }
30 };
b2b22cd6 31 }
32}
6f4ddea1 33
998373c2 34
35# Tries to determine limit dialect.
36#
6f4ddea1 37sub new {
38 my $self = shift->SUPER::new(@_);
39
40 # This prevents the caching of $dbh in S::A::L, I believe
41 # If limit_dialect is a ref (like a $dbh), go ahead and replace
42 # it with what it resolves to:
43 $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
44 if ref $self->{limit_dialect};
45
46 $self;
47}
48
6f4ddea1 49
6553ac38 50# ANSI standard Limit/Offset implementation. DB2 and MSSQL use this
6f4ddea1 51sub _RowNumberOver {
52 my ($self, $sql, $order, $rows, $offset ) = @_;
53
cb478051 54 # get the select to make the final amount of columns equal the original one
55 my ($select) = $sql =~ /^ \s* SELECT \s+ (.+?) \s+ FROM/ix
56 or croak "Unrecognizable SELECT: $sql";
57
6553ac38 58 # get the order_by only (or make up an order if none exists)
59 my $order_by = $self->_order_by(
84ddb3da 60 (delete $order->{order_by}) || $self->_rno_default_order
6553ac38 61 );
6f4ddea1 62
cb478051 63 # whatever is left of the order_by
6553ac38 64 my $group_having = $self->_order_by($order);
6f4ddea1 65
1f36ab67 66 my $qalias = $self->_quote ($self->{_dbic_rs_attrs}{alias});
67
cb478051 68 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
6f4ddea1 69
cb478051 70SELECT $select FROM (
71 SELECT $qalias.*, ROW_NUMBER() OVER($order_by ) AS rno__row__index FROM (
72 ${sql}${group_having}
73 ) $qalias
74) $qalias WHERE rno__row__index BETWEEN %d AND %d
6553ac38 75
76EOS
77
78 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
6f4ddea1 79 return $sql;
80}
81
84ddb3da 82# some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
83sub _rno_default_order {
84 return undef;
85}
86
193590c2 87# Informix specific limit, almost like LIMIT/OFFSET
88sub _SkipFirst {
89 my ($self, $sql, $order, $rows, $offset) = @_;
90
91 $sql =~ s/^ \s* SELECT \s+ //ix
92 or croak "Unrecognizable SELECT: $sql";
93
94 return sprintf ('SELECT %s%s%s%s',
95 $offset
96 ? sprintf ('SKIP %d ', $offset)
97 : ''
98 ,
99 sprintf ('FIRST %d ', $rows),
100 $sql,
101 $self->_order_by ($order),
102 );
103}
104
6553ac38 105# Crappy Top based Limit/Offset support. Legacy from MSSQL.
15827712 106sub _Top {
107 my ( $self, $sql, $order, $rows, $offset ) = @_;
108
b1e1d073 109 # mangle the input sql so it can be properly aliased in the outer queries
110 $sql =~ s/^ \s* SELECT \s+ (.+?) \s+ (?=FROM)//ix
111 or croak "Unrecognizable SELECT: $sql";
42e5b103 112 my $sql_select = $1;
113 my @sql_select = split (/\s*,\s*/, $sql_select);
114
115 # we can't support subqueries (in fact MSSQL can't) - croak
116 if (@sql_select != @{$self->{_dbic_rs_attrs}{select}}) {
117 croak (sprintf (
118 'SQL SELECT did not parse cleanly - retrieved %d comma separated elements, while '
119 . 'the resultset select attribure contains %d elements: %s',
120 scalar @sql_select,
121 scalar @{$self->{_dbic_rs_attrs}{select}},
122 $sql_select,
123 ));
124 }
b1e1d073 125
42e5b103 126 my $name_sep = $self->name_sep || '.';
ac93965c 127 my $esc_name_sep = "\Q$name_sep\E";
128 my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
129
130 my $rs_alias = $self->{_dbic_rs_attrs}{alias};
131 my $quoted_rs_alias = $self->_quote ($rs_alias);
b1e1d073 132
42e5b103 133 # construct the new select lists, rename(alias) some columns if necessary
134 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
b1e1d073 135
42e5b103 136 for (@{$self->{_dbic_rs_attrs}{select}}) {
137 next if ref $_;
138 my ($table, $orig_colname) = ( $_ =~ $col_re );
139 next unless $table;
140 $seen_names{$orig_colname}++;
141 }
b1e1d073 142
42e5b103 143 for my $i (0 .. $#sql_select) {
b1e1d073 144
42e5b103 145 my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
146 my $colsel_sql = $sql_select[$i];
b1e1d073 147
42e5b103 148 # this may or may not work (in case of a scalarref or something)
149 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
b1e1d073 150
42e5b103 151 my $quoted_alias;
152 # do not attempt to understand non-scalar selects - alias numerically
153 if (ref $colsel_arg) {
154 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
155 }
156 # column name seen more than once - alias it
ed4cdb4f 157 elsif ($orig_colname &&
158 ($seen_names{$orig_colname} && $seen_names{$orig_colname} > 1) ) {
42e5b103 159 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
160 }
b1e1d073 161
42e5b103 162 # we did rename - make a record and adjust
163 if ($quoted_alias) {
164 # alias inner
165 push @inner_select, "$colsel_sql AS $quoted_alias";
166
167 # push alias to outer
168 push @outer_select, $quoted_alias;
169
170 # Any aliasing accumulated here will be considered
171 # both for inner and outer adjustments of ORDER BY
172 $self->__record_alias (
173 \%col_aliases,
174 $quoted_alias,
175 $colsel_arg,
176 $table ? $orig_colname : undef,
177 );
b1e1d073 178 }
179
42e5b103 180 # otherwise just leave things intact inside, and use the abbreviated one outside
181 # (as we do not have table names anymore)
182 else {
183 push @inner_select, $colsel_sql;
184
185 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
186 push @outer_select, $outer_quoted;
187 $self->__record_alias (
188 \%outer_col_aliases,
189 $outer_quoted,
190 $colsel_arg,
191 $table ? $orig_colname : undef,
192 );
193 }
b1e1d073 194 }
195
196 my $outer_select = join (', ', @outer_select );
42e5b103 197 my $inner_select = join (', ', @inner_select );
b1e1d073 198
42e5b103 199 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
b1e1d073 200
201 # deal with order
15827712 202 croak '$order supplied to SQLAHacks limit emulators must be a hash'
203 if (ref $order ne 'HASH');
204
8f6dbee9 205 $order = { %$order }; #copy
206
02d133f0 207 my $req_order = $order->{order_by};
15827712 208
e2db8319 209 # examine normalized version, collapses nesting
210 my $limit_order;
211 if (scalar $self->_order_by_chunks ($req_order)) {
212 $limit_order = $req_order;
213 }
214 else {
e2db8319 215 $limit_order = [ map
216 { join ('', $rs_alias, $name_sep, $_ ) }
217 ( $self->{_dbic_rs_attrs}{_source_handle}->resolve->primary_columns )
218 ];
219 }
1cbd3034 220
42e5b103 221 my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
222 my $order_by_requested = $self->_order_by ($req_order);
15827712 223
64c7c000 224 # generate the rest
e2db8319 225 delete $order->{order_by};
8f6dbee9 226 my $grpby_having = $self->_order_by ($order);
227
64c7c000 228 # short circuit for counts - the ordering complexity is needless
229 if ($self->{_dbic_rs_attrs}{-for_count_only}) {
230 return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
231 }
232
42e5b103 233 # we can't really adjust the order_by columns, as introspection is lacking
234 # resort to simple substitution
235 for my $col (keys %outer_col_aliases) {
236 for ($order_by_requested, $order_by_outer) {
237 $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
b1e1d073 238 }
239 }
42e5b103 240 for my $col (keys %col_aliases) {
9c1ffdde 241 $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
42e5b103 242 }
15827712 243
15827712 244
42e5b103 245 my $inner_lim = $rows + $offset;
15827712 246
618a0fe3 247 $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
42e5b103 248
249 if ($offset) {
250 $sql = <<"SQL";
b1e1d073 251
252 SELECT TOP $rows $outer_select FROM
15827712 253 (
42e5b103 254 $sql
ac93965c 255 ) $quoted_rs_alias
15827712 256 $order_by_outer
b1e1d073 257SQL
258
42e5b103 259 }
15827712 260
42e5b103 261 if ($order_by_requested) {
b1e1d073 262 $sql = <<"SQL";
15827712 263
42e5b103 264 SELECT $outer_select FROM
ac93965c 265 ( $sql ) $quoted_rs_alias
266 $order_by_requested
15827712 267SQL
b1e1d073 268
269 }
270
ac93965c 271 $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
b1e1d073 272 return $sql;
15827712 273}
274
42e5b103 275# action at a distance to shorten Top code above
276sub __record_alias {
277 my ($self, $register, $alias, $fqcol, $col) = @_;
278
279 # record qualified name
280 $register->{$fqcol} = $alias;
281 $register->{$self->_quote($fqcol)} = $alias;
282
283 return unless $col;
284
b6d347e0 285 # record unqualified name, undef (no adjustment) if a duplicate is found
42e5b103 286 if (exists $register->{$col}) {
287 $register->{$col} = undef;
288 }
289 else {
290 $register->{$col} = $alias;
291 }
292
293 $register->{$self->_quote($col)} = $register->{$col};
15827712 294}
295
296
6f4ddea1 297
298# While we're at it, this should make LIMIT queries more efficient,
299# without digging into things too deeply
6f4ddea1 300sub _find_syntax {
301 my ($self, $syntax) = @_;
ac788c46 302 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
6f4ddea1 303}
304
ec7cfd36 305my $for_syntax = {
306 update => 'FOR UPDATE',
307 shared => 'FOR SHARE',
308};
998373c2 309# Quotes table names, handles "limit" dialects (e.g. where rownum between x and
310# y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
6f4ddea1 311sub select {
312 my ($self, $table, $fields, $where, $order, @rest) = @_;
1cbd3034 313
314 $self->{"${_}_bind"} = [] for (qw/having from order/);
db56cf3d 315
c2b7c5dc 316 if (not ref($table) or ref($table) eq 'SCALAR') {
6f4ddea1 317 $table = $self->_quote($table);
318 }
c2b7c5dc 319
6f4ddea1 320 local $self->{rownum_hack_count} = 1
321 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
322 @rest = (-1) unless defined $rest[0];
e8fcf76f 323 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
6f4ddea1 324 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
db56cf3d 325 my ($sql, @where_bind) = $self->SUPER::select(
6f4ddea1 326 $table, $self->_recurse_fields($fields), $where, $order, @rest
327 );
ec7cfd36 328 if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
329 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
330 }
331
1cbd3034 332 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
6f4ddea1 333}
334
998373c2 335# Quotes table names, and handles default inserts
6f4ddea1 336sub insert {
337 my $self = shift;
338 my $table = shift;
c2b7c5dc 339 $table = $self->_quote($table);
7a72e5a5 340
341 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
342 # which is sadly understood only by MySQL. Change default behavior here,
343 # until SQLA2 comes with proper dialect support
344 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
345 return "INSERT INTO ${table} DEFAULT VALUES"
346 }
347
6f4ddea1 348 $self->SUPER::insert($table, @_);
349}
350
998373c2 351# Just quotes table names.
6f4ddea1 352sub update {
353 my $self = shift;
354 my $table = shift;
c2b7c5dc 355 $table = $self->_quote($table);
6f4ddea1 356 $self->SUPER::update($table, @_);
357}
358
998373c2 359# Just quotes table names.
6f4ddea1 360sub delete {
361 my $self = shift;
362 my $table = shift;
c2b7c5dc 363 $table = $self->_quote($table);
6f4ddea1 364 $self->SUPER::delete($table, @_);
365}
366
367sub _emulate_limit {
368 my $self = shift;
369 if ($_[3] == -1) {
370 return $_[1].$self->_order_by($_[2]);
371 } else {
372 return $self->SUPER::_emulate_limit(@_);
373 }
374}
375
376sub _recurse_fields {
377 my ($self, $fields, $params) = @_;
378 my $ref = ref $fields;
379 return $self->_quote($fields) unless $ref;
380 return $$fields if $ref eq 'SCALAR';
381
382 if ($ref eq 'ARRAY') {
383 return join(', ', map {
384 $self->_recurse_fields($_)
385 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
386 ? ' AS col'.$self->{rownum_hack_count}++
387 : '')
388 } @$fields);
83e09b5b 389 }
390 elsif ($ref eq 'HASH') {
391 my %hash = %$fields;
83e09b5b 392
50136dd9 393 my $as = delete $hash{-as}; # if supplied
394
395 my ($func, $args) = each %hash;
396 delete $hash{$func};
397
398 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
399 croak (
400 'The select => { distinct => ... } syntax is not supported for multiple columns.'
401 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
402 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 403 );
6f4ddea1 404 }
83e09b5b 405
50136dd9 406 my $select = sprintf ('%s( %s )%s',
407 $self->_sqlcase($func),
408 $self->_recurse_fields($args),
409 $as
0491b597 410 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 411 : ''
412 );
413
83e09b5b 414 # there should be nothing left
415 if (keys %hash) {
416 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
6f4ddea1 417 }
83e09b5b 418
83e09b5b 419 return $select;
6f4ddea1 420 }
421 # Is the second check absolutely necessary?
422 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 423 return $self->_fold_sqlbind( $fields );
6f4ddea1 424 }
425 else {
e8fcf76f 426 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 427 }
428}
429
430sub _order_by {
1cbd3034 431 my ($self, $arg) = @_;
15827712 432
1cbd3034 433 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
434
435 my $ret = '';
436
83e09b5b 437 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
438 $ret = $self->_sqlcase(' group by ') . $g;
6f4ddea1 439 }
15827712 440
1cbd3034 441 if (defined $arg->{having}) {
442 my ($frag, @bind) = $self->_recurse_where($arg->{having});
443 push(@{$self->{having_bind}}, @bind);
6f4ddea1 444 $ret .= $self->_sqlcase(' having ').$frag;
445 }
15827712 446
1cbd3034 447 if (defined $arg->{order_by}) {
448 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
449 push(@{$self->{order_bind}}, @bind);
450 $ret .= $frag;
6f4ddea1 451 }
15827712 452
1cbd3034 453 return $ret;
fde3719a 454 }
1cbd3034 455 else {
456 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
457 push(@{$self->{order_bind}}, @bind);
458 return $sql;
fd4cb60a 459 }
6f4ddea1 460}
461
1cbd3034 462sub _order_directions {
fd4cb60a 463 my ($self, $order) = @_;
15827712 464
1cbd3034 465 # strip bind values - none of the current _order_directions users support them
466 return $self->SUPER::_order_directions( [ map
467 { ref $_ ? $_->[0] : $_ }
468 $self->_order_by_chunks ($order)
469 ]);
fd4cb60a 470}
471
6f4ddea1 472sub _table {
473 my ($self, $from) = @_;
474 if (ref $from eq 'ARRAY') {
475 return $self->_recurse_from(@$from);
476 } elsif (ref $from eq 'HASH') {
477 return $self->_make_as($from);
478 } else {
479 return $from; # would love to quote here but _table ends up getting called
480 # twice during an ->select without a limit clause due to
481 # the way S::A::Limit->select works. should maybe consider
482 # bypassing this and doing S::A::select($self, ...) in
483 # our select method above. meantime, quoting shims have
484 # been added to select/insert/update/delete here
485 }
486}
487
488sub _recurse_from {
489 my ($self, $from, @join) = @_;
490 my @sqlf;
491 push(@sqlf, $self->_make_as($from));
492 foreach my $j (@join) {
493 my ($to, $on) = @$j;
494
aa82ce29 495
6f4ddea1 496 # check whether a join type exists
6f4ddea1 497 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 498 my $join_type;
499 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
500 $join_type = $to_jt->{-join_type};
501 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 502 }
aa82ce29 503
de5f71ef 504 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 505
506 my $join_clause = sprintf ('%s JOIN ',
507 $join_type ? ' ' . uc($join_type) : ''
508 );
509 push @sqlf, $join_clause;
6f4ddea1 510
511 if (ref $to eq 'ARRAY') {
512 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
513 } else {
514 push(@sqlf, $self->_make_as($to));
515 }
516 push(@sqlf, ' ON ', $self->_join_condition($on));
517 }
518 return join('', @sqlf);
519}
520
db56cf3d 521sub _fold_sqlbind {
522 my ($self, $sqlbind) = @_;
69989ea9 523
524 my @sqlbind = @$$sqlbind; # copy
525 my $sql = shift @sqlbind;
526 push @{$self->{from_bind}}, @sqlbind;
527
db56cf3d 528 return $sql;
6f4ddea1 529}
530
531sub _make_as {
532 my ($self, $from) = @_;
db56cf3d 533 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
534 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
535 : $self->_quote($_))
6f4ddea1 536 } reverse each %{$self->_skip_options($from)});
537}
538
539sub _skip_options {
540 my ($self, $hash) = @_;
541 my $clean_hash = {};
542 $clean_hash->{$_} = $hash->{$_}
543 for grep {!/^-/} keys %$hash;
544 return $clean_hash;
545}
546
547sub _join_condition {
548 my ($self, $cond) = @_;
549 if (ref $cond eq 'HASH') {
550 my %j;
551 for (keys %$cond) {
552 my $v = $cond->{$_};
553 if (ref $v) {
e8fcf76f 554 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 555 if ref($v) ne 'SCALAR';
556 $j{$_} = $v;
557 }
558 else {
559 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
560 }
561 };
562 return scalar($self->_recurse_where(\%j));
563 } elsif (ref $cond eq 'ARRAY') {
564 return join(' OR ', map { $self->_join_condition($_) } @$cond);
565 } else {
566 die "Can't handle this yet!";
567 }
568}
569
570sub _quote {
571 my ($self, $label) = @_;
572 return '' unless defined $label;
c2b7c5dc 573 return $$label if ref($label) eq 'SCALAR';
6f4ddea1 574 return "*" if $label eq '*';
575 return $label unless $self->{quote_char};
576 if(ref $self->{quote_char} eq "ARRAY"){
577 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
578 if !defined $self->{name_sep};
579 my $sep = $self->{name_sep};
580 return join($self->{name_sep},
581 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
582 split(/\Q$sep\E/,$label));
583 }
584 return $self->SUPER::_quote($label);
585}
586
587sub limit_dialect {
588 my $self = shift;
589 $self->{limit_dialect} = shift if @_;
590 return $self->{limit_dialect};
591}
592
998373c2 593# Set to an array-ref to specify separate left and right quotes for table names.
594# A single scalar is equivalen to [ $char, $char ]
6f4ddea1 595sub quote_char {
596 my $self = shift;
597 $self->{quote_char} = shift if @_;
598 return $self->{quote_char};
599}
600
998373c2 601# Character separating quoted table names.
6f4ddea1 602sub name_sep {
603 my $self = shift;
604 $self->{name_sep} = shift if @_;
605 return $self->{name_sep};
606}
607
6081;