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 carp()/croak() functions imported into SQL::Abstract
59 # as Carp and Carp::Clan do not like each other much
60 no warnings qw/redefine/;
62 for my $f (qw/carp croak/) {
64 my $orig = \&{"SQL::Abstract::$f"};
65 my $clan_import = \&{$f};
66 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
68 if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) {
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 croak "-$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} || croak "Unable to find bindtype for -value $rhs"),
136 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
140 $self->_convert('?'),
146 my $callsites_warned;
148 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
151 local $SIG{__WARN__} = sub { $w = shift };
156 carp ("-nest in search conditions is deprecated, you most probably wanted:\n"
157 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
158 ) unless $callsites_warned->{$callsite}++;
160 shift->next::method(@_);
163 # Handle limit-dialect selection
165 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
168 $fields = $self->_recurse_fields($fields);
170 if (defined $offset) {
171 croak ('A supplied offset must be a non-negative integer')
172 if ( $offset =~ /\D/ or $offset < 0 );
176 if (defined $limit) {
177 croak ('A supplied limit must be a positive integer')
178 if ( $limit =~ /\D/ or $limit <= 0 );
181 $limit = $self->__max_int;
187 # this is legacy code-flow from SQLA::Limit, it is not set in stone
189 ($sql, @bind) = $self->next::method ($table, $fields, $where);
192 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
195 my $dialect = $self->limit_dialect
196 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
197 $self->can ("_$dialect")
198 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
202 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
205 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
208 push @{$self->{where_bind}}, @bind;
210 # this *must* be called, otherwise extra binds will remain in the sql-maker
211 my @all_bind = $self->_assemble_binds;
213 $sql .= $self->_lock_select ($rs_attrs->{for})
216 return wantarray ? ($sql, @all_bind) : $sql;
219 sub _assemble_binds {
221 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
225 update => 'FOR UPDATE',
226 shared => 'FOR SHARE',
229 my ($self, $type) = @_;
230 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
234 # Handle default inserts
236 # optimized due to hotttnesss
237 # my ($self, $table, $data, $options) = @_;
239 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
240 # which is sadly understood only by MySQL. Change default behavior here,
241 # until SQLA2 comes with proper dialect support
242 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
245 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
248 if ( ($_[3]||{})->{returning} ) {
250 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
254 return ($sql, @bind);
260 sub _recurse_fields {
261 my ($self, $fields) = @_;
262 my $ref = ref $fields;
263 return $self->_quote($fields) unless $ref;
264 return $$fields if $ref eq 'SCALAR';
266 if ($ref eq 'ARRAY') {
267 return join(', ', map { $self->_recurse_fields($_) } @$fields);
269 elsif ($ref eq 'HASH') {
270 my %hash = %$fields; # shallow copy
272 my $as = delete $hash{-as}; # if supplied
274 my ($func, $args, @toomany) = %hash;
276 # there should be only one pair
278 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
281 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
283 'The select => { distinct => ... } syntax is not supported for multiple columns.'
284 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
285 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
289 my $select = sprintf ('%s( %s )%s',
290 $self->_sqlcase($func),
291 $self->_recurse_fields($args),
293 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
299 # Is the second check absolutely necessary?
300 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
301 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
302 return $$fields->[0];
305 croak($ref . qq{ unexpected in _recurse_fields()})
310 # this used to be a part of _order_by but is broken out for clarity.
311 # What we have been doing forever is hijacking the $order arg of
312 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
313 # then pretty much the entire resultset attr-hash, as more and more
314 # things in the SQLA space need to have mopre info about the $rs they
315 # create SQL for. The alternative would be to keep expanding the
316 # signature of _select with more and more positional parameters, which
317 # is just gross. All hail SQLA2!
318 sub _parse_rs_attrs {
319 my ($self, $arg) = @_;
323 if ($arg->{group_by}) {
324 # horible horrible, waiting for refactor
325 local $self->{select_bind};
326 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
327 $sql .= $self->_sqlcase(' group by ') . $g;
328 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
332 if (defined $arg->{having}) {
333 my ($frag, @bind) = $self->_recurse_where($arg->{having});
334 push(@{$self->{having_bind}}, @bind);
335 $sql .= $self->_sqlcase(' having ') . $frag;
338 if (defined $arg->{order_by}) {
339 $sql .= $self->_order_by ($arg->{order_by});
346 my ($self, $arg) = @_;
348 # check that we are not called in legacy mode (order_by as 4th argument)
349 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
350 return $self->_parse_rs_attrs ($arg);
353 my ($sql, @bind) = $self->next::method($arg);
354 push @{$self->{order_bind}}, @bind;
360 # optimized due to hotttnesss
361 # my ($self, $from) = @_;
362 if (my $ref = ref $_[1] ) {
363 if ($ref eq 'ARRAY') {
364 return $_[0]->_recurse_from(@{$_[1]});
366 elsif ($ref eq 'HASH') {
367 return $_[0]->_recurse_from($_[1]);
371 return $_[0]->next::method ($_[1]);
374 sub _generate_join_clause {
375 my ($self, $join_type) = @_;
377 return sprintf ('%s JOIN ',
378 $join_type ? ' ' . $self->_sqlcase($join_type) : ''
383 my ($self, $from, @join) = @_;
385 push @sqlf, $self->_from_chunk_to_sql($from);
390 # check whether a join type exists
391 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
393 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
394 $join_type = $to_jt->{-join_type};
395 $join_type =~ s/^\s+ | \s+$//xg;
398 $join_type = $self->{_default_jointype} if not defined $join_type;
400 push @sqlf, $self->_generate_join_clause( $join_type );
402 if (ref $to eq 'ARRAY') {
403 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
405 push(@sqlf, $self->_from_chunk_to_sql($to));
407 push(@sqlf, ' ON ', $self->_join_condition($on));
409 return join('', @sqlf);
412 sub _from_chunk_to_sql {
413 my ($self, $fromspec) = @_;
415 return join (' ', $self->_SWITCH_refkind($fromspec, {
420 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
424 my ($as, $table, $toomuch) = ( map
425 { $_ => $fromspec->{$_} }
426 ( grep { $_ !~ /^\-/ } keys %$fromspec )
429 croak "Only one table/as pair expected in from-spec but an exra '$toomuch' key present"
432 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
435 $self->_quote($fromspec);
440 sub _join_condition {
441 my ($self, $cond) = @_;
443 if (ref $cond eq 'HASH') {
448 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
449 if ref($v) ne 'SCALAR';
453 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
456 return scalar($self->_recurse_where(\%j));
457 } elsif (ref $cond eq 'ARRAY') {
458 return join(' OR ', map { $self->_join_condition($_) } @$cond);
460 croak "Can't handle this yet!";
468 See L<DBIx::Class/CONTRIBUTORS>.
472 You may distribute this code under the same terms as Perl itself.