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/;
14 # reinstall the carp()/croak() functions imported into SQL::Abstract
15 # as Carp and Carp::Clan do not like each other much
16 no warnings qw/redefine/;
18 for my $f (qw/carp croak/) {
20 my $orig = \&{"SQL::Abstract::$f"};
21 *{"SQL::Abstract::$f"} = sub {
23 local $Carp::CarpLevel = 1; # even though Carp::Clan ignores this, $orig will not
25 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
26 __PACKAGE__->can($f)->(@_);
36 # Tries to determine limit dialect.
39 my $self = shift->SUPER::new(@_);
41 # This prevents the caching of $dbh in S::A::L, I believe
42 # If limit_dialect is a ref (like a $dbh), go ahead and replace
43 # it with what it resolves to:
44 $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
45 if ref $self->{limit_dialect};
50 # Some databases (sqlite) do not handle multiple parenthesis
51 # around in/between arguments. A tentative x IN ( (1, 2 ,3) )
52 # is interpreted as x IN 1 or something similar.
54 # Since we currently do not have access to the SQLA AST, resort
55 # to barbaric mutilation of any SQL supplied in literal form
56 sub _strip_outer_paren {
57 my ($self, $arg) = @_;
59 return $self->_SWITCH_refkind ($arg, {
61 $$arg->[0] = __strip_outer_paren ($$arg->[0]);
65 return \__strip_outer_paren( $$arg );
73 sub __strip_outer_paren {
76 if ($sql and not ref $sql) {
77 while ($sql =~ /^ \s* \( (.*) \) \s* $/x ) {
86 my ($self, $lhs, $op, $rhs) = @_;
87 $rhs = $self->_strip_outer_paren ($rhs);
88 return $self->SUPER::_where_field_IN ($lhs, $op, $rhs);
91 sub _where_field_BETWEEN {
92 my ($self, $lhs, $op, $rhs) = @_;
93 $rhs = $self->_strip_outer_paren ($rhs);
94 return $self->SUPER::_where_field_BETWEEN ($lhs, $op, $rhs);
97 # Slow but ANSI standard Limit/Offset support. DB2 uses this
99 my ($self, $sql, $order, $rows, $offset ) = @_;
102 my $last = $rows + $offset - 1;
103 my ( $order_by ) = $self->_order_by( $order );
108 SELECT Q1.*, ROW_NUMBER() OVER( ) AS ROW_NUM FROM (
113 WHERE ROW_NUM BETWEEN $offset AND $last
120 # Crappy Top based Limit/Offset support. MSSQL uses this currently,
121 # but may have to switch to RowNumberOver one day
123 my ( $self, $sql, $order, $rows, $offset ) = @_;
125 # mangle the input sql so it can be properly aliased in the outer queries
126 $sql =~ s/^ \s* SELECT \s+ (.+?) \s+ (?=FROM)//ix
127 or croak "Unrecognizable SELECT: $sql";
129 my @sql_select = split (/\s*,\s*/, $sql_select);
131 # we can't support subqueries (in fact MSSQL can't) - croak
132 if (@sql_select != @{$self->{_dbic_rs_attrs}{select}}) {
134 'SQL SELECT did not parse cleanly - retrieved %d comma separated elements, while '
135 . 'the resultset select attribure contains %d elements: %s',
137 scalar @{$self->{_dbic_rs_attrs}{select}},
142 my $name_sep = $self->name_sep || '.';
143 my $esc_name_sep = "\Q$name_sep\E";
144 my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
146 my $rs_alias = $self->{_dbic_rs_attrs}{alias};
147 my $quoted_rs_alias = $self->_quote ($rs_alias);
149 # construct the new select lists, rename(alias) some columns if necessary
150 my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
152 for (@{$self->{_dbic_rs_attrs}{select}}) {
154 my ($table, $orig_colname) = ( $_ =~ $col_re );
156 $seen_names{$orig_colname}++;
159 for my $i (0 .. $#sql_select) {
161 my $colsel_arg = $self->{_dbic_rs_attrs}{select}[$i];
162 my $colsel_sql = $sql_select[$i];
164 # this may or may not work (in case of a scalarref or something)
165 my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
168 # do not attempt to understand non-scalar selects - alias numerically
169 if (ref $colsel_arg) {
170 $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
172 # column name seen more than once - alias it
173 elsif ($orig_colname && ($seen_names{$orig_colname} > 1) ) {
174 $quoted_alias = $self->_quote ("${table}__${orig_colname}");
177 # we did rename - make a record and adjust
180 push @inner_select, "$colsel_sql AS $quoted_alias";
182 # push alias to outer
183 push @outer_select, $quoted_alias;
185 # Any aliasing accumulated here will be considered
186 # both for inner and outer adjustments of ORDER BY
187 $self->__record_alias (
191 $table ? $orig_colname : undef,
195 # otherwise just leave things intact inside, and use the abbreviated one outside
196 # (as we do not have table names anymore)
198 push @inner_select, $colsel_sql;
200 my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
201 push @outer_select, $outer_quoted;
202 $self->__record_alias (
206 $table ? $orig_colname : undef,
211 my $outer_select = join (', ', @outer_select );
212 my $inner_select = join (', ', @inner_select );
214 %outer_col_aliases = (%outer_col_aliases, %col_aliases);
217 croak '$order supplied to SQLAHacks limit emulators must be a hash'
218 if (ref $order ne 'HASH');
220 $order = { %$order }; #copy
222 my $req_order = $order->{order_by};
224 # examine normalized version, collapses nesting
226 if (scalar $self->_order_by_chunks ($req_order)) {
227 $limit_order = $req_order;
231 { join ('', $rs_alias, $name_sep, $_ ) }
232 ( $self->{_dbic_rs_attrs}{_source_handle}->resolve->primary_columns )
236 my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
237 my $order_by_requested = $self->_order_by ($req_order);
240 delete $order->{order_by};
241 my $grpby_having = $self->_order_by ($order);
243 # short circuit for counts - the ordering complexity is needless
244 if ($self->{_dbic_rs_attrs}{-for_count_only}) {
245 return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
248 # we can't really adjust the order_by columns, as introspection is lacking
249 # resort to simple substitution
250 for my $col (keys %outer_col_aliases) {
251 for ($order_by_requested, $order_by_outer) {
252 $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
255 for my $col (keys %col_aliases) {
256 $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
260 my $inner_lim = $rows + $offset;
262 $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
267 SELECT TOP $rows $outer_select FROM
276 if ($order_by_requested) {
279 SELECT $outer_select FROM
280 ( $sql ) $quoted_rs_alias
286 $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
290 # action at a distance to shorten Top code above
292 my ($self, $register, $alias, $fqcol, $col) = @_;
294 # record qualified name
295 $register->{$fqcol} = $alias;
296 $register->{$self->_quote($fqcol)} = $alias;
300 # record unqualified name, undef (no adjustment) if a duplicate is found
301 if (exists $register->{$col}) {
302 $register->{$col} = undef;
305 $register->{$col} = $alias;
308 $register->{$self->_quote($col)} = $register->{$col};
313 # While we're at it, this should make LIMIT queries more efficient,
314 # without digging into things too deeply
316 my ($self, $syntax) = @_;
317 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
321 update => 'FOR UPDATE',
322 shared => 'FOR SHARE',
324 # Quotes table names, handles "limit" dialects (e.g. where rownum between x and
325 # y), supports SELECT ... FOR UPDATE and SELECT ... FOR SHARE.
327 my ($self, $table, $fields, $where, $order, @rest) = @_;
329 $self->{"${_}_bind"} = [] for (qw/having from order/);
331 if (ref $table eq 'SCALAR') {
334 elsif (not ref $table) {
335 $table = $self->_quote($table);
337 local $self->{rownum_hack_count} = 1
338 if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
339 @rest = (-1) unless defined $rest[0];
340 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
341 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
342 my ($sql, @where_bind) = $self->SUPER::select(
343 $table, $self->_recurse_fields($fields), $where, $order, @rest
345 if (my $for = delete $self->{_dbic_rs_attrs}{for}) {
346 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
349 return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
352 # Quotes table names, and handles default inserts
356 $table = $self->_quote($table) unless ref($table);
358 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
359 # which is sadly understood only by MySQL. Change default behavior here,
360 # until SQLA2 comes with proper dialect support
361 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
362 return "INSERT INTO ${table} DEFAULT VALUES"
365 $self->SUPER::insert($table, @_);
368 # Just quotes table names.
372 $table = $self->_quote($table) unless ref($table);
373 $self->SUPER::update($table, @_);
376 # Just quotes table names.
380 $table = $self->_quote($table) unless ref($table);
381 $self->SUPER::delete($table, @_);
387 return $_[1].$self->_order_by($_[2]);
389 return $self->SUPER::_emulate_limit(@_);
393 sub _recurse_fields {
394 my ($self, $fields, $params) = @_;
395 my $ref = ref $fields;
396 return $self->_quote($fields) unless $ref;
397 return $$fields if $ref eq 'SCALAR';
399 if ($ref eq 'ARRAY') {
400 return join(', ', map {
401 $self->_recurse_fields($_)
402 .(exists $self->{rownum_hack_count} && !($params && $params->{no_rownum_hack})
403 ? ' AS col'.$self->{rownum_hack_count}++
407 elsif ($ref eq 'HASH') {
411 if ($hash{-select}) {
412 $select = $self->_recurse_fields (delete $hash{-select});
413 $as = $self->_quote (delete $hash{-as});
416 my ($func, $args) = each %hash;
419 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
421 'The select => { distinct => ... } syntax is not supported for multiple columns.'
422 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
423 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
426 $select = sprintf ('%s( %s )',
427 $self->_sqlcase($func),
428 $self->_recurse_fields($args)
432 # there should be nothing left
434 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
437 $select .= " AS $as" if $as;
440 # Is the second check absolutely necessary?
441 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
442 return $self->_fold_sqlbind( $fields );
445 croak($ref . qq{ unexpected in _recurse_fields()})
450 my ($self, $arg) = @_;
452 if (ref $arg eq 'HASH' and keys %$arg and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
456 if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
457 $ret = $self->_sqlcase(' group by ') . $g;
460 if (defined $arg->{having}) {
461 my ($frag, @bind) = $self->_recurse_where($arg->{having});
462 push(@{$self->{having_bind}}, @bind);
463 $ret .= $self->_sqlcase(' having ').$frag;
466 if (defined $arg->{order_by}) {
467 my ($frag, @bind) = $self->SUPER::_order_by($arg->{order_by});
468 push(@{$self->{order_bind}}, @bind);
475 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
476 push(@{$self->{order_bind}}, @bind);
481 sub _order_directions {
482 my ($self, $order) = @_;
484 # strip bind values - none of the current _order_directions users support them
485 return $self->SUPER::_order_directions( [ map
486 { ref $_ ? $_->[0] : $_ }
487 $self->_order_by_chunks ($order)
492 my ($self, $from) = @_;
493 if (ref $from eq 'ARRAY') {
494 return $self->_recurse_from(@$from);
495 } elsif (ref $from eq 'HASH') {
496 return $self->_make_as($from);
498 return $from; # would love to quote here but _table ends up getting called
499 # twice during an ->select without a limit clause due to
500 # the way S::A::Limit->select works. should maybe consider
501 # bypassing this and doing S::A::select($self, ...) in
502 # our select method above. meantime, quoting shims have
503 # been added to select/insert/update/delete here
508 my ($self, $from, @join) = @_;
510 push(@sqlf, $self->_make_as($from));
511 foreach my $j (@join) {
514 # check whether a join type exists
515 my $join_clause = '';
516 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
517 if (ref($to_jt) eq 'HASH' and exists($to_jt->{-join_type})) {
518 $join_clause = ' '.uc($to_jt->{-join_type}).' JOIN ';
520 $join_clause = ' JOIN ';
522 push(@sqlf, $join_clause);
524 if (ref $to eq 'ARRAY') {
525 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
527 push(@sqlf, $self->_make_as($to));
529 push(@sqlf, ' ON ', $self->_join_condition($on));
531 return join('', @sqlf);
535 my ($self, $sqlbind) = @_;
537 my @sqlbind = @$$sqlbind; # copy
538 my $sql = shift @sqlbind;
539 push @{$self->{from_bind}}, @sqlbind;
545 my ($self, $from) = @_;
546 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
547 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
549 } reverse each %{$self->_skip_options($from)});
553 my ($self, $hash) = @_;
555 $clean_hash->{$_} = $hash->{$_}
556 for grep {!/^-/} keys %$hash;
560 sub _join_condition {
561 my ($self, $cond) = @_;
562 if (ref $cond eq 'HASH') {
567 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
568 if ref($v) ne 'SCALAR';
572 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
575 return scalar($self->_recurse_where(\%j));
576 } elsif (ref $cond eq 'ARRAY') {
577 return join(' OR ', map { $self->_join_condition($_) } @$cond);
579 die "Can't handle this yet!";
584 my ($self, $label) = @_;
585 return '' unless defined $label;
586 return "*" if $label eq '*';
587 return $label unless $self->{quote_char};
588 if(ref $self->{quote_char} eq "ARRAY"){
589 return $self->{quote_char}->[0] . $label . $self->{quote_char}->[1]
590 if !defined $self->{name_sep};
591 my $sep = $self->{name_sep};
592 return join($self->{name_sep},
593 map { $self->{quote_char}->[0] . $_ . $self->{quote_char}->[1] }
594 split(/\Q$sep\E/,$label));
596 return $self->SUPER::_quote($label);
601 $self->{limit_dialect} = shift if @_;
602 return $self->{limit_dialect};
605 # Set to an array-ref to specify separate left and right quotes for table names.
606 # A single scalar is equivalen to [ $char, $char ]
609 $self->{quote_char} = shift if @_;
610 return $self->{quote_char};
613 # Character separating quoted table names.
616 $self->{name_sep} = shift if @_;
617 return $self->{name_sep};