Use _is_binary_lob_type to determine datatypes in need of PG bytea binds
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLMaker.pm
CommitLineData
d5dedbd6 1package DBIx::Class::SQLMaker;
6f4ddea1 2
a697fa31 3use strict;
4use warnings;
5
d5dedbd6 6=head1 NAME
7
8DBIx::Class::SQLMaker - An SQL::Abstract-based SQL maker class
9
10=head1 DESCRIPTION
11
12This module is a subclass of L<SQL::Abstract> and includes a number of
13DBIC-specific workarounds, not yet suitable for inclusion into the
14L<SQL::Abstract> core. It also provides all (and more than) the functionality
15of L<SQL::Abstract::Limit>, see L<DBIx::Class::SQLMaker::LimitDialects> for
16more info.
17
18Currently the enhancements to L<SQL::Abstract> are:
19
20=over
21
22=item * Support for C<JOIN> statements (via extended C<table/from> support)
23
24=item * Support of functions in C<SELECT> lists
25
26=item * C<GROUP BY>/C<HAVING> support (via extensions to the order_by parameter)
27
28=item * Support of C<...FOR UPDATE> type of select statement modifiers
29
e6600283 30=item * The -ident operator
31
41519379 32=item * The -value operator
33
d5dedbd6 34=back
35
36=cut
6a247f33 37
38use base qw/
d5dedbd6 39 DBIx::Class::SQLMaker::LimitDialects
6a247f33 40 SQL::Abstract
70c28808 41 DBIx::Class
6a247f33 42/;
43use mro 'c3';
a697fa31 44
6298a324 45use Sub::Name 'subname';
70c28808 46use DBIx::Class::Carp;
47use DBIx::Class::Exception;
e8fc51c7 48use namespace::clean;
b2b22cd6 49
6a247f33 50__PACKAGE__->mk_group_accessors (simple => qw/quote_char name_sep limit_dialect/);
51
3f5b99fe 52# for when I need a normalized l/r pair
53sub _quote_chars {
54 map
55 { defined $_ ? $_ : '' }
56 ( ref $_[0]->{quote_char} ? (@{$_[0]->{quote_char}}) : ( ($_[0]->{quote_char}) x 2 ) )
57 ;
58}
59
70c28808 60# FIXME when we bring in the storage weaklink, check its schema
61# weaklink and channel through $schema->throw_exception
62sub throw_exception { DBIx::Class::Exception->throw($_[1]) }
63
b2b22cd6 64BEGIN {
2ea6032a 65 # reinstall the belch()/puke() functions of SQL::Abstract with custom versions
70c28808 66 # that use DBIx::Class::Carp/DBIx::Class::Exception instead of plain Carp
b2b22cd6 67 no warnings qw/redefine/;
2ea6032a 68
69 *SQL::Abstract::belch = subname 'SQL::Abstract::belch' => sub (@) {
70 my($func) = (caller(1))[3];
71 carp "[$func] Warning: ", @_;
72 };
73
74 *SQL::Abstract::puke = subname 'SQL::Abstract::puke' => sub (@) {
75 my($func) = (caller(1))[3];
70c28808 76 __PACKAGE__->throw_exception("[$func] Fatal: " . join ('', @_));
2ea6032a 77 };
9c1700e3 78
79 # Current SQLA pollutes its namespace - clean for the time being
80 namespace::clean->clean_subroutines(qw/SQL::Abstract carp croak confess/);
b2b22cd6 81}
6f4ddea1 82
e9657379 83# the "oh noes offset/top without limit" constant
6a247f33 84# limited to 32 bits for sanity (and consistency,
85# since it is ultimately handed to sprintf %u)
86# Implemented as a method, since ::Storage::DBI also
87# refers to it (i.e. for the case of software_limit or
88# as the value to abuse with MSSQL ordered subqueries)
e9657379 89sub __max_int { 0xFFFFFFFF };
90
e6600283 91sub new {
92 my $self = shift->next::method(@_);
93
41519379 94 # use the same coderefs, they are prepared to handle both cases
95 my @extra_dbic_syntax = (
96 { regex => qr/^ ident $/xi, handler => '_where_op_IDENT' },
97 { regex => qr/^ value $/xi, handler => '_where_op_VALUE' },
98 );
99
100 push @{$self->{special_ops}}, @extra_dbic_syntax;
101 push @{$self->{unary_ops}}, @extra_dbic_syntax;
e6600283 102
103 $self;
104}
105
106sub _where_op_IDENT {
107 my $self = shift;
108 my ($op, $rhs) = splice @_, -2;
109 if (ref $rhs) {
70c28808 110 $self->throw_exception("-$op takes a single scalar argument (a quotable identifier)");
e6600283 111 }
112
41519379 113 # in case we are called as a top level special op (no '=')
e6600283 114 my $lhs = shift;
115
116 $_ = $self->_convert($self->_quote($_)) for ($lhs, $rhs);
117
118 return $lhs
119 ? "$lhs = $rhs"
120 : $rhs
121 ;
122}
123
41519379 124sub _where_op_VALUE {
125 my $self = shift;
126 my ($op, $rhs) = splice @_, -2;
127
128 # in case we are called as a top level special op (no '=')
129 my $lhs = shift;
130
131 my @bind = [
70c28808 132 ($lhs || $self->{_nested_func_lhs} || $self->throw_exception("Unable to find bindtype for -value $rhs") ),
41519379 133 $rhs
134 ];
135
136 return $lhs
137 ? (
138 $self->_convert($self->_quote($lhs)) . ' = ' . $self->_convert('?'),
139 @bind
140 )
141 : (
142 $self->_convert('?'),
143 @bind,
144 )
145 ;
146}
147
b1d821de 148sub _where_op_NEST {
70c28808 149 carp_unique ("-nest in search conditions is deprecated, you most probably wanted:\n"
b1d821de 150 .q|{..., -and => [ \%cond0, \@cond1, \'cond2', \[ 'cond3', [ col => bind ] ], etc. ], ... }|
70c28808 151 );
b1d821de 152
153 shift->next::method(@_);
154}
155
6a247f33 156# Handle limit-dialect selection
6f4ddea1 157sub select {
6a247f33 158 my ($self, $table, $fields, $where, $rs_attrs, $limit, $offset) = @_;
159
160
161 $fields = $self->_recurse_fields($fields);
162
163 if (defined $offset) {
70c28808 164 $self->throw_exception('A supplied offset must be a non-negative integer')
6a247f33 165 if ( $offset =~ /\D/ or $offset < 0 );
166 }
167 $offset ||= 0;
1cbd3034 168
6a247f33 169 if (defined $limit) {
70c28808 170 $self->throw_exception('A supplied limit must be a positive integer')
6a247f33 171 if ( $limit =~ /\D/ or $limit <= 0 );
172 }
173 elsif ($offset) {
174 $limit = $self->__max_int;
6f4ddea1 175 }
c2b7c5dc 176
a6b68a60 177
6a247f33 178 my ($sql, @bind);
179 if ($limit) {
180 # this is legacy code-flow from SQLA::Limit, it is not set in stone
181
182 ($sql, @bind) = $self->next::method ($table, $fields, $where);
183
184 my $limiter =
185 $self->can ('emulate_limit') # also backcompat hook from SQLA::Limit
186 ||
187 do {
188 my $dialect = $self->limit_dialect
70c28808 189 or $self->throw_exception( "Unable to generate SQL-limit - no limit dialect specified on $self, and no emulate_limit method found" );
6a247f33 190 $self->can ("_$dialect")
70c28808 191 or $self->throw_exception(__PACKAGE__ . " does not implement the requested dialect '$dialect'");
6a247f33 192 }
193 ;
194
195 $sql = $self->$limiter ($sql, $rs_attrs, $limit, $offset);
196 }
197 else {
198 ($sql, @bind) = $self->next::method ($table, $fields, $where, $rs_attrs);
199 }
200
49afd714 201 push @{$self->{where_bind}}, @bind;
583a0c65 202
203# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 204 my @all_bind = $self->_assemble_binds;
583a0c65 205
e5372da4 206 $sql .= $self->_lock_select ($rs_attrs->{for})
207 if $rs_attrs->{for};
208
49afd714 209 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 210}
211
212sub _assemble_binds {
213 my $self = shift;
0542ec57 214 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/select from where group having order/);
6f4ddea1 215}
216
e5372da4 217my $for_syntax = {
218 update => 'FOR UPDATE',
219 shared => 'FOR SHARE',
220};
221sub _lock_select {
222 my ($self, $type) = @_;
70c28808 223 my $sql = $for_syntax->{$type} || $self->throw_exception( "Unknown SELECT .. FOR type '$type' requested" );
e5372da4 224 return " $sql";
225}
226
6a247f33 227# Handle default inserts
6f4ddea1 228sub insert {
6a247f33 229# optimized due to hotttnesss
230# my ($self, $table, $data, $options) = @_;
7a72e5a5 231
232 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
233 # which is sadly understood only by MySQL. Change default behavior here,
234 # until SQLA2 comes with proper dialect support
6a247f33 235 if (! $_[2] or (ref $_[2] eq 'HASH' and !keys %{$_[2]} ) ) {
bf51641f 236 my @bind;
20595c02 237 my $sql = sprintf(
238 'INSERT INTO %s DEFAULT VALUES', $_[0]->_quote($_[1])
239 );
28d28903 240
bf51641f 241 if ( ($_[3]||{})->{returning} ) {
242 my $s;
243 ($s, @bind) = $_[0]->_insert_returning ($_[3]);
244 $sql .= $s;
28d28903 245 }
246
bf51641f 247 return ($sql, @bind);
7a72e5a5 248 }
249
6a247f33 250 next::method(@_);
6f4ddea1 251}
252
253sub _recurse_fields {
81446c4f 254 my ($self, $fields) = @_;
6f4ddea1 255 my $ref = ref $fields;
256 return $self->_quote($fields) unless $ref;
257 return $$fields if $ref eq 'SCALAR';
258
259 if ($ref eq 'ARRAY') {
81446c4f 260 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 261 }
262 elsif ($ref eq 'HASH') {
81446c4f 263 my %hash = %$fields; # shallow copy
83e09b5b 264
50136dd9 265 my $as = delete $hash{-as}; # if supplied
266
81446c4f 267 my ($func, $args, @toomany) = %hash;
268
269 # there should be only one pair
270 if (@toomany) {
70c28808 271 $self->throw_exception( "Malformed select argument - too many keys in hash: " . join (',', keys %$fields ) );
81446c4f 272 }
50136dd9 273
274 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
70c28808 275 $self->throw_exception (
50136dd9 276 'The select => { distinct => ... } syntax is not supported for multiple columns.'
277 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
278 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 279 );
6f4ddea1 280 }
83e09b5b 281
50136dd9 282 my $select = sprintf ('%s( %s )%s',
283 $self->_sqlcase($func),
284 $self->_recurse_fields($args),
285 $as
0491b597 286 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 287 : ''
288 );
289
83e09b5b 290 return $select;
6f4ddea1 291 }
292 # Is the second check absolutely necessary?
293 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
4c2b30d6 294 push @{$self->{select_bind}}, @{$$fields}[1..$#$$fields];
295 return $$fields->[0];
6f4ddea1 296 }
297 else {
70c28808 298 $self->throw_exception( $ref . qq{ unexpected in _recurse_fields()} );
6f4ddea1 299 }
300}
301
a6b68a60 302
303# this used to be a part of _order_by but is broken out for clarity.
304# What we have been doing forever is hijacking the $order arg of
305# SQLA::select to pass in arbitrary pieces of data (first the group_by,
306# then pretty much the entire resultset attr-hash, as more and more
307# things in the SQLA space need to have mopre info about the $rs they
308# create SQL for. The alternative would be to keep expanding the
309# signature of _select with more and more positional parameters, which
310# is just gross. All hail SQLA2!
311sub _parse_rs_attrs {
1cbd3034 312 my ($self, $arg) = @_;
15827712 313
a6b68a60 314 my $sql = '';
1cbd3034 315
0542ec57 316 if ($arg->{group_by}) {
317 # horible horrible, waiting for refactor
318 local $self->{select_bind};
319 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
320 $sql .= $self->_sqlcase(' group by ') . $g;
321 push @{$self->{group_bind} ||= []}, @{$self->{select_bind}||[]};
322 }
a6b68a60 323 }
1cbd3034 324
a6b68a60 325 if (defined $arg->{having}) {
326 my ($frag, @bind) = $self->_recurse_where($arg->{having});
327 push(@{$self->{having_bind}}, @bind);
328 $sql .= $self->_sqlcase(' having ') . $frag;
329 }
15827712 330
a6b68a60 331 if (defined $arg->{order_by}) {
332 $sql .= $self->_order_by ($arg->{order_by});
333 }
15827712 334
a6b68a60 335 return $sql;
336}
337
338sub _order_by {
339 my ($self, $arg) = @_;
15827712 340
a6b68a60 341 # check that we are not called in legacy mode (order_by as 4th argument)
342 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
343 return $self->_parse_rs_attrs ($arg);
fde3719a 344 }
1cbd3034 345 else {
6a247f33 346 my ($sql, @bind) = $self->next::method($arg);
a6b68a60 347 push @{$self->{order_bind}}, @bind;
1cbd3034 348 return $sql;
fd4cb60a 349 }
6f4ddea1 350}
351
352sub _table {
6a247f33 353# optimized due to hotttnesss
354# my ($self, $from) = @_;
355 if (my $ref = ref $_[1] ) {
356 if ($ref eq 'ARRAY') {
357 return $_[0]->_recurse_from(@{$_[1]});
358 }
359 elsif ($ref eq 'HASH') {
4c2b30d6 360 return $_[0]->_recurse_from($_[1]);
6a247f33 361 }
1bffc6b8 362 elsif ($ref eq 'REF' && ref ${$_[1]} eq 'ARRAY') {
363 my ($sql, @bind) = @{ ${$_[1]} };
364 push @{$_[0]->{from_bind}}, @bind;
365 return $sql
366 }
6f4ddea1 367 }
6a247f33 368 return $_[0]->next::method ($_[1]);
6f4ddea1 369}
370
b8391c87 371sub _generate_join_clause {
372 my ($self, $join_type) = @_;
373
726c8f65 374 $join_type = $self->{_default_jointype}
375 if ! defined $join_type;
376
b8391c87 377 return sprintf ('%s JOIN ',
726c8f65 378 $join_type ? $self->_sqlcase($join_type) : ''
b8391c87 379 );
380}
381
6f4ddea1 382sub _recurse_from {
726c8f65 383 my $self = shift;
384
385 return join (' ', $self->_gen_from_blocks(@_) );
386}
387
388sub _gen_from_blocks {
389 my ($self, $from, @joins) = @_;
390
391 my @fchunks = $self->_from_chunk_to_sql($from);
6f4ddea1 392
726c8f65 393 for (@joins) {
4c2b30d6 394 my ($to, $on) = @$_;
aa82ce29 395
6f4ddea1 396 # check whether a join type exists
6f4ddea1 397 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 398 my $join_type;
399 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
400 $join_type = $to_jt->{-join_type};
401 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 402 }
aa82ce29 403
726c8f65 404 my @j = $self->_generate_join_clause( $join_type );
6f4ddea1 405
406 if (ref $to eq 'ARRAY') {
726c8f65 407 push(@j, '(', $self->_recurse_from(@$to), ')');
408 }
409 else {
410 push(@j, $self->_from_chunk_to_sql($to));
6f4ddea1 411 }
726c8f65 412
a697fa31 413 my ($sql, @bind) = $self->_join_condition($on);
b4e9f590 414 push(@j, ' ON ', $sql);
a697fa31 415 push @{$self->{from_bind}}, @bind;
726c8f65 416
417 push @fchunks, join '', @j;
6f4ddea1 418 }
726c8f65 419
420 return @fchunks;
6f4ddea1 421}
422
4c2b30d6 423sub _from_chunk_to_sql {
424 my ($self, $fromspec) = @_;
425
426 return join (' ', $self->_SWITCH_refkind($fromspec, {
427 SCALARREF => sub {
428 $$fromspec;
429 },
430 ARRAYREFREF => sub {
431 push @{$self->{from_bind}}, @{$$fromspec}[1..$#$$fromspec];
432 $$fromspec->[0];
433 },
434 HASHREF => sub {
435 my ($as, $table, $toomuch) = ( map
436 { $_ => $fromspec->{$_} }
437 ( grep { $_ !~ /^\-/ } keys %$fromspec )
438 );
6f4ddea1 439
70c28808 440 $self->throw_exception( "Only one table/as pair expected in from-spec but an exra '$toomuch' key present" )
4c2b30d6 441 if defined $toomuch;
6f4ddea1 442
4c2b30d6 443 ($self->_from_chunk_to_sql($table), $self->_quote($as) );
444 },
445 SCALAR => sub {
446 $self->_quote($fromspec);
447 },
448 }));
6f4ddea1 449}
450
451sub _join_condition {
452 my ($self, $cond) = @_;
4c2b30d6 453
a697fa31 454 # Backcompat for the old days when a plain hashref
455 # { 't1.col1' => 't2.col2' } meant ON t1.col1 = t2.col2
456 # Once things settle we should start warning here so that
457 # folks unroll their hacks
458 if (
459 ref $cond eq 'HASH'
460 and
461 keys %$cond == 1
462 and
463 (keys %$cond)[0] =~ /\./
464 and
465 ! ref ( (values %$cond)[0] )
466 ) {
467 $cond = { keys %$cond => { -ident => values %$cond } }
6f4ddea1 468 }
a697fa31 469 elsif ( ref $cond eq 'ARRAY' ) {
470 # do our own ORing so that the hashref-shim above is invoked
9aae3566 471 my @parts;
472 my @binds;
473 foreach my $c (@$cond) {
474 my ($sql, @bind) = $self->_join_condition($c);
475 push @binds, @bind;
476 push @parts, $sql;
477 }
478 return join(' OR ', @parts), @binds;
6f4ddea1 479 }
a697fa31 480
481 return $self->_recurse_where($cond);
6f4ddea1 482}
483
6f4ddea1 4841;
d5dedbd6 485
486=head1 AUTHORS
487
488See L<DBIx::Class/CONTRIBUTORS>.
489
490=head1 LICENSE
491
492You may distribute this code under the same terms as Perl itself.
493
494=cut