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;
43 use DBIx::Class::Exception;
46 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
48 # for when I need a normalized l/r pair
51 { defined $_ ? $_ : '' }
52 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
56 # FIXME when we bring in the storage weaklink, check its schema
57 # weaklink and channel through $schema->throw_exception
58 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
61 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
62 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
63 no warnings qw/redefine/;
65 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
66 my($func) = (caller(1))[3];
67 carp "[$func] Warning: ", @_;
70 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
71 my($func) = (caller(1))[3];
72 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
75 # Current SQLA pollutes its namespace - clean for the time being
76 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
79 # the "oh noes offset/top without limit" constant
80 # limited to 31 bits for sanity (and consistency,
81 # since it may be handed to the like of sprintf %u)
83 # Also *some* builds of SQLite fail the test
84 # some_column BETWEEN ? AND ?: 1, 4294967295
85 # with the proper integer bind attrs
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)
90 sub __max_int () { 0x7FFFFFFF };
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);
137 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
140 my $dialect = $self->limit_dialect
141 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
142 $self->can ("_$dialect")
143 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
147 $sql = $self->$limiter (
149 { %{$rs_attrs||{}}, _selector_sql => $fields },
155 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
158 push @{$self->{where_bind}}, @bind;
160 # this *must* be called, otherwise extra binds will remain in the sql-maker
161 my @all_bind = $self->_assemble_binds;
163 $sql .= $self->_lock_select ($rs_attrs->{for})
166 return wantarray ? ($sql, @all_bind) : $sql;
169 sub _assemble_binds {
171 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
175 update => 'FOR UPDATE',
176 shared => 'FOR SHARE',
179 my ($self, $type) = @_;
182 if (ref($type) eq 'SCALAR') {
186 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
192 # Handle default inserts
194 # optimized due to hotttnesss
195 # my ($self, $table, $data, $options) = @_;
197 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
198 # which is sadly understood only by MySQL. Change default behavior here,
199 # until SQLA2 comes with proper dialect support
200 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
203 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
206 if ( ($_[3]||{})->{returning} ) {
208 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
212 return ($sql, @bind);
218 sub _recurse_fields {
219 my ($self, $fields) = @_;
220 my $ref = ref $fields;
221 return $self->_quote($fields) unless $ref;
222 return $$fields if $ref eq 'SCALAR';
224 if ($ref eq 'ARRAY') {
225 return join(', ', map { $self->_recurse_fields($_) } @$fields);
227 elsif ($ref eq 'HASH') {
228 my %hash = %$fields; # shallow copy
230 my $as = delete $hash{-as}; # if supplied
232 my ($func, $args, @toomany) = %hash;
234 # there should be only one pair
236 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
239 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
240 $self->throw_exception (
241 'The select => { distinct => ... } syntax is not supported for multiple columns.'
242 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
243 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
247 my $select = sprintf ('%s( %s )%s',
248 $self->_sqlcase($func),
249 $self->_recurse_fields($args),
251 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
257 # Is the second check absolutely necessary?
258 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
259 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
260 return $$fields->[0];
263 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
268 # this used to be a part of _order_by but is broken out for clarity.
269 # What we have been doing forever is hijacking the $order arg of
270 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
271 # then pretty much the entire resultset attr-hash, as more and more
272 # things in the SQLA space need to have mopre info about the $rs they
273 # create SQL for. The alternative would be to keep expanding the
274 # signature of _select with more and more positional parameters, which
275 # is just gross. All hail SQLA2!
276 sub _parse_rs_attrs {
277 my ($self, $arg) = @_;
281 if ($arg->{group_by}) {
282 # horible horrible, waiting for refactor
283 local $self->{select_bind};
284 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
285 $sql .= $self->_sqlcase(' group by ') . $g;
286 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
290 if (defined $arg->{having}) {
291 my ($frag, @bind) = $self->_recurse_where($arg->{having});
292 push(@{$self->{having_bind}}, @bind);
293 $sql .= $self->_sqlcase(' having ') . $frag;
296 if (defined $arg->{order_by}) {
297 $sql .= $self->_order_by ($arg->{order_by});
304 my ($self, $arg) = @_;
306 # check that we are not called in legacy mode (order_by as 4th argument)
307 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
308 return $self->_parse_rs_attrs ($arg);
311 my ($sql, @bind) = $self->next::method($arg);
312 push @{$self->{order_bind}}, @bind;
318 # optimized due to hotttnesss
319 # my ($self, $from) = @_;
320 if (my $ref = ref $_[1] ) {
321 if ($ref eq 'ARRAY') {
322 return $_[0]->_recurse_from(@{$_[1]});
324 elsif ($ref eq 'HASH') {
325 return $_[0]->_recurse_from($_[1]);
327 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
328 my ($sql, @bind) = @{ ${$_[1]} };
329 push @{$_[0]->{from_bind}}, @bind;
333 return $_[0]->next::method ($_[1]);
336 sub _generate_join_clause {
337 my ($self, $join_type) = @_;
339 $join_type = $self->{_default_jointype}
340 if ! defined $join_type;
342 return sprintf ('%s JOIN ',
343 $join_type ? $self->_sqlcase($join_type) : ''
350 return join (' ', $self->_gen_from_blocks(@_) );
353 sub _gen_from_blocks {
354 my ($self, $from, @joins) = @_;
356 my @fchunks = $self->_from_chunk_to_sql($from);
361 # check whether a join type exists
362 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
364 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
365 $join_type = $to_jt->{-join_type};
366 $join_type =~ s/^\s+ | \s+$//xg;
369 my @j = $self->_generate_join_clause( $join_type );
371 if (ref $to eq 'ARRAY') {
372 push(@j, '(', $self->_recurse_from(@$to), ')');
375 push(@j, $self->_from_chunk_to_sql($to));
378 my ($sql, @bind) = $self->_join_condition($on);
379 push(@j, ' ON ', $sql);
380 push @{$self->{from_bind}}, @bind;
382 push @fchunks, join '', @j;
388 sub _from_chunk_to_sql {
389 my ($self, $fromspec) = @_;
391 return join (' ', do {
392 if (! ref $fromspec) {
393 $self->_quote($fromspec);
395 elsif (ref $fromspec eq 'SCALAR') {
398 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
399 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
402 elsif (ref $fromspec eq 'HASH') {
403 my ($as, $table, $toomuch) = ( map
404 { $_ => $fromspec->{$_} }
405 ( grep { $_ !~ /^\-/ } keys %$fromspec )
408 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
411 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
414 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
419 sub _join_condition {
420 my ($self, $cond) = @_;
422 # Backcompat for the old days when a plain hashref
423 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
424 # Once things settle we should start warning here so that
425 # folks unroll their hacks
431 (keys %$cond)[0] =~ /\./
433 ! ref ( (values %$cond)[0] )
435 $cond = { keys %$cond => { -ident => values %$cond } }
437 elsif ( ref $cond eq 'ARRAY' ) {
438 # do our own ORing so that the hashref-shim above is invoked
441 foreach my $c (@$cond) {
442 my ($sql, @bind) = $self->_join_condition($c);
446 return join(' OR ', @parts), @binds;
449 return $self->_recurse_where($cond);
456 See L<DBIx::Class/CONTRIBUTORS>.
460 You may distribute this code under the same terms as Perl itself.