1 package DBIx::Class::SQLMaker;
8 DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
12 This module is a subclass of L<SQL::Abstract> and includes a number of
13 DBIC-specific workarounds, not yet suitable for inclusion into the
14 L<SQL::Abstract> core. It also provides all (and more than) the functionality
15 of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
18 Currently the enhancements to L<SQL::Abstract> are:
22 =item * Support for C<JOIN> statements (via extended C<table/from> support)
24 =item * Support of functions in C<SELECT> lists
26 =item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
28 =item * Support of C<...FOR UPDATE> type of select statement modifiers
35 DBIx::Class::SQLMaker::LimitDialects
41 use Sub::Name 'subname';
42 use DBIx::Class::Carp;
45 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
47 # for when I need a normalized l/r pair
50 { defined $_ ? $_ : '' }
51 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
55 # FIXME when we bring in the storage weaklink, check its schema
56 # weaklink and channel through $schema->throw_exception
57 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
60 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
61 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
62 no warnings qw/redefine/;
64 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
65 my($func) = (caller(1))[3];
66 carp "[$func] Warning: ", @_;
69 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
70 my($func) = (caller(1))[3];
71 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
75 # the "oh noes offset/top without limit" constant
76 # limited to 31 bits for sanity (and consistency,
77 # since it may be handed to the like of sprintf %u)
79 # Also *some* builds of SQLite fail the test
80 # some_column BETWEEN ? AND ?: 1, 4294967295
81 # with the proper integer bind attrs
83 # Implemented as a method, since ::Storage::DBI also
84 # refers to it (i.e. for the case of software_limit or
85 # as the value to abuse with MSSQL ordered subqueries)
86 sub __max_int () { 0x7FFFFFFF };
88 # we ne longer need to check this - DBIC has ways of dealing with it
89 # specifically ::Storage::DBI::_resolve_bindattrs()
90 sub _assert_bindval_matches_bindtype () { 1 };
92 # poor man's de-qualifier
94 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
95 ? $_[1] =~ / ([^\.]+) $ /x
101 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
102 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
105 shift->next::method(@_);
108 # Handle limit-dialect selection
110 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
113 $fields = $self->_recurse_fields($fields);
115 if (defined $offset) {
116 $self->throw_exception('A supplied offset must be a non-negative integer')
117 if ( $offset =~ /\D/ or $offset < 0 );
121 if (defined $limit) {
122 $self->throw_exception('A supplied limit must be a positive integer')
123 if ( $limit =~ /\D/ or $limit <= 0 );
126 $limit = $self->__max_int;
132 # this is legacy code-flow from SQLA::Limit, it is not set in stone
134 ($sql, @bind) = $self->next::method ($table, $fields, $where);
138 if( $limiter = $self->can ('emulate_limit') ) {
140 'Support for the legacy emulate_limit() mechanism inherited from '
141 . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
142 . 'DBIC transitions to Data::Query. If your code uses this type of '
143 . 'limit specification please file an RT and provide the source of '
144 . 'your emulate_limit() implementation, so an acceptable upgrade-path '
149 my $dialect = $self->limit_dialect
150 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
152 $limiter = $self->can ("_$dialect")
153 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
156 $sql = $self->$limiter (
158 { %{$rs_attrs||{}}, _selector_sql => $fields },
164 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
167 push @{$self->{where_bind}}, @bind;
169 # this *must* be called, otherwise extra binds will remain in the sql-maker
170 my @all_bind = $self->_assemble_binds;
172 $sql .= $self->_lock_select ($rs_attrs->{for})
175 return wantarray ? ($sql, @all_bind) : $sql;
178 sub _assemble_binds {
180 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
184 update => 'FOR UPDATE',
185 shared => 'FOR SHARE',
188 my ($self, $type) = @_;
191 if (ref($type) eq 'SCALAR') {
195 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
201 # Handle default inserts
203 # optimized due to hotttnesss
204 # my ($self, $table, $data, $options) = @_;
206 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
207 # which is sadly understood only by MySQL. Change default behavior here,
208 # until SQLA2 comes with proper dialect support
209 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
212 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
215 if ( ($_[3]||{})->{returning} ) {
217 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
221 return ($sql, @bind);
227 sub _recurse_fields {
228 my ($self, $fields) = @_;
229 my $ref = ref $fields;
230 return $self->_quote($fields) unless $ref;
231 return $$fields if $ref eq 'SCALAR';
233 if ($ref eq 'ARRAY') {
234 return join(', ', map { $self->_recurse_fields($_) } @$fields);
236 elsif ($ref eq 'HASH') {
237 my %hash = %$fields; # shallow copy
239 my $as = delete $hash{-as}; # if supplied
241 my ($func, $args, @toomany) = %hash;
243 # there should be only one pair
245 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
248 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
249 $self->throw_exception (
250 'The select => { distinct => ... } syntax is not supported for multiple columns.'
251 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
252 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
256 my $select = sprintf ('%s( %s )%s',
257 $self->_sqlcase($func),
258 $self->_recurse_fields($args),
260 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
266 # Is the second check absolutely necessary?
267 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
268 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
269 return $$fields->[0];
272 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
277 # this used to be a part of _order_by but is broken out for clarity.
278 # What we have been doing forever is hijacking the $order arg of
279 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
280 # then pretty much the entire resultset attr-hash, as more and more
281 # things in the SQLA space need to have more info about the $rs they
282 # create SQL for. The alternative would be to keep expanding the
283 # signature of _select with more and more positional parameters, which
284 # is just gross. All hail SQLA2!
285 sub _parse_rs_attrs {
286 my ($self, $arg) = @_;
290 if ($arg->{group_by}) {
291 # horrible horrible, waiting for refactor
292 local $self->{select_bind};
293 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
294 $sql .= $self->_sqlcase(' group by ') . $g;
295 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
299 if (defined $arg->{having}) {
300 my ($frag, @bind) = $self->_recurse_where($arg->{having});
301 push(@{$self->{having_bind}}, @bind);
302 $sql .= $self->_sqlcase(' having ') . $frag;
305 if (defined $arg->{order_by}) {
306 $sql .= $self->_order_by ($arg->{order_by});
313 my ($self, $arg) = @_;
315 # check that we are not called in legacy mode (order_by as 4th argument)
316 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
317 return $self->_parse_rs_attrs ($arg);
320 my ($sql, @bind) = $self->next::method($arg);
321 push @{$self->{order_bind}}, @bind;
326 sub _split_order_chunk {
327 my ($self, $chunk) = @_;
329 # strip off sort modifiers, but always succeed, so $1 gets reset
330 $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
334 ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
339 # optimized due to hotttnesss
340 # my ($self, $from) = @_;
341 if (my $ref = ref $_[1] ) {
342 if ($ref eq 'ARRAY') {
343 return $_[0]->_recurse_from(@{$_[1]});
345 elsif ($ref eq 'HASH') {
346 return $_[0]->_recurse_from($_[1]);
348 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
349 my ($sql, @bind) = @{ ${$_[1]} };
350 push @{$_[0]->{from_bind}}, @bind;
354 return $_[0]->next::method ($_[1]);
357 sub _generate_join_clause {
358 my ($self, $join_type) = @_;
360 $join_type = $self->{_default_jointype}
361 if ! defined $join_type;
363 return sprintf ('%s JOIN ',
364 $join_type ? $self->_sqlcase($join_type) : ''
370 return join (' ', $self->_gen_from_blocks(@_) );
373 sub _gen_from_blocks {
374 my ($self, $from, @joins) = @_;
376 my @fchunks = $self->_from_chunk_to_sql($from);
381 # check whether a join type exists
382 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
384 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
385 $join_type = $to_jt->{-join_type};
386 $join_type =~ s/^\s+ | \s+$//xg;
389 my @j = $self->_generate_join_clause( $join_type );
391 if (ref $to eq 'ARRAY') {
392 push(@j, '(', $self->_recurse_from(@$to), ')');
395 push(@j, $self->_from_chunk_to_sql($to));
398 my ($sql, @bind) = $self->_join_condition($on);
399 push(@j, ' ON ', $sql);
400 push @{$self->{from_bind}}, @bind;
402 push @fchunks, join '', @j;
408 sub _from_chunk_to_sql {
409 my ($self, $fromspec) = @_;
411 return join (' ', do {
412 if (! ref $fromspec) {
413 $self->_quote($fromspec);
415 elsif (ref $fromspec eq 'SCALAR') {
418 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
419 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
422 elsif (ref $fromspec eq 'HASH') {
423 my ($as, $table, $toomuch) = ( map
424 { $_ => $fromspec->{$_} }
425 ( grep { $_ !~ /^\-/ } keys %$fromspec )
428 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
431 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
434 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
439 sub _join_condition {
440 my ($self, $cond) = @_;
442 # Backcompat for the old days when a plain hashref
443 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
444 # Once things settle we should start warning here so that
445 # folks unroll their hacks
451 (keys %$cond)[0] =~ /\./
453 ! ref ( (values %$cond)[0] )
455 $cond = { keys %$cond => { -ident => values %$cond } }
457 elsif ( ref $cond eq 'ARRAY' ) {
458 # do our own ORing so that the hashref-shim above is invoked
461 foreach my $c (@$cond) {
462 my ($sql, @bind) = $self->_join_condition($c);
466 return join(' OR ', @parts), @binds;
469 return $self->_recurse_where($cond);
472 # This is hideously ugly, but SQLA does not understand multicol IN expressions
473 # FIXME TEMPORARY - DQ should have native syntax for this
474 # moved here to raise API questions
476 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
477 sub _where_op_multicolumn_in {
478 my ($self, $lhs, $rhs) = @_;
480 if (! ref $lhs or ref $lhs eq 'ARRAY') {
482 for (ref $lhs ? @$lhs : $lhs) {
484 push @sql, $self->_quote($_);
486 elsif (ref $_ eq 'SCALAR') {
489 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
495 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
498 $lhs = \[ join(', ', @sql), @bind];
500 elsif (ref $lhs eq 'SCALAR') {
503 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
507 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
511 $rhs = \[ $self->_recurse_where($rhs) ];
514 $$_->[0] = "( $$_->[0] )"
515 unless $$_->[0] =~ /^ \s* \( .* \) \s* ^/xs;
518 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
525 See L<DBIx::Class/CONTRIBUTORS>.
529 You may distribute this code under the same terms as Perl itself.