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) {
78 # the "oh noes offset/top without limit" constant
79 # limited to 32 bits for sanity (and consistency,
80 # since it is ultimately handed to sprintf %u)
81 # Implemented as a method, since ::Storage::DBI also
82 # refers to it (i.e. for the case of software_limit or
83 # as the value to abuse with MSSQL ordered subqueries)
84 sub __max_int { 0xFFFFFFFF };
87 my $self = shift->next::method(@_);
89 # use the same coderefs, they are prepared to handle both cases
90 my @extra_dbic_syntax = (
91 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
92 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
95 push @{$self->{special_ops}}, @extra_dbic_syntax;
96 push @{$self->{unary_ops}}, @extra_dbic_syntax;
101 sub _where_op_IDENT {
103 my ($op, $rhs) = splice @_, -2;
105 croak "-$op takes a single scalar argument (a quotable identifier)";
108 # in case we are called as a top level special op (no '=')
111 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
119 sub _where_op_VALUE {
121 my ($op, $rhs) = splice @_, -2;
123 # in case we are called as a top level special op (no '=')
127 ($lhs || $self->{_nested_func_lhs} || croak "Unable to find bindtype for -value $rhs"),
133 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
137 $self->_convert('?'),
143 my $callsites_warned;
145 # determine callsite obeying Carp::Clan rules (fucking ugly but don't have better ideas)
148 local $SIG{__WARN__} = sub { $w = shift };
153 carp ("-nest in search conditions is deprecated, you most probably wanted:\n"
154 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
155 ) unless $callsites_warned->{$callsite}++;
157 shift->next::method(@_);
160 # Handle limit-dialect selection
162 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
165 $fields = $self->_recurse_fields($fields);
167 if (defined $offset) {
168 croak ('A supplied offset must be a non-negative integer')
169 if ( $offset =~ /\D/ or $offset < 0 );
173 if (defined $limit) {
174 croak ('A supplied limit must be a positive integer')
175 if ( $limit =~ /\D/ or $limit <= 0 );
178 $limit = $self->__max_int;
184 # this is legacy code-flow from SQLA::Limit, it is not set in stone
186 ($sql, @bind) = $self->next::method ($table, $fields, $where);
189 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
192 my $dialect = $self->limit_dialect
193 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
194 $self->can ("_$dialect")
195 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
199 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
202 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
205 push @{$self->{where_bind}}, @bind;
207 # this *must* be called, otherwise extra binds will remain in the sql-maker
208 my @all_bind = $self->_assemble_binds;
210 $sql .= $self->_lock_select ($rs_attrs->{for})
213 return wantarray ? ($sql, @all_bind) : $sql;
216 sub _assemble_binds {
218 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
222 update => 'FOR UPDATE',
223 shared => 'FOR SHARE',
226 my ($self, $type) = @_;
227 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
231 # Handle default inserts
233 # optimized due to hotttnesss
234 # my ($self, $table, $data, $options) = @_;
236 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
237 # which is sadly understood only by MySQL. Change default behavior here,
238 # until SQLA2 comes with proper dialect support
239 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
242 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
245 if ( ($_[3]||{})->{returning} ) {
247 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
251 return ($sql, @bind);
257 sub _recurse_fields {
258 my ($self, $fields) = @_;
259 my $ref = ref $fields;
260 return $self->_quote($fields) unless $ref;
261 return $$fields if $ref eq 'SCALAR';
263 if ($ref eq 'ARRAY') {
264 return join(', ', map { $self->_recurse_fields($_) } @$fields);
266 elsif ($ref eq 'HASH') {
267 my %hash = %$fields; # shallow copy
269 my $as = delete $hash{-as}; # if supplied
271 my ($func, $args, @toomany) = %hash;
273 # there should be only one pair
275 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
278 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
280 'The select => { distinct => ... } syntax is not supported for multiple columns.'
281 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
282 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
286 my $select = sprintf ('%s( %s )%s',
287 $self->_sqlcase($func),
288 $self->_recurse_fields($args),
290 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
296 # Is the second check absolutely necessary?
297 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
298 return $self->_fold_sqlbind( $fields );
301 croak($ref . qq{ unexpected in _recurse_fields()})
306 # this used to be a part of _order_by but is broken out for clarity.
307 # What we have been doing forever is hijacking the $order arg of
308 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
309 # then pretty much the entire resultset attr-hash, as more and more
310 # things in the SQLA space need to have mopre info about the $rs they
311 # create SQL for. The alternative would be to keep expanding the
312 # signature of _select with more and more positional parameters, which
313 # is just gross. All hail SQLA2!
314 sub _parse_rs_attrs {
315 my ($self, $arg) = @_;
319 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
320 $sql .= $self->_sqlcase(' group by ') . $g;
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]->_make_as($_[1]);
362 return $_[0]->next::method ($_[1]);
365 sub _generate_join_clause {
366 my ($self, $join_type) = @_;
368 return sprintf ('%s JOIN ',
369 $join_type ? ' ' . uc($join_type) : ''
374 my ($self, $from, @join) = @_;
376 push(@sqlf, $self->_make_as($from));
377 foreach my $j (@join) {
381 # check whether a join type exists
382 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
384 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
385 $join_type = $to_jt->{-join_type};
386 $join_type =~ s/^\s+ | \s+$//xg;
389 $join_type = $self->{_default_jointype} if not defined $join_type;
391 push @sqlf, $self->_generate_join_clause( $join_type );
393 if (ref $to eq 'ARRAY') {
394 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
396 push(@sqlf, $self->_make_as($to));
398 push(@sqlf, ' ON ', $self->_join_condition($on));
400 return join('', @sqlf);
404 my ($self, $sqlbind) = @_;
406 my @sqlbind = @$$sqlbind; # copy
407 my $sql = shift @sqlbind;
408 push @{$self->{from_bind}}, @sqlbind;
414 my ($self, $from) = @_;
415 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
416 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
418 } reverse each %{$self->_skip_options($from)});
422 my ($self, $hash) = @_;
424 $clean_hash->{$_} = $hash->{$_}
425 for grep {!/^-/} keys %$hash;
429 sub _join_condition {
430 my ($self, $cond) = @_;
431 if (ref $cond eq 'HASH') {
436 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
437 if ref($v) ne 'SCALAR';
441 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
444 return scalar($self->_recurse_where(\%j));
445 } elsif (ref $cond eq 'ARRAY') {
446 return join(' OR ', map { $self->_join_condition($_) } @$cond);
448 croak "Can't handle this yet!";
456 See L<DBIx::Class/CONTRIBUTORS>.
460 You may distribute this code under the same terms as Perl itself.