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