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