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
34 DBIx::Class::SQLMaker::LimitDialects
36 Class::Accessor::Grouped
41 use Sub::Name 'subname';
42 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
45 __PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
47 # for when I need a normalized l/r pair
50 { defined $_ ? $_ : '' }
51 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
56 # reinstall the carp()/croak() functions imported into SQL::Abstract
57 # as Carp and Carp::Clan do not like each other much
58 no warnings qw/redefine/;
60 for my $f (qw/carp croak/) {
62 my $orig = \&{"SQL::Abstract::$f"};
63 my $clan_import = \&{$f};
64 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
66 if (Carp::longmess() =~ /DBIx::Class::SQLMaker::[\w]+ .+? called \s at/x) {
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 coderef, it is prepared to handle both cases
88 push @{$self->{special_ops}}, {
89 regex => qr/^ ident $/xi, handler => '_where_op_IDENT',
91 push @{$self->{unary_ops}}, {
92 regex => qr/^ ident $/xi, handler => '_where_op_IDENT',
100 my ($op, $rhs) = splice @_, -2;
102 croak "-$op takes a single scalar argument (a quotable identifier)";
105 # in case we are called as a top level special op
108 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
116 # Handle limit-dialect selection
118 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
121 $fields = $self->_recurse_fields($fields);
123 if (defined $offset) {
124 croak ('A supplied offset must be a non-negative integer')
125 if ( $offset =~ /\D/ or $offset < 0 );
129 if (defined $limit) {
130 croak ('A supplied limit must be a positive integer')
131 if ( $limit =~ /\D/ or $limit <= 0 );
134 $limit = $self->__max_int;
140 # this is legacy code-flow from SQLA::Limit, it is not set in stone
142 ($sql, @bind) = $self->next::method ($table, $fields, $where);
145 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
148 my $dialect = $self->limit_dialect
149 or croak "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found";
150 $self->can ("_$dialect")
151 or croak (__PACKAGE__ . " does not implement the requested dialect '$dialect'");
155 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
158 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
161 push @{$self->{where_bind}}, @bind;
163 # this *must* be called, otherwise extra binds will remain in the sql-maker
164 my @all_bind = $self->_assemble_binds;
166 $sql .= $self->_lock_select ($rs_attrs->{for})
169 return wantarray ? ($sql, @all_bind) : $sql;
172 sub _assemble_binds {
174 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
178 update => 'FOR UPDATE',
179 shared => 'FOR SHARE',
182 my ($self, $type) = @_;
183 my $sql = $for_syntax->{$type} || croak "Unknown SELECT .. FOR type '$type' requested";
187 # Handle default inserts
189 # optimized due to hotttnesss
190 # my ($self, $table, $data, $options) = @_;
192 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
193 # which is sadly understood only by MySQL. Change default behavior here,
194 # until SQLA2 comes with proper dialect support
195 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
196 my $sql = "INSERT INTO $_[1] DEFAULT VALUES";
198 if (my $ret = ($_[3]||{})->{returning} ) {
199 $sql .= $_[0]->_insert_returning ($ret);
208 sub _recurse_fields {
209 my ($self, $fields) = @_;
210 my $ref = ref $fields;
211 return $self->_quote($fields) unless $ref;
212 return $$fields if $ref eq 'SCALAR';
214 if ($ref eq 'ARRAY') {
215 return join(', ', map { $self->_recurse_fields($_) } @$fields);
217 elsif ($ref eq 'HASH') {
218 my %hash = %$fields; # shallow copy
220 my $as = delete $hash{-as}; # if supplied
222 my ($func, $args, @toomany) = %hash;
224 # there should be only one pair
226 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
229 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
231 'The select => { distinct => ... } syntax is not supported for multiple columns.'
232 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
233 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
237 my $select = sprintf ('%s( %s )%s',
238 $self->_sqlcase($func),
239 $self->_recurse_fields($args),
241 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
247 # Is the second check absolutely necessary?
248 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
249 return $self->_fold_sqlbind( $fields );
252 croak($ref . qq{ unexpected in _recurse_fields()})
257 # this used to be a part of _order_by but is broken out for clarity.
258 # What we have been doing forever is hijacking the $order arg of
259 # SQLA::select to pass in arbitrary pieces of data (first the group_by,
260 # then pretty much the entire resultset attr-hash, as more and more
261 # things in the SQLA space need to have mopre info about the $rs they
262 # create SQL for. The alternative would be to keep expanding the
263 # signature of _select with more and more positional parameters, which
264 # is just gross. All hail SQLA2!
265 sub _parse_rs_attrs {
266 my ($self, $arg) = @_;
270 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
271 $sql .= $self->_sqlcase(' group by ') . $g;
274 if (defined $arg->{having}) {
275 my ($frag, @bind) = $self->_recurse_where($arg->{having});
276 push(@{$self->{having_bind}}, @bind);
277 $sql .= $self->_sqlcase(' having ') . $frag;
280 if (defined $arg->{order_by}) {
281 $sql .= $self->_order_by ($arg->{order_by});
288 my ($self, $arg) = @_;
290 # check that we are not called in legacy mode (order_by as 4th argument)
291 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
292 return $self->_parse_rs_attrs ($arg);
295 my ($sql, @bind) = $self->next::method($arg);
296 push @{$self->{order_bind}}, @bind;
302 # optimized due to hotttnesss
303 # my ($self, $from) = @_;
304 if (my $ref = ref $_[1] ) {
305 if ($ref eq 'ARRAY') {
306 return $_[0]->_recurse_from(@{$_[1]});
308 elsif ($ref eq 'HASH') {
309 return $_[0]->_make_as($_[1]);
313 return $_[0]->next::method ($_[1]);
316 sub _generate_join_clause {
317 my ($self, $join_type) = @_;
319 return sprintf ('%s JOIN ',
320 $join_type ? ' ' . uc($join_type) : ''
325 my ($self, $from, @join) = @_;
327 push(@sqlf, $self->_make_as($from));
328 foreach my $j (@join) {
332 # check whether a join type exists
333 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
335 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
336 $join_type = $to_jt->{-join_type};
337 $join_type =~ s/^\s+ | \s+$//xg;
340 $join_type = $self->{_default_jointype} if not defined $join_type;
342 push @sqlf, $self->_generate_join_clause( $join_type );
344 if (ref $to eq 'ARRAY') {
345 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
347 push(@sqlf, $self->_make_as($to));
349 push(@sqlf, ' ON ', $self->_join_condition($on));
351 return join('', @sqlf);
355 my ($self, $sqlbind) = @_;
357 my @sqlbind = @$$sqlbind; # copy
358 my $sql = shift @sqlbind;
359 push @{$self->{from_bind}}, @sqlbind;
365 my ($self, $from) = @_;
366 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
367 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
369 } reverse each %{$self->_skip_options($from)});
373 my ($self, $hash) = @_;
375 $clean_hash->{$_} = $hash->{$_}
376 for grep {!/^-/} keys %$hash;
380 sub _join_condition {
381 my ($self, $cond) = @_;
382 if (ref $cond eq 'HASH') {
387 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
388 if ref($v) ne 'SCALAR';
392 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
395 return scalar($self->_recurse_where(\%j));
396 } elsif (ref $cond eq 'ARRAY') {
397 return join(' OR ', map { $self->_join_condition($_) } @$cond);
399 croak "Can't handle this yet!";
407 See L<DBIx::Class/CONTRIBUTORS>.
411 You may distribute this code under the same terms as Perl itself.