1 package # Hide from PAUSE
2 DBIx::Class::SQLAHacks;
4 # This module is a subclass of SQL::Abstract and includes a number of
5 # DBIC-specific workarounds, not yet suitable for inclusion into the
7 # It also provides all (and more than) the functionality of
8 # SQL::Abstract::Limit, which proved to be very hard to keep updated
11 DBIx::Class::SQLAHacks::LimitDialects
13 Class::Accessor::Grouped
18 use Sub::Name 'subname';
19 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
22 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
25 # reinstall the carp()/croak() functions imported into SQL::Abstract
26 # as Carp and Carp::Clan do not like each other much
27 no warnings qw/redefine/;
29 for my $f (qw/carp croak/) {
31 my $orig = \&{"SQL::Abstract::$f"};
32 my $clan_import = \&{$f};
33 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
35 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
45 # the "oh noes offset/top without limit" constant
46 # limited to 32 bits for sanity (and consistency,
47 # since it is ultimately handed to sprintf %u)
48 # Implemented as a method, since ::Storage::DBI also
49 # refers to it (i.e. for the case of software_limit or
50 # as the value to abuse with MSSQL ordered subqueries)
51 sub __max_int { 0xFFFFFFFF };
53 # Handle limit-dialect selection
55 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
58 $fields = $self->_recurse_fields($fields);
60 if (defined $offset) {
61 croak ('A supplied offset must be a non-negative integer')
62 if ( $offset =~ /\D/ or $offset < 0 );
67 croak ('A supplied limit must be a positive integer')
68 if ( $limit =~ /\D/ or $limit <= 0 );
71 $limit = $self->__max_int;
77 # this is legacy code-flow from SQLA::Limit, it is not set in stone
79 ($sql, @bind) = $self->next::method ($table, $fields, $where);
82 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
85 my $dialect = $self->limit_dialect
86 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
87 $self->can ("_$dialect")
88 or croak "SQLAHacks does not implement the requested dialect '$dialect'";
92 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
95 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
98 push @{$self->{where_bind}}, @bind;
100 # this *must* be called, otherwise extra binds will remain in the sql-maker
101 my @all_bind = $self->_assemble_binds;
103 return wantarray ? ($sql, @all_bind) : $sql;
106 sub _assemble_binds {
108 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
111 # Handle default inserts
113 # optimized due to hotttnesss
114 # my ($self, $table, $data, $options) = @_;
116 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
117 # which is sadly understood only by MySQL. Change default behavior here,
118 # until SQLA2 comes with proper dialect support
119 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
120 my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
122 if (my $ret = ($_[3]||{})->{returning} ) {
123 $sql .= $_[0]->_insert_returning ($ret);
132 sub _recurse_fields {
133 my ($self, $fields) = @_;
134 my $ref = ref $fields;
135 return $self->_quote($fields) unless $ref;
136 return $$fields if $ref eq 'SCALAR';
138 if ($ref eq 'ARRAY') {
139 return join(', ', map { $self->_recurse_fields($_) } @$fields);
141 elsif ($ref eq 'HASH') {
142 my %hash = %$fields; # shallow copy
144 my $as = delete $hash{-as}; # if supplied
146 my ($func, $args, @toomany) = %hash;
148 # there should be only one pair
150 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
153 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
155 'The select => { distinct => ... } syntax is not supported for multiple columns.'
156 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
157 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
161 my $select = sprintf ('%s( %s )%s',
162 $self->_sqlcase($func),
163 $self->_recurse_fields($args),
165 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
171 # Is the second check absolutely necessary?
172 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
173 return $self->_fold_sqlbind( $fields );
176 croak($ref . qq{ unexpected in _recurse_fields()})
181 update => 'FOR UPDATE',
182 shared => 'FOR SHARE',
185 # this used to be a part of _order_by but is broken out for clarity.
186 # What we have been doing forever is hijacking the $order arg of
187 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
188 # then pretty much the entire resultset attr-hash, as more and more
189 # things in the SQLA space need to have mopre info about the $rs they
190 # create SQL for. The alternative would be to keep expanding the
191 # signature of _select with more and more positional parameters, which
192 # is just gross. All hail SQLA2!
193 sub _parse_rs_attrs {
194 my ($self, $arg) = @_;
198 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
199 $sql .= $self->_sqlcase(' group by ') . $g;
202 if (defined $arg->{having}) {
203 my ($frag, @bind) = $self->_recurse_where($arg->{having});
204 push(@{$self->{having_bind}}, @bind);
205 $sql .= $self->_sqlcase(' having ') . $frag;
208 if (defined $arg->{order_by}) {
209 $sql .= $self->_order_by ($arg->{order_by});
212 if (my $for = $arg->{for}) {
213 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
220 my ($self, $arg) = @_;
222 # check that we are not called in legacy mode (order_by as 4th argument)
223 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
224 return $self->_parse_rs_attrs ($arg);
227 my ($sql, @bind) = $self->next::method($arg);
228 push @{$self->{order_bind}}, @bind;
234 # optimized due to hotttnesss
235 # my ($self, $from) = @_;
236 if (my $ref = ref $_[1] ) {
237 if ($ref eq 'ARRAY') {
238 return $_[0]->_recurse_from(@{$_[1]});
240 elsif ($ref eq 'HASH') {
241 return $_[0]->_make_as($_[1]);
245 return $_[0]->next::method ($_[1]);
248 sub _generate_join_clause {
249 my ($self, $join_type) = @_;
251 return sprintf ('%s JOIN ',
252 $join_type ? ' ' . uc($join_type) : ''
257 my ($self, $from, @join) = @_;
259 push(@sqlf, $self->_make_as($from));
260 foreach my $j (@join) {
264 # check whether a join type exists
265 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
267 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
268 $join_type = $to_jt->{-join_type};
269 $join_type =~ s/^\s+ | \s+$//xg;
272 $join_type = $self->{_default_jointype} if not defined $join_type;
274 push @sqlf, $self->_generate_join_clause( $join_type );
276 if (ref $to eq 'ARRAY') {
277 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
279 push(@sqlf, $self->_make_as($to));
281 push(@sqlf, ' ON ', $self->_join_condition($on));
283 return join('', @sqlf);
287 my ($self, $sqlbind) = @_;
289 my @sqlbind = @$$sqlbind; # copy
290 my $sql = shift @sqlbind;
291 push @{$self->{from_bind}}, @sqlbind;
297 my ($self, $from) = @_;
298 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
299 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
301 } reverse each %{$self->_skip_options($from)});
305 my ($self, $hash) = @_;
307 $clean_hash->{$_} = $hash->{$_}
308 for grep {!/^-/} keys %$hash;
312 sub _join_condition {
313 my ($self, $cond) = @_;
314 if (ref $cond eq 'HASH') {
319 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
320 if ref($v) ne 'SCALAR';
324 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
327 return scalar($self->_recurse_where(\%j));
328 } elsif (ref $cond eq 'ARRAY') {
329 return join(' OR ', map { $self->_join_condition($_) } @$cond);
331 croak "Can't handle this yet!";