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 L</-ident> operator
32 =item * The L</-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 };
96 # poor man's de-qualifier
98 $_[0]->next::method( ( $_[0]{_dequalify_idents} and ! ref $_[1] )
99 ? $_[1] =~ / ([^\.]+) $ /x
105 my $self = shift->next::method(@_);
107 # use the same coderefs, they are prepared to handle both cases
108 my @extra_dbic_syntax = (
109 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
110 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
113 push @{$self->{special_ops}}, @extra_dbic_syntax;
114 push @{$self->{unary_ops}}, @extra_dbic_syntax;
119 sub _where_op_IDENT {
121 my ($op, $rhs) = splice @_, -2;
123 $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
126 # in case we are called as a top level special op (no '=')
129 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
137 sub _where_op_VALUE {
139 my ($op, $rhs) = splice @_, -2;
141 # in case we are called as a top level special op (no '=')
145 ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
151 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
155 $self->_convert('?'),
162 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
163 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
166 shift->next::method(@_);
169 # Handle limit-dialect selection
171 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
174 $fields = $self->_recurse_fields($fields);
176 if (defined $offset) {
177 $self->throw_exception('A supplied offset must be a non-negative integer')
178 if ( $offset =~ /\D/ or $offset < 0 );
182 if (defined $limit) {
183 $self->throw_exception('A supplied limit must be a positive integer')
184 if ( $limit =~ /\D/ or $limit <= 0 );
187 $limit = $self->__max_int;
193 # this is legacy code-flow from SQLA::Limit, it is not set in stone
195 ($sql, @bind) = $self->next::method ($table, $fields, $where);
198 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
201 my $dialect = $self->limit_dialect
202 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
203 $self->can ("_$dialect")
204 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
208 $sql = $self->$limiter (
210 { %{$rs_attrs||{}}, _selector_sql => $fields },
216 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
219 push @{$self->{where_bind}}, @bind;
221 # this *must* be called, otherwise extra binds will remain in the sql-maker
222 my @all_bind = $self->_assemble_binds;
224 $sql .= $self->_lock_select ($rs_attrs->{for})
227 return wantarray ? ($sql, @all_bind) : $sql;
230 sub _assemble_binds {
232 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/pre_select select from where group having order limit/);
236 update => 'FOR UPDATE',
237 shared => 'FOR SHARE',
240 my ($self, $type) = @_;
243 if (ref($type) eq 'SCALAR') {
247 $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
253 # Handle default inserts
255 # optimized due to hotttnesss
256 # my ($self, $table, $data, $options) = @_;
258 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
259 # which is sadly understood only by MySQL. Change default behavior here,
260 # until SQLA2 comes with proper dialect support
261 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
264 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
267 if ( ($_[3]||{})->{returning} ) {
269 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
273 return ($sql, @bind);
279 sub _recurse_fields {
280 my ($self, $fields) = @_;
281 my $ref = ref $fields;
282 return $self->_quote($fields) unless $ref;
283 return $$fields if $ref eq 'SCALAR';
285 if ($ref eq 'ARRAY') {
286 return join(', ', map { $self->_recurse_fields($_) } @$fields);
288 elsif ($ref eq 'HASH') {
289 my %hash = %$fields; # shallow copy
291 my $as = delete $hash{-as}; # if supplied
293 my ($func, $args, @toomany) = %hash;
295 # there should be only one pair
297 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
300 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
301 $self->throw_exception (
302 'The select => { distinct => ... } syntax is not supported for multiple columns.'
303 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
304 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
308 my $select = sprintf ('%s( %s )%s',
309 $self->_sqlcase($func),
310 $self->_recurse_fields($args),
312 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
318 # Is the second check absolutely necessary?
319 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
320 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
321 return $$fields->[0];
324 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
329 # this used to be a part of _order_by but is broken out for clarity.
330 # What we have been doing forever is hijacking the $order arg of
331 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
332 # then pretty much the entire resultset attr-hash, as more and more
333 # things in the SQLA space need to have mopre info about the $rs they
334 # create SQL for. The alternative would be to keep expanding the
335 # signature of _select with more and more positional parameters, which
336 # is just gross. All hail SQLA2!
337 sub _parse_rs_attrs {
338 my ($self, $arg) = @_;
342 if ($arg->{group_by}) {
343 # horible horrible, waiting for refactor
344 local $self->{select_bind};
345 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
346 $sql .= $self->_sqlcase(' group by ') . $g;
347 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
351 if (defined $arg->{having}) {
352 my ($frag, @bind) = $self->_recurse_where($arg->{having});
353 push(@{$self->{having_bind}}, @bind);
354 $sql .= $self->_sqlcase(' having ') . $frag;
357 if (defined $arg->{order_by}) {
358 $sql .= $self->_order_by ($arg->{order_by});
365 my ($self, $arg) = @_;
367 # check that we are not called in legacy mode (order_by as 4th argument)
368 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
369 return $self->_parse_rs_attrs ($arg);
372 my ($sql, @bind) = $self->next::method($arg);
373 push @{$self->{order_bind}}, @bind;
379 # optimized due to hotttnesss
380 # my ($self, $from) = @_;
381 if (my $ref = ref $_[1] ) {
382 if ($ref eq 'ARRAY') {
383 return $_[0]->_recurse_from(@{$_[1]});
385 elsif ($ref eq 'HASH') {
386 return $_[0]->_recurse_from($_[1]);
388 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
389 my ($sql, @bind) = @{ ${$_[1]} };
390 push @{$_[0]->{from_bind}}, @bind;
394 return $_[0]->next::method ($_[1]);
397 sub _generate_join_clause {
398 my ($self, $join_type) = @_;
400 $join_type = $self->{_default_jointype}
401 if ! defined $join_type;
403 return sprintf ('%s JOIN ',
404 $join_type ? $self->_sqlcase($join_type) : ''
411 return join (' ', $self->_gen_from_blocks(@_) );
414 sub _gen_from_blocks {
415 my ($self, $from, @joins) = @_;
417 my @fchunks = $self->_from_chunk_to_sql($from);
422 # check whether a join type exists
423 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
425 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
426 $join_type = $to_jt->{-join_type};
427 $join_type =~ s/^\s+ | \s+$//xg;
430 my @j = $self->_generate_join_clause( $join_type );
432 if (ref $to eq 'ARRAY') {
433 push(@j, '(', $self->_recurse_from(@$to), ')');
436 push(@j, $self->_from_chunk_to_sql($to));
439 my ($sql, @bind) = $self->_join_condition($on);
440 push(@j, ' ON ', $sql);
441 push @{$self->{from_bind}}, @bind;
443 push @fchunks, join '', @j;
449 sub _from_chunk_to_sql {
450 my ($self, $fromspec) = @_;
452 return join (' ', do {
453 if (! ref $fromspec) {
454 $self->_quote($fromspec);
456 elsif (ref $fromspec eq 'SCALAR') {
459 elsif (ref $fromspec eq 'REF' and ref $$fromspec eq 'ARRAY') {
460 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
463 elsif (ref $fromspec eq 'HASH') {
464 my ($as, $table, $toomuch) = ( map
465 { $_ => $fromspec->{$_} }
466 ( grep { $_ !~ /^\-/ } keys %$fromspec )
469 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
472 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
475 $self->throw_exception('Unsupported from refkind: ' . ref $fromspec );
480 sub _join_condition {
481 my ($self, $cond) = @_;
483 # Backcompat for the old days when a plain hashref
484 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
485 # Once things settle we should start warning here so that
486 # folks unroll their hacks
492 (keys %$cond)[0] =~ /\./
494 ! ref ( (values %$cond)[0] )
496 $cond = { keys %$cond => { -ident => values %$cond } }
498 elsif ( ref $cond eq 'ARRAY' ) {
499 # do our own ORing so that the hashref-shim above is invoked
502 foreach my $c (@$cond) {
503 my ($sql, @bind) = $self->_join_condition($c);
507 return join(' OR ', @parts), @binds;
510 return $self->_recurse_where($cond);
519 Used to explicitly specify an SQL identifier. Takes a plain string as value
520 which is then invariably treated as a column name (and is being properly
521 quoted if quoting has been requested). Most useful for comparison of two
525 priority => { '<', 2 },
526 requestor => { -ident => 'submitter' }
531 $stmt = 'WHERE "priority" < ? AND "requestor" = "submitter"';
536 The -value operator signals that the argument to the right is a raw bind value.
537 It will be passed straight to DBI, without invoking any of the SQL::Abstract
538 condition-parsing logic. This allows you to, for example, pass an array as a
539 column value for databases that support array datatypes, e.g.:
542 array => { -value => [1, 2, 3] }
547 $stmt = 'WHERE array = ?';
552 See L<DBIx::Class/CONTRIBUTORS>.
556 You may distribute this code under the same terms as Perl itself.