Factor out the limit implementations into a separate file
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLAHacks.pm
CommitLineData
6f4ddea1 1package # Hide from PAUSE
855c6fd0 2 DBIx::Class::SQLAHacks;
6f4ddea1 3
6a247f33 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
6# SQLA core.
7# It also provides all (and more than) the functionality of
8# SQL::Abstract::Limit, which proved to be very hard to keep updated
9
10use base qw/
7fca91be 11 DBIx::Class::SQLAHacks::LimitDialects
6a247f33 12 SQL::Abstract
13 Class::Accessor::Grouped
14/;
15use mro 'c3';
e3764383 16use strict;
17use warnings;
6298a324 18use Sub::Name 'subname';
ac322978 19use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
e8fc51c7 20use namespace::clean;
b2b22cd6 21
6a247f33 22__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
23
b2b22cd6 24BEGIN {
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/;
28 no strict qw/refs/;
29 for my $f (qw/carp croak/) {
329d7385 30
b2b22cd6 31 my $orig = \&{"SQL::Abstract::$f"};
e8fc51c7 32 my $clan_import = \&{$f};
6298a324 33 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
8637bb24 34 sub {
35 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
e8fc51c7 36 $clan_import->(@_);
8637bb24 37 }
38 else {
39 goto $orig;
40 }
41 };
b2b22cd6 42 }
43}
6f4ddea1 44
e9657379 45# the "oh noes offset/top without limit" constant
6a247f33 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)
e9657379 51sub __max_int { 0xFFFFFFFF };
52
6a247f33 53# Handle limit-dialect selection
6f4ddea1 54sub select {
6a247f33 55 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
56
57
58 $fields = $self->_recurse_fields($fields);
59
60 if (defined $offset) {
61 croak ('A supplied offset must be a non-negative integer')
62 if ( $offset =~ /\D/ or $offset < 0 );
63 }
64 $offset ||= 0;
1cbd3034 65
6a247f33 66 if (defined $limit) {
67 croak ('A supplied limit must be a positive integer')
68 if ( $limit =~ /\D/ or $limit <= 0 );
69 }
70 elsif ($offset) {
71 $limit = $self->__max_int;
6f4ddea1 72 }
c2b7c5dc 73
a6b68a60 74
6a247f33 75 my ($sql, @bind);
76 if ($limit) {
77 # this is legacy code-flow from SQLA::Limit, it is not set in stone
78
79 ($sql, @bind) = $self->next::method ($table, $fields, $where);
80
81 my $limiter =
82 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
83 ||
84 do {
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'";
89 }
90 ;
91
92 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
93 }
94 else {
95 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
96 }
97
49afd714 98 push @{$self->{where_bind}}, @bind;
583a0c65 99
100# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 101 my @all_bind = $self->_assemble_binds;
583a0c65 102
49afd714 103 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 104}
105
106sub _assemble_binds {
107 my $self = shift;
108 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
6f4ddea1 109}
110
6a247f33 111# Handle default inserts
6f4ddea1 112sub insert {
6a247f33 113# optimized due to hotttnesss
114# my ($self, $table, $data, $options) = @_;
7a72e5a5 115
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
6a247f33 119 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
120 my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
28d28903 121
6a247f33 122 if (my $ret = ($_[3]||{})->{returning} ) {
123 $sql .= $_[0]->_insert_returning ($ret);
28d28903 124 }
125
126 return $sql;
7a72e5a5 127 }
128
6a247f33 129 next::method(@_);
6f4ddea1 130}
131
132sub _recurse_fields {
81446c4f 133 my ($self, $fields) = @_;
6f4ddea1 134 my $ref = ref $fields;
135 return $self->_quote($fields) unless $ref;
136 return $$fields if $ref eq 'SCALAR';
137
138 if ($ref eq 'ARRAY') {
81446c4f 139 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 140 }
141 elsif ($ref eq 'HASH') {
81446c4f 142 my %hash = %$fields; # shallow copy
83e09b5b 143
50136dd9 144 my $as = delete $hash{-as}; # if supplied
145
81446c4f 146 my ($func, $args, @toomany) = %hash;
147
148 # there should be only one pair
149 if (@toomany) {
150 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
151 }
50136dd9 152
153 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
154 croak (
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 }'
83e09b5b 158 );
6f4ddea1 159 }
83e09b5b 160
50136dd9 161 my $select = sprintf ('%s( %s )%s',
162 $self->_sqlcase($func),
163 $self->_recurse_fields($args),
164 $as
0491b597 165 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 166 : ''
167 );
168
83e09b5b 169 return $select;
6f4ddea1 170 }
171 # Is the second check absolutely necessary?
172 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 173 return $self->_fold_sqlbind( $fields );
6f4ddea1 174 }
175 else {
e8fcf76f 176 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 177 }
178}
179
a6b68a60 180my $for_syntax = {
181 update => 'FOR UPDATE',
182 shared => 'FOR SHARE',
183};
184
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!
193sub _parse_rs_attrs {
1cbd3034 194 my ($self, $arg) = @_;
15827712 195
a6b68a60 196 my $sql = '';
1cbd3034 197
b03f30a3 198 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
a6b68a60 199 $sql .= $self->_sqlcase(' group by ') . $g;
200 }
1cbd3034 201
a6b68a60 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;
206 }
15827712 207
a6b68a60 208 if (defined $arg->{order_by}) {
209 $sql .= $self->_order_by ($arg->{order_by});
210 }
15827712 211
a6b68a60 212 if (my $for = $arg->{for}) {
213 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
214 }
215
216 return $sql;
217}
218
219sub _order_by {
220 my ($self, $arg) = @_;
15827712 221
a6b68a60 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);
fde3719a 225 }
1cbd3034 226 else {
6a247f33 227 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 228 push @{$self->{order_bind}}, @bind;
1cbd3034 229 return $sql;
fd4cb60a 230 }
6f4ddea1 231}
232
233sub _table {
6a247f33 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]});
239 }
240 elsif ($ref eq 'HASH') {
241 return $_[0]->_make_as($_[1]);
242 }
6f4ddea1 243 }
6a247f33 244
245 return $_[0]->next::method ($_[1]);
6f4ddea1 246}
247
b8391c87 248sub _generate_join_clause {
249 my ($self, $join_type) = @_;
250
251 return sprintf ('%s JOIN ',
252 $join_type ? ' ' . uc($join_type) : ''
253 );
254}
255
6f4ddea1 256sub _recurse_from {
257 my ($self, $from, @join) = @_;
258 my @sqlf;
259 push(@sqlf, $self->_make_as($from));
260 foreach my $j (@join) {
261 my ($to, $on) = @$j;
262
aa82ce29 263
6f4ddea1 264 # check whether a join type exists
6f4ddea1 265 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 266 my $join_type;
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;
6f4ddea1 270 }
aa82ce29 271
de5f71ef 272 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 273
b8391c87 274 push @sqlf, $self->_generate_join_clause( $join_type );
6f4ddea1 275
276 if (ref $to eq 'ARRAY') {
277 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
278 } else {
279 push(@sqlf, $self->_make_as($to));
280 }
281 push(@sqlf, ' ON ', $self->_join_condition($on));
282 }
283 return join('', @sqlf);
284}
285
db56cf3d 286sub _fold_sqlbind {
287 my ($self, $sqlbind) = @_;
69989ea9 288
289 my @sqlbind = @$$sqlbind; # copy
290 my $sql = shift @sqlbind;
291 push @{$self->{from_bind}}, @sqlbind;
292
db56cf3d 293 return $sql;
6f4ddea1 294}
295
296sub _make_as {
297 my ($self, $from) = @_;
db56cf3d 298 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
299 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
300 : $self->_quote($_))
6f4ddea1 301 } reverse each %{$self->_skip_options($from)});
302}
303
304sub _skip_options {
305 my ($self, $hash) = @_;
306 my $clean_hash = {};
307 $clean_hash->{$_} = $hash->{$_}
308 for grep {!/^-/} keys %$hash;
309 return $clean_hash;
310}
311
312sub _join_condition {
313 my ($self, $cond) = @_;
314 if (ref $cond eq 'HASH') {
315 my %j;
316 for (keys %$cond) {
317 my $v = $cond->{$_};
318 if (ref $v) {
e8fcf76f 319 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 320 if ref($v) ne 'SCALAR';
321 $j{$_} = $v;
322 }
323 else {
324 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
325 }
326 };
327 return scalar($self->_recurse_where(\%j));
328 } elsif (ref $cond eq 'ARRAY') {
329 return join(' OR ', map { $self->_join_condition($_) } @$cond);
330 } else {
b48d3b4e 331 croak "Can't handle this yet!";
6f4ddea1 332 }
333}
334
6f4ddea1 3351;