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
30 =item * The -ident operator
32 =item * The -value operator
39 DBIx::Class::SQLMaker::LimitDialects
45 use Sub::Name 'subname';
46 use DBIx::Class::Carp;
47 use DBIx::Class::Exception;
50 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
52 # for when I need a normalized l/r pair
55 { defined $_ ? $_ : '' }
56 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
60 # FIXME when we bring in the storage weaklink, check its schema
61 # weaklink and channel through $schema->throw_exception
62 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
65 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
66 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
67 no warnings qw/redefine/;
69 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
70 my($func) = (caller(1))[3];
71 carp "[$func] Warning: ", @_;
74 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
75 my($func) = (caller(1))[3];
76 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
79 # Current SQLA pollutes its namespace - clean for the time being
80 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
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 };
97 my $self = shift->next::method(@_);
99 # use the same coderefs, they are prepared to handle both cases
100 my @extra_dbic_syntax = (
101 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
102 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
105 push @{$self->{special_ops}}, @extra_dbic_syntax;
106 push @{$self->{unary_ops}}, @extra_dbic_syntax;
111 sub _where_op_IDENT {
113 my ($op, $rhs) = splice @_, -2;
115 $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
118 # in case we are called as a top level special op (no '=')
121 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
129 sub _where_op_VALUE {
131 my ($op, $rhs) = splice @_, -2;
133 # in case we are called as a top level special op (no '=')
137 ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
143 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
147 $self->_convert('?'),
154 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
155 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
158 shift->next::method(@_);
161 # Handle limit-dialect selection
163 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
166 $fields = $self->_recurse_fields($fields);
168 if (defined $offset) {
169 $self->throw_exception('A supplied offset must be a non-negative integer')
170 if ( $offset =~ /\D/ or $offset < 0 );
174 if (defined $limit) {
175 $self->throw_exception('A supplied limit must be a positive integer')
176 if ( $limit =~ /\D/ or $limit <= 0 );
179 $limit = $self->__max_int;
185 # this is legacy code-flow from SQLA::Limit, it is not set in stone
187 ($sql, @bind) = $self->next::method ($table, $fields, $where);
190 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
193 my $dialect = $self->limit_dialect
194 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
195 $self->can ("_$dialect")
196 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
200 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
203 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
206 push @{$self->{where_bind}}, @bind;
208 # this *must* be called, otherwise extra binds will remain in the sql-maker
209 my @all_bind = $self->_assemble_binds;
211 $sql .= $self->_lock_select ($rs_attrs->{for})
214 return wantarray ? ($sql, @all_bind) : $sql;
217 sub _assemble_binds {
219 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order limit/);
223 update => 'FOR UPDATE',
224 shared => 'FOR SHARE',
227 my ($self, $type) = @_;
228 my $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
232 # Handle default inserts
234 # optimized due to hotttnesss
235 # my ($self, $table, $data, $options) = @_;
237 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
238 # which is sadly understood only by MySQL. Change default behavior here,
239 # until SQLA2 comes with proper dialect support
240 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
243 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
246 if ( ($_[3]||{})->{returning} ) {
248 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
252 return ($sql, @bind);
258 sub _recurse_fields {
259 my ($self, $fields) = @_;
260 my $ref = ref $fields;
261 return $self->_quote($fields) unless $ref;
262 return $$fields if $ref eq 'SCALAR';
264 if ($ref eq 'ARRAY') {
265 return join(', ', map { $self->_recurse_fields($_) } @$fields);
267 elsif ($ref eq 'HASH') {
268 my %hash = %$fields; # shallow copy
270 my $as = delete $hash{-as}; # if supplied
272 my ($func, $args, @toomany) = %hash;
274 # there should be only one pair
276 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
279 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
280 $self->throw_exception (
281 'The select => { distinct => ... } syntax is not supported for multiple columns.'
282 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
283 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
287 my $select = sprintf ('%s( %s )%s',
288 $self->_sqlcase($func),
289 $self->_recurse_fields($args),
291 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
297 # Is the second check absolutely necessary?
298 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
299 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
300 return $$fields->[0];
303 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
308 # this used to be a part of _order_by but is broken out for clarity.
309 # What we have been doing forever is hijacking the $order arg of
310 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
311 # then pretty much the entire resultset attr-hash, as more and more
312 # things in the SQLA space need to have mopre info about the $rs they
313 # create SQL for. The alternative would be to keep expanding the
314 # signature of _select with more and more positional parameters, which
315 # is just gross. All hail SQLA2!
316 sub _parse_rs_attrs {
317 my ($self, $arg) = @_;
321 if ($arg->{group_by}) {
322 # horible horrible, waiting for refactor
323 local $self->{select_bind};
324 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
325 $sql .= $self->_sqlcase(' group by ') . $g;
326 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
330 if (defined $arg->{having}) {
331 my ($frag, @bind) = $self->_recurse_where($arg->{having});
332 push(@{$self->{having_bind}}, @bind);
333 $sql .= $self->_sqlcase(' having ') . $frag;
336 if (defined $arg->{order_by}) {
337 $sql .= $self->_order_by ($arg->{order_by});
344 my ($self, $arg) = @_;
346 # check that we are not called in legacy mode (order_by as 4th argument)
347 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
348 return $self->_parse_rs_attrs ($arg);
351 my ($sql, @bind) = $self->next::method($arg);
352 push @{$self->{order_bind}}, @bind;
358 # optimized due to hotttnesss
359 # my ($self, $from) = @_;
360 if (my $ref = ref $_[1] ) {
361 if ($ref eq 'ARRAY') {
362 return $_[0]->_recurse_from(@{$_[1]});
364 elsif ($ref eq 'HASH') {
365 return $_[0]->_recurse_from($_[1]);
367 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
368 my ($sql, @bind) = @{ ${$_[1]} };
369 push @{$_[0]->{from_bind}}, @bind;
373 return $_[0]->next::method ($_[1]);
376 sub _generate_join_clause {
377 my ($self, $join_type) = @_;
379 $join_type = $self->{_default_jointype}
380 if ! defined $join_type;
382 return sprintf ('%s JOIN ',
383 $join_type ? $self->_sqlcase($join_type) : ''
390 return join (' ', $self->_gen_from_blocks(@_) );
393 sub _gen_from_blocks {
394 my ($self, $from, @joins) = @_;
396 my @fchunks = $self->_from_chunk_to_sql($from);
401 # check whether a join type exists
402 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
404 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
405 $join_type = $to_jt->{-join_type};
406 $join_type =~ s/^\s+ | \s+$//xg;
409 my @j = $self->_generate_join_clause( $join_type );
411 if (ref $to eq 'ARRAY') {
412 push(@j, '(', $self->_recurse_from(@$to), ')');
415 push(@j, $self->_from_chunk_to_sql($to));
418 my ($sql, @bind) = $self->_join_condition($on);
419 push(@j, ' ON ', $sql);
420 push @{$self->{from_bind}}, @bind;
422 push @fchunks, join '', @j;
428 sub _from_chunk_to_sql {
429 my ($self, $fromspec) = @_;
431 return join (' ', $self->_SWITCH_refkind($fromspec, {
436 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
440 my ($as, $table, $toomuch) = ( map
441 { $_ => $fromspec->{$_} }
442 ( grep { $_ !~ /^\-/ } keys %$fromspec )
445 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
448 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
451 $self->_quote($fromspec);
456 sub _join_condition {
457 my ($self, $cond) = @_;
459 # Backcompat for the old days when a plain hashref
460 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
461 # Once things settle we should start warning here so that
462 # folks unroll their hacks
468 (keys %$cond)[0] =~ /\./
470 ! ref ( (values %$cond)[0] )
472 $cond = { keys %$cond => { -ident => values %$cond } }
474 elsif ( ref $cond eq 'ARRAY' ) {
475 # do our own ORing so that the hashref-shim above is invoked
478 foreach my $c (@$cond) {
479 my ($sql, @bind) = $self->_join_condition($c);
483 return join(' OR ', @parts), @binds;
486 return $self->_recurse_where($cond);
493 See L<DBIx::Class/CONTRIBUTORS>.
497 You may distribute this code under the same terms as Perl itself.