Merge 'trunk' into 'mssql_top_fixes'
[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 || '.';
138 $name_sep = "\Q$name_sep\E";
139 my $col_re = qr/ ^ (?: (.+) $name_sep )? ([^$name_sep]+) $ /x;
b1e1d073 140
42e5b103 141 # construct the new select lists, rename(alias) some columns if necessary
142 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
b1e1d073 143
42e5b103 144 for (@{$self->{_dbic_rs_attrs}{select}}) {
145 next if ref $_;
146 my ($table, $orig_colname) = ( $_ =~ $col_re );
147 next unless $table;
148 $seen_names{$orig_colname}++;
149 }
b1e1d073 150
42e5b103 151 for my $i (0 .. $#sql_select) {
b1e1d073 152
42e5b103 153 my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
154 my $colsel_sql = $sql_select[$i];
b1e1d073 155
42e5b103 156 # this may or may not work (in case of a scalarref or something)
157 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
b1e1d073 158
42e5b103 159 my $quoted_alias;
160 # do not attempt to understand non-scalar selects - alias numerically
161 if (ref $colsel_arg) {
162 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
163 }
164 # column name seen more than once - alias it
165 elsif ($orig_colname && ($seen_names{$orig_colname} > 1) ) {
166 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
167 }
b1e1d073 168
42e5b103 169 # we did rename - make a record and adjust
170 if ($quoted_alias) {
171 # alias inner
172 push @inner_select, "$colsel_sql AS $quoted_alias";
173
174 # push alias to outer
175 push @outer_select, $quoted_alias;
176
177 # Any aliasing accumulated here will be considered
178 # both for inner and outer adjustments of ORDER BY
179 $self->__record_alias (
180 \%col_aliases,
181 $quoted_alias,
182 $colsel_arg,
183 $table ? $orig_colname : undef,
184 );
b1e1d073 185 }
186
42e5b103 187 # otherwise just leave things intact inside, and use the abbreviated one outside
188 # (as we do not have table names anymore)
189 else {
190 push @inner_select, $colsel_sql;
191
192 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
193 push @outer_select, $outer_quoted;
194 $self->__record_alias (
195 \%outer_col_aliases,
196 $outer_quoted,
197 $colsel_arg,
198 $table ? $orig_colname : undef,
199 );
200 }
b1e1d073 201 }
202
203 my $outer_select = join (', ', @outer_select );
42e5b103 204 my $inner_select = join (', ', @inner_select );
b1e1d073 205
42e5b103 206 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
b1e1d073 207
208 # deal with order
15827712 209 croak '$order supplied to SQLAHacks limit emulators must be a hash'
210 if (ref $order ne 'HASH');
211
8f6dbee9 212 $order = { %$order }; #copy
213
02d133f0 214 my $req_order = $order->{order_by};
215 my $limit_order =
893403c8 216 scalar $self->_order_by_chunks ($req_order) # examine normalized version, collapses nesting
02d133f0 217 ? $req_order
218 : $order->{_virtual_order_by}
219 ;
b1e1d073 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
225 delete $order->{$_} for qw/order_by _virtual_order_by/;
226 my $grpby_having = $self->_order_by ($order);
227
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) {
241 $order_by_inner =~ s/\s+$col\s+/$col_aliases{$col}/g;
242 }
1cbd3034 243
02d133f0 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
02d133f0 255 ) AS me
15827712 256 $order_by_outer
b1e1d073 257SQL
258
42e5b103 259 }
15827712 260
42e5b103 261 if ($order_by_requested) {
b1e1d073 262 $sql = <<"SQL";
263
42e5b103 264 SELECT $outer_select FROM
02d133f0 265 ( $sql ) AS me
42e5b103 266 $order_by_requested;
15827712 267SQL
b1e1d073 268
269 }
270
271 return $sql;
15827712 272}
273
42e5b103 274# action at a distance to shorten Top code above
275sub __record_alias {
276 my ($self, $register, $alias, $fqcol, $col) = @_;
277
278 # record qualified name
279 $register->{$fqcol} = $alias;
280 $register->{$self->_quote($fqcol)} = $alias;
281
282 return unless $col;
283
b6d347e0 284 # record unqualified name, undef (no adjustment) if a duplicate is found
42e5b103 285 if (exists $register->{$col}) {
286 $register->{$col} = undef;
287 }
288 else {
289 $register->{$col} = $alias;
290 }
291
292 $register->{$self->_quote($col)} = $register->{$col};
293}
294
15827712 295
6f4ddea1 296
297# While we're at it, this should make LIMIT queries more efficient,
298# without digging into things too deeply
6f4ddea1 299sub _find_syntax {
300 my ($self, $syntax) = @_;
ac788c46 301 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
6f4ddea1 302}
303
ec7cfd36 304my $for_syntax = {
305 update => 'FOR UPDATE',
306 shared => 'FOR SHARE',
307};
6f4ddea1 308sub select {
309 my ($self, $table, $fields, $where, $order, @rest) = @_;
1cbd3034 310
311 $self->{"${_}_bind"} = [] for (qw/having from order/);
db56cf3d 312
6f4ddea1 313 if (ref $table eq 'SCALAR') {
314 $table = $$table;
315 }
316 elsif (not ref $table) {
317 $table = $self->_quote($table);
318 }
319 local $self->{rownum_hack_count} = 1
320 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
321 @rest = (-1) unless defined $rest[0];
e8fcf76f 322 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
6f4ddea1 323 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
db56cf3d 324 my ($sql, @where_bind) = $self->SUPER::select(
6f4ddea1 325 $table, $self->_recurse_fields($fields), $where, $order, @rest
326 );
ec7cfd36 327 if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
328 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
329 }
330
1cbd3034 331 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
6f4ddea1 332}
333
334sub insert {
335 my $self = shift;
336 my $table = shift;
337 $table = $self->_quote($table) unless ref($table);
7a72e5a5 338
339 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
340 # which is sadly understood only by MySQL. Change default behavior here,
341 # until SQLA2 comes with proper dialect support
342 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
343 return "INSERT INTO ${table} DEFAULT VALUES"
344 }
345
6f4ddea1 346 $self->SUPER::insert($table, @_);
347}
348
349sub update {
350 my $self = shift;
351 my $table = shift;
352 $table = $self->_quote($table) unless ref($table);
353 $self->SUPER::update($table, @_);
354}
355
356sub delete {
357 my $self = shift;
358 my $table = shift;
359 $table = $self->_quote($table) unless ref($table);
360 $self->SUPER::delete($table, @_);
361}
362
363sub _emulate_limit {
364 my $self = shift;
365 if ($_[3] == -1) {
366 return $_[1].$self->_order_by($_[2]);
367 } else {
368 return $self->SUPER::_emulate_limit(@_);
369 }
370}
371
372sub _recurse_fields {
373 my ($self, $fields, $params) = @_;
374 my $ref = ref $fields;
375 return $self->_quote($fields) unless $ref;
376 return $$fields if $ref eq 'SCALAR';
377
378 if ($ref eq 'ARRAY') {
379 return join(', ', map {
380 $self->_recurse_fields($_)
381 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
382 ? ' AS col'.$self->{rownum_hack_count}++
383 : '')
384 } @$fields);
83e09b5b 385 }
386 elsif ($ref eq 'HASH') {
387 my %hash = %$fields;
388 my ($select, $as);
389
390 if ($hash{-select}) {
391 $select = $self->_recurse_fields (delete $hash{-select});
392 $as = $self->_quote (delete $hash{-as});
393 }
394 else {
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 }'
403 );
db56cf3d 404 }
83e09b5b 405 $select = sprintf ('%s( %s )',
406 $self->_sqlcase($func),
407 $self->_recurse_fields($args)
408 );
6f4ddea1 409 }
83e09b5b 410
411 # there should be nothing left
412 if (keys %hash) {
413 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
6f4ddea1 414 }
83e09b5b 415
416 $select .= " AS $as" if $as;
417 return $select;
6f4ddea1 418 }
419 # Is the second check absolutely necessary?
420 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 421 return $self->_fold_sqlbind( $fields );
6f4ddea1 422 }
423 else {
e8fcf76f 424 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 425 }
426}
427
428sub _order_by {
1cbd3034 429 my ($self, $arg) = @_;
15827712 430
1cbd3034 431 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
432
433 my $ret = '';
434
83e09b5b 435 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
436 $ret = $self->_sqlcase(' group by ') . $g;
6f4ddea1 437 }
15827712 438
1cbd3034 439 if (defined $arg->{having}) {
440 my ($frag, @bind) = $self->_recurse_where($arg->{having});
441 push(@{$self->{having_bind}}, @bind);
6f4ddea1 442 $ret .= $self->_sqlcase(' having ').$frag;
443 }
15827712 444
1cbd3034 445 if (defined $arg->{order_by}) {
446 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
447 push(@{$self->{order_bind}}, @bind);
448 $ret .= $frag;
6f4ddea1 449 }
15827712 450
1cbd3034 451 return $ret;
fde3719a 452 }
1cbd3034 453 else {
454 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
455 push(@{$self->{order_bind}}, @bind);
456 return $sql;
fd4cb60a 457 }
6f4ddea1 458}
459
1cbd3034 460sub _order_directions {
fd4cb60a 461 my ($self, $order) = @_;
15827712 462
1cbd3034 463 # strip bind values - none of the current _order_directions users support them
464 return $self->SUPER::_order_directions( [ map
465 { ref $_ ? $_->[0] : $_ }
466 $self->_order_by_chunks ($order)
467 ]);
fd4cb60a 468}
469
6f4ddea1 470sub _table {
471 my ($self, $from) = @_;
472 if (ref $from eq 'ARRAY') {
473 return $self->_recurse_from(@$from);
474 } elsif (ref $from eq 'HASH') {
475 return $self->_make_as($from);
476 } else {
477 return $from; # would love to quote here but _table ends up getting called
478 # twice during an ->select without a limit clause due to
479 # the way S::A::Limit->select works. should maybe consider
480 # bypassing this and doing S::A::select($self, ...) in
481 # our select method above. meantime, quoting shims have
482 # been added to select/insert/update/delete here
483 }
484}
485
486sub _recurse_from {
487 my ($self, $from, @join) = @_;
488 my @sqlf;
489 push(@sqlf, $self->_make_as($from));
490 foreach my $j (@join) {
491 my ($to, $on) = @$j;
492
493 # check whether a join type exists
494 my $join_clause = '';
495 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
496 if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
497 $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
498 } else {
499 $join_clause = ' JOIN ';
500 }
501 push(@sqlf, $join_clause);
502
503 if (ref $to eq 'ARRAY') {
504 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
505 } else {
506 push(@sqlf, $self->_make_as($to));
507 }
508 push(@sqlf, ' ON ', $self->_join_condition($on));
509 }
510 return join('', @sqlf);
511}
512
db56cf3d 513sub _fold_sqlbind {
514 my ($self, $sqlbind) = @_;
69989ea9 515
516 my @sqlbind = @$$sqlbind; # copy
517 my $sql = shift @sqlbind;
518 push @{$self->{from_bind}}, @sqlbind;
519
db56cf3d 520 return $sql;
6f4ddea1 521}
522
523sub _make_as {
524 my ($self, $from) = @_;
db56cf3d 525 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
526 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
527 : $self->_quote($_))
6f4ddea1 528 } reverse each %{$self->_skip_options($from)});
529}
530
531sub _skip_options {
532 my ($self, $hash) = @_;
533 my $clean_hash = {};
534 $clean_hash->{$_} = $hash->{$_}
535 for grep {!/^-/} keys %$hash;
536 return $clean_hash;
537}
538
539sub _join_condition {
540 my ($self, $cond) = @_;
541 if (ref $cond eq 'HASH') {
542 my %j;
543 for (keys %$cond) {
544 my $v = $cond->{$_};
545 if (ref $v) {
e8fcf76f 546 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 547 if ref($v) ne 'SCALAR';
548 $j{$_} = $v;
549 }
550 else {
551 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
552 }
553 };
554 return scalar($self->_recurse_where(\%j));
555 } elsif (ref $cond eq 'ARRAY') {
556 return join(' OR ', map { $self->_join_condition($_) } @$cond);
557 } else {
558 die "Can't handle this yet!";
559 }
560}
561
562sub _quote {
563 my ($self, $label) = @_;
564 return '' unless defined $label;
565 return "*" if $label eq '*';
566 return $label unless $self->{quote_char};
567 if(ref $self->{quote_char} eq "ARRAY"){
568 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
569 if !defined $self->{name_sep};
570 my $sep = $self->{name_sep};
571 return join($self->{name_sep},
572 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
573 split(/\Q$sep\E/,$label));
574 }
575 return $self->SUPER::_quote($label);
576}
577
578sub limit_dialect {
579 my $self = shift;
580 $self->{limit_dialect} = shift if @_;
581 return $self->{limit_dialect};
582}
583
584sub quote_char {
585 my $self = shift;
586 $self->{quote_char} = shift if @_;
587 return $self->{quote_char};
588}
589
590sub name_sep {
591 my $self = shift;
592 $self->{name_sep} = shift if @_;
593 return $self->{name_sep};
594}
595
5961;
597
598__END__
599
600=pod
601
602=head1 NAME
603
855c6fd0 604DBIx::Class::SQLAHacks - This module is a subclass of SQL::Abstract::Limit
605and includes a number of DBIC-specific workarounds, not yet suitable for
606inclusion into SQLA proper.
6f4ddea1 607
608=head1 METHODS
609
610=head2 new
611
612Tries to determine limit dialect.
613
614=head2 select
615
616Quotes table names, handles "limit" dialects (e.g. where rownum between x and
617y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
618
619=head2 insert update delete
620
621Just quotes table names.
622
623=head2 limit_dialect
624
625Specifies the dialect of used for implementing an SQL "limit" clause for
626restricting the number of query results returned. Valid values are: RowNum.
627
628See L<DBIx::Class::Storage::DBI/connect_info> for details.
629
630=head2 name_sep
631
632Character separating quoted table names.
633
634See L<DBIx::Class::Storage::DBI/connect_info> for details.
635
636=head2 quote_char
637
638Set to an array-ref to specify separate left and right quotes for table names.
639
640See L<DBIx::Class::Storage::DBI/connect_info> for details.
641
642=cut
643