Fix the taint mode test to correctly work under local-lib or similar
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
CommitLineData
d5dedbd6 1package DBIx::Class::SQLMaker;
6f4ddea1 2
d5dedbd6 3=head1 NAME
4
5DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
6
7=head1 DESCRIPTION
8
9This module is a subclass of L<SQL::Abstract> and includes a number of
10DBIC-specific workarounds, not yet suitable for inclusion into the
11L<SQL::Abstract> core. It also provides all (and more than) the functionality
12of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
13more info.
14
15Currently the enhancements to L<SQL::Abstract> are:
16
17=over
18
19=item * Support for C<JOIN> statements (via extended C<table/from> support)
20
21=item * Support of functions in C<SELECT> lists
22
23=item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
24
25=item * Support of C<...FOR UPDATE> type of select statement modifiers
26
27=back
28
29=cut
6a247f33 30
31use base qw/
d5dedbd6 32 DBIx::Class::SQLMaker::LimitDialects
6a247f33 33 SQL::Abstract
34 Class::Accessor::Grouped
35/;
36use mro 'c3';
e3764383 37use strict;
38use warnings;
6298a324 39use Sub::Name 'subname';
ac322978 40use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
e8fc51c7 41use namespace::clean;
b2b22cd6 42
6a247f33 43__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
44
b2b22cd6 45BEGIN {
46 # reinstall the carp()/croak() functions imported into SQL::Abstract
47 # as Carp and Carp::Clan do not like each other much
48 no warnings qw/redefine/;
49 no strict qw/refs/;
50 for my $f (qw/carp croak/) {
329d7385 51
b2b22cd6 52 my $orig = \&{"SQL::Abstract::$f"};
e8fc51c7 53 my $clan_import = \&{$f};
6298a324 54 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
8637bb24 55 sub {
d5dedbd6 56 if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) {
e8fc51c7 57 $clan_import->(@_);
8637bb24 58 }
59 else {
60 goto $orig;
61 }
62 };
b2b22cd6 63 }
64}
6f4ddea1 65
e9657379 66# the "oh noes offset/top without limit" constant
6a247f33 67# limited to 32 bits for sanity (and consistency,
68# since it is ultimately handed to sprintf %u)
69# Implemented as a method, since ::Storage::DBI also
70# refers to it (i.e. for the case of software_limit or
71# as the value to abuse with MSSQL ordered subqueries)
e9657379 72sub __max_int { 0xFFFFFFFF };
73
6a247f33 74# Handle limit-dialect selection
6f4ddea1 75sub select {
6a247f33 76 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
77
78
79 $fields = $self->_recurse_fields($fields);
80
81 if (defined $offset) {
82 croak ('A supplied offset must be a non-negative integer')
83 if ( $offset =~ /\D/ or $offset < 0 );
84 }
85 $offset ||= 0;
1cbd3034 86
6a247f33 87 if (defined $limit) {
88 croak ('A supplied limit must be a positive integer')
89 if ( $limit =~ /\D/ or $limit <= 0 );
90 }
91 elsif ($offset) {
92 $limit = $self->__max_int;
6f4ddea1 93 }
c2b7c5dc 94
a6b68a60 95
6a247f33 96 my ($sql, @bind);
97 if ($limit) {
98 # this is legacy code-flow from SQLA::Limit, it is not set in stone
99
100 ($sql, @bind) = $self->next::method ($table, $fields, $where);
101
102 my $limiter =
103 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
104 ||
105 do {
106 my $dialect = $self->limit_dialect
107 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
108 $self->can ("_$dialect")
d5dedbd6 109 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 110 }
111 ;
112
113 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
114 }
115 else {
116 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
117 }
118
49afd714 119 push @{$self->{where_bind}}, @bind;
583a0c65 120
121# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 122 my @all_bind = $self->_assemble_binds;
583a0c65 123
49afd714 124 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 125}
126
127sub _assemble_binds {
128 my $self = shift;
129 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
6f4ddea1 130}
131
6a247f33 132# Handle default inserts
6f4ddea1 133sub insert {
6a247f33 134# optimized due to hotttnesss
135# my ($self, $table, $data, $options) = @_;
7a72e5a5 136
137 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
138 # which is sadly understood only by MySQL. Change default behavior here,
139 # until SQLA2 comes with proper dialect support
6a247f33 140 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
141 my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
28d28903 142
6a247f33 143 if (my $ret = ($_[3]||{})->{returning} ) {
144 $sql .= $_[0]->_insert_returning ($ret);
28d28903 145 }
146
147 return $sql;
7a72e5a5 148 }
149
6a247f33 150 next::method(@_);
6f4ddea1 151}
152
153sub _recurse_fields {
81446c4f 154 my ($self, $fields) = @_;
6f4ddea1 155 my $ref = ref $fields;
156 return $self->_quote($fields) unless $ref;
157 return $$fields if $ref eq 'SCALAR';
158
159 if ($ref eq 'ARRAY') {
81446c4f 160 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 161 }
162 elsif ($ref eq 'HASH') {
81446c4f 163 my %hash = %$fields; # shallow copy
83e09b5b 164
50136dd9 165 my $as = delete $hash{-as}; # if supplied
166
81446c4f 167 my ($func, $args, @toomany) = %hash;
168
169 # there should be only one pair
170 if (@toomany) {
171 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
172 }
50136dd9 173
174 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
175 croak (
176 'The select => { distinct => ... } syntax is not supported for multiple columns.'
177 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
178 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 179 );
6f4ddea1 180 }
83e09b5b 181
50136dd9 182 my $select = sprintf ('%s( %s )%s',
183 $self->_sqlcase($func),
184 $self->_recurse_fields($args),
185 $as
0491b597 186 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 187 : ''
188 );
189
83e09b5b 190 return $select;
6f4ddea1 191 }
192 # Is the second check absolutely necessary?
193 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 194 return $self->_fold_sqlbind( $fields );
6f4ddea1 195 }
196 else {
e8fcf76f 197 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 198 }
199}
200
a6b68a60 201my $for_syntax = {
202 update => 'FOR UPDATE',
203 shared => 'FOR SHARE',
204};
205
206# this used to be a part of _order_by but is broken out for clarity.
207# What we have been doing forever is hijacking the $order arg of
208# SQLA::select to pass in arbitrary pieces of data (first the group_by,
209# then pretty much the entire resultset attr-hash, as more and more
210# things in the SQLA space need to have mopre info about the $rs they
211# create SQL for. The alternative would be to keep expanding the
212# signature of _select with more and more positional parameters, which
213# is just gross. All hail SQLA2!
214sub _parse_rs_attrs {
1cbd3034 215 my ($self, $arg) = @_;
15827712 216
a6b68a60 217 my $sql = '';
1cbd3034 218
b03f30a3 219 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
a6b68a60 220 $sql .= $self->_sqlcase(' group by ') . $g;
221 }
1cbd3034 222
a6b68a60 223 if (defined $arg->{having}) {
224 my ($frag, @bind) = $self->_recurse_where($arg->{having});
225 push(@{$self->{having_bind}}, @bind);
226 $sql .= $self->_sqlcase(' having ') . $frag;
227 }
15827712 228
a6b68a60 229 if (defined $arg->{order_by}) {
230 $sql .= $self->_order_by ($arg->{order_by});
231 }
15827712 232
a6b68a60 233 if (my $for = $arg->{for}) {
234 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
235 }
236
237 return $sql;
238}
239
240sub _order_by {
241 my ($self, $arg) = @_;
15827712 242
a6b68a60 243 # check that we are not called in legacy mode (order_by as 4th argument)
244 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
245 return $self->_parse_rs_attrs ($arg);
fde3719a 246 }
1cbd3034 247 else {
6a247f33 248 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 249 push @{$self->{order_bind}}, @bind;
1cbd3034 250 return $sql;
fd4cb60a 251 }
6f4ddea1 252}
253
254sub _table {
6a247f33 255# optimized due to hotttnesss
256# my ($self, $from) = @_;
257 if (my $ref = ref $_[1] ) {
258 if ($ref eq 'ARRAY') {
259 return $_[0]->_recurse_from(@{$_[1]});
260 }
261 elsif ($ref eq 'HASH') {
262 return $_[0]->_make_as($_[1]);
263 }
6f4ddea1 264 }
6a247f33 265
266 return $_[0]->next::method ($_[1]);
6f4ddea1 267}
268
b8391c87 269sub _generate_join_clause {
270 my ($self, $join_type) = @_;
271
272 return sprintf ('%s JOIN ',
273 $join_type ? ' ' . uc($join_type) : ''
274 );
275}
276
6f4ddea1 277sub _recurse_from {
278 my ($self, $from, @join) = @_;
279 my @sqlf;
280 push(@sqlf, $self->_make_as($from));
281 foreach my $j (@join) {
282 my ($to, $on) = @$j;
283
aa82ce29 284
6f4ddea1 285 # check whether a join type exists
6f4ddea1 286 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 287 my $join_type;
288 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
289 $join_type = $to_jt->{-join_type};
290 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 291 }
aa82ce29 292
de5f71ef 293 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 294
b8391c87 295 push @sqlf, $self->_generate_join_clause( $join_type );
6f4ddea1 296
297 if (ref $to eq 'ARRAY') {
298 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
299 } else {
300 push(@sqlf, $self->_make_as($to));
301 }
302 push(@sqlf, ' ON ', $self->_join_condition($on));
303 }
304 return join('', @sqlf);
305}
306
db56cf3d 307sub _fold_sqlbind {
308 my ($self, $sqlbind) = @_;
69989ea9 309
310 my @sqlbind = @$$sqlbind; # copy
311 my $sql = shift @sqlbind;
312 push @{$self->{from_bind}}, @sqlbind;
313
db56cf3d 314 return $sql;
6f4ddea1 315}
316
317sub _make_as {
318 my ($self, $from) = @_;
db56cf3d 319 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
320 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
321 : $self->_quote($_))
6f4ddea1 322 } reverse each %{$self->_skip_options($from)});
323}
324
325sub _skip_options {
326 my ($self, $hash) = @_;
327 my $clean_hash = {};
328 $clean_hash->{$_} = $hash->{$_}
329 for grep {!/^-/} keys %$hash;
330 return $clean_hash;
331}
332
333sub _join_condition {
334 my ($self, $cond) = @_;
335 if (ref $cond eq 'HASH') {
336 my %j;
337 for (keys %$cond) {
338 my $v = $cond->{$_};
339 if (ref $v) {
e8fcf76f 340 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 341 if ref($v) ne 'SCALAR';
342 $j{$_} = $v;
343 }
344 else {
345 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
346 }
347 };
348 return scalar($self->_recurse_where(\%j));
349 } elsif (ref $cond eq 'ARRAY') {
350 return join(' OR ', map { $self->_join_condition($_) } @$cond);
351 } else {
b48d3b4e 352 croak "Can't handle this yet!";
6f4ddea1 353 }
354}
355
6f4ddea1 3561;
d5dedbd6 357
358=head1 AUTHORS
359
360See L<DBIx::Class/CONTRIBUTORS>.
361
362=head1 LICENSE
363
364You may distribute this code under the same terms as Perl itself.
365
366=cut