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
38 Class::Accessor::Grouped
43 use Sub::Name 'subname';
44 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
47 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
49 # for when I need a normalized l/r pair
52 { defined $_ ? $_ : '' }
53 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
58 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
59 # that use Carp::Clan instead of plain Carp (they do not like each other much)
60 no warnings qw/redefine/;
62 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
63 my($func) = (caller(1))[3];
64 carp "[$func] Warning: ", @_;
67 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
68 my($func) = (caller(1))[3];
69 croak "[$func] Fatal: ", @_;
72 # Current SQLA pollutes its namespace - clean for the time being
73 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
76 # the "oh noes offset/top without limit" constant
77 # limited to 32 bits for sanity (and consistency,
78 # since it is ultimately handed to sprintf %u)
79 # Implemented as a method, since ::Storage::DBI also
80 # refers to it (i.e. for the case of software_limit or
81 # as the value to abuse with MSSQL ordered subqueries)
82 sub __max_int { 0xFFFFFFFF };
85 my $self = shift->next::method(@_);
87 # use the same coderefs, they are prepared to handle both cases
88 my @extra_dbic_syntax = (
89 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
90 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
93 push @{$self->{special_ops}}, @extra_dbic_syntax;
94 push @{$self->{unary_ops}}, @extra_dbic_syntax;
101 my ($op, $rhs) = splice @_, -2;
103 croak "-$op takes a single scalar argument (a quotable identifier)";
106 # in case we are called as a top level special op (no '=')
109 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
117 sub _where_op_VALUE {
119 my ($op, $rhs) = splice @_, -2;
121 # in case we are called as a top level special op (no '=')
125 ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"),
131 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
135 $self->_convert('?'),
141 my $callsites_warned;
143 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
146 local $SIG{__WARN__} = sub { $w = shift };
151 carp ("-nest in search conditions is deprecated, you most probably wanted:\n"
152 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
153 ) unless $callsites_warned->{$callsite}++;
155 shift->next::method(@_);
158 # Handle limit-dialect selection
160 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
163 $fields = $self->_recurse_fields($fields);
165 if (defined $offset) {
166 croak ('A supplied offset must be a non-negative integer')
167 if ( $offset =~ /\D/ or $offset < 0 );
171 if (defined $limit) {
172 croak ('A supplied limit must be a positive integer')
173 if ( $limit =~ /\D/ or $limit <= 0 );
176 $limit = $self->__max_int;
182 # this is legacy code-flow from SQLA::Limit, it is not set in stone
184 ($sql, @bind) = $self->next::method ($table, $fields, $where);
187 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
190 my $dialect = $self->limit_dialect
191 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
192 $self->can ("_$dialect")
193 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
197 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
200 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
203 push @{$self->{where_bind}}, @bind;
205 # this *must* be called, otherwise extra binds will remain in the sql-maker
206 my @all_bind = $self->_assemble_binds;
208 $sql .= $self->_lock_select ($rs_attrs->{for})
211 return wantarray ? ($sql, @all_bind) : $sql;
214 sub _assemble_binds {
216 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
220 update => 'FOR UPDATE',
221 shared => 'FOR SHARE',
224 my ($self, $type) = @_;
225 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
229 # Handle default inserts
231 # optimized due to hotttnesss
232 # my ($self, $table, $data, $options) = @_;
234 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
235 # which is sadly understood only by MySQL. Change default behavior here,
236 # until SQLA2 comes with proper dialect support
237 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
240 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
243 if ( ($_[3]||{})->{returning} ) {
245 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
249 return ($sql, @bind);
255 sub _recurse_fields {
256 my ($self, $fields) = @_;
257 my $ref = ref $fields;
258 return $self->_quote($fields) unless $ref;
259 return $$fields if $ref eq 'SCALAR';
261 if ($ref eq 'ARRAY') {
262 return join(', ', map { $self->_recurse_fields($_) } @$fields);
264 elsif ($ref eq 'HASH') {
265 my %hash = %$fields; # shallow copy
267 my $as = delete $hash{-as}; # if supplied
269 my ($func, $args, @toomany) = %hash;
271 # there should be only one pair
273 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
276 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
278 'The select => { distinct => ... } syntax is not supported for multiple columns.'
279 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
280 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
284 my $select = sprintf ('%s( %s )%s',
285 $self->_sqlcase($func),
286 $self->_recurse_fields($args),
288 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
294 # Is the second check absolutely necessary?
295 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
296 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
297 return $$fields->[0];
300 croak($ref . qq{ unexpected in _recurse_fields()})
305 # this used to be a part of _order_by but is broken out for clarity.
306 # What we have been doing forever is hijacking the $order arg of
307 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
308 # then pretty much the entire resultset attr-hash, as more and more
309 # things in the SQLA space need to have mopre info about the $rs they
310 # create SQL for. The alternative would be to keep expanding the
311 # signature of _select with more and more positional parameters, which
312 # is just gross. All hail SQLA2!
313 sub _parse_rs_attrs {
314 my ($self, $arg) = @_;
318 if ($arg->{group_by}) {
319 # horible horrible, waiting for refactor
320 local $self->{select_bind};
321 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
322 $sql .= $self->_sqlcase(' group by ') . $g;
323 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
327 if (defined $arg->{having}) {
328 my ($frag, @bind) = $self->_recurse_where($arg->{having});
329 push(@{$self->{having_bind}}, @bind);
330 $sql .= $self->_sqlcase(' having ') . $frag;
333 if (defined $arg->{order_by}) {
334 $sql .= $self->_order_by ($arg->{order_by});
341 my ($self, $arg) = @_;
343 # check that we are not called in legacy mode (order_by as 4th argument)
344 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
345 return $self->_parse_rs_attrs ($arg);
348 my ($sql, @bind) = $self->next::method($arg);
349 push @{$self->{order_bind}}, @bind;
355 # optimized due to hotttnesss
356 # my ($self, $from) = @_;
357 if (my $ref = ref $_[1] ) {
358 if ($ref eq 'ARRAY') {
359 return $_[0]->_recurse_from(@{$_[1]});
361 elsif ($ref eq 'HASH') {
362 return $_[0]->_recurse_from($_[1]);
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 croak "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 croak (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 croak "Can't handle this yet!";
463 See L<DBIx::Class/CONTRIBUTORS>.
467 You may distribute this code under the same terms as Perl itself.