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};
50 # ANSI standard Limit/Offset implementation. DB2 and MSSQL use this
52 my ($self, $sql, $order, $rows, $offset ) = @_;
54 # get the select to make the final amount of columns equal the original one
55 my ($select) = $sql =~ /^ \s* SELECT \s+ (.+?) \s+ FROM/ix
56 or croak "Unrecognizable SELECT: $sql";
58 # get the order_by only (or make up an order if none exists)
59 my $order_by = $self->_order_by(
60 (delete $order->{order_by}) || $self->_rno_default_order
63 # whatever is left of the order_by
64 my $group_having = $self->_order_by($order);
66 my $qalias = $self->_quote ($self->{_dbic_rs_attrs}{alias});
68 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
71 SELECT $qalias.*, ROW_NUMBER() OVER($order_by ) AS rno__row__index FROM (
74 ) $qalias WHERE rno__row__index BETWEEN %d AND %d
78 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
82 # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
83 sub _rno_default_order {
87 # Informix specific limit, almost like LIMIT/OFFSET
89 my ($self, $sql, $order, $rows, $offset) = @_;
91 $sql =~ s/^ \s* SELECT \s+ //ix
92 or croak "Unrecognizable SELECT: $sql";
94 return sprintf ('SELECT %s%s%s%s',
96 ? sprintf ('SKIP %d ', $offset)
99 sprintf ('FIRST %d ', $rows),
101 $self->_order_by ($order),
105 # Firebird specific limit, reverse of _SkipFirst for Informix
107 my ($self, $sql, $order, $rows, $offset) = @_;
109 $sql =~ s/^ \s* SELECT \s+ //ix
110 or croak "Unrecognizable SELECT: $sql";
112 return sprintf ('SELECT %s%s%s%s',
113 sprintf ('FIRST %d ', $rows),
115 ? sprintf ('SKIP %d ', $offset)
119 $self->_order_by ($order),
123 # Crappy Top based Limit/Offset support. Legacy from MSSQL.
125 my ( $self, $sql, $order, $rows, $offset ) = @_;
127 # mangle the input sql so it can be properly aliased in the outer queries
128 $sql =~ s/^ \s* SELECT \s+ (.+?) \s+ (?=FROM)//ix
129 or croak "Unrecognizable SELECT: $sql";
131 my @sql_select = split (/\s*,\s*/, $sql_select);
133 # we can't support subqueries (in fact MSSQL can't) - croak
134 if (@sql_select != @{$self->{_dbic_rs_attrs}{select}}) {
136 'SQL SELECT did not parse cleanly - retrieved %d comma separated elements, while '
137 . 'the resultset select attribure contains %d elements: %s',
139 scalar @{$self->{_dbic_rs_attrs}{select}},
144 my $name_sep = $self->name_sep || '.';
145 my $esc_name_sep = "\Q$name_sep\E";
146 my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
148 my $rs_alias = $self->{_dbic_rs_attrs}{alias};
149 my $quoted_rs_alias = $self->_quote ($rs_alias);
151 # construct the new select lists, rename(alias) some columns if necessary
152 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
154 for (@{$self->{_dbic_rs_attrs}{select}}) {
156 my ($table, $orig_colname) = ( $_ =~ $col_re );
158 $seen_names{$orig_colname}++;
161 for my $i (0 .. $#sql_select) {
163 my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
164 my $colsel_sql = $sql_select[$i];
166 # this may or may not work (in case of a scalarref or something)
167 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
170 # do not attempt to understand non-scalar selects - alias numerically
171 if (ref $colsel_arg) {
172 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
174 # column name seen more than once - alias it
175 elsif ($orig_colname &&
176 ($seen_names{$orig_colname} && $seen_names{$orig_colname} > 1) ) {
177 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
180 # we did rename - make a record and adjust
183 push @inner_select, "$colsel_sql AS $quoted_alias";
185 # push alias to outer
186 push @outer_select, $quoted_alias;
188 # Any aliasing accumulated here will be considered
189 # both for inner and outer adjustments of ORDER BY
190 $self->__record_alias (
194 $table ? $orig_colname : undef,
198 # otherwise just leave things intact inside, and use the abbreviated one outside
199 # (as we do not have table names anymore)
201 push @inner_select, $colsel_sql;
203 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
204 push @outer_select, $outer_quoted;
205 $self->__record_alias (
209 $table ? $orig_colname : undef,
214 my $outer_select = join (', ', @outer_select );
215 my $inner_select = join (', ', @inner_select );
217 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
220 croak '$order supplied to SQLAHacks limit emulators must be a hash'
221 if (ref $order ne 'HASH');
223 $order = { %$order }; #copy
225 my $req_order = $order->{order_by};
227 # examine normalized version, collapses nesting
229 if (scalar $self->_order_by_chunks ($req_order)) {
230 $limit_order = $req_order;
234 { join ('', $rs_alias, $name_sep, $_ ) }
235 ( $self->{_dbic_rs_attrs}{_source_handle}->resolve->primary_columns )
239 my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
240 my $order_by_requested = $self->_order_by ($req_order);
243 delete $order->{order_by};
244 my $grpby_having = $self->_order_by ($order);
246 # short circuit for counts - the ordering complexity is needless
247 if ($self->{_dbic_rs_attrs}{-for_count_only}) {
248 return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
251 # we can't really adjust the order_by columns, as introspection is lacking
252 # resort to simple substitution
253 for my $col (keys %outer_col_aliases) {
254 for ($order_by_requested, $order_by_outer) {
255 $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
258 for my $col (keys %col_aliases) {
259 $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
263 my $inner_lim = $rows + $offset;
265 $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
270 SELECT TOP $rows $outer_select FROM
279 if ($order_by_requested) {
282 SELECT $outer_select FROM
283 ( $sql ) $quoted_rs_alias
289 $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
293 # action at a distance to shorten Top code above
295 my ($self, $register, $alias, $fqcol, $col) = @_;
297 # record qualified name
298 $register->{$fqcol} = $alias;
299 $register->{$self->_quote($fqcol)} = $alias;
303 # record unqualified name, undef (no adjustment) if a duplicate is found
304 if (exists $register->{$col}) {
305 $register->{$col} = undef;
308 $register->{$col} = $alias;
311 $register->{$self->_quote($col)} = $register->{$col};
316 # While we're at it, this should make LIMIT queries more efficient,
317 # without digging into things too deeply
319 my ($self, $syntax) = @_;
320 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
324 update => 'FOR UPDATE',
325 shared => 'FOR SHARE',
327 # Quotes table names, handles "limit" dialects (e.g. where rownum between x and
328 # y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
330 my ($self, $table, $fields, $where, $order, @rest) = @_;
332 $self->{"${_}_bind"} = [] for (qw/having from order/);
334 if (not ref($table) or ref($table) eq 'SCALAR') {
335 $table = $self->_quote($table);
338 local $self->{rownum_hack_count} = 1
339 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
340 @rest = (-1) unless defined $rest[0];
341 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
342 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
343 my ($sql, @where_bind) = $self->SUPER::select(
344 $table, $self->_recurse_fields($fields), $where, $order, @rest
346 if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
347 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
350 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
353 # Quotes table names, and handles default inserts
357 $table = $self->_quote($table);
359 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
360 # which is sadly understood only by MySQL. Change default behavior here,
361 # until SQLA2 comes with proper dialect support
362 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
363 my $sql = "INSERT INTO ${table} DEFAULT VALUES";
365 if (my $ret = ($_[1]||{})->{returning} ) {
366 $sql .= $self->_insert_returning ($ret);
372 $self->SUPER::insert($table, @_);
375 # Just quotes table names.
379 $table = $self->_quote($table);
380 $self->SUPER::update($table, @_);
383 # Just quotes table names.
387 $table = $self->_quote($table);
388 $self->SUPER::delete($table, @_);
394 return $_[1].$self->_order_by($_[2]);
396 return $self->SUPER::_emulate_limit(@_);
400 sub _recurse_fields {
401 my ($self, $fields, $params) = @_;
402 my $ref = ref $fields;
403 return $self->_quote($fields) unless $ref;
404 return $$fields if $ref eq 'SCALAR';
406 if ($ref eq 'ARRAY') {
407 return join(', ', map {
408 $self->_recurse_fields($_)
409 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
410 ? ' AS col'.$self->{rownum_hack_count}++
414 elsif ($ref eq 'HASH') {
417 my $as = delete $hash{-as}; # if supplied
419 my ($func, $args) = each %hash;
422 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
424 'The select => { distinct => ... } syntax is not supported for multiple columns.'
425 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
426 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
430 my $select = sprintf ('%s( %s )%s',
431 $self->_sqlcase($func),
432 $self->_recurse_fields($args),
434 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
438 # there should be nothing left
440 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
445 # Is the second check absolutely necessary?
446 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
447 return $self->_fold_sqlbind( $fields );
450 croak($ref . qq{ unexpected in _recurse_fields()})
455 my ($self, $arg) = @_;
457 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
461 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
462 $ret = $self->_sqlcase(' group by ') . $g;
465 if (defined $arg->{having}) {
466 my ($frag, @bind) = $self->_recurse_where($arg->{having});
467 push(@{$self->{having_bind}}, @bind);
468 $ret .= $self->_sqlcase(' having ').$frag;
471 if (defined $arg->{order_by}) {
472 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
473 push(@{$self->{order_bind}}, @bind);
480 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
481 push(@{$self->{order_bind}}, @bind);
486 sub _order_directions {
487 my ($self, $order) = @_;
489 # strip bind values - none of the current _order_directions users support them
490 return $self->SUPER::_order_directions( [ map
491 { ref $_ ? $_->[0] : $_ }
492 $self->_order_by_chunks ($order)
497 my ($self, $from) = @_;
498 if (ref $from eq 'ARRAY') {
499 return $self->_recurse_from(@$from);
500 } elsif (ref $from eq 'HASH') {
501 return $self->_make_as($from);
503 return $from; # would love to quote here but _table ends up getting called
504 # twice during an ->select without a limit clause due to
505 # the way S::A::Limit->select works. should maybe consider
506 # bypassing this and doing S::A::select($self, ...) in
507 # our select method above. meantime, quoting shims have
508 # been added to select/insert/update/delete here
512 sub _generate_join_clause {
513 my ($self, $join_type) = @_;
515 return sprintf ('%s JOIN ',
516 $join_type ? ' ' . uc($join_type) : ''
521 my ($self, $from, @join) = @_;
523 push(@sqlf, $self->_make_as($from));
524 foreach my $j (@join) {
528 # check whether a join type exists
529 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
531 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
532 $join_type = $to_jt->{-join_type};
533 $join_type =~ s/^\s+ | \s+$//xg;
536 $join_type = $self->{_default_jointype} if not defined $join_type;
538 push @sqlf, $self->_generate_join_clause( $join_type );
540 if (ref $to eq 'ARRAY') {
541 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
543 push(@sqlf, $self->_make_as($to));
545 push(@sqlf, ' ON ', $self->_join_condition($on));
547 return join('', @sqlf);
551 my ($self, $sqlbind) = @_;
553 my @sqlbind = @$$sqlbind; # copy
554 my $sql = shift @sqlbind;
555 push @{$self->{from_bind}}, @sqlbind;
561 my ($self, $from) = @_;
562 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
563 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
565 } reverse each %{$self->_skip_options($from)});
569 my ($self, $hash) = @_;
571 $clean_hash->{$_} = $hash->{$_}
572 for grep {!/^-/} keys %$hash;
576 sub _join_condition {
577 my ($self, $cond) = @_;
578 if (ref $cond eq 'HASH') {
583 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
584 if ref($v) ne 'SCALAR';
588 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
591 return scalar($self->_recurse_where(\%j));
592 } elsif (ref $cond eq 'ARRAY') {
593 return join(' OR ', map { $self->_join_condition($_) } @$cond);
595 die "Can't handle this yet!";
600 my ($self, $label) = @_;
601 return '' unless defined $label;
602 return $$label if ref($label) eq 'SCALAR';
603 return "*" if $label eq '*';
604 return $label unless $self->{quote_char};
605 if(ref $self->{quote_char} eq "ARRAY"){
606 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
607 if !defined $self->{name_sep};
608 my $sep = $self->{name_sep};
609 return join($self->{name_sep},
610 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
611 split(/\Q$sep\E/,$label));
613 return $self->SUPER::_quote($label);
618 $self->{limit_dialect} = shift if @_;
619 return $self->{limit_dialect};
622 # Set to an array-ref to specify separate left and right quotes for table names.
623 # A single scalar is equivalen to [ $char, $char ]
626 $self->{quote_char} = shift if @_;
627 return $self->{quote_char};
630 # Character separating quoted table names.
633 $self->{name_sep} = shift if @_;
634 return $self->{name_sep};