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