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