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 sub _quoting_enabled {
48 ( defined $_[0]->{quote_char} and length $_[0]->{quote_char} ) ? 1 : 0
51 # for when I need a normalized l/r pair
54 # in case we are called in the old !!$sm->_quote_chars fashion
55 return () if !wantarray and ( ! defined $_[0]->{quote_char} or ! length $_[0]->{quote_char} );
58 { defined $_ ? $_ : '' }
59 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
63 # FIXME when we bring in the storage weaklink, check its schema
64 # weaklink and channel through $schema->throw_exception
65 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
68 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
69 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
70 no warnings qw/redefine/;
72 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
73 my($func) = (caller(1))[3];
74 carp "[$func] Warning: ", @_;
77 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
78 my($func) = (caller(1))[3];
79 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
83 # the "oh noes offset/top without limit" constant
84 # limited to 31 bits for sanity (and consistency,
85 # since it may be handed to the like of sprintf %u)
87 # Also *some* builds of SQLite fail the test
88 # some_column BETWEEN ? AND ?: 1, 4294967295
89 # with the proper integer bind attrs
91 # Implemented as a method, since ::Storage::DBI also
92 # refers to it (i.e. for the case of software_limit or
93 # as the value to abuse with MSSQL ordered subqueries)
94 sub __max_int () { 0x7FFFFFFF };
96 # we ne longer need to check this - DBIC has ways of dealing with it
97 # specifically ::Storage::DBI::_resolve_bindattrs()
98 sub _assert_bindval_matches_bindtype () { 1 };
100 # poor man's de-qualifier
102 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
103 ? $_[1] =~ / ([^\.]+) $ /x
109 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
110 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
113 shift->next::method(@_);
116 # Handle limit-dialect selection
118 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
121 ($fields, @{$self->{select_bind}}) = $self->_recurse_fields($fields);
123 if (defined $offset) {
124 $self->throw_exception('A supplied offset must be a non-negative integer')
125 if ( $offset =~ /\D/ or $offset < 0 );
129 if (defined $limit) {
130 $self->throw_exception('A supplied limit must be a positive integer')
131 if ( $limit =~ /\D/ or $limit <= 0 );
134 $limit = $self->__max_int;
140 # this is legacy code-flow from SQLA::Limit, it is not set in stone
141 ($sql, @bind) = $self->next::method ($table, $fields, $where);
145 if( $limiter = $self->can ('emulate_limit') ) {
147 'Support for the legacy emulate_limit() mechanism inherited from '
148 . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
149 . 'DBIC transitions to Data::Query. If your code uses this type of '
150 . 'limit specification please file an RT and provide the source of '
151 . 'your emulate_limit() implementation, so an acceptable upgrade-path '
156 my $dialect = $self->limit_dialect
157 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
159 $limiter = $self->can ("_$dialect")
160 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
163 $sql = $self->$limiter (
165 { %{$rs_attrs||{}}, _selector_sql => $fields },
171 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
174 push @{$self->{where_bind}}, @bind;
176 # this *must* be called, otherwise extra binds will remain in the sql-maker
177 my @all_bind = $self->_assemble_binds;
179 $sql .= $self->_lock_select ($rs_attrs->{for})
182 return wantarray ? ($sql, @all_bind) : $sql;
185 sub _assemble_binds {
187 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
191 update => 'FOR UPDATE',
192 shared => 'FOR SHARE',
195 my ($self, $type) = @_;
198 if (ref($type) eq 'SCALAR') {
202 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
208 # Handle default inserts
210 # optimized due to hotttnesss
211 # my ($self, $table, $data, $options) = @_;
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
216 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
219 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
222 if ( ($_[3]||{})->{returning} ) {
224 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
228 return ($sql, @bind);
234 sub _recurse_fields {
235 my ($self, $fields) = @_;
236 my $ref = ref $fields;
237 return $self->_quote($fields) unless $ref;
238 return $$fields if $ref eq 'SCALAR';
240 if ($ref eq 'ARRAY') {
242 for my $field (@$fields) {
243 my ($select, @new_bind) = $self->_recurse_fields($field);
244 push @select, $select;
245 push @bind, @new_bind;
247 return (join(', ', @select), @bind);
249 elsif ($ref eq 'HASH') {
250 my %hash = %$fields; # shallow copy
252 my $as = delete $hash{-as}; # if supplied
254 my ($func, $rhs, @toomany) = %hash;
256 # there should be only one pair
258 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
261 if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
262 $self->throw_exception (
263 'The select => { distinct => ... } syntax is not supported for multiple columns.'
264 .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
265 .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
269 my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
270 my $select = sprintf ('%s( %s )%s',
271 $self->_sqlcase($func),
274 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
278 return ($select, @rhs_bind);
280 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
284 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
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 more 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!
297 sub _parse_rs_attrs {
298 my ($self, $arg) = @_;
302 if ($arg->{group_by}) {
303 if ( my ($group_sql, @group_bind) = $self->_recurse_fields($arg->{group_by}) ) {
304 $sql .= $self->_sqlcase(' group by ') . $group_sql;
305 push @{$self->{group_bind}}, @group_bind;
309 if (defined $arg->{having}) {
310 my ($frag, @bind) = $self->_recurse_where($arg->{having});
311 push(@{$self->{having_bind}}, @bind);
312 $sql .= $self->_sqlcase(' having ') . $frag;
315 if (defined $arg->{order_by}) {
316 $sql .= $self->_order_by ($arg->{order_by});
323 my ($self, $arg) = @_;
325 # check that we are not called in legacy mode (order_by as 4th argument)
326 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
327 return $self->_parse_rs_attrs ($arg);
330 my ($sql, @bind) = $self->next::method($arg);
331 push @{$self->{order_bind}}, @bind;
336 sub _split_order_chunk {
337 my ($self, $chunk) = @_;
339 # strip off sort modifiers, but always succeed, so $1 gets reset
340 $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
344 ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
349 # optimized due to hotttnesss
350 # my ($self, $from) = @_;
351 if (my $ref = ref $_[1] ) {
352 if ($ref eq 'ARRAY') {
353 return $_[0]->_recurse_from(@{$_[1]});
355 elsif ($ref eq 'HASH') {
356 return $_[0]->_recurse_from($_[1]);
358 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
359 my ($sql, @bind) = @{ ${$_[1]} };
360 push @{$_[0]->{from_bind}}, @bind;
364 return $_[0]->next::method ($_[1]);
367 sub _generate_join_clause {
368 my ($self, $join_type) = @_;
370 $join_type = $self->{_default_jointype}
371 if ! defined $join_type;
373 return sprintf ('%s JOIN ',
374 $join_type ? $self->_sqlcase($join_type) : ''
380 return join (' ', $self->_gen_from_blocks(@_) );
383 sub _gen_from_blocks {
384 my ($self, $from, @joins) = @_;
386 my @fchunks = $self->_from_chunk_to_sql($from);
391 # check whether a join type exists
392 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
394 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
395 $join_type = $to_jt->{-join_type};
396 $join_type =~ s/^\s+ | \s+$//xg;
399 my @j = $self->_generate_join_clause( $join_type );
401 if (ref $to eq 'ARRAY') {
402 push(@j, '(', $self->_recurse_from(@$to), ')');
405 push(@j, $self->_from_chunk_to_sql($to));
408 my ($sql, @bind) = $self->_join_condition($on);
409 push(@j, ' ON ', $sql);
410 push @{$self->{from_bind}}, @bind;
412 push @fchunks, join '', @j;
418 sub _from_chunk_to_sql {
419 my ($self, $fromspec) = @_;
421 return join (' ', do {
422 if (! ref $fromspec) {
423 $self->_quote($fromspec);
425 elsif (ref $fromspec eq 'SCALAR') {
428 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
429 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
432 elsif (ref $fromspec eq 'HASH') {
433 my ($as, $table, $toomuch) = ( map
434 { $_ => $fromspec->{$_} }
435 ( grep { $_ !~ /^\-/ } keys %$fromspec )
438 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
441 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
444 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
449 sub _join_condition {
450 my ($self, $cond) = @_;
452 # Backcompat for the old days when a plain hashref
453 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
459 (keys %$cond)[0] =~ /\./
461 ! ref ( (values %$cond)[0] )
464 "ResultSet {from} structures with conditions not conforming to the "
465 . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
466 . "{from} altogether, or express the condition properly using the "
467 . "{ -ident => ... } operator"
469 $cond = { keys %$cond => { -ident => values %$cond } }
471 elsif ( ref $cond eq 'ARRAY' ) {
472 # do our own ORing so that the hashref-shim above is invoked
475 foreach my $c (@$cond) {
476 my ($sql, @bind) = $self->_join_condition($c);
480 return join(' OR ', @parts), @binds;
483 return $self->_recurse_where($cond);
486 # This is hideously ugly, but SQLA does not understand multicol IN expressions
487 # FIXME TEMPORARY - DQ should have native syntax for this
488 # moved here to raise API questions
490 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
491 sub _where_op_multicolumn_in {
492 my ($self, $lhs, $rhs) = @_;
494 if (! ref $lhs or ref $lhs eq 'ARRAY') {
496 for (ref $lhs ? @$lhs : $lhs) {
498 push @sql, $self->_quote($_);
500 elsif (ref $_ eq 'SCALAR') {
503 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
509 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
512 $lhs = \[ join(', ', @sql), @bind];
514 elsif (ref $lhs eq 'SCALAR') {
517 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
521 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
525 $rhs = \[ $self->_recurse_where($rhs) ];
528 $$_->[0] = "( $$_->[0] )"
529 unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
532 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
535 =head1 FURTHER QUESTIONS?
537 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
539 =head1 COPYRIGHT AND LICENSE
541 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
542 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
543 redistribute it and/or modify it under the same terms as the
544 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.