Cleanup that namespacing mess
[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 }
9c1700e3 76
77 # Current SQLA pollutes its namespace - clean for the time being
78 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
b2b22cd6 79}
6f4ddea1 80
e9657379 81# the "oh noes offset/top without limit" constant
6a247f33 82# limited to 32 bits for sanity (and consistency,
83# since it is ultimately handed to sprintf %u)
84# Implemented as a method, since ::Storage::DBI also
85# refers to it (i.e. for the case of software_limit or
86# as the value to abuse with MSSQL ordered subqueries)
e9657379 87sub __max_int { 0xFFFFFFFF };
88
e6600283 89sub new {
90 my $self = shift->next::method(@_);
91
41519379 92 # use the same coderefs, they are prepared to handle both cases
93 my @extra_dbic_syntax = (
94 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
95 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
96 );
97
98 push @{$self->{special_ops}}, @extra_dbic_syntax;
99 push @{$self->{unary_ops}}, @extra_dbic_syntax;
e6600283 100
101 $self;
102}
103
104sub _where_op_IDENT {
105 my $self = shift;
106 my ($op, $rhs) = splice @_, -2;
107 if (ref $rhs) {
108 croak "-$op takes a single scalar argument (a quotable identifier)";
109 }
110
41519379 111 # in case we are called as a top level special op (no '=')
e6600283 112 my $lhs = shift;
113
114 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
115
116 return $lhs
117 ? "$lhs = $rhs"
118 : $rhs
119 ;
120}
121
41519379 122sub _where_op_VALUE {
123 my $self = shift;
124 my ($op, $rhs) = splice @_, -2;
125
126 # in case we are called as a top level special op (no '=')
127 my $lhs = shift;
128
129 my @bind = [
130 ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"),
131 $rhs
132 ];
133
134 return $lhs
135 ? (
136 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
137 @bind
138 )
139 : (
140 $self->_convert('?'),
141 @bind,
142 )
143 ;
144}
145
b1d821de 146my $callsites_warned;
147sub _where_op_NEST {
148 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
149 my $callsite = do {
150 my $w;
151 local $SIG{__WARN__} = sub { $w = shift };
152 carp;
153 $w
154 };
155
156 carp ("-nest in search conditions is deprecated, you most probably wanted:\n"
157 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
158 ) unless $callsites_warned->{$callsite}++;
159
160 shift->next::method(@_);
161}
162
6a247f33 163# Handle limit-dialect selection
6f4ddea1 164sub select {
6a247f33 165 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
166
167
168 $fields = $self->_recurse_fields($fields);
169
170 if (defined $offset) {
171 croak ('A supplied offset must be a non-negative integer')
172 if ( $offset =~ /\D/ or $offset < 0 );
173 }
174 $offset ||= 0;
1cbd3034 175
6a247f33 176 if (defined $limit) {
177 croak ('A supplied limit must be a positive integer')
178 if ( $limit =~ /\D/ or $limit <= 0 );
179 }
180 elsif ($offset) {
181 $limit = $self->__max_int;
6f4ddea1 182 }
c2b7c5dc 183
a6b68a60 184
6a247f33 185 my ($sql, @bind);
186 if ($limit) {
187 # this is legacy code-flow from SQLA::Limit, it is not set in stone
188
189 ($sql, @bind) = $self->next::method ($table, $fields, $where);
190
191 my $limiter =
192 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
193 ||
194 do {
195 my $dialect = $self->limit_dialect
196 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
197 $self->can ("_$dialect")
d5dedbd6 198 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 199 }
200 ;
201
202 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
203 }
204 else {
205 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
206 }
207
49afd714 208 push @{$self->{where_bind}}, @bind;
583a0c65 209
210# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 211 my @all_bind = $self->_assemble_binds;
583a0c65 212
e5372da4 213 $sql .= $self->_lock_select ($rs_attrs->{for})
214 if $rs_attrs->{for};
215
49afd714 216 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 217}
218
219sub _assemble_binds {
220 my $self = shift;
0542ec57 221 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
6f4ddea1 222}
223
e5372da4 224my $for_syntax = {
225 update => 'FOR UPDATE',
226 shared => 'FOR SHARE',
227};
228sub _lock_select {
229 my ($self, $type) = @_;
230 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
231 return " $sql";
232}
233
6a247f33 234# Handle default inserts
6f4ddea1 235sub insert {
6a247f33 236# optimized due to hotttnesss
237# my ($self, $table, $data, $options) = @_;
7a72e5a5 238
239 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
240 # which is sadly understood only by MySQL. Change default behavior here,
241 # until SQLA2 comes with proper dialect support
6a247f33 242 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 243 my @bind;
20595c02 244 my $sql = sprintf(
245 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
246 );
28d28903 247
bf51641f 248 if ( ($_[3]||{})->{returning} ) {
249 my $s;
250 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
251 $sql .= $s;
28d28903 252 }
253
bf51641f 254 return ($sql, @bind);
7a72e5a5 255 }
256
6a247f33 257 next::method(@_);
6f4ddea1 258}
259
260sub _recurse_fields {
81446c4f 261 my ($self, $fields) = @_;
6f4ddea1 262 my $ref = ref $fields;
263 return $self->_quote($fields) unless $ref;
264 return $$fields if $ref eq 'SCALAR';
265
266 if ($ref eq 'ARRAY') {
81446c4f 267 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 268 }
269 elsif ($ref eq 'HASH') {
81446c4f 270 my %hash = %$fields; # shallow copy
83e09b5b 271
50136dd9 272 my $as = delete $hash{-as}; # if supplied
273
81446c4f 274 my ($func, $args, @toomany) = %hash;
275
276 # there should be only one pair
277 if (@toomany) {
278 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
279 }
50136dd9 280
281 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
282 croak (
283 'The select => { distinct => ... } syntax is not supported for multiple columns.'
284 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
285 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 286 );
6f4ddea1 287 }
83e09b5b 288
50136dd9 289 my $select = sprintf ('%s( %s )%s',
290 $self->_sqlcase($func),
291 $self->_recurse_fields($args),
292 $as
0491b597 293 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 294 : ''
295 );
296
83e09b5b 297 return $select;
6f4ddea1 298 }
299 # Is the second check absolutely necessary?
300 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 301 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
302 return $$fields->[0];
6f4ddea1 303 }
304 else {
e8fcf76f 305 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 306 }
307}
308
a6b68a60 309
310# this used to be a part of _order_by but is broken out for clarity.
311# What we have been doing forever is hijacking the $order arg of
312# SQLA::select to pass in arbitrary pieces of data (first the group_by,
313# then pretty much the entire resultset attr-hash, as more and more
314# things in the SQLA space need to have mopre info about the $rs they
315# create SQL for. The alternative would be to keep expanding the
316# signature of _select with more and more positional parameters, which
317# is just gross. All hail SQLA2!
318sub _parse_rs_attrs {
1cbd3034 319 my ($self, $arg) = @_;
15827712 320
a6b68a60 321 my $sql = '';
1cbd3034 322
0542ec57 323 if ($arg->{group_by}) {
324 # horible horrible, waiting for refactor
325 local $self->{select_bind};
326 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
327 $sql .= $self->_sqlcase(' group by ') . $g;
328 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
329 }
a6b68a60 330 }
1cbd3034 331
a6b68a60 332 if (defined $arg->{having}) {
333 my ($frag, @bind) = $self->_recurse_where($arg->{having});
334 push(@{$self->{having_bind}}, @bind);
335 $sql .= $self->_sqlcase(' having ') . $frag;
336 }
15827712 337
a6b68a60 338 if (defined $arg->{order_by}) {
339 $sql .= $self->_order_by ($arg->{order_by});
340 }
15827712 341
a6b68a60 342 return $sql;
343}
344
345sub _order_by {
346 my ($self, $arg) = @_;
15827712 347
a6b68a60 348 # check that we are not called in legacy mode (order_by as 4th argument)
349 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
350 return $self->_parse_rs_attrs ($arg);
fde3719a 351 }
1cbd3034 352 else {
6a247f33 353 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 354 push @{$self->{order_bind}}, @bind;
1cbd3034 355 return $sql;
fd4cb60a 356 }
6f4ddea1 357}
358
359sub _table {
6a247f33 360# optimized due to hotttnesss
361# my ($self, $from) = @_;
362 if (my $ref = ref $_[1] ) {
363 if ($ref eq 'ARRAY') {
364 return $_[0]->_recurse_from(@{$_[1]});
365 }
366 elsif ($ref eq 'HASH') {
4c2b30d6 367 return $_[0]->_recurse_from($_[1]);
6a247f33 368 }
6f4ddea1 369 }
6a247f33 370
371 return $_[0]->next::method ($_[1]);
6f4ddea1 372}
373
b8391c87 374sub _generate_join_clause {
375 my ($self, $join_type) = @_;
376
377 return sprintf ('%s JOIN ',
4c2b30d6 378 $join_type ? ' ' . $self->_sqlcase($join_type) : ''
b8391c87 379 );
380}
381
6f4ddea1 382sub _recurse_from {
383 my ($self, $from, @join) = @_;
384 my @sqlf;
4c2b30d6 385 push @sqlf, $self->_from_chunk_to_sql($from);
6f4ddea1 386
4c2b30d6 387 for (@join) {
388 my ($to, $on) = @$_;
aa82ce29 389
6f4ddea1 390 # check whether a join type exists
6f4ddea1 391 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 392 my $join_type;
393 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
394 $join_type = $to_jt->{-join_type};
395 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 396 }
aa82ce29 397
de5f71ef 398 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 399
b8391c87 400 push @sqlf, $self->_generate_join_clause( $join_type );
6f4ddea1 401
402 if (ref $to eq 'ARRAY') {
403 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
404 } else {
4c2b30d6 405 push(@sqlf, $self->_from_chunk_to_sql($to));
6f4ddea1 406 }
407 push(@sqlf, ' ON ', $self->_join_condition($on));
408 }
409 return join('', @sqlf);
410}
411
4c2b30d6 412sub _from_chunk_to_sql {
413 my ($self, $fromspec) = @_;
414
415 return join (' ', $self->_SWITCH_refkind($fromspec, {
416 SCALARREF => sub {
417 $$fromspec;
418 },
419 ARRAYREFREF => sub {
420 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
421 $$fromspec->[0];
422 },
423 HASHREF => sub {
424 my ($as, $table, $toomuch) = ( map
425 { $_ => $fromspec->{$_} }
426 ( grep { $_ !~ /^\-/ } keys %$fromspec )
427 );
6f4ddea1 428
4c2b30d6 429 croak "Only one table/as pair expected in from-spec but an exra '$toomuch' key present"
430 if defined $toomuch;
6f4ddea1 431
4c2b30d6 432 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
433 },
434 SCALAR => sub {
435 $self->_quote($fromspec);
436 },
437 }));
6f4ddea1 438}
439
440sub _join_condition {
441 my ($self, $cond) = @_;
4c2b30d6 442
6f4ddea1 443 if (ref $cond eq 'HASH') {
444 my %j;
445 for (keys %$cond) {
446 my $v = $cond->{$_};
447 if (ref $v) {
e8fcf76f 448 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 449 if ref($v) ne 'SCALAR';
450 $j{$_} = $v;
451 }
452 else {
453 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
454 }
455 };
456 return scalar($self->_recurse_where(\%j));
457 } elsif (ref $cond eq 'ARRAY') {
458 return join(' OR ', map { $self->_join_condition($_) } @$cond);
459 } else {
b48d3b4e 460 croak "Can't handle this yet!";
6f4ddea1 461 }
462}
463
6f4ddea1 4641;
d5dedbd6 465
466=head1 AUTHORS
467
468See L<DBIx::Class/CONTRIBUTORS>.
469
470=head1 LICENSE
471
472You may distribute this code under the same terms as Perl itself.
473
474=cut