1 package DBIx::Class::SQLAHacks::LimitDialects;
6 use Carp::Clan qw/^DBIx::Class|^SQL::Abstract|^Try::Tiny/;
7 use List::Util 'first';
10 # PostgreSQL and SQLite
12 my ( $self, $sql, $order, $rows, $offset ) = @_;
13 $sql .= $self->_order_by( $order ) . " LIMIT $rows";
14 $sql .= " OFFSET $offset" if +$offset;
18 # MySQL and any SQL::Statement based DBD
20 my ( $self, $sql, $order, $rows, $offset ) = @_;
21 $sql .= $self->_order_by( $order ) . " LIMIT ";
22 $sql .= "$offset, " if +$offset;
26 # ANSI standard Limit/Offset implementation. DB2 and MSSQL >= 2005 use this
28 my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;
30 # mangle the input sql as we will be replacing the selector
31 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
32 or croak "Unrecognizable SELECT: $sql";
34 # get selectors, and scan the order_by (if any)
35 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
36 = $self->_subqueried_limit_attrs ( $rs_attrs );
38 # make up an order if none exists
39 my $requested_order = (delete $rs_attrs->{order_by}) || $self->_rno_default_order;
40 my $rno_ord = $self->_order_by ($requested_order);
42 # this is the order supplement magic
43 my $mid_sel = $out_sel;
44 if ($extra_order_sel) {
45 for my $extra_col (sort
46 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
47 keys %$extra_order_sel
49 $in_sel .= sprintf (', %s AS %s',
51 $extra_order_sel->{$extra_col},
54 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
58 # and this is order re-alias magic
59 for ($extra_order_sel, $alias_map) {
60 for my $col (keys %$_) {
61 my $re_col = quotemeta ($col);
62 $rno_ord =~ s/$re_col/$_->{$col}/;
66 # whatever is left of the order_by (only where is processed at this point)
67 my $group_having = $self->_parse_rs_attrs($rs_attrs);
69 my $qalias = $self->_quote ($rs_attrs->{alias});
70 my $idx_name = $self->_quote ('rno__row__index');
72 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
74 SELECT $out_sel FROM (
75 SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM (
76 SELECT $in_sel ${sql}${group_having}
78 ) $qalias WHERE $idx_name BETWEEN %u AND %u
82 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
86 # some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
87 sub _rno_default_order {
91 # Informix specific limit, almost like LIMIT/OFFSET
92 # According to SQLA::Limit informix also supports
93 # SKIP X LIMIT Y (in addition to SKIP X FIRST Y)
95 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
97 $sql =~ s/^ \s* SELECT \s+ //ix
98 or croak "Unrecognizable SELECT: $sql";
100 return sprintf ('SELECT %s%s%s%s',
102 ? sprintf ('SKIP %u ', $offset)
105 sprintf ('FIRST %u ', $rows),
107 $self->_parse_rs_attrs ($rs_attrs),
111 # Firebird specific limit, reverse of _SkipFirst for Informix
112 # According to SQLA::Limit firebird/interbase also supports
113 # ROWS X TO Y (in addition to FIRST X SKIP Y)
115 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
117 $sql =~ s/^ \s* SELECT \s+ //ix
118 or croak "Unrecognizable SELECT: $sql";
120 return sprintf ('SELECT %s%s%s%s',
121 sprintf ('FIRST %u ', $rows),
123 ? sprintf ('SKIP %u ', $offset)
127 $self->_parse_rs_attrs ($rs_attrs),
133 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
135 # mangle the input sql as we will be replacing the selector
136 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
137 or croak "Unrecognizable SELECT: $sql";
139 my ($insel, $outsel) = $self->_subqueried_limit_attrs ($rs_attrs);
141 my $qalias = $self->_quote ($rs_attrs->{alias});
142 my $idx_name = $self->_quote ('rownum__index');
143 my $order_group_having = $self->_parse_rs_attrs($rs_attrs);
145 $sql = sprintf (<<EOS, $offset + 1, $offset + $rows, );
147 SELECT $outsel FROM (
148 SELECT $outsel, ROWNUM $idx_name FROM (
149 SELECT $insel ${sql}${order_group_having}
151 ) $qalias WHERE $idx_name BETWEEN %u AND %u
155 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
159 # Crappy Top based Limit/Offset support. Legacy for MSSQL < 2005
161 my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
163 # mangle the input sql as we will be replacing the selector
164 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
165 or croak "Unrecognizable SELECT: $sql";
168 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
169 = $self->_subqueried_limit_attrs ($rs_attrs);
171 my $requested_order = delete $rs_attrs->{order_by};
173 my $order_by_requested = $self->_order_by ($requested_order);
175 # make up an order unless supplied
176 my $inner_order = ($order_by_requested
179 { join ('', $rs_attrs->{alias}, $self->{name_sep}||'.', $_ ) }
180 ( $rs_attrs->{_rsroot_source_handle}->resolve->_pri_cols )
184 my ($order_by_inner, $order_by_reversed);
186 # localise as we already have all the bind values we need
188 local $self->{order_bind};
189 $order_by_inner = $self->_order_by ($inner_order);
192 for my $ch ($self->_order_by_chunks ($inner_order)) {
193 $ch = $ch->[0] if ref $ch eq 'ARRAY';
195 $ch =~ s/\s+ ( ASC|DESC ) \s* $//ix;
196 my $dir = uc ($1||'ASC');
198 push @out_chunks, \join (' ', $ch, $dir eq 'ASC' ? 'DESC' : 'ASC' );
201 $order_by_reversed = $self->_order_by (\@out_chunks);
204 # this is the order supplement magic
205 my $mid_sel = $out_sel;
206 if ($extra_order_sel) {
207 for my $extra_col (sort
208 { $extra_order_sel->{$a} cmp $extra_order_sel->{$b} }
209 keys %$extra_order_sel
211 $in_sel .= sprintf (', %s AS %s',
213 $extra_order_sel->{$extra_col},
216 $mid_sel .= ', ' . $extra_order_sel->{$extra_col};
219 # since whatever order bindvals there are, they will be realiased
220 # and need to show up in front of the entire initial inner subquery
221 # Unshift *from_bind* to make this happen (horrible, horrible, but
222 # we don't have another mechanism yet)
223 unshift @{$self->{from_bind}}, @{$self->{order_bind}};
226 # and this is order re-alias magic
227 for my $map ($extra_order_sel, $alias_map) {
228 for my $col (keys %$map) {
229 my $re_col = quotemeta ($col);
230 $_ =~ s/$re_col/$map->{$col}/
231 for ($order_by_reversed, $order_by_requested);
235 # generate the rest of the sql
236 my $grpby_having = $self->_parse_rs_attrs ($rs_attrs);
238 my $quoted_rs_alias = $self->_quote ($rs_attrs->{alias});
240 $sql = sprintf ('SELECT TOP %u %s %s %s %s',
241 $rows + ($offset||0),
248 $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
256 $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
262 ) if ( ($offset && $order_by_requested) || ($mid_sel ne $out_sel) );
264 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
268 # This for Sybase ASE, to use SET ROWCOUNT when there is no offset, and
269 # GenericSubQ otherwise.
270 sub _RowCountOrGenericSubQ {
272 my ($sql, $rs_attrs, $rows, $offset) = @_;
274 return $self->_GenericSubQ(@_) if $offset;
276 return sprintf <<"EOF", $rows, $sql;
283 # This is the most evil limit "dialect" (more of a hack) for *really*
284 # stupid databases. It works by ordering the set by some unique column,
285 # and calculating amount of rows that have a less-er value (thus
286 # emulating a RowNum-like index). Of course this implies the set can
287 # only be ordered by a single unique columns.
289 my ($self, $sql, $rs_attrs, $rows, $offset) = @_;
291 my $root_rsrc = $rs_attrs->{_rsroot_source_handle}->resolve;
292 my $root_tbl_name = $root_rsrc->name;
294 # mangle the input sql as we will be replacing the selector
295 $sql =~ s/^ \s* SELECT \s+ .+? \s+ (?= \b FROM \b )//ix
296 or croak "Unrecognizable SELECT: $sql";
298 my ($order_by, @rest) = do {
299 local $self->{quote_char};
300 $self->_order_by_chunks ($rs_attrs->{order_by})
310 ( ref $order_by eq 'ARRAY' and @$order_by == 1 )
314 'Generic Subquery Limit does not work on resultsets without an order, or resultsets '
315 . 'with complex order criteria (multicolumn and/or functions). Provide a single, '
316 . 'unique-column order criteria.'
320 ($order_by) = @$order_by if ref $order_by;
322 $order_by =~ s/\s+ ( ASC|DESC ) \s* $//ix;
323 my $direction = lc ($1 || 'asc');
325 my ($unq_sort_col) = $order_by =~ /(?:^|\.)([^\.]+)$/;
327 my $inf = $root_rsrc->storage->_resolve_column_info (
328 $rs_attrs->{from}, [$order_by, $unq_sort_col]
331 my $ord_colinfo = $inf->{$order_by} || croak "Unable to determine source of order-criteria '$order_by'";
333 if ($ord_colinfo->{-result_source}->name ne $root_tbl_name) {
334 croak "Generic Subquery Limit order criteria can be only based on the root-source '"
335 . $root_rsrc->source_name . "' (aliased as '$rs_attrs->{alias}')";
338 # make sure order column is qualified
339 $order_by = "$rs_attrs->{alias}.$order_by"
340 unless $order_by =~ /^$rs_attrs->{alias}\./;
343 my $ucs = { $root_rsrc->unique_constraints };
344 for (values %$ucs ) {
345 if (@$_ == 1 && "$rs_attrs->{alias}.$_->[0]" eq $order_by) {
350 croak "Generic Subquery Limit order criteria column '$order_by' must be unique (no unique constraint found)"
353 my ($in_sel, $out_sel, $alias_map, $extra_order_sel)
354 = $self->_subqueried_limit_attrs ($rs_attrs);
356 my $cmp_op = $direction eq 'desc' ? '>' : '<';
357 my $count_tbl_alias = 'rownum__emulation';
359 my $order_sql = $self->_order_by (delete $rs_attrs->{order_by});
360 my $group_having_sql = $self->_parse_rs_attrs($rs_attrs);
362 # add the order supplement (if any) as this is what will be used for the outer WHERE
363 $in_sel .= ", $_" for keys %{$extra_order_sel||{}};
365 $sql = sprintf (<<EOS,
368 SELECT $in_sel ${sql}${group_having_sql}
370 WHERE ( SELECT COUNT(*) FROM %s %s WHERE %s $cmp_op %s ) %s
373 ( map { $self->_quote ($_) } (
377 "$count_tbl_alias.$unq_sort_col",
381 ? sprintf ('BETWEEN %u AND %u', $offset, $offset + $rows - 1)
382 : sprintf ('< %u', $rows )
386 $sql =~ s/\s*\n\s*/ /g; # easier to read in the debugger
391 # !!! THIS IS ALSO HORRIFIC !!! /me ashamed
393 # Generates inner/outer select lists for various limit dialects
394 # which result in one or more subqueries (e.g. RNO, Top, RowNum)
395 # Any non-root-table columns need to have their table qualifier
396 # turned into a column alias (otherwise names in subqueries clash
397 # and/or lose their source table)
399 # Returns inner/outer strings of SQL QUOTED selectors with aliases
400 # (to be used in whatever select statement), and an alias index hashref
401 # of QUOTED SEL => QUOTED ALIAS pairs (to maybe be used for string-subst
403 # If an order_by is supplied, the inner select needs to bring out columns
404 # used in implicit (non-selected) orders, and the order condition itself
405 # needs to be realiased to the proper names in the outer query. Thus we
406 # also return a hashref (order doesn't matter) of QUOTED EXTRA-SEL =>
407 # QUOTED ALIAS pairs, which is a list of extra selectors that do *not*
408 # exist in the original select list
410 sub _subqueried_limit_attrs {
411 my ($self, $rs_attrs) = @_;
413 croak 'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)'
414 unless ref ($rs_attrs) eq 'HASH';
416 my ($re_sep, $re_alias) = map { quotemeta $_ } (
417 $self->name_sep || '.',
421 # correlate select and as, build selection index
422 my (@sel, $in_sel_index);
423 for my $i (0 .. $#{$rs_attrs->{select}}) {
425 my $s = $rs_attrs->{select}[$i];
426 my $sql_sel = $self->_recurse_fields ($s);
427 my $sql_alias = (ref $s) eq 'HASH' ? $s->{-as} : undef;
432 unquoted_sql => do { local $self->{quote_char}; $self->_recurse_fields ($s) },
438 croak "Select argument $i ($s) without corresponding 'as'"
442 $in_sel_index->{$sql_sel}++;
443 $in_sel_index->{$self->_quote ($sql_alias)}++ if $sql_alias;
445 # record unqualified versions too, so we do not have
446 # to reselect the same column twice (in qualified and
448 if (! ref $s && $sql_sel =~ / $re_sep (.+) $/x) {
449 $in_sel_index->{$1}++;
454 # re-alias and remove any name separators from aliases,
455 # unless we are dealing with the current source alias
456 # (which will transcend the subqueries as it is necessary
457 # for possible further chaining)
458 my (@in_sel, @out_sel, %renamed);
459 for my $node (@sel) {
460 if (first { $_ =~ / (?<! ^ $re_alias ) $re_sep /x } ($node->{as}, $node->{unquoted_sql}) ) {
461 $node->{as} = $self->_unqualify_colname($node->{as});
462 my $quoted_as = $self->_quote($node->{as});
463 push @in_sel, sprintf '%s AS %s', $node->{sql}, $quoted_as;
464 push @out_sel, $quoted_as;
465 $renamed{$node->{sql}} = $quoted_as;
468 push @in_sel, $node->{sql};
469 push @out_sel, $self->_quote ($node->{as});
473 # see if the order gives us anything
475 for my $chunk ($self->_order_by_chunks ($rs_attrs->{order_by})) {
477 $chunk = $chunk->[0] if (ref $chunk) eq 'ARRAY';
478 $chunk =~ s/\s+ (?: ASC|DESC ) \s* $//ix;
480 next if $in_sel_index->{$chunk};
482 $extra_order_sel{$chunk} ||= $self->_quote (
483 'ORDER__BY__' . scalar keys %extra_order_sel
488 (map { join (', ', @$_ ) } (
493 keys %extra_order_sel ? \%extra_order_sel : (),
497 sub _unqualify_colname {
498 my ($self, $fqcn) = @_;
499 my $re_sep = quotemeta($self->name_sep || '.');
500 $fqcn =~ s/ $re_sep /__/xg;