package # Hide from PAUSE
DBIx::Class::SQLAHacks;
-# This module is a subclass of SQL::Abstract::Limit and includes a number
-# of DBIC-specific workarounds, not yet suitable for inclusion into the
-# SQLA core
-
-use base qw/SQL::Abstract::Limit/;
+# This module is a subclass of SQL::Abstract and includes a number of
+# DBIC-specific workarounds, not yet suitable for inclusion into the
+# SQLA core.
+# It also provides all (and more than) the functionality of
+# SQL::Abstract::Limit, which proved to be very hard to keep updated
+
+use base qw/
+ DBIx::Class::SQLAHacks::LimitDialects
+ SQL::Abstract
+ Class::Accessor::Grouped
+/;
+use mro 'c3';
use strict;
use warnings;
-use Carp::Clan qw/^DBIx::Class|^SQL::Abstract/;
-use Sub::Name();
+use Sub::Name 'subname';
+use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
+use namespace::clean;
+
+__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
BEGIN {
# reinstall the carp()/croak() functions imported into SQL::Abstract
for my $f (qw/carp croak/) {
my $orig = \&{"SQL::Abstract::$f"};
- *{"SQL::Abstract::$f"} = Sub::Name::subname "SQL::Abstract::$f" =>
+ my $clan_import = \&{$f};
+ *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
sub {
if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
- __PACKAGE__->can($f)->(@_);
+ $clan_import->(@_);
}
else {
goto $orig;
}
}
+# the "oh noes offset/top without limit" constant
+# limited to 32 bits for sanity (and consistency,
+# since it is ultimately handed to sprintf %u)
+# Implemented as a method, since ::Storage::DBI also
+# refers to it (i.e. for the case of software_limit or
+# as the value to abuse with MSSQL ordered subqueries)
+sub __max_int { 0xFFFFFFFF };
-# Tries to determine limit dialect.
-#
-sub new {
- my $self = shift->SUPER::new(@_);
+# Handle limit-dialect selection
+sub select {
+ my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
- # This prevents the caching of $dbh in S::A::L, I believe
- # If limit_dialect is a ref (like a $dbh), go ahead and replace
- # it with what it resolves to:
- $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
- if ref $self->{limit_dialect};
- $self;
-}
+ $fields = $self->_recurse_fields($fields);
-# generate inner/outer select lists for various limit dialects
-# which result in one or more subqueries (e.g. RNO, Top, RowNum)
-# Any non-root-table columns need to have their table qualifier
-# turned into a column name (otherwise names in subqueries clash
-# and/or lose their source table)
-sub _subqueried_selection {
- my ($self, $rs_attrs) = @_;
-
- croak 'Limit usable only in the context of DBIC (missing $rs_attrs)' unless $rs_attrs;
-
- # correlate select and as
- my @sel;
- for my $i (0 .. $#{$rs_attrs->{select}}) {
- my $s = $rs_attrs->{select}[$i];
- push @sel, {
- sql => $self->_recurse_fields ($s),
- unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) },
- as =>
- ( (ref $s) eq 'HASH' ? $s->{-as} : undef)
- ||
- $rs_attrs->{as}[$i]
- ||
- croak "Select argument $i ($s) without corresponding 'as'"
- ,
- };
+ if (defined $offset) {
+ croak ('A supplied offset must be a non-negative integer')
+ if ( $offset =~ /\D/ or $offset < 0 );
}
+ $offset ||= 0;
- my ($qsep, $qalias) = map { quotemeta $_ } (
- $self->name_sep || '.',
- $rs_attrs->{alias},
- );
-
- # re-alias and remove any name separators from aliases,
- # unless we are dealing with the current source alias
- # (which will transcend the subqueries and is necessary
- # for possible further chaining)
- my (@insel, @outsel);
- for my $node (@sel) {
- if (List::Util::first { $_ =~ / (?<! $qalias ) $qsep /x } ($node->{as}, $node->{unquoted_sql}) ) {
- $node->{as} =~ s/ $qsep /__/xg;
- push @insel, sprintf '%s AS %s', $node->{sql}, $self->_quote($node->{as});
- push @outsel, $self->_quote ($node->{as});
- }
- else {
- push @insel, $node->{sql};
- push @outsel, $self->_quote ($node->{as});
- }
+ if (defined $limit) {
+ croak ('A supplied limit must be a positive integer')
+ if ( $limit =~ /\D/ or $limit <= 0 );
}
-
- return map { join (', ', @$_ ) } (\@insel, \@outsel);
-}
-
-
-# ANSI standard Limit/Offset implementation. DB2 and MSSQL use this
-sub _RowNumberOver {
- my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
-
- # mangle the input sql as we will be replacing the selector
- $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
- or croak "Unrecognizable SELECT: $sql";
-
- # get selectors
- my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
-
- # make up an order if none exists
- my $order_by = $self->_order_by(
- (delete $rs_attrs->{order_by}) || $self->_rno_default_order
- );
-
- # whatever is left of the order_by (only where is processed at this point)
- my $group_having = $self->_parse_rs_attrs($rs_attrs);
-
- my $qalias = $self->_quote ($rs_attrs->{alias});
-
- my $idx_name = $self->_quote ('rno__row__index');
-
- $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
-
-SELECT $outsel FROM (
- SELECT $outsel, ROW_NUMBER() OVER($order_by ) AS $idx_name FROM (
- SELECT $insel ${sql}${group_having}
- ) $qalias
-) $qalias WHERE $idx_name BETWEEN %d AND %d
-
-EOS
-
- $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
- return $sql;
-}
-
-# some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
-sub _rno_default_order {
- return undef;
-}
-
-# Informix specific limit, almost like LIMIT/OFFSET
-sub _SkipFirst {
- my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
-
- $sql =~ s/^ \s* SELECT \s+ //ix
- or croak "Unrecognizable SELECT: $sql";
-
- return sprintf ('SELECT %s%s%s%s',
- $offset
- ? sprintf ('SKIP %d ', $offset)
- : ''
- ,
- sprintf ('FIRST %d ', $rows),
- $sql,
- $self->_parse_rs_attrs ($rs_attrs),
- );
-}
-
-# Firebird specific limit, reverse of _SkipFirst for Informix
-sub _FirstSkip {
- my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
-
- $sql =~ s/^ \s* SELECT \s+ //ix
- or croak "Unrecognizable SELECT: $sql";
-
- return sprintf ('SELECT %s%s%s%s',
- sprintf ('FIRST %d ', $rows),
- $offset
- ? sprintf ('SKIP %d ', $offset)
- : ''
- ,
- $sql,
- $self->_parse_rs_attrs ($rs_attrs),
- );
-}
-
-# WhOracle limits
-sub _RowNum {
- my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
-
- # mangle the input sql as we will be replacing the selector
- $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
- or croak "Unrecognizable SELECT: $sql";
-
- my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
-
- my $qalias = $self->_quote ($rs_attrs->{alias});
- my $idx_name = $self->_quote ('rownum__index');
- my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
-
- $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
-
-SELECT $outsel FROM (
- SELECT $outsel, ROWNUM $idx_name FROM (
- SELECT $insel ${sql}${order_group_having}
- ) $qalias
-) $qalias WHERE $idx_name BETWEEN %d AND %d
-
-EOS
-
- $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
- return $sql;
-}
-
-=begin
-# Crappy Top based Limit/Offset support. Legacy from MSSQL.
-sub _Top {
- my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
-
- # mangle the input sql as we will be replacing the selector
- $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
- or croak "Unrecognizable SELECT: $sql";
-
- # get selectors
- my ($insel, $outsel) = $self->_subqueried_selection ($rs_attrs);
-
- # deal with order
- my $rs_alias = $rs_attrs->{alias};
- my $req_order = delete $rs_attrs->{order_by};
- my $name_sep = $self->name_sep || '.';
-
- # examine normalized version, collapses nesting
- my $limit_order = scalar $self->_order_by_chunks ($req_order)
- ? $req_order
- : [ map
- { join ('', $rs_alias, $name_sep, $_ ) }
- ( $rs_attrs->{_rsroot_source_handle}->resolve->primary_columns )
- ]
- ;
-
- my ( $order_by_inner, $order_by_outer ) = $self->_order_directions($limit_order);
- my $order_by_requested = $self->_order_by ($req_order);
-
-
-
-
- my $esc_name_sep = "\Q$name_sep\E";
- my $col_re = qr/ ^ (?: (.+) $esc_name_sep )? ([^$esc_name_sep]+) $ /x;
-
- my $quoted_rs_alias = $self->_quote ($rs_alias);
-
- # construct the new select lists, rename(alias) some columns if necessary
- my (@outer_select, @inner_select, %seen_names, %col_aliases, %outer_col_aliases);
-
- for (@{$rs_attrs->{select}}) {
- next if ref $_;
- my ($table, $orig_colname) = ( $_ =~ $col_re );
- next unless $table;
- $seen_names{$orig_colname}++;
+ elsif ($offset) {
+ $limit = $self->__max_int;
}
- for my $i (0 .. $#sql_select) {
- my $colsel_arg = $rs_attrs->{select}[$i];
- my $colsel_sql = $sql_select[$i];
+ my ($sql, @bind);
+ if ($limit) {
+ # this is legacy code-flow from SQLA::Limit, it is not set in stone
- # this may or may not work (in case of a scalarref or something)
- my ($table, $orig_colname) = ( $colsel_arg =~ $col_re );
+ ($sql, @bind) = $self->next::method ($table, $fields, $where);
- my $quoted_alias;
- # do not attempt to understand non-scalar selects - alias numerically
- if (ref $colsel_arg) {
- $quoted_alias = $self->_quote ('column_' . (@inner_select + 1) );
- }
- # column name seen more than once - alias it
- elsif ($orig_colname &&
- ($seen_names{$orig_colname} && $seen_names{$orig_colname} > 1) ) {
- $quoted_alias = $self->_quote ("${table}__${orig_colname}");
- }
-
- # we did rename - make a record and adjust
- if ($quoted_alias) {
- # alias inner
- push @inner_select, "$colsel_sql AS $quoted_alias";
-
- # push alias to outer
- push @outer_select, $quoted_alias;
-
- # Any aliasing accumulated here will be considered
- # both for inner and outer adjustments of ORDER BY
- $self->__record_alias (
- \%col_aliases,
- $quoted_alias,
- $colsel_arg,
- $table ? $orig_colname : undef,
- );
- }
-
- # otherwise just leave things intact inside, and use the abbreviated one outside
- # (as we do not have table names anymore)
- else {
- push @inner_select, $colsel_sql;
-
- my $outer_quoted = $self->_quote ($orig_colname); # it was not a duplicate so should just work
- push @outer_select, $outer_quoted;
- $self->__record_alias (
- \%outer_col_aliases,
- $outer_quoted,
- $colsel_arg,
- $table ? $orig_colname : undef,
- );
- }
- }
-
- my $outer_select = join (', ', @outer_select );
- my $inner_select = join (', ', @inner_select );
-
- %outer_col_aliases = (%outer_col_aliases, %col_aliases);
-
-
-
-
- # generate the rest
- my $grpby_having = $self->_parse_rs_attrs ($rs_attrs);
-
- # short circuit for counts - the ordering complexity is needless
- if ($rs_attrs->{-for_count_only}) {
- return "SELECT TOP $rows $inner_select $sql $grpby_having $order_by_outer";
- }
+ my $limiter =
+ $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
+ ||
+ do {
+ my $dialect = $self->limit_dialect
+ or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
+ $self->can ("_$dialect")
+ or croak "SQLAHacks does not implement the requested dialect '$dialect'";
+ }
+ ;
- # we can't really adjust the order_by columns, as introspection is lacking
- # resort to simple substitution
- for my $col (keys %outer_col_aliases) {
- for ($order_by_requested, $order_by_outer) {
- $_ =~ s/\s+$col\s+/ $outer_col_aliases{$col} /g;
- }
- }
- for my $col (keys %col_aliases) {
- $order_by_inner =~ s/\s+$col\s+/ $col_aliases{$col} /g;
+ $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
}
-
-
- my $inner_lim = $rows + $offset;
-
- $sql = "SELECT TOP $inner_lim $inner_select $sql $grpby_having $order_by_inner";
-
- if ($offset) {
- $sql = <<"SQL";
-
- SELECT TOP $rows $outer_select FROM
- (
- $sql
- ) $quoted_rs_alias
- $order_by_outer
-SQL
-
+ else {
+ ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
}
- if ($order_by_requested) {
- $sql = <<"SQL";
+ push @{$self->{where_bind}}, @bind;
- SELECT $outer_select FROM
- ( $sql ) $quoted_rs_alias
- $order_by_requested
-SQL
+# this *must* be called, otherwise extra binds will remain in the sql-maker
+ my @all_bind = $self->_assemble_binds;
- }
-
- $sql =~ s/\s*\n\s*/ /g; # parsing out multiline statements is harder than a single line
- return $sql;
+ return wantarray ? ($sql, @all_bind) : $sql;
}
-=cut
-
-# While we're at it, this should make LIMIT queries more efficient,
-# without digging into things too deeply
-sub _find_syntax {
- my ($self, $syntax) = @_;
- return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
-}
-
-# Quotes table names, handles "limit" dialects (e.g. where rownum between x and
-# y)
-sub select {
- my ($self, $table, $fields, $where, $rs_attrs, @rest) = @_;
-
- $self->{"${_}_bind"} = [] for (qw/having from order/);
-
- if (not ref($table) or ref($table) eq 'SCALAR') {
- $table = $self->_quote($table);
- }
-
- local $self->{rownum_hack_count} = 1
- if (defined $rest[0] && $self->{limit_dialect} eq 'RowNum');
- @rest = (-1) unless defined $rest[0];
- croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
- # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
- my ($sql, @where_bind) = $self->SUPER::select(
- $table, $self->_recurse_fields($fields), $where, $rs_attrs, @rest
- );
- return wantarray ? ($sql, @{$self->{from_bind}}, @where_bind, @{$self->{having_bind}}, @{$self->{order_bind}} ) : $sql;
+sub _assemble_binds {
+ my $self = shift;
+ return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
}
-# Quotes table names, and handles default inserts
+# Handle default inserts
sub insert {
- my $self = shift;
- my $table = shift;
- $table = $self->_quote($table);
+# optimized due to hotttnesss
+# my ($self, $table, $data, $options) = @_;
# SQLA will emit INSERT INTO $table ( ) VALUES ( )
# which is sadly understood only by MySQL. Change default behavior here,
# until SQLA2 comes with proper dialect support
- if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
- my $sql = "INSERT INTO ${table} DEFAULT VALUES";
+ if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
+ my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
- if (my $ret = ($_[1]||{})->{returning} ) {
- $sql .= $self->_insert_returning ($ret);
+ if (my $ret = ($_[3]||{})->{returning} ) {
+ $sql .= $_[0]->_insert_returning ($ret);
}
return $sql;
}
- $self->SUPER::insert($table, @_);
-}
-
-# Just quotes table names.
-sub update {
- my $self = shift;
- my $table = shift;
- $table = $self->_quote($table);
- $self->SUPER::update($table, @_);
-}
-
-# Just quotes table names.
-sub delete {
- my $self = shift;
- my $table = shift;
- $table = $self->_quote($table);
- $self->SUPER::delete($table, @_);
-}
-
-sub _emulate_limit {
- my $self = shift;
- # my ( $syntax, $sql, $order, $rows, $offset ) = @_;
-
- if ($_[3] == -1) {
- return $_[1] . $self->_parse_rs_attrs($_[2]);
- } else {
- return $self->SUPER::_emulate_limit(@_);
- }
+ next::method(@_);
}
sub _recurse_fields {
my $sql = '';
- if (my $g = $self->_recurse_fields($arg->{group_by}, { no_rownum_hack => 1 }) ) {
+ if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
$sql .= $self->_sqlcase(' group by ') . $g;
}
return $self->_parse_rs_attrs ($arg);
}
else {
- my ($sql, @bind) = $self->SUPER::_order_by ($arg);
+ my ($sql, @bind) = $self->next::method($arg);
push @{$self->{order_bind}}, @bind;
return $sql;
}
}
-sub _order_directions {
- my ($self, $order) = @_;
-
- # strip bind values - none of the current _order_directions users support them
- return $self->SUPER::_order_directions( [ map
- { ref $_ ? $_->[0] : $_ }
- $self->_order_by_chunks ($order)
- ]);
-}
-
sub _table {
- my ($self, $from) = @_;
- if (ref $from eq 'ARRAY') {
- return $self->_recurse_from(@$from);
- } elsif (ref $from eq 'HASH') {
- return $self->_make_as($from);
- } else {
- return $from; # would love to quote here but _table ends up getting called
- # twice during an ->select without a limit clause due to
- # the way S::A::Limit->select works. should maybe consider
- # bypassing this and doing S::A::select($self, ...) in
- # our select method above. meantime, quoting shims have
- # been added to select/insert/update/delete here
+# optimized due to hotttnesss
+# my ($self, $from) = @_;
+ if (my $ref = ref $_[1] ) {
+ if ($ref eq 'ARRAY') {
+ return $_[0]->_recurse_from(@{$_[1]});
+ }
+ elsif ($ref eq 'HASH') {
+ return $_[0]->_make_as($_[1]);
+ }
}
+
+ return $_[0]->next::method ($_[1]);
}
sub _generate_join_clause {
} elsif (ref $cond eq 'ARRAY') {
return join(' OR ', map { $self->_join_condition($_) } @$cond);
} else {
- die "Can't handle this yet!";
+ croak "Can't handle this yet!";
}
}
-sub limit_dialect {
- my $self = shift;
- if (@_) {
- $self->{limit_dialect} = shift;
- undef $self->{_cached_syntax};
- }
- return $self->{limit_dialect};
-}
-
-# Set to an array-ref to specify separate left and right quotes for table names.
-# A single scalar is equivalen to [ $char, $char ]
-sub quote_char {
- my $self = shift;
- $self->{quote_char} = shift if @_;
- return $self->{quote_char};
-}
-
-# Character separating quoted table names.
-sub name_sep {
- my $self = shift;
- $self->{name_sep} = shift if @_;
- return $self->{name_sep};
-}
-
1;