1 package # Hide from PAUSE
2 DBIx::Class::SQLAHacks;
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
8 use base qw/SQL::Abstract::Limit/;
11 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract/;
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/;
19 for my $f (qw/carp croak/) {
21 my $orig = \&{"SQL::Abstract::$f"};
22 *{"SQL::Abstract::$f"} = Sub::Name::subname "SQL::Abstract::$f" =>
24 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
25 __PACKAGE__->can($f)->(@_);
35 # Tries to determine limit dialect.
38 my $self = shift->SUPER::new(@_);
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};
49 # !!! THIS IS ALSO HORRIFIC !!! /me ashamed
51 # generate inner/outer select lists for various limit dialects
52 # which result in one or more subqueries (e.g. RNO, Top, RowNum)
53 # Any non-root-table columns need to have their table qualifier
54 # turned into a column alias (otherwise names in subqueries clash
55 # and/or lose their source table)
57 # returns inner/outer strings of SQL QUOTED selectors with aliases
58 # (to be used in whatever select statement), and an alias index hashref
59 # of QUOTED SEL => QUOTED ALIAS pairs (to maybe be used for string-subst
62 # If the $scan_order option is supplied, it signals that the limit dialect
63 # needs to order the outer side of the query, which in turn means that the
64 # inner select needs to bring out columns used in implicit (non-selected)
65 # orders, and the order condition itself needs to be realiased to the proper
66 # names in the outer query.
68 # In this case ($scan_order os true) we also return a hashref (order doesn't
69 # matter) of QUOTED EXTRA-SEL => QUOTED ALIAS pairs, which is a list of extra
70 # selectors that do *not* exist in the original select list
72 sub _subqueried_limit_attrs {
73 my ($self, $rs_attrs, $scan_order) = @_;
75 croak 'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)'
76 unless ref ($rs_attrs) eq 'HASH';
78 my ($re_sep, $re_alias) = map { quotemeta $_ } (
79 $self->name_sep || '.',
83 # correlate select and as, build selection index
84 my (@sel, $in_sel_index);
85 for my $i (0 .. $#{$rs_attrs->{select}}) {
87 my $s = $rs_attrs->{select}[$i];
88 my $sql_sel = $self->_recurse_fields ($s);
89 my $sql_alias = (ref $s) eq 'HASH' ? $s->{-as} : undef;
94 unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) },
100 croak "Select argument $i ($s) without corresponding 'as'"
104 $in_sel_index->{$sql_sel}++;
105 $in_sel_index->{$self->_quote ($sql_alias)}++ if $sql_alias;
107 # this *may* turn out to be necessary, not sure yet
108 # my ($sql_unqualified_sel) = $sql_sel =~ / $re_sep (.+) $/x
110 # $in_sel_index->{$sql_unqualified_sel}++;
114 # re-alias and remove any name separators from aliases,
115 # unless we are dealing with the current source alias
116 # (which will transcend the subqueries as it is necessary
117 # for possible further chaining)
118 my (@in_sel, @out_sel, %renamed);
119 for my $node (@sel) {
120 if (List::Util::first { $_ =~ / (?<! $re_alias ) $re_sep /x } ($node->{as}, $node->{unquoted_sql}) ) {
121 $node->{as} =~ s/ $re_sep /__/xg;
122 my $quoted_as = $self->_quote($node->{as});
123 push @in_sel, sprintf '%s AS %s', $node->{sql}, $quoted_as;
124 push @out_sel, $quoted_as;
125 $renamed{$node->{sql}} = $quoted_as;
128 push @in_sel, $node->{sql};
129 push @out_sel, $self->_quote ($node->{as});
135 for my $chunk ($self->_order_by_chunks (
136 ref $rs_attrs->{order_by} eq 'ARRAY'
137 ? @{$rs_attrs->{order_by}}
138 : $rs_attrs->{order_by}
141 $chunk = $chunk->[0] if (ref $chunk) eq 'ARRAY';
142 $chunk =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
144 next if $in_sel_index->{$chunk};
146 $extra_order_sel{$chunk} ||= $self->_quote (
147 '__ORDER_BY_' . scalar keys %extra_order_sel
152 (map { join (', ', @$_ ) } (
157 keys %extra_order_sel ? \%extra_order_sel : (),
161 # ANSI standard Limit/Offset implementation. DB2 and MSSQL >= 2005 use this
163 my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
165 # mangle the input sql as we will be replacing the selector
166 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
167 or croak "Unrecognizable SELECT: $sql";
169 # get selectors, and scan the order_by (if any)
170 my ($in_sel, $out_sel, $alias_map, $extra_order_sel) = $self->_subqueried_limit_attrs (
171 $rs_attrs, 'scan_order_by',
174 # make up an order if none exists
175 my $requested_order = (delete $rs_attrs->{order_by}) || $self->_rno_default_order;
176 my $rno_ord = $self->_order_by ($requested_order);
178 # this is the order supplement magic
179 my $mid_sel = $out_sel;
180 if ($extra_order_sel) {
181 for my $extra_col (keys %$extra_order_sel) {
182 $in_sel .= sprintf (', %s AS %s',
184 $extra_order_sel->{$extra_col},
187 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
191 # and this is order re-alias magic
192 for ($extra_order_sel, $alias_map) {
193 for my $col (keys %$_) {
194 my $re_col = quotemeta ($col);
195 $rno_ord =~ s/$re_col/$_->{$col}/;
199 # whatever is left of the order_by (only where is processed at this point)
200 my $group_having = $self->_parse_rs_attrs($rs_attrs);
202 my $qalias = $self->_quote ($rs_attrs->{alias});
203 my $idx_name = $self->_quote ('rno__row__index');
205 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
207 SELECT $out_sel FROM (
208 SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM (
209 SELECT $in_sel ${sql}${group_having}
211 ) $qalias WHERE $idx_name BETWEEN %d AND %d
215 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
219 # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
220 sub _rno_default_order {
224 # Informix specific limit, almost like LIMIT/OFFSET
226 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
228 $sql =~ s/^ \s* SELECT \s+ //ix
229 or croak "Unrecognizable SELECT: $sql";
231 return sprintf ('SELECT %s%s%s%s',
233 ? sprintf ('SKIP %d ', $offset)
236 sprintf ('FIRST %d ', $rows),
238 $self->_parse_rs_attrs ($rs_attrs),
242 # Firebird specific limit, reverse of _SkipFirst for Informix
244 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
246 $sql =~ s/^ \s* SELECT \s+ //ix
247 or croak "Unrecognizable SELECT: $sql";
249 return sprintf ('SELECT %s%s%s%s',
250 sprintf ('FIRST %d ', $rows),
252 ? sprintf ('SKIP %d ', $offset)
256 $self->_parse_rs_attrs ($rs_attrs),
262 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
264 # mangle the input sql as we will be replacing the selector
265 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
266 or croak "Unrecognizable SELECT: $sql";
268 my ($insel, $outsel) = $self->_subqueried_limit_attrs ($rs_attrs);
270 my $qalias = $self->_quote ($rs_attrs->{alias});
271 my $idx_name = $self->_quote ('rownum__index');
272 my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
274 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
276 SELECT $outsel FROM (
277 SELECT $outsel, ROWNUM $idx_name FROM (
278 SELECT $insel ${sql}${order_group_having}
280 ) $qalias WHERE $idx_name BETWEEN %d AND %d
284 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
288 # Crappy Top based Limit/Offset support. Legacy for MSSQL < 2005
290 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
292 # mangle the input sql as we will be replacing the selector
293 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
294 or croak "Unrecognizable SELECT: $sql";
297 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
298 = $self->_subqueried_limit_attrs ($rs_attrs, 'outer_order_by');
300 my $requested_order = delete $rs_attrs->{order_by};
302 my $order_by_requested = $self->_order_by ($requested_order);
304 # make up an order unless supplied
305 my $inner_order = ($order_by_requested
308 { join ('', $rs_attrs->{alias}, $self->{name_sep}||'.', $_ ) }
309 ( $rs_attrs->{_rsroot_source_handle}->resolve->_pri_cols )
313 my ($order_by_inner, $order_by_reversed);
315 # localise as we already have all the bind values we need
317 local $self->{order_bind};
318 $order_by_inner = $self->_order_by ($inner_order);
321 for my $ch ($self->_order_by_chunks ($inner_order)) {
322 $ch = $ch->[0] if ref $ch eq 'ARRAY';
323 $ch =~ s/\s+ ( ASC|DESC ) \s* $//ix;
324 my $dir = uc ($1||'ASC');
326 push @out_chunks, \join (' ', $ch, $dir eq 'ASC' ? 'DESC' : 'ASC' );
329 $order_by_reversed = $self->_order_by (@out_chunks);
332 # this is the order supplement magic
333 my $mid_sel = $out_sel;
334 if ($extra_order_sel) {
335 for my $extra_col (keys %$extra_order_sel) {
336 $in_sel .= sprintf (', %s AS %s',
338 $extra_order_sel->{$extra_col},
341 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
345 # and this is order re-alias magic
346 for my $map ($extra_order_sel, $alias_map) {
347 for my $col (keys %$map) {
348 my $re_col = quotemeta ($col);
349 $_ =~ s/$re_col/$map->{$col}/
350 for ($order_by_reversed, $order_by_requested);
354 # generate the rest of the sql
355 my $grpby_having = $self->_parse_rs_attrs ($rs_attrs);
357 my $quoted_rs_alias = $self->_quote ($rs_attrs->{alias});
359 $sql = sprintf ('SELECT TOP %d %s %s %s %s',
360 $rows + ($offset||0),
367 $sql = sprintf ('SELECT TOP %d %s FROM ( %s ) %s %s',
375 $sql = sprintf ('SELECT TOP %d %s FROM ( %s ) %s %s',
381 ) if $order_by_requested;
383 $sql = sprintf ('SELECT TOP %d %s FROM ( %s ) %s',
388 ) if ($mid_sel ne $out_sel);
394 # While we're at it, this should make LIMIT queries more efficient,
395 # without digging into things too deeply
397 my ($self, $syntax) = @_;
398 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
401 # Quotes table names, handles "limit" dialects (e.g. where rownum between x and
404 my ($self, $table, $fields, $where, $rs_attrs, @rest) = @_;
406 $self->{"${_}_bind"} = [] for (qw/having from order/);
408 if (not ref($table) or ref($table) eq 'SCALAR') {
409 $table = $self->_quote($table);
412 local $self->{rownum_hack_count} = 1
413 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
414 @rest = (-1) unless defined $rest[0];
415 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
416 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
418 my ($sql, @where_bind) = $self->SUPER::select(
419 $table, $self->_recurse_fields($fields), $where, $rs_attrs, @rest
421 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
424 # Quotes table names, and handles default inserts
428 $table = $self->_quote($table);
430 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
431 # which is sadly understood only by MySQL. Change default behavior here,
432 # until SQLA2 comes with proper dialect support
433 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
434 my $sql = "INSERT INTO ${table} DEFAULT VALUES";
436 if (my $ret = ($_[1]||{})->{returning} ) {
437 $sql .= $self->_insert_returning ($ret);
443 $self->SUPER::insert($table, @_);
446 # Just quotes table names.
450 $table = $self->_quote($table);
451 $self->SUPER::update($table, @_);
454 # Just quotes table names.
458 $table = $self->_quote($table);
459 $self->SUPER::delete($table, @_);
464 # my ( $syntax, $sql, $order, $rows, $offset ) = @_;
467 return $_[1] . $self->_parse_rs_attrs($_[2]);
469 return $self->SUPER::_emulate_limit(@_);
473 sub _recurse_fields {
474 my ($self, $fields) = @_;
475 my $ref = ref $fields;
476 return $self->_quote($fields) unless $ref;
477 return $$fields if $ref eq 'SCALAR';
479 if ($ref eq 'ARRAY') {
480 return join(', ', map { $self->_recurse_fields($_) } @$fields);
482 elsif ($ref eq 'HASH') {
483 my %hash = %$fields; # shallow copy
485 my $as = delete $hash{-as}; # if supplied
487 my ($func, $args, @toomany) = %hash;
489 # there should be only one pair
491 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
494 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
496 'The select => { distinct => ... } syntax is not supported for multiple columns.'
497 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
498 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
502 my $select = sprintf ('%s( %s )%s',
503 $self->_sqlcase($func),
504 $self->_recurse_fields($args),
506 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
512 # Is the second check absolutely necessary?
513 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
514 return $self->_fold_sqlbind( $fields );
517 croak($ref . qq{ unexpected in _recurse_fields()})
522 update => 'FOR UPDATE',
523 shared => 'FOR SHARE',
526 # this used to be a part of _order_by but is broken out for clarity.
527 # What we have been doing forever is hijacking the $order arg of
528 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
529 # then pretty much the entire resultset attr-hash, as more and more
530 # things in the SQLA space need to have mopre info about the $rs they
531 # create SQL for. The alternative would be to keep expanding the
532 # signature of _select with more and more positional parameters, which
533 # is just gross. All hail SQLA2!
534 sub _parse_rs_attrs {
535 my ($self, $arg) = @_;
539 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
540 $sql .= $self->_sqlcase(' group by ') . $g;
543 if (defined $arg->{having}) {
544 my ($frag, @bind) = $self->_recurse_where($arg->{having});
545 push(@{$self->{having_bind}}, @bind);
546 $sql .= $self->_sqlcase(' having ') . $frag;
549 if (defined $arg->{order_by}) {
550 $sql .= $self->_order_by ($arg->{order_by});
553 if (my $for = $arg->{for}) {
554 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
561 my ($self, $arg) = @_;
563 # check that we are not called in legacy mode (order_by as 4th argument)
564 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
565 return $self->_parse_rs_attrs ($arg);
568 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
569 push @{$self->{order_bind}}, @bind;
574 sub _order_directions {
575 my ($self, $order) = @_;
577 # strip bind values - none of the current _order_directions users support them
578 return $self->SUPER::_order_directions( [ map
579 { ref $_ ? $_->[0] : $_ }
580 $self->_order_by_chunks ($order)
585 my ($self, $from) = @_;
586 if (ref $from eq 'ARRAY') {
587 return $self->_recurse_from(@$from);
588 } elsif (ref $from eq 'HASH') {
589 return $self->_make_as($from);
591 return $from; # would love to quote here but _table ends up getting called
592 # twice during an ->select without a limit clause due to
593 # the way S::A::Limit->select works. should maybe consider
594 # bypassing this and doing S::A::select($self, ...) in
595 # our select method above. meantime, quoting shims have
596 # been added to select/insert/update/delete here
600 sub _generate_join_clause {
601 my ($self, $join_type) = @_;
603 return sprintf ('%s JOIN ',
604 $join_type ? ' ' . uc($join_type) : ''
609 my ($self, $from, @join) = @_;
611 push(@sqlf, $self->_make_as($from));
612 foreach my $j (@join) {
616 # check whether a join type exists
617 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
619 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
620 $join_type = $to_jt->{-join_type};
621 $join_type =~ s/^\s+ | \s+$//xg;
624 $join_type = $self->{_default_jointype} if not defined $join_type;
626 push @sqlf, $self->_generate_join_clause( $join_type );
628 if (ref $to eq 'ARRAY') {
629 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
631 push(@sqlf, $self->_make_as($to));
633 push(@sqlf, ' ON ', $self->_join_condition($on));
635 return join('', @sqlf);
639 my ($self, $sqlbind) = @_;
641 my @sqlbind = @$$sqlbind; # copy
642 my $sql = shift @sqlbind;
643 push @{$self->{from_bind}}, @sqlbind;
649 my ($self, $from) = @_;
650 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
651 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
653 } reverse each %{$self->_skip_options($from)});
657 my ($self, $hash) = @_;
659 $clean_hash->{$_} = $hash->{$_}
660 for grep {!/^-/} keys %$hash;
664 sub _join_condition {
665 my ($self, $cond) = @_;
666 if (ref $cond eq 'HASH') {
671 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
672 if ref($v) ne 'SCALAR';
676 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
679 return scalar($self->_recurse_where(\%j));
680 } elsif (ref $cond eq 'ARRAY') {
681 return join(' OR ', map { $self->_join_condition($_) } @$cond);
683 die "Can't handle this yet!";
690 $self->{limit_dialect} = shift;
691 undef $self->{_cached_syntax};
693 return $self->{limit_dialect};
696 # Set to an array-ref to specify separate left and right quotes for table names.
697 # A single scalar is equivalen to [ $char, $char ]
700 $self->{quote_char} = shift if @_;
701 return $self->{quote_char};
704 # Character separating quoted table names.
707 $self->{name_sep} = shift if @_;
708 return $self->{name_sep};