Fix no-quoting assumptions in 'having' docs (RT#64129)
[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
e6600283 27=item * The -ident operator
28
41519379 29=item * The -value operator
30
d5dedbd6 31=back
32
33=cut
6a247f33 34
35use base qw/
d5dedbd6 36 DBIx::Class::SQLMaker::LimitDialects
6a247f33 37 SQL::Abstract
38 Class::Accessor::Grouped
39/;
40use mro 'c3';
e3764383 41use strict;
42use warnings;
6298a324 43use Sub::Name 'subname';
ac322978 44use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
e8fc51c7 45use namespace::clean;
b2b22cd6 46
6a247f33 47__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
48
3f5b99fe 49# for when I need a normalized l/r pair
50sub _quote_chars {
51 map
52 { defined $_ ? $_ : '' }
53 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
54 ;
55}
56
b2b22cd6 57BEGIN {
58 # reinstall the carp()/croak() functions imported into SQL::Abstract
59 # as Carp and Carp::Clan do not like each other much
60 no warnings qw/redefine/;
61 no strict qw/refs/;
62 for my $f (qw/carp croak/) {
329d7385 63
b2b22cd6 64 my $orig = \&{"SQL::Abstract::$f"};
e8fc51c7 65 my $clan_import = \&{$f};
6298a324 66 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
8637bb24 67 sub {
d5dedbd6 68 if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) {
ff04fc51 69 goto $clan_import;
8637bb24 70 }
71 else {
72 goto $orig;
73 }
74 };
b2b22cd6 75 }
76}
6f4ddea1 77
e9657379 78# the "oh noes offset/top without limit" constant
6a247f33 79# limited to 32 bits for sanity (and consistency,
80# since it is ultimately handed to sprintf %u)
81# Implemented as a method, since ::Storage::DBI also
82# refers to it (i.e. for the case of software_limit or
83# as the value to abuse with MSSQL ordered subqueries)
e9657379 84sub __max_int { 0xFFFFFFFF };
85
e6600283 86sub new {
87 my $self = shift->next::method(@_);
88
41519379 89 # use the same coderefs, they are prepared to handle both cases
90 my @extra_dbic_syntax = (
91 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
92 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
93 );
94
95 push @{$self->{special_ops}}, @extra_dbic_syntax;
96 push @{$self->{unary_ops}}, @extra_dbic_syntax;
e6600283 97
98 $self;
99}
100
101sub _where_op_IDENT {
102 my $self = shift;
103 my ($op, $rhs) = splice @_, -2;
104 if (ref $rhs) {
105 croak "-$op takes a single scalar argument (a quotable identifier)";
106 }
107
41519379 108 # in case we are called as a top level special op (no '=')
e6600283 109 my $lhs = shift;
110
111 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
112
113 return $lhs
114 ? "$lhs = $rhs"
115 : $rhs
116 ;
117}
118
41519379 119sub _where_op_VALUE {
120 my $self = shift;
121 my ($op, $rhs) = splice @_, -2;
122
123 # in case we are called as a top level special op (no '=')
124 my $lhs = shift;
125
126 my @bind = [
127 ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"),
128 $rhs
129 ];
130
131 return $lhs
132 ? (
133 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
134 @bind
135 )
136 : (
137 $self->_convert('?'),
138 @bind,
139 )
140 ;
141}
142
6a247f33 143# Handle limit-dialect selection
6f4ddea1 144sub select {
6a247f33 145 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
146
147
148 $fields = $self->_recurse_fields($fields);
149
150 if (defined $offset) {
151 croak ('A supplied offset must be a non-negative integer')
152 if ( $offset =~ /\D/ or $offset < 0 );
153 }
154 $offset ||= 0;
1cbd3034 155
6a247f33 156 if (defined $limit) {
157 croak ('A supplied limit must be a positive integer')
158 if ( $limit =~ /\D/ or $limit <= 0 );
159 }
160 elsif ($offset) {
161 $limit = $self->__max_int;
6f4ddea1 162 }
c2b7c5dc 163
a6b68a60 164
6a247f33 165 my ($sql, @bind);
166 if ($limit) {
167 # this is legacy code-flow from SQLA::Limit, it is not set in stone
168
169 ($sql, @bind) = $self->next::method ($table, $fields, $where);
170
171 my $limiter =
172 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
173 ||
174 do {
175 my $dialect = $self->limit_dialect
176 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
177 $self->can ("_$dialect")
d5dedbd6 178 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 179 }
180 ;
181
182 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
183 }
184 else {
185 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
186 }
187
49afd714 188 push @{$self->{where_bind}}, @bind;
583a0c65 189
190# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 191 my @all_bind = $self->_assemble_binds;
583a0c65 192
e5372da4 193 $sql .= $self->_lock_select ($rs_attrs->{for})
194 if $rs_attrs->{for};
195
49afd714 196 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 197}
198
199sub _assemble_binds {
200 my $self = shift;
201 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
6f4ddea1 202}
203
e5372da4 204my $for_syntax = {
205 update => 'FOR UPDATE',
206 shared => 'FOR SHARE',
207};
208sub _lock_select {
209 my ($self, $type) = @_;
210 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
211 return " $sql";
212}
213
6a247f33 214# Handle default inserts
6f4ddea1 215sub insert {
6a247f33 216# optimized due to hotttnesss
217# my ($self, $table, $data, $options) = @_;
7a72e5a5 218
219 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
220 # which is sadly understood only by MySQL. Change default behavior here,
221 # until SQLA2 comes with proper dialect support
6a247f33 222 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 223 my @bind;
20595c02 224 my $sql = sprintf(
225 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
226 );
28d28903 227
bf51641f 228 if ( ($_[3]||{})->{returning} ) {
229 my $s;
230 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
231 $sql .= $s;
28d28903 232 }
233
bf51641f 234 return ($sql, @bind);
7a72e5a5 235 }
236
6a247f33 237 next::method(@_);
6f4ddea1 238}
239
240sub _recurse_fields {
81446c4f 241 my ($self, $fields) = @_;
6f4ddea1 242 my $ref = ref $fields;
243 return $self->_quote($fields) unless $ref;
244 return $$fields if $ref eq 'SCALAR';
245
246 if ($ref eq 'ARRAY') {
81446c4f 247 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 248 }
249 elsif ($ref eq 'HASH') {
81446c4f 250 my %hash = %$fields; # shallow copy
83e09b5b 251
50136dd9 252 my $as = delete $hash{-as}; # if supplied
253
81446c4f 254 my ($func, $args, @toomany) = %hash;
255
256 # there should be only one pair
257 if (@toomany) {
258 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
259 }
50136dd9 260
261 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
262 croak (
263 'The select => { distinct => ... } syntax is not supported for multiple columns.'
264 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
265 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 266 );
6f4ddea1 267 }
83e09b5b 268
50136dd9 269 my $select = sprintf ('%s( %s )%s',
270 $self->_sqlcase($func),
271 $self->_recurse_fields($args),
272 $as
0491b597 273 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 274 : ''
275 );
276
83e09b5b 277 return $select;
6f4ddea1 278 }
279 # Is the second check absolutely necessary?
280 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 281 return $self->_fold_sqlbind( $fields );
6f4ddea1 282 }
283 else {
e8fcf76f 284 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 285 }
286}
287
a6b68a60 288
289# this used to be a part of _order_by but is broken out for clarity.
290# What we have been doing forever is hijacking the $order arg of
291# SQLA::select to pass in arbitrary pieces of data (first the group_by,
292# then pretty much the entire resultset attr-hash, as more and more
293# things in the SQLA space need to have mopre info about the $rs they
294# create SQL for. The alternative would be to keep expanding the
295# signature of _select with more and more positional parameters, which
296# is just gross. All hail SQLA2!
297sub _parse_rs_attrs {
1cbd3034 298 my ($self, $arg) = @_;
15827712 299
a6b68a60 300 my $sql = '';
1cbd3034 301
b03f30a3 302 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
a6b68a60 303 $sql .= $self->_sqlcase(' group by ') . $g;
304 }
1cbd3034 305
a6b68a60 306 if (defined $arg->{having}) {
307 my ($frag, @bind) = $self->_recurse_where($arg->{having});
308 push(@{$self->{having_bind}}, @bind);
309 $sql .= $self->_sqlcase(' having ') . $frag;
310 }
15827712 311
a6b68a60 312 if (defined $arg->{order_by}) {
313 $sql .= $self->_order_by ($arg->{order_by});
314 }
15827712 315
a6b68a60 316 return $sql;
317}
318
319sub _order_by {
320 my ($self, $arg) = @_;
15827712 321
a6b68a60 322 # check that we are not called in legacy mode (order_by as 4th argument)
323 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
324 return $self->_parse_rs_attrs ($arg);
fde3719a 325 }
1cbd3034 326 else {
6a247f33 327 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 328 push @{$self->{order_bind}}, @bind;
1cbd3034 329 return $sql;
fd4cb60a 330 }
6f4ddea1 331}
332
333sub _table {
6a247f33 334# optimized due to hotttnesss
335# my ($self, $from) = @_;
336 if (my $ref = ref $_[1] ) {
337 if ($ref eq 'ARRAY') {
338 return $_[0]->_recurse_from(@{$_[1]});
339 }
340 elsif ($ref eq 'HASH') {
341 return $_[0]->_make_as($_[1]);
342 }
6f4ddea1 343 }
6a247f33 344
345 return $_[0]->next::method ($_[1]);
6f4ddea1 346}
347
b8391c87 348sub _generate_join_clause {
349 my ($self, $join_type) = @_;
350
351 return sprintf ('%s JOIN ',
352 $join_type ? ' ' . uc($join_type) : ''
353 );
354}
355
6f4ddea1 356sub _recurse_from {
357 my ($self, $from, @join) = @_;
358 my @sqlf;
359 push(@sqlf, $self->_make_as($from));
360 foreach my $j (@join) {
361 my ($to, $on) = @$j;
362
aa82ce29 363
6f4ddea1 364 # check whether a join type exists
6f4ddea1 365 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 366 my $join_type;
367 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
368 $join_type = $to_jt->{-join_type};
369 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 370 }
aa82ce29 371
de5f71ef 372 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 373
b8391c87 374 push @sqlf, $self->_generate_join_clause( $join_type );
6f4ddea1 375
376 if (ref $to eq 'ARRAY') {
377 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
378 } else {
379 push(@sqlf, $self->_make_as($to));
380 }
381 push(@sqlf, ' ON ', $self->_join_condition($on));
382 }
383 return join('', @sqlf);
384}
385
db56cf3d 386sub _fold_sqlbind {
387 my ($self, $sqlbind) = @_;
69989ea9 388
389 my @sqlbind = @$$sqlbind; # copy
390 my $sql = shift @sqlbind;
391 push @{$self->{from_bind}}, @sqlbind;
392
db56cf3d 393 return $sql;
6f4ddea1 394}
395
396sub _make_as {
397 my ($self, $from) = @_;
db56cf3d 398 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
399 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
400 : $self->_quote($_))
6f4ddea1 401 } reverse each %{$self->_skip_options($from)});
402}
403
404sub _skip_options {
405 my ($self, $hash) = @_;
406 my $clean_hash = {};
407 $clean_hash->{$_} = $hash->{$_}
408 for grep {!/^-/} keys %$hash;
409 return $clean_hash;
410}
411
412sub _join_condition {
413 my ($self, $cond) = @_;
414 if (ref $cond eq 'HASH') {
415 my %j;
416 for (keys %$cond) {
417 my $v = $cond->{$_};
418 if (ref $v) {
e8fcf76f 419 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 420 if ref($v) ne 'SCALAR';
421 $j{$_} = $v;
422 }
423 else {
424 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
425 }
426 };
427 return scalar($self->_recurse_where(\%j));
428 } elsif (ref $cond eq 'ARRAY') {
429 return join(' OR ', map { $self->_join_condition($_) } @$cond);
430 } else {
b48d3b4e 431 croak "Can't handle this yet!";
6f4ddea1 432 }
433}
434
6f4ddea1 4351;
d5dedbd6 436
437=head1 AUTHORS
438
439See L<DBIx::Class/CONTRIBUTORS>.
440
441=head1 LICENSE
442
443You may distribute this code under the same terms as Perl itself.
444
445=cut