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