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 # generate inner/outer select lists for various limit dialects
50 # which result in one or more subqueries (e.g. RNO, Top, RowNum)
51 # Any non-root-table columns need to have their table qualifier
52 # turned into a column name (otherwise names in subqueries clash
53 # and/or lose their source table)
54 sub _subqueried_selection {
55 my ($self, $rs_attrs) = @_;
57 croak 'Limit usable only in the context of DBIC (missing $rs_attrs)' unless $rs_attrs;
59 # correlate select and as
61 for my $i (0 .. $#{$rs_attrs->{select}}) {
62 my $s = $rs_attrs->{select}[$i];
64 sql => $self->_recurse_fields ($s),
65 unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) },
67 ( (ref $s) eq 'HASH' ? $s->{-as} : undef)
71 croak "Select argument $i ($s) without corresponding 'as'"
76 my ($qsep, $qalias) = map { quotemeta $_ } (
77 $self->name_sep || '.',
81 # re-alias and remove any name separators from aliases,
82 # unless we are dealing with the current source alias
83 # (which will transcend the subqueries and is necessary
84 # for possible further chaining)
87 if (List::Util::first { $_ =~ / (?<! $qalias ) $qsep /x } ($node->{as}, $node->{unquoted_sql}) ) {
88 $node->{as} =~ s/ $qsep /__/xg;
89 push @insel, sprintf '%s AS %s', $node->{sql}, $self->_quote($node->{as});
90 push @outsel, $self->_quote ($node->{as});
93 push @insel, $node->{sql};
94 push @outsel, $self->_quote ($node->{as});
98 return map { join (', ', @$_ ) } (\@insel, \@outsel);
102 # ANSI standard Limit/Offset implementation. DB2 and MSSQL use this
104 my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
106 # mangle the input sql as we will be replacing the selector
107 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
108 or croak "Unrecognizable SELECT: $sql";
111 my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
113 # make up an order if none exists
114 my $order_by = $self->_order_by(
115 (delete $rs_attrs->{order_by}) || $self->_rno_default_order
118 # whatever is left of the order_by (only where is processed at this point)
119 my $group_having = $self->_parse_rs_attrs($rs_attrs);
121 my $qalias = $self->_quote ($rs_attrs->{alias});
123 my $idx_name = $self->_quote ('rno__row__index');
125 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
127 SELECT $outsel FROM (
128 SELECT $outsel, ROW_NUMBER() OVER($order_by ) AS $idx_name FROM (
129 SELECT $insel ${sql}${group_having}
131 ) $qalias WHERE $idx_name BETWEEN %d AND %d
135 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
139 # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
140 sub _rno_default_order {
144 # Informix specific limit, almost like LIMIT/OFFSET
146 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
148 $sql =~ s/^ \s* SELECT \s+ //ix
149 or croak "Unrecognizable SELECT: $sql";
151 return sprintf ('SELECT %s%s%s%s',
153 ? sprintf ('SKIP %d ', $offset)
156 sprintf ('FIRST %d ', $rows),
158 $self->_parse_rs_attrs ($rs_attrs),
162 # Firebird specific limit, reverse of _SkipFirst for Informix
164 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
166 $sql =~ s/^ \s* SELECT \s+ //ix
167 or croak "Unrecognizable SELECT: $sql";
169 return sprintf ('SELECT %s%s%s%s',
170 sprintf ('FIRST %d ', $rows),
172 ? sprintf ('SKIP %d ', $offset)
176 $self->_parse_rs_attrs ($rs_attrs),
182 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
184 # mangle the input sql as we will be replacing the selector
185 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
186 or croak "Unrecognizable SELECT: $sql";
188 my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
190 my $qalias = $self->_quote ($rs_attrs->{alias});
191 my $idx_name = $self->_quote ('rownum__index');
192 my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
194 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
196 SELECT $outsel FROM (
197 SELECT $outsel, ROWNUM $idx_name FROM (
198 SELECT $insel ${sql}${order_group_having}
200 ) $qalias WHERE $idx_name BETWEEN %d AND %d
204 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
209 # Crappy Top based Limit/Offset support. Legacy from MSSQL.
211 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
213 # mangle the input sql as we will be replacing the selector
214 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
215 or croak "Unrecognizable SELECT: $sql";
218 my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
221 my $rs_alias = $rs_attrs->{alias};
222 my $req_order = delete $rs_attrs->{order_by};
223 my $name_sep = $self->name_sep || '.';
225 # examine normalized version, collapses nesting
226 my $limit_order = scalar $self->_order_by_chunks ($req_order)
229 { join ('', $rs_alias, $name_sep, $_ ) }
230 ( $rs_attrs->{_rsroot_source_handle}->resolve->primary_columns )
234 my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
235 my $order_by_requested = $self->_order_by ($req_order);
240 my $esc_name_sep = "\Q$name_sep\E";
241 my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
243 my $quoted_rs_alias = $self->_quote ($rs_alias);
245 # construct the new select lists, rename(alias) some columns if necessary
246 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
248 for (@{$rs_attrs->{select}}) {
250 my ($table, $orig_colname) = ( $_ =~ $col_re );
252 $seen_names{$orig_colname}++;
255 for my $i (0 .. $#sql_select) {
257 my $colsel_arg = $rs_attrs->{select}[$i];
258 my $colsel_sql = $sql_select[$i];
260 # this may or may not work (in case of a scalarref or something)
261 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
264 # do not attempt to understand non-scalar selects - alias numerically
265 if (ref $colsel_arg) {
266 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
268 # column name seen more than once - alias it
269 elsif ($orig_colname &&
270 ($seen_names{$orig_colname} && $seen_names{$orig_colname} > 1) ) {
271 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
274 # we did rename - make a record and adjust
277 push @inner_select, "$colsel_sql AS $quoted_alias";
279 # push alias to outer
280 push @outer_select, $quoted_alias;
282 # Any aliasing accumulated here will be considered
283 # both for inner and outer adjustments of ORDER BY
284 $self->__record_alias (
288 $table ? $orig_colname : undef,
292 # otherwise just leave things intact inside, and use the abbreviated one outside
293 # (as we do not have table names anymore)
295 push @inner_select, $colsel_sql;
297 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
298 push @outer_select, $outer_quoted;
299 $self->__record_alias (
303 $table ? $orig_colname : undef,
308 my $outer_select = join (', ', @outer_select );
309 my $inner_select = join (', ', @inner_select );
311 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
317 my $grpby_having = $self->_parse_rs_attrs ($rs_attrs);
319 # short circuit for counts - the ordering complexity is needless
320 if ($rs_attrs->{-for_count_only}) {
321 return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
324 # we can't really adjust the order_by columns, as introspection is lacking
325 # resort to simple substitution
326 for my $col (keys %outer_col_aliases) {
327 for ($order_by_requested, $order_by_outer) {
328 $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
331 for my $col (keys %col_aliases) {
332 $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
336 my $inner_lim = $rows + $offset;
338 $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
343 SELECT TOP $rows $outer_select FROM
352 if ($order_by_requested) {
355 SELECT $outer_select FROM
356 ( $sql ) $quoted_rs_alias
362 $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
367 # While we're at it, this should make LIMIT queries more efficient,
368 # without digging into things too deeply
370 my ($self, $syntax) = @_;
371 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
374 # Quotes table names, handles "limit" dialects (e.g. where rownum between x and
377 my ($self, $table, $fields, $where, $rs_attrs, @rest) = @_;
379 $self->{"${_}_bind"} = [] for (qw/having from order/);
381 if (not ref($table) or ref($table) eq 'SCALAR') {
382 $table = $self->_quote($table);
385 local $self->{rownum_hack_count} = 1
386 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
387 @rest = (-1) unless defined $rest[0];
388 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
389 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
391 my ($sql, @where_bind) = $self->SUPER::select(
392 $table, $self->_recurse_fields($fields), $where, $rs_attrs, @rest
394 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
397 # Quotes table names, and handles default inserts
401 $table = $self->_quote($table);
403 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
404 # which is sadly understood only by MySQL. Change default behavior here,
405 # until SQLA2 comes with proper dialect support
406 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
407 my $sql = "INSERT INTO ${table} DEFAULT VALUES";
409 if (my $ret = ($_[1]||{})->{returning} ) {
410 $sql .= $self->_insert_returning ($ret);
416 $self->SUPER::insert($table, @_);
419 # Just quotes table names.
423 $table = $self->_quote($table);
424 $self->SUPER::update($table, @_);
427 # Just quotes table names.
431 $table = $self->_quote($table);
432 $self->SUPER::delete($table, @_);
437 # my ( $syntax, $sql, $order, $rows, $offset ) = @_;
440 return $_[1] . $self->_parse_rs_attrs($_[2]);
442 return $self->SUPER::_emulate_limit(@_);
446 sub _recurse_fields {
447 my ($self, $fields) = @_;
448 my $ref = ref $fields;
449 return $self->_quote($fields) unless $ref;
450 return $$fields if $ref eq 'SCALAR';
452 if ($ref eq 'ARRAY') {
453 return join(', ', map { $self->_recurse_fields($_) } @$fields);
455 elsif ($ref eq 'HASH') {
456 my %hash = %$fields; # shallow copy
458 my $as = delete $hash{-as}; # if supplied
460 my ($func, $args, @toomany) = %hash;
462 # there should be only one pair
464 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
467 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
469 'The select => { distinct => ... } syntax is not supported for multiple columns.'
470 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
471 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
475 my $select = sprintf ('%s( %s )%s',
476 $self->_sqlcase($func),
477 $self->_recurse_fields($args),
479 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
485 # Is the second check absolutely necessary?
486 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
487 return $self->_fold_sqlbind( $fields );
490 croak($ref . qq{ unexpected in _recurse_fields()})
495 update => 'FOR UPDATE',
496 shared => 'FOR SHARE',
499 # this used to be a part of _order_by but is broken out for clarity.
500 # What we have been doing forever is hijacking the $order arg of
501 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
502 # then pretty much the entire resultset attr-hash, as more and more
503 # things in the SQLA space need to have mopre info about the $rs they
504 # create SQL for. The alternative would be to keep expanding the
505 # signature of _select with more and more positional parameters, which
506 # is just gross. All hail SQLA2!
507 sub _parse_rs_attrs {
508 my ($self, $arg) = @_;
512 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
513 $sql .= $self->_sqlcase(' group by ') . $g;
516 if (defined $arg->{having}) {
517 my ($frag, @bind) = $self->_recurse_where($arg->{having});
518 push(@{$self->{having_bind}}, @bind);
519 $sql .= $self->_sqlcase(' having ') . $frag;
522 if (defined $arg->{order_by}) {
523 $sql .= $self->_order_by ($arg->{order_by});
526 if (my $for = $arg->{for}) {
527 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
534 my ($self, $arg) = @_;
536 # check that we are not called in legacy mode (order_by as 4th argument)
537 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
538 return $self->_parse_rs_attrs ($arg);
541 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
542 push @{$self->{order_bind}}, @bind;
547 sub _order_directions {
548 my ($self, $order) = @_;
550 # strip bind values - none of the current _order_directions users support them
551 return $self->SUPER::_order_directions( [ map
552 { ref $_ ? $_->[0] : $_ }
553 $self->_order_by_chunks ($order)
558 my ($self, $from) = @_;
559 if (ref $from eq 'ARRAY') {
560 return $self->_recurse_from(@$from);
561 } elsif (ref $from eq 'HASH') {
562 return $self->_make_as($from);
564 return $from; # would love to quote here but _table ends up getting called
565 # twice during an ->select without a limit clause due to
566 # the way S::A::Limit->select works. should maybe consider
567 # bypassing this and doing S::A::select($self, ...) in
568 # our select method above. meantime, quoting shims have
569 # been added to select/insert/update/delete here
573 sub _generate_join_clause {
574 my ($self, $join_type) = @_;
576 return sprintf ('%s JOIN ',
577 $join_type ? ' ' . uc($join_type) : ''
582 my ($self, $from, @join) = @_;
584 push(@sqlf, $self->_make_as($from));
585 foreach my $j (@join) {
589 # check whether a join type exists
590 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
592 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
593 $join_type = $to_jt->{-join_type};
594 $join_type =~ s/^\s+ | \s+$//xg;
597 $join_type = $self->{_default_jointype} if not defined $join_type;
599 push @sqlf, $self->_generate_join_clause( $join_type );
601 if (ref $to eq 'ARRAY') {
602 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
604 push(@sqlf, $self->_make_as($to));
606 push(@sqlf, ' ON ', $self->_join_condition($on));
608 return join('', @sqlf);
612 my ($self, $sqlbind) = @_;
614 my @sqlbind = @$$sqlbind; # copy
615 my $sql = shift @sqlbind;
616 push @{$self->{from_bind}}, @sqlbind;
622 my ($self, $from) = @_;
623 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
624 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
626 } reverse each %{$self->_skip_options($from)});
630 my ($self, $hash) = @_;
632 $clean_hash->{$_} = $hash->{$_}
633 for grep {!/^-/} keys %$hash;
637 sub _join_condition {
638 my ($self, $cond) = @_;
639 if (ref $cond eq 'HASH') {
644 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
645 if ref($v) ne 'SCALAR';
649 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
652 return scalar($self->_recurse_where(\%j));
653 } elsif (ref $cond eq 'ARRAY') {
654 return join(' OR ', map { $self->_join_condition($_) } @$cond);
656 die "Can't handle this yet!";
663 $self->{limit_dialect} = shift;
664 undef $self->{_cached_syntax};
666 return $self->{limit_dialect};
669 # Set to an array-ref to specify separate left and right quotes for table names.
670 # A single scalar is equivalen to [ $char, $char ]
673 $self->{quote_char} = shift if @_;
674 return $self->{quote_char};
677 # Character separating quoted table names.
680 $self->{name_sep} = shift if @_;
681 return $self->{name_sep};