1 package DBIx::Class::SQLMaker;
5 DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
9 This module is a subclass of L<SQL::Abstract> and includes a number of
10 DBIC-specific workarounds, not yet suitable for inclusion into the
11 L<SQL::Abstract> core. It also provides all (and more than) the functionality
12 of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
15 Currently the enhancements to L<SQL::Abstract> are:
19 =item * Support for C<JOIN> statements (via extended C<table/from> support)
21 =item * Support of functions in C<SELECT> lists
23 =item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
25 =item * Support of C<...FOR UPDATE> type of select statement modifiers
27 =item * The -ident operator
29 =item * The -value operator
36 DBIx::Class::SQLMaker::LimitDialects
43 use Sub::Name 'subname';
44 use DBIx::Class::Carp;
45 use DBIx::Class::Exception;
48 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
50 # for when I need a normalized l/r pair
53 { defined $_ ? $_ : '' }
54 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
58 # FIXME when we bring in the storage weaklink, check its schema
59 # weaklink and channel through $schema->throw_exception
60 sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
63 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
64 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
65 no warnings qw/redefine/;
67 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
68 my($func) = (caller(1))[3];
69 carp "[$func] Warning: ", @_;
72 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
73 my($func) = (caller(1))[3];
74 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
77 # Current SQLA pollutes its namespace - clean for the time being
78 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
81 # the "oh noes offset/top without limit" constant
82 # limited to 32 bits for sanity (and consistency,
83 # since it is ultimately handed to sprintf %u)
84 # Implemented as a method, since ::Storage::DBI also
85 # refers to it (i.e. for the case of software_limit or
86 # as the value to abuse with MSSQL ordered subqueries)
87 sub __max_int { 0xFFFFFFFF };
90 my $self = shift->next::method(@_);
92 # use the same coderefs, they are prepared to handle both cases
93 my @extra_dbic_syntax = (
94 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
95 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
98 push @{$self->{special_ops}}, @extra_dbic_syntax;
99 push @{$self->{unary_ops}}, @extra_dbic_syntax;
104 sub _where_op_IDENT {
106 my ($op, $rhs) = splice @_, -2;
108 $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
111 # in case we are called as a top level special op (no '=')
114 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
122 sub _where_op_VALUE {
124 my ($op, $rhs) = splice @_, -2;
126 # in case we are called as a top level special op (no '=')
130 ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
136 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
140 $self->_convert('?'),
147 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
148 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
151 shift->next::method(@_);
154 # Handle limit-dialect selection
156 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
159 $fields = $self->_recurse_fields($fields);
161 if (defined $offset) {
162 $self->throw_exception('A supplied offset must be a non-negative integer')
163 if ( $offset =~ /\D/ or $offset < 0 );
167 if (defined $limit) {
168 $self->throw_exception('A supplied limit must be a positive integer')
169 if ( $limit =~ /\D/ or $limit <= 0 );
172 $limit = $self->__max_int;
178 # this is legacy code-flow from SQLA::Limit, it is not set in stone
180 ($sql, @bind) = $self->next::method ($table, $fields, $where);
183 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
186 my $dialect = $self->limit_dialect
187 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
188 $self->can ("_$dialect")
189 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
193 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
196 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
199 push @{$self->{where_bind}}, @bind;
201 # this *must* be called, otherwise extra binds will remain in the sql-maker
202 my @all_bind = $self->_assemble_binds;
204 $sql .= $self->_lock_select ($rs_attrs->{for})
207 return wantarray ? ($sql, @all_bind) : $sql;
210 sub _assemble_binds {
212 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
216 update => 'FOR UPDATE',
217 shared => 'FOR SHARE',
220 my ($self, $type) = @_;
221 my $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
225 # Handle default inserts
227 # optimized due to hotttnesss
228 # my ($self, $table, $data, $options) = @_;
230 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
231 # which is sadly understood only by MySQL. Change default behavior here,
232 # until SQLA2 comes with proper dialect support
233 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
236 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
239 if ( ($_[3]||{})->{returning} ) {
241 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
245 return ($sql, @bind);
251 sub _recurse_fields {
252 my ($self, $fields) = @_;
253 my $ref = ref $fields;
254 return $self->_quote($fields) unless $ref;
255 return $$fields if $ref eq 'SCALAR';
257 if ($ref eq 'ARRAY') {
258 return join(', ', map { $self->_recurse_fields($_) } @$fields);
260 elsif ($ref eq 'HASH') {
261 my %hash = %$fields; # shallow copy
263 my $as = delete $hash{-as}; # if supplied
265 my ($func, $args, @toomany) = %hash;
267 # there should be only one pair
269 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
272 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
273 $self->throw_exception (
274 'The select => { distinct => ... } syntax is not supported for multiple columns.'
275 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
276 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
280 my $select = sprintf ('%s( %s )%s',
281 $self->_sqlcase($func),
282 $self->_recurse_fields($args),
284 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
290 # Is the second check absolutely necessary?
291 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
292 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
293 return $$fields->[0];
296 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
301 # this used to be a part of _order_by but is broken out for clarity.
302 # What we have been doing forever is hijacking the $order arg of
303 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
304 # then pretty much the entire resultset attr-hash, as more and more
305 # things in the SQLA space need to have mopre info about the $rs they
306 # create SQL for. The alternative would be to keep expanding the
307 # signature of _select with more and more positional parameters, which
308 # is just gross. All hail SQLA2!
309 sub _parse_rs_attrs {
310 my ($self, $arg) = @_;
314 if ($arg->{group_by}) {
315 # horible horrible, waiting for refactor
316 local $self->{select_bind};
317 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
318 $sql .= $self->_sqlcase(' group by ') . $g;
319 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
323 if (defined $arg->{having}) {
324 my ($frag, @bind) = $self->_recurse_where($arg->{having});
325 push(@{$self->{having_bind}}, @bind);
326 $sql .= $self->_sqlcase(' having ') . $frag;
329 if (defined $arg->{order_by}) {
330 $sql .= $self->_order_by ($arg->{order_by});
337 my ($self, $arg) = @_;
339 # check that we are not called in legacy mode (order_by as 4th argument)
340 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
341 return $self->_parse_rs_attrs ($arg);
344 my ($sql, @bind) = $self->next::method($arg);
345 push @{$self->{order_bind}}, @bind;
351 # optimized due to hotttnesss
352 # my ($self, $from) = @_;
353 if (my $ref = ref $_[1] ) {
354 if ($ref eq 'ARRAY') {
355 return $_[0]->_recurse_from(@{$_[1]});
357 elsif ($ref eq 'HASH') {
358 return $_[0]->_recurse_from($_[1]);
360 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
361 my ($sql, @bind) = @{ ${$_[1]} };
362 push @{$_[0]->{from_bind}}, @bind;
366 return $_[0]->next::method ($_[1]);
369 sub _generate_join_clause {
370 my ($self, $join_type) = @_;
372 return sprintf ('%s JOIN ',
373 $join_type ? ' ' . $self->_sqlcase($join_type) : ''
378 my ($self, $from, @join) = @_;
380 push @sqlf, $self->_from_chunk_to_sql($from);
385 # check whether a join type exists
386 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
388 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
389 $join_type = $to_jt->{-join_type};
390 $join_type =~ s/^\s+ | \s+$//xg;
393 $join_type = $self->{_default_jointype} if not defined $join_type;
395 push @sqlf, $self->_generate_join_clause( $join_type );
397 if (ref $to eq 'ARRAY') {
398 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
400 push(@sqlf, $self->_from_chunk_to_sql($to));
402 push(@sqlf, ' ON ', $self->_join_condition($on));
404 return join('', @sqlf);
407 sub _from_chunk_to_sql {
408 my ($self, $fromspec) = @_;
410 return join (' ', $self->_SWITCH_refkind($fromspec, {
415 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
419 my ($as, $table, $toomuch) = ( map
420 { $_ => $fromspec->{$_} }
421 ( grep { $_ !~ /^\-/ } keys %$fromspec )
424 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
427 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
430 $self->_quote($fromspec);
435 sub _join_condition {
436 my ($self, $cond) = @_;
438 if (ref $cond eq 'HASH') {
443 $self->throw_exception (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
444 if ref($v) ne 'SCALAR';
448 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
451 return scalar($self->_recurse_where(\%j));
452 } elsif (ref $cond eq 'ARRAY') {
453 return join(' OR ', map { $self->_join_condition($_) } @$cond);
455 die "Can't handle this yet!";
463 See L<DBIx::Class/CONTRIBUTORS>.
467 You may distribute this code under the same terms as Perl itself.