Test to make sure optional deps does not use any external modules
[dbsrgits/DBIx-Class.git] / lib / DBIx / Class / SQLAHacks.pm
CommitLineData
6f4ddea1 1package # Hide from PAUSE
855c6fd0 2 DBIx::Class::SQLAHacks;
6f4ddea1 3
998373c2 4# This module is a subclass of SQL::Abstract::Limit and includes a number
5# of DBIC-specific workarounds, not yet suitable for inclusion into the
6# SQLA core
7
6f4ddea1 8use base qw/SQL::Abstract::Limit/;
e3764383 9use strict;
10use warnings;
6298a324 11use List::Util 'first';
12use Sub::Name 'subname';
13use namespace::clean;
ac322978 14use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
b2b22cd6 15
16BEGIN {
17 # reinstall the carp()/croak() functions imported into SQL::Abstract
18 # as Carp and Carp::Clan do not like each other much
19 no warnings qw/redefine/;
20 no strict qw/refs/;
21 for my $f (qw/carp croak/) {
329d7385 22
b2b22cd6 23 my $orig = \&{"SQL::Abstract::$f"};
6298a324 24 *{"SQL::Abstract::$f"} = subname "SQL::Abstract::$f" =>
8637bb24 25 sub {
26 if (Carp::longmess() =~ /DBIx::Class::SQLAHacks::[\w]+ .+? called \s at/x) {
27 __PACKAGE__->can($f)->(@_);
28 }
29 else {
30 goto $orig;
31 }
32 };
b2b22cd6 33 }
34}
6f4ddea1 35
e9657379 36# the "oh noes offset/top without limit" constant
02a8d945 37# limited to 32 bits for sanity (and since it is fed
38# to sprintf %u)
e9657379 39sub __max_int { 0xFFFFFFFF };
40
998373c2 41
42# Tries to determine limit dialect.
43#
6f4ddea1 44sub new {
45 my $self = shift->SUPER::new(@_);
46
47 # This prevents the caching of $dbh in S::A::L, I believe
48 # If limit_dialect is a ref (like a $dbh), go ahead and replace
49 # it with what it resolves to:
50 $self->{limit_dialect} = $self->_find_syntax($self->{limit_dialect})
51 if ref $self->{limit_dialect};
52
53 $self;
54}
55
a54bd479 56# !!! THIS IS ALSO HORRIFIC !!! /me ashamed
57#
75f025cf 58# Generates inner/outer select lists for various limit dialects
81446c4f 59# which result in one or more subqueries (e.g. RNO, Top, RowNum)
60# Any non-root-table columns need to have their table qualifier
a54bd479 61# turned into a column alias (otherwise names in subqueries clash
81446c4f 62# and/or lose their source table)
a54bd479 63#
75f025cf 64# Returns inner/outer strings of SQL QUOTED selectors with aliases
a54bd479 65# (to be used in whatever select statement), and an alias index hashref
66# of QUOTED SEL => QUOTED ALIAS pairs (to maybe be used for string-subst
75f025cf 67# higher up).
68# If an order_by is supplied, the inner select needs to bring out columns
69# used in implicit (non-selected) orders, and the order condition itself
70# needs to be realiased to the proper names in the outer query. Thus we
71# also return a hashref (order doesn't matter) of QUOTED EXTRA-SEL =>
72# QUOTED ALIAS pairs, which is a list of extra selectors that do *not*
73# exist in the original select list
a54bd479 74
75sub _subqueried_limit_attrs {
75f025cf 76 my ($self, $rs_attrs) = @_;
81446c4f 77
a54bd479 78 croak 'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)'
79 unless ref ($rs_attrs) eq 'HASH';
80
81 my ($re_sep, $re_alias) = map { quotemeta $_ } (
82 $self->name_sep || '.',
83 $rs_attrs->{alias},
84 );
81446c4f 85
a54bd479 86 # correlate select and as, build selection index
87 my (@sel, $in_sel_index);
81446c4f 88 for my $i (0 .. $#{$rs_attrs->{select}}) {
a54bd479 89
81446c4f 90 my $s = $rs_attrs->{select}[$i];
a54bd479 91 my $sql_sel = $self->_recurse_fields ($s);
92 my $sql_alias = (ref $s) eq 'HASH' ? $s->{-as} : undef;
93
94
81446c4f 95 push @sel, {
a54bd479 96 sql => $sql_sel,
81446c4f 97 unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) },
98 as =>
a54bd479 99 $sql_alias
81446c4f 100 ||
101 $rs_attrs->{as}[$i]
102 ||
103 croak "Select argument $i ($s) without corresponding 'as'"
104 ,
105 };
a54bd479 106
107 $in_sel_index->{$sql_sel}++;
108 $in_sel_index->{$self->_quote ($sql_alias)}++ if $sql_alias;
109
75f025cf 110 # record unqualified versions too, so we do not have
111 # to reselect the same column twice (in qualified and
112 # unqualified form)
113 if (! ref $s && $sql_sel =~ / $re_sep (.+) $/x) {
114 $in_sel_index->{$1}++;
115 }
81446c4f 116 }
117
81446c4f 118
119 # re-alias and remove any name separators from aliases,
120 # unless we are dealing with the current source alias
a54bd479 121 # (which will transcend the subqueries as it is necessary
81446c4f 122 # for possible further chaining)
a54bd479 123 my (@in_sel, @out_sel, %renamed);
81446c4f 124 for my $node (@sel) {
6298a324 125 if (first { $_ =~ / (?<! $re_alias ) $re_sep /x } ($node->{as}, $node->{unquoted_sql}) ) {
a54bd479 126 $node->{as} =~ s/ $re_sep /__/xg;
127 my $quoted_as = $self->_quote($node->{as});
128 push @in_sel, sprintf '%s AS %s', $node->{sql}, $quoted_as;
129 push @out_sel, $quoted_as;
130 $renamed{$node->{sql}} = $quoted_as;
81446c4f 131 }
132 else {
a54bd479 133 push @in_sel, $node->{sql};
134 push @out_sel, $self->_quote ($node->{as});
81446c4f 135 }
136 }
137
75f025cf 138 # see if the order gives us anything
a54bd479 139 my %extra_order_sel;
75f025cf 140 for my $chunk ($self->_order_by_chunks ($rs_attrs->{order_by})) {
141 # order with bind
142 $chunk = $chunk->[0] if (ref $chunk) eq 'ARRAY';
143 $chunk =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
a54bd479 144
75f025cf 145 next if $in_sel_index->{$chunk};
a54bd479 146
75f025cf 147 $extra_order_sel{$chunk} ||= $self->_quote (
148 'ORDER__BY__' . scalar keys %extra_order_sel
149 );
a54bd479 150 }
75f025cf 151
a54bd479 152 return (
153 (map { join (', ', @$_ ) } (
154 \@in_sel,
155 \@out_sel)
156 ),
157 \%renamed,
158 keys %extra_order_sel ? \%extra_order_sel : (),
159 );
81446c4f 160}
161
a54bd479 162# ANSI standard Limit/Offset implementation. DB2 and MSSQL >= 2005 use this
6f4ddea1 163sub _RowNumberOver {
a6b68a60 164 my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
6f4ddea1 165
81446c4f 166 # mangle the input sql as we will be replacing the selector
167 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
cb478051 168 or croak "Unrecognizable SELECT: $sql";
169
a54bd479 170 # get selectors, and scan the order_by (if any)
75f025cf 171 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
172 = $self->_subqueried_limit_attrs ( $rs_attrs );
81446c4f 173
a6b68a60 174 # make up an order if none exists
a54bd479 175 my $requested_order = (delete $rs_attrs->{order_by}) || $self->_rno_default_order;
176 my $rno_ord = $self->_order_by ($requested_order);
177
178 # this is the order supplement magic
179 my $mid_sel = $out_sel;
180 if ($extra_order_sel) {
20f44a33 181 for my $extra_col (sort
182 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
183 keys %$extra_order_sel
184 ) {
a54bd479 185 $in_sel .= sprintf (', %s AS %s',
186 $extra_col,
187 $extra_order_sel->{$extra_col},
188 );
189
190 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
191 }
192 }
193
194 # and this is order re-alias magic
195 for ($extra_order_sel, $alias_map) {
196 for my $col (keys %$_) {
197 my $re_col = quotemeta ($col);
198 $rno_ord =~ s/$re_col/$_->{$col}/;
199 }
200 }
6f4ddea1 201
81446c4f 202 # whatever is left of the order_by (only where is processed at this point)
a6b68a60 203 my $group_having = $self->_parse_rs_attrs($rs_attrs);
6f4ddea1 204
a6b68a60 205 my $qalias = $self->_quote ($rs_attrs->{alias});
81446c4f 206 my $idx_name = $self->_quote ('rno__row__index');
207
cb478051 208 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
6f4ddea1 209
a54bd479 210SELECT $out_sel FROM (
211 SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM (
212 SELECT $in_sel ${sql}${group_having}
cb478051 213 ) $qalias
75f025cf 214) $qalias WHERE $idx_name BETWEEN %u AND %u
6553ac38 215
216EOS
217
218 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
6f4ddea1 219 return $sql;
220}
221
84ddb3da 222# some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
223sub _rno_default_order {
224 return undef;
225}
226
193590c2 227# Informix specific limit, almost like LIMIT/OFFSET
228sub _SkipFirst {
a6b68a60 229 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
193590c2 230
231 $sql =~ s/^ \s* SELECT \s+ //ix
232 or croak "Unrecognizable SELECT: $sql";
233
234 return sprintf ('SELECT %s%s%s%s',
235 $offset
75f025cf 236 ? sprintf ('SKIP %u ', $offset)
193590c2 237 : ''
238 ,
75f025cf 239 sprintf ('FIRST %u ', $rows),
193590c2 240 $sql,
a6b68a60 241 $self->_parse_rs_attrs ($rs_attrs),
193590c2 242 );
243}
244
145b2a3d 245# Firebird specific limit, reverse of _SkipFirst for Informix
246sub _FirstSkip {
a6b68a60 247 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
145b2a3d 248
249 $sql =~ s/^ \s* SELECT \s+ //ix
250 or croak "Unrecognizable SELECT: $sql";
251
252 return sprintf ('SELECT %s%s%s%s',
75f025cf 253 sprintf ('FIRST %u ', $rows),
145b2a3d 254 $offset
75f025cf 255 ? sprintf ('SKIP %u ', $offset)
145b2a3d 256 : ''
257 ,
258 $sql,
a6b68a60 259 $self->_parse_rs_attrs ($rs_attrs),
145b2a3d 260 );
261}
262
81446c4f 263# WhOracle limits
264sub _RowNum {
265 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
266
267 # mangle the input sql as we will be replacing the selector
268 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
269 or croak "Unrecognizable SELECT: $sql";
270
a54bd479 271 my ($insel, $outsel) = $self->_subqueried_limit_attrs ($rs_attrs);
81446c4f 272
273 my $qalias = $self->_quote ($rs_attrs->{alias});
274 my $idx_name = $self->_quote ('rownum__index');
275 my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
276
277 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
278
279SELECT $outsel FROM (
280 SELECT $outsel, ROWNUM $idx_name FROM (
281 SELECT $insel ${sql}${order_group_having}
282 ) $qalias
75f025cf 283) $qalias WHERE $idx_name BETWEEN %u AND %u
81446c4f 284
285EOS
286
287 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
288 return $sql;
289}
290
a54bd479 291# Crappy Top based Limit/Offset support. Legacy for MSSQL < 2005
15827712 292sub _Top {
a6b68a60 293 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
15827712 294
81446c4f 295 # mangle the input sql as we will be replacing the selector
296 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
b1e1d073 297 or croak "Unrecognizable SELECT: $sql";
b1e1d073 298
81446c4f 299 # get selectors
a54bd479 300 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
75f025cf 301 = $self->_subqueried_limit_attrs ($rs_attrs);
81446c4f 302
a54bd479 303 my $requested_order = delete $rs_attrs->{order_by};
81446c4f 304
a54bd479 305 my $order_by_requested = $self->_order_by ($requested_order);
306
307 # make up an order unless supplied
308 my $inner_order = ($order_by_requested
309 ? $requested_order
81446c4f 310 : [ map
a54bd479 311 { join ('', $rs_attrs->{alias}, $self->{name_sep}||'.', $_ ) }
312 ( $rs_attrs->{_rsroot_source_handle}->resolve->_pri_cols )
81446c4f 313 ]
a54bd479 314 );
81446c4f 315
a54bd479 316 my ($order_by_inner, $order_by_reversed);
81446c4f 317
a54bd479 318 # localise as we already have all the bind values we need
319 {
320 local $self->{order_bind};
321 $order_by_inner = $self->_order_by ($inner_order);
ac93965c 322
a54bd479 323 my @out_chunks;
324 for my $ch ($self->_order_by_chunks ($inner_order)) {
325 $ch = $ch->[0] if ref $ch eq 'ARRAY';
20f44a33 326
a54bd479 327 $ch =~ s/\s+ ( ASC|DESC ) \s* $//ix;
328 my $dir = uc ($1||'ASC');
b1e1d073 329
a54bd479 330 push @out_chunks, \join (' ', $ch, $dir eq 'ASC' ? 'DESC' : 'ASC' );
331 }
b1e1d073 332
20f44a33 333 $order_by_reversed = $self->_order_by (\@out_chunks);
42e5b103 334 }
b1e1d073 335
a54bd479 336 # this is the order supplement magic
337 my $mid_sel = $out_sel;
338 if ($extra_order_sel) {
20f44a33 339 for my $extra_col (sort
340 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
341 keys %$extra_order_sel
342 ) {
a54bd479 343 $in_sel .= sprintf (', %s AS %s',
344 $extra_col,
345 $extra_order_sel->{$extra_col},
42e5b103 346 );
b1e1d073 347
a54bd479 348 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
42e5b103 349 }
25abda27 350
351 # since whatever order bindvals there are, they will be realiased
352 # and need to show up in front of the entire initial inner subquery
353 # Unshift *from_bind* to make this happen (horrible, horrible, but
354 # we don't have another mechanism yet)
355 unshift @{$self->{from_bind}}, @{$self->{order_bind}};
b1e1d073 356 }
357
a54bd479 358 # and this is order re-alias magic
359 for my $map ($extra_order_sel, $alias_map) {
360 for my $col (keys %$map) {
361 my $re_col = quotemeta ($col);
362 $_ =~ s/$re_col/$map->{$col}/
363 for ($order_by_reversed, $order_by_requested);
b1e1d073 364 }
365 }
15827712 366
a54bd479 367 # generate the rest of the sql
368 my $grpby_having = $self->_parse_rs_attrs ($rs_attrs);
15827712 369
a54bd479 370 my $quoted_rs_alias = $self->_quote ($rs_attrs->{alias});
b1e1d073 371
75f025cf 372 $sql = sprintf ('SELECT TOP %u %s %s %s %s',
a54bd479 373 $rows + ($offset||0),
374 $in_sel,
375 $sql,
376 $grpby_having,
377 $order_by_inner,
378 );
15827712 379
75f025cf 380 $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
a54bd479 381 $rows,
382 $mid_sel,
383 $sql,
384 $quoted_rs_alias,
385 $order_by_reversed,
386 ) if $offset;
15827712 387
75f025cf 388 $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
a54bd479 389 $rows,
a54bd479 390 $out_sel,
391 $sql,
392 $quoted_rs_alias,
20f44a33 393 $order_by_requested,
76fc0d71 394 ) if ( ($offset && $order_by_requested) || ($mid_sel ne $out_sel) );
b1e1d073 395
75f025cf 396 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
397 return $sql;
398}
399
3f528319 400# This for Sybase ASE, to use SET ROWCOUNT when there is no offset, and
401# GenericSubQ otherwise.
402sub _RowCountOrGenericSubQ {
403 my $self = shift;
404 my ($sql, $rs_attrs, $rows, $offset) = @_;
405
406 return $self->_GenericSubQ(@_) if $offset;
407
408 return sprintf <<"EOF", $rows, $sql;
409SET ROWCOUNT %d
410%s
411SET ROWCOUNT 0
412EOF
413}
414
75f025cf 415# This is the most evil limit "dialect" (more of a hack) for *really*
416# stupid databases. It works by ordering the set by some unique column,
417# and calculating amount of rows that have a less-er value (thus
418# emulating a RowNum-like index). Of course this implies the set can
419# only be ordered by a single unique columns.
420sub _GenericSubQ {
421 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
422
423 my $root_rsrc = $rs_attrs->{_rsroot_source_handle}->resolve;
424 my $root_tbl_name = $root_rsrc->name;
425
426 # mangle the input sql as we will be replacing the selector
427 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
428 or croak "Unrecognizable SELECT: $sql";
429
430 my ($order_by, @rest) = do {
431 local $self->{quote_char};
432 $self->_order_by_chunks ($rs_attrs->{order_by})
433 };
434
435 unless (
436 $order_by
437 &&
438 ! @rest
439 &&
440 ( ! ref $order_by
441 ||
442 ( ref $order_by eq 'ARRAY' and @$order_by == 1 )
443 )
444 ) {
445 croak (
446 'Generic Subquery Limit does not work on resultsets without an order, or resultsets '
447 . 'with complex order criteria (multicolumn and/or functions). Provide a single, '
448 . 'unique-column order criteria.'
449 );
450 }
451
452 ($order_by) = @$order_by if ref $order_by;
453
454 $order_by =~ s/\s+ ( ASC|DESC ) \s* $//ix;
455 my $direction = lc ($1 || 'asc');
456
457 my ($unq_sort_col) = $order_by =~ /(?:^|\.)([^\.]+)$/;
458
459 my $inf = $root_rsrc->storage->_resolve_column_info (
460 $rs_attrs->{from}, [$order_by, $unq_sort_col]
461 );
462
463 my $ord_colinfo = $inf->{$order_by} || croak "Unable to determine source of order-criteria '$order_by'";
464
465 if ($ord_colinfo->{-result_source}->name ne $root_tbl_name) {
466 croak "Generic Subquery Limit order criteria can be only based on the root-source '"
467 . $root_rsrc->source_name . "' (aliased as '$rs_attrs->{alias}')";
468 }
469
470 # make sure order column is qualified
471 $order_by = "$rs_attrs->{alias}.$order_by"
472 unless $order_by =~ /^$rs_attrs->{alias}\./;
473
474 my $is_u;
475 my $ucs = { $root_rsrc->unique_constraints };
476 for (values %$ucs ) {
477 if (@$_ == 1 && "$rs_attrs->{alias}.$_->[0]" eq $order_by) {
478 $is_u++;
479 last;
480 }
481 }
482 croak "Generic Subquery Limit order criteria column '$order_by' must be unique (no unique constraint found)"
483 unless $is_u;
484
485 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
486 = $self->_subqueried_limit_attrs ($rs_attrs);
487
488 my $cmp_op = $direction eq 'desc' ? '>' : '<';
489 my $count_tbl_alias = 'rownum__emulation';
490
b13d2248 491 my $order_sql = $self->_order_by (delete $rs_attrs->{order_by});
492 my $group_having_sql = $self->_parse_rs_attrs($rs_attrs);
75f025cf 493
494 # add the order supplement (if any) as this is what will be used for the outer WHERE
495 $in_sel .= ", $_" for keys %{$extra_order_sel||{}};
496
497 $sql = sprintf (<<EOS,
498SELECT $out_sel
499 FROM (
b13d2248 500 SELECT $in_sel ${sql}${group_having_sql}
75f025cf 501 ) %s
502WHERE ( SELECT COUNT(*) FROM %s %s WHERE %s $cmp_op %s ) %s
b13d2248 503$order_sql
75f025cf 504EOS
505 ( map { $self->_quote ($_) } (
506 $rs_attrs->{alias},
507 $root_tbl_name,
508 $count_tbl_alias,
509 "$count_tbl_alias.$unq_sort_col",
510 $order_by,
511 )),
512 $offset
513 ? sprintf ('BETWEEN %u AND %u', $offset, $offset + $rows - 1)
514 : sprintf ('< %u', $rows )
515 ,
516 );
517
518 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
b1e1d073 519 return $sql;
15827712 520}
a54bd479 521
6f4ddea1 522
523# While we're at it, this should make LIMIT queries more efficient,
524# without digging into things too deeply
6f4ddea1 525sub _find_syntax {
526 my ($self, $syntax) = @_;
ac788c46 527 return $self->{_cached_syntax} ||= $self->SUPER::_find_syntax($syntax);
6f4ddea1 528}
529
998373c2 530# Quotes table names, handles "limit" dialects (e.g. where rownum between x and
a6b68a60 531# y)
6f4ddea1 532sub select {
a6b68a60 533 my ($self, $table, $fields, $where, $rs_attrs, @rest) = @_;
1cbd3034 534
c2b7c5dc 535 if (not ref($table) or ref($table) eq 'SCALAR') {
6f4ddea1 536 $table = $self->_quote($table);
537 }
c2b7c5dc 538
6f4ddea1 539 @rest = (-1) unless defined $rest[0];
e8fcf76f 540 croak "LIMIT 0 Does Not Compute" if $rest[0] == 0;
6f4ddea1 541 # and anyway, SQL::Abstract::Limit will cause a barf if we don't first
a6b68a60 542
49afd714 543 my ($sql, @bind) = $self->SUPER::select(
a6b68a60 544 $table, $self->_recurse_fields($fields), $where, $rs_attrs, @rest
6f4ddea1 545 );
49afd714 546 push @{$self->{where_bind}}, @bind;
583a0c65 547
548# this *must* be called, otherwise extra binds will remain in the sql-maker
49afd714 549 my @all_bind = $self->_assemble_binds;
583a0c65 550
49afd714 551 return wantarray ? ($sql, @all_bind) : $sql;
583a0c65 552}
553
554sub _assemble_binds {
555 my $self = shift;
556 return map { @{ (delete $self->{"${_}_bind"}) || [] } } (qw/from where having order/);
6f4ddea1 557}
558
998373c2 559# Quotes table names, and handles default inserts
6f4ddea1 560sub insert {
561 my $self = shift;
562 my $table = shift;
c2b7c5dc 563 $table = $self->_quote($table);
7a72e5a5 564
565 # SQLA will emit INSERT INTO $table ( ) VALUES ( )
566 # which is sadly understood only by MySQL. Change default behavior here,
567 # until SQLA2 comes with proper dialect support
568 if (! $_[0] or (ref $_[0] eq 'HASH' and !keys %{$_[0]} ) ) {
28d28903 569 my $sql = "INSERT INTO ${table} DEFAULT VALUES";
570
ef8d02eb 571 if (my $ret = ($_[1]||{})->{returning} ) {
572 $sql .= $self->_insert_returning ($ret);
28d28903 573 }
574
575 return $sql;
7a72e5a5 576 }
577
6f4ddea1 578 $self->SUPER::insert($table, @_);
579}
580
998373c2 581# Just quotes table names.
6f4ddea1 582sub update {
583 my $self = shift;
584 my $table = shift;
c2b7c5dc 585 $table = $self->_quote($table);
6f4ddea1 586 $self->SUPER::update($table, @_);
587}
588
998373c2 589# Just quotes table names.
6f4ddea1 590sub delete {
591 my $self = shift;
592 my $table = shift;
c2b7c5dc 593 $table = $self->_quote($table);
6f4ddea1 594 $self->SUPER::delete($table, @_);
595}
596
597sub _emulate_limit {
598 my $self = shift;
a6b68a60 599 # my ( $syntax, $sql, $order, $rows, $offset ) = @_;
600
6f4ddea1 601 if ($_[3] == -1) {
a6b68a60 602 return $_[1] . $self->_parse_rs_attrs($_[2]);
6f4ddea1 603 } else {
604 return $self->SUPER::_emulate_limit(@_);
605 }
606}
607
608sub _recurse_fields {
81446c4f 609 my ($self, $fields) = @_;
6f4ddea1 610 my $ref = ref $fields;
611 return $self->_quote($fields) unless $ref;
612 return $$fields if $ref eq 'SCALAR';
613
614 if ($ref eq 'ARRAY') {
81446c4f 615 return join(', ', map { $self->_recurse_fields($_) } @$fields);
83e09b5b 616 }
617 elsif ($ref eq 'HASH') {
81446c4f 618 my %hash = %$fields; # shallow copy
83e09b5b 619
50136dd9 620 my $as = delete $hash{-as}; # if supplied
621
81446c4f 622 my ($func, $args, @toomany) = %hash;
623
624 # there should be only one pair
625 if (@toomany) {
626 croak "Malformed select argument - too many keys in hash: " . join (',', keys %$fields );
627 }
50136dd9 628
629 if (lc ($func) eq 'distinct' && ref $args eq 'ARRAY' && @$args > 1) {
630 croak (
631 'The select => { distinct => ... } syntax is not supported for multiple columns.'
632 .' Instead please use { group_by => [ qw/' . (join ' ', @$args) . '/ ] }'
633 .' or { select => [ qw/' . (join ' ', @$args) . '/ ], distinct => 1 }'
83e09b5b 634 );
6f4ddea1 635 }
83e09b5b 636
50136dd9 637 my $select = sprintf ('%s( %s )%s',
638 $self->_sqlcase($func),
639 $self->_recurse_fields($args),
640 $as
0491b597 641 ? sprintf (' %s %s', $self->_sqlcase('as'), $self->_quote ($as) )
50136dd9 642 : ''
643 );
644
83e09b5b 645 return $select;
6f4ddea1 646 }
647 # Is the second check absolutely necessary?
648 elsif ( $ref eq 'REF' and ref($$fields) eq 'ARRAY' ) {
db56cf3d 649 return $self->_fold_sqlbind( $fields );
6f4ddea1 650 }
651 else {
e8fcf76f 652 croak($ref . qq{ unexpected in _recurse_fields()})
6f4ddea1 653 }
654}
655
a6b68a60 656my $for_syntax = {
657 update => 'FOR UPDATE',
658 shared => 'FOR SHARE',
659};
660
661# this used to be a part of _order_by but is broken out for clarity.
662# What we have been doing forever is hijacking the $order arg of
663# SQLA::select to pass in arbitrary pieces of data (first the group_by,
664# then pretty much the entire resultset attr-hash, as more and more
665# things in the SQLA space need to have mopre info about the $rs they
666# create SQL for. The alternative would be to keep expanding the
667# signature of _select with more and more positional parameters, which
668# is just gross. All hail SQLA2!
669sub _parse_rs_attrs {
1cbd3034 670 my ($self, $arg) = @_;
15827712 671
a6b68a60 672 my $sql = '';
1cbd3034 673
b03f30a3 674 if (my $g = $self->_recurse_fields($arg->{group_by}) ) {
a6b68a60 675 $sql .= $self->_sqlcase(' group by ') . $g;
676 }
1cbd3034 677
a6b68a60 678 if (defined $arg->{having}) {
679 my ($frag, @bind) = $self->_recurse_where($arg->{having});
680 push(@{$self->{having_bind}}, @bind);
681 $sql .= $self->_sqlcase(' having ') . $frag;
682 }
15827712 683
a6b68a60 684 if (defined $arg->{order_by}) {
685 $sql .= $self->_order_by ($arg->{order_by});
686 }
15827712 687
a6b68a60 688 if (my $for = $arg->{for}) {
689 $sql .= " $for_syntax->{$for}" if $for_syntax->{$for};
690 }
691
692 return $sql;
693}
694
695sub _order_by {
696 my ($self, $arg) = @_;
15827712 697
a6b68a60 698 # check that we are not called in legacy mode (order_by as 4th argument)
699 if (ref $arg eq 'HASH' and not grep { $_ =~ /^-(?:desc|asc)/i } keys %$arg ) {
700 return $self->_parse_rs_attrs ($arg);
fde3719a 701 }
1cbd3034 702 else {
703 my ($sql, @bind) = $self->SUPER::_order_by ($arg);
a6b68a60 704 push @{$self->{order_bind}}, @bind;
1cbd3034 705 return $sql;
fd4cb60a 706 }
6f4ddea1 707}
708
1cbd3034 709sub _order_directions {
fd4cb60a 710 my ($self, $order) = @_;
15827712 711
1cbd3034 712 # strip bind values - none of the current _order_directions users support them
713 return $self->SUPER::_order_directions( [ map
714 { ref $_ ? $_->[0] : $_ }
715 $self->_order_by_chunks ($order)
716 ]);
fd4cb60a 717}
718
6f4ddea1 719sub _table {
720 my ($self, $from) = @_;
721 if (ref $from eq 'ARRAY') {
722 return $self->_recurse_from(@$from);
723 } elsif (ref $from eq 'HASH') {
724 return $self->_make_as($from);
725 } else {
726 return $from; # would love to quote here but _table ends up getting called
727 # twice during an ->select without a limit clause due to
728 # the way S::A::Limit->select works. should maybe consider
729 # bypassing this and doing S::A::select($self, ...) in
730 # our select method above. meantime, quoting shims have
731 # been added to select/insert/update/delete here
732 }
733}
734
b8391c87 735sub _generate_join_clause {
736 my ($self, $join_type) = @_;
737
738 return sprintf ('%s JOIN ',
739 $join_type ? ' ' . uc($join_type) : ''
740 );
741}
742
6f4ddea1 743sub _recurse_from {
744 my ($self, $from, @join) = @_;
745 my @sqlf;
746 push(@sqlf, $self->_make_as($from));
747 foreach my $j (@join) {
748 my ($to, $on) = @$j;
749
aa82ce29 750
6f4ddea1 751 # check whether a join type exists
6f4ddea1 752 my $to_jt = ref($to) eq 'ARRAY' ? $to->[0] : $to;
aa82ce29 753 my $join_type;
754 if (ref($to_jt) eq 'HASH' and defined($to_jt->{-join_type})) {
755 $join_type = $to_jt->{-join_type};
756 $join_type =~ s/^\s+ | \s+$//xg;
6f4ddea1 757 }
aa82ce29 758
de5f71ef 759 $join_type = $self->{_default_jointype} if not defined $join_type;
aa82ce29 760
b8391c87 761 push @sqlf, $self->_generate_join_clause( $join_type );
6f4ddea1 762
763 if (ref $to eq 'ARRAY') {
764 push(@sqlf, '(', $self->_recurse_from(@$to), ')');
765 } else {
766 push(@sqlf, $self->_make_as($to));
767 }
768 push(@sqlf, ' ON ', $self->_join_condition($on));
769 }
770 return join('', @sqlf);
771}
772
db56cf3d 773sub _fold_sqlbind {
774 my ($self, $sqlbind) = @_;
69989ea9 775
776 my @sqlbind = @$$sqlbind; # copy
777 my $sql = shift @sqlbind;
778 push @{$self->{from_bind}}, @sqlbind;
779
db56cf3d 780 return $sql;
6f4ddea1 781}
782
783sub _make_as {
784 my ($self, $from) = @_;
db56cf3d 785 return join(' ', map { (ref $_ eq 'SCALAR' ? $$_
786 : ref $_ eq 'REF' ? $self->_fold_sqlbind($_)
787 : $self->_quote($_))
6f4ddea1 788 } reverse each %{$self->_skip_options($from)});
789}
790
791sub _skip_options {
792 my ($self, $hash) = @_;
793 my $clean_hash = {};
794 $clean_hash->{$_} = $hash->{$_}
795 for grep {!/^-/} keys %$hash;
796 return $clean_hash;
797}
798
799sub _join_condition {
800 my ($self, $cond) = @_;
801 if (ref $cond eq 'HASH') {
802 my %j;
803 for (keys %$cond) {
804 my $v = $cond->{$_};
805 if (ref $v) {
e8fcf76f 806 croak (ref($v) . qq{ reference arguments are not supported in JOINS - try using \"..." instead'})
6f4ddea1 807 if ref($v) ne 'SCALAR';
808 $j{$_} = $v;
809 }
810 else {
811 my $x = '= '.$self->_quote($v); $j{$_} = \$x;
812 }
813 };
814 return scalar($self->_recurse_where(\%j));
815 } elsif (ref $cond eq 'ARRAY') {
816 return join(' OR ', map { $self->_join_condition($_) } @$cond);
817 } else {
818 die "Can't handle this yet!";
819 }
820}
821
6f4ddea1 822sub limit_dialect {
823 my $self = shift;
b2c7cf74 824 if (@_) {
825 $self->{limit_dialect} = shift;
826 undef $self->{_cached_syntax};
827 }
6f4ddea1 828 return $self->{limit_dialect};
829}
830
998373c2 831# Set to an array-ref to specify separate left and right quotes for table names.
832# A single scalar is equivalen to [ $char, $char ]
6f4ddea1 833sub quote_char {
834 my $self = shift;
835 $self->{quote_char} = shift if @_;
836 return $self->{quote_char};
837}
838
998373c2 839# Character separating quoted table names.
6f4ddea1 840sub name_sep {
841 my $self = shift;
842 $self->{name_sep} = shift if @_;
843 return $self->{name_sep};
844}
845
8461;