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
142 ($sql, @bind) = $self->next::method ($table, $fields, $where);
146 if( $limiter = $self->can ('emulate_limit') ) {
148 'Support for the legacy emulate_limit() mechanism inherited from '
149 . 'SQL::Abstract::Limit has been deprecated, and will be removed when '
150 . 'DBIC transitions to Data::Query. If your code uses this type of '
151 . 'limit specification please file an RT and provide the source of '
152 . 'your emulate_limit() implementation, so an acceptable upgrade-path '
157 my $dialect = $self->limit_dialect
158 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self" );
160 $limiter = $self->can ("_$dialect")
161 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
164 $sql = $self->$limiter (
166 { %{$rs_attrs||{}}, _selector_sql => $fields },
172 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
175 push @{$self->{where_bind}}, @bind;
177 # this *must* be called, otherwise extra binds will remain in the sql-maker
178 my @all_bind = $self->_assemble_binds;
180 $sql .= $self->_lock_select ($rs_attrs->{for})
183 return wantarray ? ($sql, @all_bind) : $sql;
186 sub _assemble_binds {
188 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
192 update => 'FOR UPDATE',
193 shared => 'FOR SHARE',
196 my ($self, $type) = @_;
199 if (ref($type) eq 'SCALAR') {
203 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
209 # Handle default inserts
211 # optimized due to hotttnesss
212 # my ($self, $table, $data, $options) = @_;
214 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
215 # which is sadly understood only by MySQL. Change default behavior here,
216 # until SQLA2 comes with proper dialect support
217 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
220 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
223 if ( ($_[3]||{})->{returning} ) {
225 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
229 return ($sql, @bind);
235 sub _recurse_fields {
236 my ($self, $fields) = @_;
237 my $ref = ref $fields;
238 return $self->_quote($fields) unless $ref;
239 return $$fields if $ref eq 'SCALAR';
241 if ($ref eq 'ARRAY') {
243 for my $field (@$fields) {
244 my ($select, @new_bind) = $self->_recurse_fields($field);
245 push @select, $select;
246 push @bind, @new_bind;
248 return (join(', ', @select), @bind);
250 elsif ($ref eq 'HASH') {
251 my %hash = %$fields; # shallow copy
253 my $as = delete $hash{-as}; # if supplied
255 my ($func, $rhs, @toomany) = %hash;
257 # there should be only one pair
259 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
262 if (lc ($func) eq 'distinct' && ref $rhs eq 'ARRAY' && @$rhs > 1) {
263 $self->throw_exception (
264 'The select => { distinct => ... } syntax is not supported for multiple columns.'
265 .' Instead please use { group_by => [ qw/' . (join ' ', @$rhs) . '/ ] }'
266 .' or { select => [ qw/' . (join ' ', @$rhs) . '/ ], distinct => 1 }'
270 my ($rhs_sql, @rhs_bind) = $self->_recurse_fields($rhs);
271 my $select = sprintf ('%s( %s )%s',
272 $self->_sqlcase($func),
275 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
279 return ($select, @rhs_bind);
281 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
285 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
290 # this used to be a part of _order_by but is broken out for clarity.
291 # What we have been doing forever is hijacking the $order arg of
292 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
293 # then pretty much the entire resultset attr-hash, as more and more
294 # things in the SQLA space need to have more info about the $rs they
295 # create SQL for. The alternative would be to keep expanding the
296 # signature of _select with more and more positional parameters, which
297 # is just gross. All hail SQLA2!
298 sub _parse_rs_attrs {
299 my ($self, $arg) = @_;
303 if ($arg->{group_by}) {
304 if ( my ($group_sql, @group_bind) = $self->_recurse_fields($arg->{group_by}) ) {
305 $sql .= $self->_sqlcase(' group by ') . $group_sql;
306 push @{$self->{group_bind}}, @group_bind;
310 if (defined $arg->{having}) {
311 my ($frag, @bind) = $self->_recurse_where($arg->{having});
312 push(@{$self->{having_bind}}, @bind);
313 $sql .= $self->_sqlcase(' having ') . $frag;
316 if (defined $arg->{order_by}) {
317 $sql .= $self->_order_by ($arg->{order_by});
324 my ($self, $arg) = @_;
326 # check that we are not called in legacy mode (order_by as 4th argument)
327 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
328 return $self->_parse_rs_attrs ($arg);
331 my ($sql, @bind) = $self->next::method($arg);
332 push @{$self->{order_bind}}, @bind;
337 sub _split_order_chunk {
338 my ($self, $chunk) = @_;
340 # strip off sort modifiers, but always succeed, so $1 gets reset
341 $chunk =~ s/ (?: \s+ (ASC|DESC) )? \s* $//ix;
345 ( $1 and uc($1) eq 'DESC' ) ? 1 : 0,
350 # optimized due to hotttnesss
351 # my ($self, $from) = @_;
352 if (my $ref = ref $_[1] ) {
353 if ($ref eq 'ARRAY') {
354 return $_[0]->_recurse_from(@{$_[1]});
356 elsif ($ref eq 'HASH') {
357 return $_[0]->_recurse_from($_[1]);
359 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
360 my ($sql, @bind) = @{ ${$_[1]} };
361 push @{$_[0]->{from_bind}}, @bind;
365 return $_[0]->next::method ($_[1]);
368 sub _generate_join_clause {
369 my ($self, $join_type) = @_;
371 $join_type = $self->{_default_jointype}
372 if ! defined $join_type;
374 return sprintf ('%s JOIN ',
375 $join_type ? $self->_sqlcase($join_type) : ''
381 return join (' ', $self->_gen_from_blocks(@_) );
384 sub _gen_from_blocks {
385 my ($self, $from, @joins) = @_;
387 my @fchunks = $self->_from_chunk_to_sql($from);
392 # check whether a join type exists
393 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
395 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
396 $join_type = $to_jt->{-join_type};
397 $join_type =~ s/^\s+ | \s+$//xg;
400 my @j = $self->_generate_join_clause( $join_type );
402 if (ref $to eq 'ARRAY') {
403 push(@j, '(', $self->_recurse_from(@$to), ')');
406 push(@j, $self->_from_chunk_to_sql($to));
409 my ($sql, @bind) = $self->_join_condition($on);
410 push(@j, ' ON ', $sql);
411 push @{$self->{from_bind}}, @bind;
413 push @fchunks, join '', @j;
419 sub _from_chunk_to_sql {
420 my ($self, $fromspec) = @_;
422 return join (' ', do {
423 if (! ref $fromspec) {
424 $self->_quote($fromspec);
426 elsif (ref $fromspec eq 'SCALAR') {
429 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
430 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
433 elsif (ref $fromspec eq 'HASH') {
434 my ($as, $table, $toomuch) = ( map
435 { $_ => $fromspec->{$_} }
436 ( grep { $_ !~ /^\-/ } keys %$fromspec )
439 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
442 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
445 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
450 sub _join_condition {
451 my ($self, $cond) = @_;
453 # Backcompat for the old days when a plain hashref
454 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
460 (keys %$cond)[0] =~ /\./
462 ! ref ( (values %$cond)[0] )
465 "ResultSet {from} structures with conditions not conforming to the "
466 . "SQL::Abstract syntax are deprecated: you either need to stop abusing "
467 . "{from} altogether, or express the condition properly using the "
468 . "{ -ident => ... } operator"
470 $cond = { keys %$cond => { -ident => values %$cond } }
472 elsif ( ref $cond eq 'ARRAY' ) {
473 # do our own ORing so that the hashref-shim above is invoked
476 foreach my $c (@$cond) {
477 my ($sql, @bind) = $self->_join_condition($c);
481 return join(' OR ', @parts), @binds;
484 return $self->_recurse_where($cond);
487 # This is hideously ugly, but SQLA does not understand multicol IN expressions
488 # FIXME TEMPORARY - DQ should have native syntax for this
489 # moved here to raise API questions
491 # !!! EXPERIMENTAL API !!! WILL CHANGE !!!
492 sub _where_op_multicolumn_in {
493 my ($self, $lhs, $rhs) = @_;
495 if (! ref $lhs or ref $lhs eq 'ARRAY') {
497 for (ref $lhs ? @$lhs : $lhs) {
499 push @sql, $self->_quote($_);
501 elsif (ref $_ eq 'SCALAR') {
504 elsif (ref $_ eq 'REF' and ref $$_ eq 'ARRAY') {
510 $self->throw_exception("ARRAY of @{[ ref $_ ]}es unsupported for multicolumn IN lhs...");
513 $lhs = \[ join(', ', @sql), @bind];
515 elsif (ref $lhs eq 'SCALAR') {
518 elsif (ref $lhs eq 'REF' and ref $$lhs eq 'ARRAY' ) {
522 $self->throw_exception( ref($lhs) . "es unsupported for multicolumn IN lhs...");
526 $rhs = \[ $self->_recurse_where($rhs) ];
529 $$_->[0] = "( $$_->[0] )"
530 unless $$_->[0] =~ /^ \s* \( .* \) \s* $/xs;
533 \[ join( ' IN ', shift @$$lhs, shift @$$rhs ), @$$lhs, @$$rhs ];
536 =head1 FURTHER QUESTIONS?
538 Check the list of L<additional DBIC resources|DBIx::Class/GETTING HELP/SUPPORT>.
540 =head1 COPYRIGHT AND LICENSE
542 This module is free software L<copyright|DBIx::Class/COPYRIGHT AND LICENSE>
543 by the L<DBIx::Class (DBIC) authors|DBIx::Class/AUTHORS>. You can
544 redistribute it and/or modify it under the same terms as the
545 L<DBIx::Class library|DBIx::Class/COPYRIGHT AND LICENSE>.