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