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 # Slow but ANSI standard Limit/Offset support. DB2 uses this
52 my ($self, $sql, $order, $rows, $offset ) = @_;
55 my $last = $rows + $offset - 1;
56 my ( $order_by ) = $self->_order_by( $order );
61 SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
66 WHERE ROW_NUM BETWEEN $offset AND $last
73 # Crappy Top based Limit/Offset support. MSSQL uses this currently,
74 # but may have to switch to RowNumberOver one day
76 my ( $self, $sql, $order, $rows, $offset ) = @_;
78 # mangle the input sql so it can be properly aliased in the outer queries
79 $sql =~ s/^ \s* SELECT \s+ (.+?) \s+ (?=FROM)//ix
80 or croak "Unrecognizable SELECT: $sql";
82 my @sql_select = split (/\s*,\s*/, $sql_select);
84 # we can't support subqueries (in fact MSSQL can't) - croak
85 if (@sql_select != @{$self->{_dbic_rs_attrs}{select}}) {
87 'SQL SELECT did not parse cleanly - retrieved %d comma separated elements, while '
88 . 'the resultset select attribure contains %d elements: %s',
90 scalar @{$self->{_dbic_rs_attrs}{select}},
95 my $name_sep = $self->name_sep || '.';
96 my $esc_name_sep = "\Q$name_sep\E";
97 my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
99 my $rs_alias = $self->{_dbic_rs_attrs}{alias};
100 my $quoted_rs_alias = $self->_quote ($rs_alias);
102 # construct the new select lists, rename(alias) some columns if necessary
103 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
105 for (@{$self->{_dbic_rs_attrs}{select}}) {
107 my ($table, $orig_colname) = ( $_ =~ $col_re );
109 $seen_names{$orig_colname}++;
112 for my $i (0 .. $#sql_select) {
114 my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
115 my $colsel_sql = $sql_select[$i];
117 # this may or may not work (in case of a scalarref or something)
118 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
121 # do not attempt to understand non-scalar selects - alias numerically
122 if (ref $colsel_arg) {
123 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
125 # column name seen more than once - alias it
126 elsif ($orig_colname &&
127 ($seen_names{$orig_colname} && $seen_names{$orig_colname} > 1) ) {
128 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
131 # we did rename - make a record and adjust
134 push @inner_select, "$colsel_sql AS $quoted_alias";
136 # push alias to outer
137 push @outer_select, $quoted_alias;
139 # Any aliasing accumulated here will be considered
140 # both for inner and outer adjustments of ORDER BY
141 $self->__record_alias (
145 $table ? $orig_colname : undef,
149 # otherwise just leave things intact inside, and use the abbreviated one outside
150 # (as we do not have table names anymore)
152 push @inner_select, $colsel_sql;
154 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
155 push @outer_select, $outer_quoted;
156 $self->__record_alias (
160 $table ? $orig_colname : undef,
165 my $outer_select = join (', ', @outer_select );
166 my $inner_select = join (', ', @inner_select );
168 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
171 croak '$order supplied to SQLAHacks limit emulators must be a hash'
172 if (ref $order ne 'HASH');
174 $order = { %$order }; #copy
176 my $req_order = $order->{order_by};
178 # examine normalized version, collapses nesting
180 if (scalar $self->_order_by_chunks ($req_order)) {
181 $limit_order = $req_order;
185 { join ('', $rs_alias, $name_sep, $_ ) }
186 ( $self->{_dbic_rs_attrs}{_source_handle}->resolve->primary_columns )
190 my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
191 my $order_by_requested = $self->_order_by ($req_order);
194 delete $order->{order_by};
195 my $grpby_having = $self->_order_by ($order);
197 # short circuit for counts - the ordering complexity is needless
198 if ($self->{_dbic_rs_attrs}{-for_count_only}) {
199 return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
202 # we can't really adjust the order_by columns, as introspection is lacking
203 # resort to simple substitution
204 for my $col (keys %outer_col_aliases) {
205 for ($order_by_requested, $order_by_outer) {
206 $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
209 for my $col (keys %col_aliases) {
210 $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
214 my $inner_lim = $rows + $offset;
216 $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
221 SELECT TOP $rows $outer_select FROM
230 if ($order_by_requested) {
233 SELECT $outer_select FROM
234 ( $sql ) $quoted_rs_alias
240 $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
244 # action at a distance to shorten Top code above
246 my ($self, $register, $alias, $fqcol, $col) = @_;
248 # record qualified name
249 $register->{$fqcol} = $alias;
250 $register->{$self->_quote($fqcol)} = $alias;
254 # record unqualified name, undef (no adjustment) if a duplicate is found
255 if (exists $register->{$col}) {
256 $register->{$col} = undef;
259 $register->{$col} = $alias;
262 $register->{$self->_quote($col)} = $register->{$col};
267 # While we're at it, this should make LIMIT queries more efficient,
268 # without digging into things too deeply
270 my ($self, $syntax) = @_;
271 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
275 update => 'FOR UPDATE',
276 shared => 'FOR SHARE',
278 # Quotes table names, handles "limit" dialects (e.g. where rownum between x and
279 # y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
281 my ($self, $table, $fields, $where, $order, @rest) = @_;
283 $self->{"${_}_bind"} = [] for (qw/having from order/);
285 if (not ref($table) or ref($table) eq 'SCALAR') {
286 $table = $self->_quote($table);
289 local $self->{rownum_hack_count} = 1
290 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
291 @rest = (-1) unless defined $rest[0];
292 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
293 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
294 my ($sql, @where_bind) = $self->SUPER::select(
295 $table, $self->_recurse_fields($fields), $where, $order, @rest
297 if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
298 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
301 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
304 # Quotes table names, and handles default inserts
308 $table = $self->_quote($table);
310 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
311 # which is sadly understood only by MySQL. Change default behavior here,
312 # until SQLA2 comes with proper dialect support
313 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
314 return "INSERT INTO ${table} DEFAULT VALUES"
317 $self->SUPER::insert($table, @_);
320 # Just quotes table names.
324 $table = $self->_quote($table);
325 $self->SUPER::update($table, @_);
328 # Just quotes table names.
332 $table = $self->_quote($table);
333 $self->SUPER::delete($table, @_);
339 return $_[1].$self->_order_by($_[2]);
341 return $self->SUPER::_emulate_limit(@_);
345 sub _recurse_fields {
346 my ($self, $fields, $params) = @_;
347 my $ref = ref $fields;
348 return $self->_quote($fields) unless $ref;
349 return $$fields if $ref eq 'SCALAR';
351 if ($ref eq 'ARRAY') {
352 return join(', ', map {
353 $self->_recurse_fields($_)
354 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
355 ? ' AS col'.$self->{rownum_hack_count}++
359 elsif ($ref eq 'HASH') {
362 my $as = delete $hash{-as}; # if supplied
364 my ($func, $args) = each %hash;
367 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
369 'The select => { distinct => ... } syntax is not supported for multiple columns.'
370 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
371 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
375 my $select = sprintf ('%s( %s )%s',
376 $self->_sqlcase($func),
377 $self->_recurse_fields($args),
379 ? sprintf (' %s %s', $self->_sqlcase('as'), $as)
383 # there should be nothing left
385 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
390 # Is the second check absolutely necessary?
391 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
392 return $self->_fold_sqlbind( $fields );
395 croak($ref . qq{ unexpected in _recurse_fields()})
400 my ($self, $arg) = @_;
402 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
406 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
407 $ret = $self->_sqlcase(' group by ') . $g;
410 if (defined $arg->{having}) {
411 my ($frag, @bind) = $self->_recurse_where($arg->{having});
412 push(@{$self->{having_bind}}, @bind);
413 $ret .= $self->_sqlcase(' having ').$frag;
416 if (defined $arg->{order_by}) {
417 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
418 push(@{$self->{order_bind}}, @bind);
425 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
426 push(@{$self->{order_bind}}, @bind);
431 sub _order_directions {
432 my ($self, $order) = @_;
434 # strip bind values - none of the current _order_directions users support them
435 return $self->SUPER::_order_directions( [ map
436 { ref $_ ? $_->[0] : $_ }
437 $self->_order_by_chunks ($order)
442 my ($self, $from) = @_;
443 if (ref $from eq 'ARRAY') {
444 return $self->_recurse_from(@$from);
445 } elsif (ref $from eq 'HASH') {
446 return $self->_make_as($from);
448 return $from; # would love to quote here but _table ends up getting called
449 # twice during an ->select without a limit clause due to
450 # the way S::A::Limit->select works. should maybe consider
451 # bypassing this and doing S::A::select($self, ...) in
452 # our select method above. meantime, quoting shims have
453 # been added to select/insert/update/delete here
458 my ($self, $from, @join) = @_;
460 push(@sqlf, $self->_make_as($from));
461 foreach my $j (@join) {
465 # check whether a join type exists
466 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
468 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
469 $join_type = $to_jt->{-join_type};
470 $join_type =~ s/^\s+ | \s+$//xg;
473 $join_type = $self->{_default_jointype} if not defined $join_type;
475 my $join_clause = sprintf ('%s JOIN ',
476 $join_type ? ' ' . uc($join_type) : ''
478 push @sqlf, $join_clause;
480 if (ref $to eq 'ARRAY') {
481 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
483 push(@sqlf, $self->_make_as($to));
485 push(@sqlf, ' ON ', $self->_join_condition($on));
487 return join('', @sqlf);
491 my ($self, $sqlbind) = @_;
493 my @sqlbind = @$$sqlbind; # copy
494 my $sql = shift @sqlbind;
495 push @{$self->{from_bind}}, @sqlbind;
501 my ($self, $from) = @_;
502 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
503 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
505 } reverse each %{$self->_skip_options($from)});
509 my ($self, $hash) = @_;
511 $clean_hash->{$_} = $hash->{$_}
512 for grep {!/^-/} keys %$hash;
516 sub _join_condition {
517 my ($self, $cond) = @_;
518 if (ref $cond eq 'HASH') {
523 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
524 if ref($v) ne 'SCALAR';
528 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
531 return scalar($self->_recurse_where(\%j));
532 } elsif (ref $cond eq 'ARRAY') {
533 return join(' OR ', map { $self->_join_condition($_) } @$cond);
535 die "Can't handle this yet!";
540 my ($self, $label) = @_;
541 return '' unless defined $label;
542 return $$label if ref($label) eq 'SCALAR';
543 return "*" if $label eq '*';
544 return $label unless $self->{quote_char};
545 if(ref $self->{quote_char} eq "ARRAY"){
546 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
547 if !defined $self->{name_sep};
548 my $sep = $self->{name_sep};
549 return join($self->{name_sep},
550 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
551 split(/\Q$sep\E/,$label));
553 return $self->SUPER::_quote($label);
558 $self->{limit_dialect} = shift if @_;
559 return $self->{limit_dialect};
562 # Set to an array-ref to specify separate left and right quotes for table names.
563 # A single scalar is equivalen to [ $char, $char ]
566 $self->{quote_char} = shift if @_;
567 return $self->{quote_char};
570 # Character separating quoted table names.
573 $self->{name_sep} = shift if @_;
574 return $self->{name_sep};