begin work on column aliasing feature
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
CommitLineData
d5dedbd6 1package DBIx::Class::SQLMaker;
6f4ddea1 2
a697fa31 3use strict;
4use warnings;
5
d5dedbd6 6=head1 NAME
7
8DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
9
10=head1 DESCRIPTION
11
12This module is a subclass of L<SQL::Abstract> and includes a number of
13DBIC-specific workarounds, not yet suitable for inclusion into the
14L<SQL::Abstract> core. It also provides all (and more than) the functionality
15of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
16more info.
17
18Currently the enhancements to L<SQL::Abstract> are:
19
20=over
21
22=item * Support for C<JOIN> statements (via extended C<table/from> support)
23
24=item * Support of functions in C<SELECT> lists
25
26=item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
27
28=item * Support of C<...FOR UPDATE> type of select statement modifiers
29
30=back
31
32=cut
6a247f33 33
34use base qw/
d5dedbd6 35 DBIx::Class::SQLMaker::LimitDialects
6a247f33 36 SQL::Abstract
70c28808 37 DBIx::Class
6a247f33 38/;
39use mro 'c3';
a697fa31 40
6298a324 41use Sub::Name 'subname';
70c28808 42use DBIx::Class::Carp;
43use DBIx::Class::Exception;
e8fc51c7 44use namespace::clean;
b2b22cd6 45
61063249 46__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect storage/);
6a247f33 47
3f5b99fe 48# for when I need a normalized l/r pair
49sub _quote_chars {
50 map
51 { defined $_ ? $_ : '' }
52 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
53 ;
54}
55
70c28808 56# FIXME when we bring in the storage weaklink, check its schema
57# weaklink and channel through $schema->throw_exception
58sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
59
b2b22cd6 60BEGIN {
2ea6032a 61 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
70c28808 62 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
b2b22cd6 63 no warnings qw/redefine/;
2ea6032a 64
65 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
66 my($func) = (caller(1))[3];
67 carp "[$func] Warning: ", @_;
68 };
69
70 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
71 my($func) = (caller(1))[3];
70c28808 72 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
2ea6032a 73 };
9c1700e3 74
75 # Current SQLA pollutes its namespace - clean for the time being
76 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
b2b22cd6 77}
6f4ddea1 78
e9657379 79# the "oh noes offset/top without limit" constant
fcb7fcbb 80# limited to 31 bits for sanity (and consistency,
81# since it may be handed to the like of sprintf %u)
82#
83# Also *some* builds of SQLite fail the test
84# some_column BETWEEN ? AND ?: 1, 4294967295
85# with the proper integer bind attrs
86#
6a247f33 87# Implemented as a method, since ::Storage::DBI also
88# refers to it (i.e. for the case of software_limit or
89# as the value to abuse with MSSQL ordered subqueries)
fcb7fcbb 90sub __max_int () { 0x7FFFFFFF };
e9657379 91
e39f188a 92# poor man's de-qualifier
93sub _quote {
61063249 94 return undef if not defined $_[1];
95
96 my $col = ( $_[0]{_dequalify_idents} and ! ref $_[1] )
e39f188a 97 ? $_[1] =~ / ([^\.]+) $ /x
98 : $_[1]
61063249 99 ;
100
101 if (
102 $_[0]->{FROM}
103 and
104 $_[0]->storage
105 and
106 my $alias = ($_[0]->storage->_resolve_column_info($_[0]->{FROM}, [$col]) || {})->{$col}{sql_alias}
107 ) {
108 $col =~ s/[^\.]+$/$alias/;
109 }
110
111 $_[0]->next::method( $col );
e39f188a 112}
113
b1d821de 114sub _where_op_NEST {
70c28808 115 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
b1d821de 116 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
70c28808 117 );
b1d821de 118
119 shift->next::method(@_);
120}
121
6a247f33 122# Handle limit-dialect selection
6f4ddea1 123sub select {
6a247f33 124 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
125
126
61063249 127 local $self->{FROM} = $table;
6a247f33 128 $fields = $self->_recurse_fields($fields);
129
130 if (defined $offset) {
70c28808 131 $self->throw_exception('A supplied offset must be a non-negative integer')
6a247f33 132 if ( $offset =~ /\D/ or $offset < 0 );
133 }
134 $offset ||= 0;
1cbd3034 135
6a247f33 136 if (defined $limit) {
70c28808 137 $self->throw_exception('A supplied limit must be a positive integer')
6a247f33 138 if ( $limit =~ /\D/ or $limit <= 0 );
139 }
140 elsif ($offset) {
141 $limit = $self->__max_int;
6f4ddea1 142 }
c2b7c5dc 143
a6b68a60 144
6a247f33 145 my ($sql, @bind);
146 if ($limit) {
147 # this is legacy code-flow from SQLA::Limit, it is not set in stone
148
149 ($sql, @bind) = $self->next::method ($table, $fields, $where);
150
151 my $limiter =
152 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
153 ||
154 do {
155 my $dialect = $self->limit_dialect
70c28808 156 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
6a247f33 157 $self->can ("_$dialect")
70c28808 158 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 159 }
160 ;
161
f74d22e2 162 $sql = $self->$limiter (
163 $sql,
164 { %{$rs_attrs||{}}, _selector_sql => $fields },
165 $limit,
166 $offset
167 );
6a247f33 168 }
169 else {
170 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
171 }
172
49afd714 173 push @{$self->{where_bind}}, @bind;
583a0c65 174
175# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 176 my @all_bind = $self->_assemble_binds;
583a0c65 177
e5372da4 178 $sql .= $self->_lock_select ($rs_attrs->{for})
179 if $rs_attrs->{for};
180
49afd714 181 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 182}
183
184sub _assemble_binds {
185 my $self = shift;
8b31f62e 186 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
6f4ddea1 187}
188
e5372da4 189my $for_syntax = {
190 update => 'FOR UPDATE',
191 shared => 'FOR SHARE',
192};
193sub _lock_select {
194 my ($self, $type) = @_;
8249c09b 195
196 my $sql;
197 if (ref($type) eq 'SCALAR') {
198 $sql = "FOR $$type";
199 }
200 else {
201 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
202 }
203
e5372da4 204 return " $sql";
205}
206
6a247f33 207# Handle default inserts
6f4ddea1 208sub insert {
6a247f33 209# optimized due to hotttnesss
210# my ($self, $table, $data, $options) = @_;
7a72e5a5 211
61063249 212 local $_[0]->{FROM} = $_[1];
7a72e5a5 213 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
214 # which is sadly understood only by MySQL. Change default behavior here,
215 # until SQLA2 comes with proper dialect support
6a247f33 216 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 217 my @bind;
20595c02 218 my $sql = sprintf(
219 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
220 );
28d28903 221
bf51641f 222 if ( ($_[3]||{})->{returning} ) {
223 my $s;
224 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
225 $sql .= $s;
28d28903 226 }
227
bf51641f 228 return ($sql, @bind);
7a72e5a5 229 }
230
6a247f33 231 next::method(@_);
6f4ddea1 232}
233
61063249 234sub update {
235 local $_[0]->{FROM} = $_[1];
236
237 shift->next::method(@_);
238}
239
240sub delete {
241
242 shift->next::method(@_);
243}
244
6f4ddea1 245sub _recurse_fields {
81446c4f 246 my ($self, $fields) = @_;
6f4ddea1 247 my $ref = ref $fields;
248 return $self->_quote($fields) unless $ref;
249 return $$fields if $ref eq 'SCALAR';
250
251 if ($ref eq 'ARRAY') {
81446c4f 252 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 253 }
254 elsif ($ref eq 'HASH') {
81446c4f 255 my %hash = %$fields; # shallow copy
83e09b5b 256
50136dd9 257 my $as = delete $hash{-as}; # if supplied
258
81446c4f 259 my ($func, $args, @toomany) = %hash;
260
261 # there should be only one pair
262 if (@toomany) {
70c28808 263 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 264 }
50136dd9 265
266 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
70c28808 267 $self->throw_exception (
50136dd9 268 'The select => { distinct => ... } syntax is not supported for multiple columns.'
269 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
270 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 271 );
6f4ddea1 272 }
83e09b5b 273
50136dd9 274 my $select = sprintf ('%s( %s )%s',
275 $self->_sqlcase($func),
276 $self->_recurse_fields($args),
277 $as
0491b597 278 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 279 : ''
280 );
281
83e09b5b 282 return $select;
6f4ddea1 283 }
284 # Is the second check absolutely necessary?
285 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 286 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
287 return $$fields->[0];
6f4ddea1 288 }
289 else {
70c28808 290 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 291 }
292}
293
a6b68a60 294
295# this used to be a part of _order_by but is broken out for clarity.
296# What we have been doing forever is hijacking the $order arg of
297# SQLA::select to pass in arbitrary pieces of data (first the group_by,
298# then pretty much the entire resultset attr-hash, as more and more
299# things in the SQLA space need to have mopre info about the $rs they
300# create SQL for. The alternative would be to keep expanding the
301# signature of _select with more and more positional parameters, which
302# is just gross. All hail SQLA2!
303sub _parse_rs_attrs {
1cbd3034 304 my ($self, $arg) = @_;
15827712 305
a6b68a60 306 my $sql = '';
1cbd3034 307
0542ec57 308 if ($arg->{group_by}) {
309 # horible horrible, waiting for refactor
310 local $self->{select_bind};
311 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
312 $sql .= $self->_sqlcase(' group by ') . $g;
313 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
314 }
a6b68a60 315 }
1cbd3034 316
a6b68a60 317 if (defined $arg->{having}) {
318 my ($frag, @bind) = $self->_recurse_where($arg->{having});
319 push(@{$self->{having_bind}}, @bind);
320 $sql .= $self->_sqlcase(' having ') . $frag;
321 }
15827712 322
a6b68a60 323 if (defined $arg->{order_by}) {
324 $sql .= $self->_order_by ($arg->{order_by});
325 }
15827712 326
a6b68a60 327 return $sql;
328}
329
330sub _order_by {
331 my ($self, $arg) = @_;
15827712 332
a6b68a60 333 # check that we are not called in legacy mode (order_by as 4th argument)
334 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
335 return $self->_parse_rs_attrs ($arg);
fde3719a 336 }
1cbd3034 337 else {
6a247f33 338 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 339 push @{$self->{order_bind}}, @bind;
1cbd3034 340 return $sql;
fd4cb60a 341 }
6f4ddea1 342}
343
344sub _table {
6a247f33 345# optimized due to hotttnesss
346# my ($self, $from) = @_;
347 if (my $ref = ref $_[1] ) {
348 if ($ref eq 'ARRAY') {
349 return $_[0]->_recurse_from(@{$_[1]});
350 }
351 elsif ($ref eq 'HASH') {
4c2b30d6 352 return $_[0]->_recurse_from($_[1]);
6a247f33 353 }
1bffc6b8 354 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
355 my ($sql, @bind) = @{ ${$_[1]} };
356 push @{$_[0]->{from_bind}}, @bind;
357 return $sql
358 }
6f4ddea1 359 }
6a247f33 360 return $_[0]->next::method ($_[1]);
6f4ddea1 361}
362
b8391c87 363sub _generate_join_clause {
364 my ($self, $join_type) = @_;
365
726c8f65 366 $join_type = $self->{_default_jointype}
367 if ! defined $join_type;
368
b8391c87 369 return sprintf ('%s JOIN ',
726c8f65 370 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 371 );
372}
373
6f4ddea1 374sub _recurse_from {
726c8f65 375 my $self = shift;
376
377 return join (' ', $self->_gen_from_blocks(@_) );
378}
379
380sub _gen_from_blocks {
381 my ($self, $from, @joins) = @_;
382
383 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 384
726c8f65 385 for (@joins) {
4c2b30d6 386 my ($to, $on) = @$_;
aa82ce29 387
6f4ddea1 388 # check whether a join type exists
6f4ddea1 389 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 390 my $join_type;
391 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
392 $join_type = $to_jt->{-join_type};
393 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 394 }
aa82ce29 395
726c8f65 396 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 397
398 if (ref $to eq 'ARRAY') {
726c8f65 399 push(@j, '(', $self->_recurse_from(@$to), ')');
400 }
401 else {
402 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 403 }
726c8f65 404
a697fa31 405 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 406 push(@j, ' ON ', $sql);
a697fa31 407 push @{$self->{from_bind}}, @bind;
726c8f65 408
409 push @fchunks, join '', @j;
6f4ddea1 410 }
726c8f65 411
412 return @fchunks;
6f4ddea1 413}
414
4c2b30d6 415sub _from_chunk_to_sql {
416 my ($self, $fromspec) = @_;
417
e8885a53 418 return join (' ', do {
419 if (! ref $fromspec) {
420 $self->_quote($fromspec);
421 }
422 elsif (ref $fromspec eq 'SCALAR') {
4c2b30d6 423 $$fromspec;
e8885a53 424 }
425 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
4c2b30d6 426 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
427 $$fromspec->[0];
e8885a53 428 }
429 elsif (ref $fromspec eq 'HASH') {
4c2b30d6 430 my ($as, $table, $toomuch) = ( map
431 { $_ => $fromspec->{$_} }
432 ( grep { $_ !~ /^\-/ } keys %$fromspec )
433 );
6f4ddea1 434
70c28808 435 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 436 if defined $toomuch;
6f4ddea1 437
4c2b30d6 438 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
e8885a53 439 }
440 else {
441 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
442 }
443 });
6f4ddea1 444}
445
446sub _join_condition {
447 my ($self, $cond) = @_;
4c2b30d6 448
a697fa31 449 # Backcompat for the old days when a plain hashref
450 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
451 # Once things settle we should start warning here so that
452 # folks unroll their hacks
453 if (
454 ref $cond eq 'HASH'
455 and
456 keys %$cond == 1
457 and
458 (keys %$cond)[0] =~ /\./
459 and
460 ! ref ( (values %$cond)[0] )
461 ) {
462 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 463 }
a697fa31 464 elsif ( ref $cond eq 'ARRAY' ) {
465 # do our own ORing so that the hashref-shim above is invoked
9aae3566 466 my @parts;
467 my @binds;
468 foreach my $c (@$cond) {
469 my ($sql, @bind) = $self->_join_condition($c);
470 push @binds, @bind;
471 push @parts, $sql;
472 }
473 return join(' OR ', @parts), @binds;
6f4ddea1 474 }
a697fa31 475
476 return $self->_recurse_where($cond);
6f4ddea1 477}
478
6f4ddea1 4791;
d5dedbd6 480
481=head1 AUTHORS
482
483See L<DBIx::Class/CONTRIBUTORS>.
484
485=head1 LICENSE
486
487You may distribute this code under the same terms as Perl itself.
488
489=cut