<html><head><meta name="color-scheme" content="light dark"></head><body><pre style="word-wrap: break-word; white-space: pre-wrap;">package DBIx::Class::SQLMaker::LimitDialects;

use warnings;
use strict;

use List::Util 'first';
use namespace::clean;

# constants are used not only here, but also in comparison tests
sub __rows_bindtype () {
  +{ sqlt_datatype =&gt; 'integer' }
}
sub __offset_bindtype () {
  +{ sqlt_datatype =&gt; 'integer' }
}
sub __total_bindtype () {
  +{ sqlt_datatype =&gt; 'integer' }
}

=head1 NAME

DBIx::Class::SQLMaker::LimitDialects - SQL::Abstract::Limit-like functionality for DBIx::Class::SQLMaker

=head1 DESCRIPTION

This module replicates a lot of the functionality originally found in
L&lt;SQL::Abstract::Limit&gt;. While simple limits would work as-is, the more
complex dialects that require e.g. subqueries could not be reliably
implemented without taking full advantage of the metadata locked within
L&lt;DBIx::Class::ResultSource&gt; classes. After reimplementation of close to
80% of the L&lt;SQL::Abstract::Limit&gt; functionality it was deemed more
practical to simply make an independent DBIx::Class-specific limit-dialect
provider.

=head1 SQL LIMIT DIALECTS

Note that the actual implementations listed below never use C&lt;*&gt; literally.
Instead proper re-aliasing of selectors and order criteria is done, so that
the limit dialect are safe to use on joined resultsets with clashing column
names.

Currently the provided dialects are:

=head2 LimitOffset

 SELECT ... LIMIT $limit OFFSET $offset

Supported by B&lt;PostgreSQL&gt; and B&lt;SQLite&gt;

=cut
sub _LimitOffset {
    my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
    $sql .= $self-&gt;_parse_rs_attrs( $rs_attrs ) . " LIMIT ?";
    push @{$self-&gt;{limit_bind}}, [ $self-&gt;__rows_bindtype =&gt; $rows ];
    if ($offset) {
      $sql .= " OFFSET ?";
      push @{$self-&gt;{limit_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset ];
    }
    return $sql;
}

=head2 LimitXY

 SELECT ... LIMIT $offset $limit

Supported by B&lt;MySQL&gt; and any L&lt;SQL::Statement&gt; based DBD

=cut
sub _LimitXY {
    my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;
    $sql .= $self-&gt;_parse_rs_attrs( $rs_attrs ) . " LIMIT ";
    if ($offset) {
      $sql .= '?, ';
      push @{$self-&gt;{limit_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset ];
    }
    $sql .= '?';
    push @{$self-&gt;{limit_bind}}, [ $self-&gt;__rows_bindtype =&gt; $rows ];

    return $sql;
}

=head2 RowNumberOver

 SELECT * FROM (
  SELECT *, ROW_NUMBER() OVER( ORDER BY ... ) AS RNO__ROW__INDEX FROM (
   SELECT ...
  )
 ) WHERE RNO__ROW__INDEX BETWEEN ($offset+1) AND ($limit+$offset)


ANSI standard Limit/Offset implementation. Supported by B&lt;DB2&gt; and
B&lt;&lt; MSSQL &gt;= 2005 &gt;&gt;.

=cut
sub _RowNumberOver {
  my ($self, $sql, $rs_attrs, $rows, $offset ) = @_;

  # get selectors, and scan the order_by (if any)
  my $sq_attrs = $self-&gt;_subqueried_limit_attrs ( $sql, $rs_attrs );

  # make up an order if none exists
  my $requested_order = (delete $rs_attrs-&gt;{order_by}) || $self-&gt;_rno_default_order;

  # the order binds (if any) will need to go at the end of the entire inner select
  local $self-&gt;{order_bind};
  my $rno_ord = $self-&gt;_order_by ($requested_order);
  push @{$self-&gt;{select_bind}}, @{$self-&gt;{order_bind}};

  # this is the order supplement magic
  my $mid_sel = $sq_attrs-&gt;{selection_outer};
  if (my $extra_order_sel = $sq_attrs-&gt;{order_supplement}) {
    for my $extra_col (sort
      { $extra_order_sel-&gt;{$a} cmp $extra_order_sel-&gt;{$b} }
      keys %$extra_order_sel
    ) {
      $sq_attrs-&gt;{selection_inner} .= sprintf (', %s AS %s',
        $extra_col,
        $extra_order_sel-&gt;{$extra_col},
      );
    }
  }

  # and this is order re-alias magic
  for my $map ($sq_attrs-&gt;{order_supplement}, $sq_attrs-&gt;{outer_renames}) {
    for my $col (sort { (length $b) &lt;=&gt; (length $a) } keys %{$map||{}} ) {
      my $re_col = quotemeta ($col);
      $rno_ord =~ s/$re_col/$map-&gt;{$col}/;
    }
  }

  # whatever is left of the order_by (only where is processed at this point)
  my $group_having = $self-&gt;_parse_rs_attrs($rs_attrs);

  my $qalias = $self-&gt;_quote ($rs_attrs-&gt;{alias});
  my $idx_name = $self-&gt;_quote ('rno__row__index');

  push @{$self-&gt;{limit_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset + 1], [ $self-&gt;__total_bindtype =&gt; $offset + $rows ];

  return &lt;&lt;EOS;

SELECT $sq_attrs-&gt;{selection_outer} FROM (
  SELECT $mid_sel, ROW_NUMBER() OVER( $rno_ord ) AS $idx_name FROM (
    SELECT $sq_attrs-&gt;{selection_inner} $sq_attrs-&gt;{query_leftover}${group_having}
  ) $qalias
) $qalias WHERE $idx_name &gt;= ? AND $idx_name &lt;= ?

EOS

}

# some databases are happy with OVER (), some need OVER (ORDER BY (SELECT (1)) )
sub _rno_default_order {
  return undef;
}

=head2 SkipFirst

 SELECT SKIP $offset FIRST $limit * FROM ...

Suported by B&lt;Informix&gt;, almost like LimitOffset. According to
L&lt;SQL::Abstract::Limit&gt; C&lt;... SKIP $offset LIMIT $limit ...&gt; is also supported.

=cut
sub _SkipFirst {
  my ($self, $sql, $rs_attrs, $rows, $offset) = @_;

  $sql =~ s/^ \s* SELECT \s+ //ix
    or $self-&gt;throw_exception("Unrecognizable SELECT: $sql");

  return sprintf ('SELECT %s%s%s%s',
    $offset
      ? do {
         push @{$self-&gt;{pre_select_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset];
         'SKIP ? '
      }
      : ''
    ,
    do {
       push @{$self-&gt;{pre_select_bind}}, [ $self-&gt;__rows_bindtype =&gt; $rows ];
       'FIRST ? '
    },
    $sql,
    $self-&gt;_parse_rs_attrs ($rs_attrs),
  );
}

=head2 FirstSkip

 SELECT FIRST $limit SKIP $offset * FROM ...

Supported by B&lt;Firebird/Interbase&gt;, reverse of SkipFirst. According to
L&lt;SQL::Abstract::Limit&gt; C&lt;... ROWS $limit TO $offset ...&gt; is also supported.

=cut
sub _FirstSkip {
  my ($self, $sql, $rs_attrs, $rows, $offset) = @_;

  $sql =~ s/^ \s* SELECT \s+ //ix
    or $self-&gt;throw_exception("Unrecognizable SELECT: $sql");

  return sprintf ('SELECT %s%s%s%s',
    do {
       push @{$self-&gt;{pre_select_bind}}, [ $self-&gt;__rows_bindtype =&gt; $rows ];
       'FIRST ? '
    },
    $offset
      ? do {
         push @{$self-&gt;{pre_select_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset];
         'SKIP ? '
      }
      : ''
    ,
    $sql,
    $self-&gt;_parse_rs_attrs ($rs_attrs),
  );
}


=head2 RowNum

Depending on the resultset attributes one of:

 SELECT * FROM (
  SELECT *, ROWNUM rownum__index FROM (
   SELECT ...
  ) WHERE ROWNUM &lt;= ($limit+$offset)
 ) WHERE rownum__index &gt;= ($offset+1)

or

 SELECT * FROM (
  SELECT *, ROWNUM rownum__index FROM (
    SELECT ...
  )
 ) WHERE rownum__index BETWEEN ($offset+1) AND ($limit+$offset)

or

 SELECT * FROM (
    SELECT ...
  ) WHERE ROWNUM &lt;= ($limit+1)

Supported by B&lt;Oracle&gt;.

=cut
sub _RowNum {
  my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;

  my $sq_attrs = $self-&gt;_subqueried_limit_attrs ($sql, $rs_attrs);

  my $qalias = $self-&gt;_quote ($rs_attrs-&gt;{alias});
  my $idx_name = $self-&gt;_quote ('rownum__index');
  my $order_group_having = $self-&gt;_parse_rs_attrs($rs_attrs);


  # if no offset (e.g. first page) - we can skip one of the subqueries
  if (! $offset) {
    push @{$self-&gt;{limit_bind}}, [ $self-&gt;__rows_bindtype =&gt; $rows ];

    return &lt;&lt;EOS;
SELECT $sq_attrs-&gt;{selection_outer} FROM (
  SELECT $sq_attrs-&gt;{selection_inner} $sq_attrs-&gt;{query_leftover}${order_group_having}
) $qalias WHERE ROWNUM &lt;= ?
EOS
  }

  #
  # There are two ways to limit in Oracle, one vastly faster than the other
  # on large resultsets: https://decipherinfosys.wordpress.com/2007/08/09/paging-and-countstopkey-optimization/
  # However Oracle is retarded and does not preserve stable ROWNUM() values
  # when called twice in the same scope. Therefore unless the resultset is
  # ordered by a unique set of columns, it is not safe to use the faster
  # method, and the slower BETWEEN query is used instead
  #
  # FIXME - this is quite expensive, and does not perform caching of any sort
  # as soon as some of the DQ work becomes viable consider switching this
  # over
  if (
    $rs_attrs-&gt;{order_by}
      and
    $rs_attrs-&gt;{_rsroot_rsrc}-&gt;storage-&gt;_order_by_is_stable(
      @{$rs_attrs}{qw/from order_by where/}
    )
  ) {
    push @{$self-&gt;{limit_bind}}, [ $self-&gt;__total_bindtype =&gt; $offset + $rows ], [ $self-&gt;__offset_bindtype =&gt; $offset + 1 ];

    return &lt;&lt;EOS;
SELECT $sq_attrs-&gt;{selection_outer} FROM (
  SELECT $sq_attrs-&gt;{selection_outer}, ROWNUM $idx_name FROM (
    SELECT $sq_attrs-&gt;{selection_inner} $sq_attrs-&gt;{query_leftover}${order_group_having}
  ) $qalias WHERE ROWNUM &lt;= ?
) $qalias WHERE $idx_name &gt;= ?
EOS
  }
  else {
    push @{$self-&gt;{limit_bind}}, [ $self-&gt;__offset_bindtype =&gt; $offset + 1 ], [ $self-&gt;__total_bindtype =&gt; $offset + $rows ];

    return &lt;&lt;EOS;
SELECT $sq_attrs-&gt;{selection_outer} FROM (
  SELECT $sq_attrs-&gt;{selection_outer}, ROWNUM $idx_name FROM (
    SELECT $sq_attrs-&gt;{selection_inner} $sq_attrs-&gt;{query_leftover}${order_group_having}
  ) $qalias
) $qalias WHERE $idx_name BETWEEN ? AND ?
EOS
  }
}

# used by _Top and _FetchFirst below
sub _prep_for_skimming_limit {
  my ( $self, $sql, $rs_attrs ) = @_;

  # get selectors
  my $sq_attrs = $self-&gt;_subqueried_limit_attrs ($sql, $rs_attrs);

  my $requested_order = delete $rs_attrs-&gt;{order_by};
  $sq_attrs-&gt;{order_by_requested} = $self-&gt;_order_by ($requested_order);
  $sq_attrs-&gt;{grpby_having} = $self-&gt;_parse_rs_attrs ($rs_attrs);

  # without an offset things are easy
  if (! $rs_attrs-&gt;{offset}) {
    $sq_attrs-&gt;{order_by_inner} = $sq_attrs-&gt;{order_by_requested};
  }
  else {
    $sq_attrs-&gt;{quoted_rs_alias} = $self-&gt;_quote ($rs_attrs-&gt;{alias});

    # localise as we already have all the bind values we need
    local $self-&gt;{order_bind};

    # make up an order unless supplied or sanity check what we are given
    my $inner_order;
    if ($sq_attrs-&gt;{order_by_requested}) {
      $self-&gt;throw_exception (
        'Unable to safely perform "skimming type" limit with supplied unstable order criteria'
      ) unless ($rs_attrs-&gt;{_rsroot_rsrc}-&gt;schema-&gt;storage-&gt;_order_by_is_stable(
        $rs_attrs-&gt;{from},
        $requested_order,
        $rs_attrs-&gt;{where},
      ));

      $inner_order = $requested_order;
    }
    else {
      $inner_order = [ map
        { "$rs_attrs-&gt;{alias}.$_" }
        ( @{
          $rs_attrs-&gt;{_rsroot_rsrc}-&gt;_identifying_column_set
            ||
          $self-&gt;throw_exception(sprintf(
            'Unable to auto-construct stable order criteria for "skimming type" limit '
          . "dialect based on source '%s'", $rs_attrs-&gt;{_rsroot_rsrc}-&gt;name) );
        } )
      ];
    }

    $sq_attrs-&gt;{order_by_inner} = $self-&gt;_order_by ($inner_order);

    my @out_chunks;
    for my $ch ($self-&gt;_order_by_chunks ($inner_order)) {
      $ch = $ch-&gt;[0] if ref $ch eq 'ARRAY';

      $ch =~ s/\s+ ( ASC|DESC ) \s* $//ix;
      my $dir = uc ($1||'ASC');
      push @out_chunks, \join (' ', $ch, $dir eq 'ASC' ? 'DESC' : 'ASC' );
    }

    $sq_attrs-&gt;{order_by_middle} = $self-&gt;_order_by (\@out_chunks);

    # this is the order supplement magic
    $sq_attrs-&gt;{selection_middle} = $sq_attrs-&gt;{selection_outer};
    if (my $extra_order_sel = $sq_attrs-&gt;{order_supplement}) {
      for my $extra_col (sort
        { $extra_order_sel-&gt;{$a} cmp $extra_order_sel-&gt;{$b} }
        keys %$extra_order_sel
      ) {
        $sq_attrs-&gt;{selection_inner} .= sprintf (', %s AS %s',
          $extra_col,
          $extra_order_sel-&gt;{$extra_col},
        );

        $sq_attrs-&gt;{selection_middle} .= ', ' . $extra_order_sel-&gt;{$extra_col};
      }

      # Whatever order bindvals there are, they will be realiased and
      # reselected, and need to show up at end of the initial inner select
      push @{$self-&gt;{select_bind}}, @{$self-&gt;{order_bind}};
    }

    # and this is order re-alias magic
    for my $map ($sq_attrs-&gt;{order_supplement}, $sq_attrs-&gt;{outer_renames}) {
      for my $col (sort { (length $b) &lt;=&gt; (length $a) } keys %{$map||{}}) {
        my $re_col = quotemeta ($col);
        $_ =~ s/$re_col/$map-&gt;{$col}/
          for ($sq_attrs-&gt;{order_by_middle}, $sq_attrs-&gt;{order_by_requested});
      }
    }
  }

  $sq_attrs;
}

=head2 Top

 SELECT * FROM

 SELECT TOP $limit FROM (
  SELECT TOP $limit FROM (
   SELECT TOP ($limit+$offset) ...
  ) ORDER BY $reversed_original_order
 ) ORDER BY $original_order

Unreliable Top-based implementation, supported by B&lt;&lt; MSSQL &lt; 2005 &gt;&gt;.

=head3 CAVEAT

Due to its implementation, this limit dialect returns B&lt;incorrect results&gt;
when $limit+$offset &gt; total amount of rows in the resultset.

=cut

sub _Top {
  my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;

  my $lim = $self-&gt;_prep_for_skimming_limit($sql, $rs_attrs);

  $sql = sprintf ('SELECT TOP %u %s %s %s %s',
    $rows + ($offset||0),
    $offset ? $lim-&gt;{selection_inner} : $lim-&gt;{selection_original},
    $lim-&gt;{query_leftover},
    $lim-&gt;{grpby_having},
    $lim-&gt;{order_by_inner},
  );

  $sql = sprintf ('SELECT TOP %u %s FROM ( %s ) %s %s',
    $rows,
    $lim-&gt;{selection_middle},
    $sql,
    $lim-&gt;{quoted_rs_alias},
    $lim-&gt;{order_by_middle},
  ) if $offset;

  $sql = sprintf ('SELECT %s FROM ( %s ) %s %s',
    $lim-&gt;{selection_outer},
    $sql,
    $lim-&gt;{quoted_rs_alias},
    $lim-&gt;{order_by_requested},
  ) if $offset and (
    $lim-&gt;{order_by_requested} or $lim-&gt;{selection_middle} ne $lim-&gt;{selection_outer}
  );

  return $sql;
}

=head2 FetchFirst

 SELECT * FROM
 (
 SELECT * FROM (
  SELECT * FROM (
   SELECT * FROM ...
  ) ORDER BY $reversed_original_order
    FETCH FIRST $limit ROWS ONLY
 ) ORDER BY $original_order
   FETCH FIRST $limit ROWS ONLY
 )

Unreliable FetchFirst-based implementation, supported by B&lt;&lt; IBM DB2 &lt;= V5R3 &gt;&gt;.

=head3 CAVEAT

Due to its implementation, this limit dialect returns B&lt;incorrect results&gt;
when $limit+$offset &gt; total amount of rows in the resultset.

=cut

sub _FetchFirst {
  my ( $self, $sql, $rs_attrs, $rows, $offset ) = @_;

  my $lim = $self-&gt;_prep_for_skimming_limit($sql, $rs_attrs);

  $sql = sprintf ('SELECT %s %s %s %s FETCH FIRST %u ROWS ONLY',
    $offset ? $lim-&gt;{selection_inner} : $lim-&gt;{selection_original},
    $lim-&gt;{query_leftover},
    $lim-&gt;{grpby_having},
    $lim-&gt;{order_by_inner},
    $rows + ($offset||0),
  );

  $sql = sprintf ('SELECT %s FROM ( %s ) %s %s FETCH FIRST %u ROWS ONLY',
    $lim-&gt;{selection_middle},
    $sql,
    $lim-&gt;{quoted_rs_alias},
    $lim-&gt;{order_by_middle},
    $rows,
  ) if $offset;


  $sql = sprintf ('SELECT %s FROM ( %s ) %s %s',
    $lim-&gt;{selection_outer},
    $sql,
    $lim-&gt;{quoted_rs_alias},
    $lim-&gt;{order_by_requested},
  ) if $offset and (
    $lim-&gt;{order_by_requested} or $lim-&gt;{selection_middle} ne $lim-&gt;{selection_outer}
  );

  return $sql;
}

=head2 RowCountOrGenericSubQ

This is not exactly a limit dialect, but more of a proxy for B&lt;Sybase ASE&gt;.
If no $offset is supplied the limit is simply performed as:

 SET ROWCOUNT $limit
 SELECT ...
 SET ROWCOUNT 0

Otherwise we fall back to L&lt;/GenericSubQ&gt;

=cut

sub _RowCountOrGenericSubQ {
  my $self = shift;
  my ($sql, $rs_attrs, $rows, $offset) = @_;

  return $self-&gt;_GenericSubQ(@_) if $offset;

  return sprintf &lt;&lt;"EOF", $rows, $sql, $self-&gt;_parse_rs_attrs( $rs_attrs );
SET ROWCOUNT %d
%s %s
SET ROWCOUNT 0
EOF
}

=head2 GenericSubQ

 SELECT * FROM (
  SELECT ...
 )
 WHERE (
  SELECT COUNT(*) FROM $original_table cnt WHERE cnt.id &lt; $original_table.id
 ) BETWEEN $offset AND ($offset+$rows-1)

This is the most evil limit "dialect" (more of a hack) for I&lt;really&gt; stupid
databases. It works by ordering the set by some unique column, and calculating
the amount of rows that have a less-er value (thus emulating a L&lt;/RowNum&gt;-like
index). Of course this implies the set can only be ordered by a single unique
column.

Also note that this technique can be and often is B&lt;excruciatingly slow&gt;. You
may have much better luck using L&lt;DBIx::Class::ResultSet/software_limit&gt;
instead.

Currently used by B&lt;Sybase ASE&gt;, due to lack of any other option.

=cut
sub _GenericSubQ {
  my ($self, $sql, $rs_attrs, $rows, $offset) = @_;

  my $root_rsrc = $rs_attrs-&gt;{_rsroot_rsrc};
  my $root_tbl_name = $root_rsrc-&gt;name;

  my ($first_order_by) = do {
    local $self-&gt;{quote_char};
    local $self-&gt;{order_bind};
    map { ref $_ ? $_-&gt;[0] : $_ } $self-&gt;_order_by_chunks ($rs_attrs-&gt;{order_by})
  } or $self-&gt;throw_exception (
    'Generic Subquery Limit does not work on resultsets without an order. Provide a single, '
  . 'unique-column order criteria.'
  );

  $first_order_by =~ s/\s+ ( ASC|DESC ) \s* $//ix;
  my $direction = lc ($1 || 'asc');

  my ($first_ord_alias, $first_ord_col) = $first_order_by =~ /^ (?: ([^\.]+) \. )? ([^\.]+) $/x;

  $self-&gt;throw_exception(sprintf
    "Generic Subquery Limit order criteria can be only based on the root-source '%s'"
  . " (aliased as '%s')", $root_rsrc-&gt;source_name, $rs_attrs-&gt;{alias},
  ) if ($first_ord_alias and $first_ord_alias ne $rs_attrs-&gt;{alias});

  $first_ord_alias ||= $rs_attrs-&gt;{alias};

  $self-&gt;throw_exception(
    "Generic Subquery Limit first order criteria '$first_ord_col' must be unique"
  ) unless $root_rsrc-&gt;_identifying_column_set([$first_ord_col]);

  my $sq_attrs = do {
    # perform the mangling only using the very first order crietria
    # (the one we care about)
    local $rs_attrs-&gt;{order_by} = $first_order_by;
    $self-&gt;_subqueried_limit_attrs ($sql, $rs_attrs);
  };

  my $cmp_op = $direction eq 'desc' ? '&gt;' : '&lt;';
  my $count_tbl_alias = 'rownum__emulation';

  my ($order_sql, @order_bind) = do {
    local $self-&gt;{order_bind};
    my $s = $self-&gt;_order_by (delete $rs_attrs-&gt;{order_by});
    ($s, @{$self-&gt;{order_bind}});
  };
  my $group_having_sql = $self-&gt;_parse_rs_attrs($rs_attrs);

  my $in_sel = $sq_attrs-&gt;{selection_inner};

  # add the order supplement (if any) as this is what will be used for the outer WHERE
  $in_sel .= ", $_" for keys %{$sq_attrs-&gt;{order_supplement}};

  my $rownum_cond;
  if ($offset) {
    $rownum_cond = 'BETWEEN ? AND ?';

    push @{$self-&gt;{limit_bind}},
      [ $self-&gt;__offset_bindtype =&gt; $offset ],
      [ $self-&gt;__total_bindtype =&gt; $offset + $rows - 1]
    ;
  }
  else {
    $rownum_cond = '&lt; ?';

    push @{$self-&gt;{limit_bind}},
      [ $self-&gt;__rows_bindtype =&gt; $rows ]
    ;
  }

  # even though binds in order_by make no sense here (the rs needs to be
  # ordered by a unique column first) - pass whatever there may be through
  # anyway
  push @{$self-&gt;{limit_bind}}, @order_bind;

  return sprintf ("
SELECT $sq_attrs-&gt;{selection_outer}
  FROM (
    SELECT $in_sel $sq_attrs-&gt;{query_leftover}${group_having_sql}
  ) %s
WHERE ( SELECT COUNT(*) FROM %s %s WHERE %s $cmp_op %s ) $rownum_cond
$order_sql
  ", map { $self-&gt;_quote ($_) } (
    $rs_attrs-&gt;{alias},
    $root_tbl_name,
    $count_tbl_alias,
    "$count_tbl_alias.$first_ord_col",
    "$first_ord_alias.$first_ord_col",
  ));
}


# !!! THIS IS ALSO HORRIFIC !!! /me ashamed
#
# Generates inner/outer select lists for various limit dialects
# which result in one or more subqueries (e.g. RNO, Top, RowNum)
# Any non-root-table columns need to have their table qualifier
# turned into a column alias (otherwise names in subqueries clash
# and/or lose their source table)
#
# Returns mangled proto-sql, inner/outer strings of SQL QUOTED selectors
# with aliases (to be used in whatever select statement), and an alias
# index hashref of QUOTED SEL =&gt; QUOTED ALIAS pairs (to maybe be used
# for string-subst higher up).
# If an order_by is supplied, the inner select needs to bring out columns
# used in implicit (non-selected) orders, and the order condition itself
# needs to be realiased to the proper names in the outer query. Thus we
# also return a hashref (order doesn't matter) of QUOTED EXTRA-SEL =&gt;
# QUOTED ALIAS pairs, which is a list of extra selectors that do *not*
# exist in the original select list
sub _subqueried_limit_attrs {
  my ($self, $proto_sql, $rs_attrs) = @_;

  $self-&gt;throw_exception(
    'Limit dialect implementation usable only in the context of DBIC (missing $rs_attrs)'
  ) unless ref ($rs_attrs) eq 'HASH';

  # mangle the input sql as we will be replacing the selector entirely
  unless (
    $rs_attrs-&gt;{_selector_sql}
      and
    $proto_sql =~ s/^ \s* SELECT \s* \Q$rs_attrs-&gt;{_selector_sql}//ix
  ) {
    $self-&gt;throw_exception("Unrecognizable SELECT: $proto_sql");
  }

  my ($re_sep, $re_alias) = map { quotemeta $_ } ( $self-&gt;{name_sep}, $rs_attrs-&gt;{alias} );

  # insulate from the multiple _recurse_fields calls below
  local $self-&gt;{select_bind};

  # correlate select and as, build selection index
  my (@sel, $in_sel_index);
  for my $i (0 .. $#{$rs_attrs-&gt;{select}}) {

    my $s = $rs_attrs-&gt;{select}[$i];
    my $sql_sel = $self-&gt;_recurse_fields ($s);
    my $sql_alias = (ref $s) eq 'HASH' ? $s-&gt;{-as} : undef;

    push @sel, {
      arg =&gt; $s,
      sql =&gt; $sql_sel,
      unquoted_sql =&gt; do {
        local $self-&gt;{quote_char};
        $self-&gt;_recurse_fields ($s);
      },
      as =&gt;
        $sql_alias
          ||
        $rs_attrs-&gt;{as}[$i]
          ||
        $self-&gt;throw_exception("Select argument $i ($s) without corresponding 'as'")
      ,
    };

    # anything with a placeholder in it needs re-selection
    $in_sel_index-&gt;{$sql_sel}++ unless $sql_sel =~ / (?: ^ | \W ) \? (?: \W | $ ) /x;

    $in_sel_index-&gt;{$self-&gt;_quote ($sql_alias)}++ if $sql_alias;

    # record unqualified versions too, so we do not have
    # to reselect the same column twice (in qualified and
    # unqualified form)
    if (! ref $s &amp;&amp; $sql_sel =~ / $re_sep (.+) $/x) {
      $in_sel_index-&gt;{$1}++;
    }
  }


  # re-alias and remove any name separators from aliases,
  # unless we are dealing with the current source alias
  # (which will transcend the subqueries as it is necessary
  # for possible further chaining)
  # same for anything we do not recognize
  my ($sel, $renamed);
  for my $node (@sel) {
    push @{$sel-&gt;{original}}, $node-&gt;{sql};

    if (
      ! $in_sel_index-&gt;{$node-&gt;{sql}}
        or
      $node-&gt;{as} =~ / (?&lt;! ^ $re_alias ) \. /x
        or
      $node-&gt;{unquoted_sql} =~ / (?&lt;! ^ $re_alias ) $re_sep /x
    ) {
      $node-&gt;{as} = $self-&gt;_unqualify_colname($node-&gt;{as});
      my $quoted_as = $self-&gt;_quote($node-&gt;{as});
      push @{$sel-&gt;{inner}}, sprintf '%s AS %s', $node-&gt;{sql}, $quoted_as;
      push @{$sel-&gt;{outer}}, $quoted_as;
      $renamed-&gt;{$node-&gt;{sql}} = $quoted_as;
    }
    else {
      push @{$sel-&gt;{inner}}, $node-&gt;{sql};
      push @{$sel-&gt;{outer}}, $self-&gt;_quote (ref $node-&gt;{arg} ? $node-&gt;{as} : $node-&gt;{arg});
    }
  }

  # see if the order gives us anything
  my $extra_order_sel;
  for my $chunk ($self-&gt;_order_by_chunks ($rs_attrs-&gt;{order_by})) {
    # order with bind
    $chunk = $chunk-&gt;[0] if (ref $chunk) eq 'ARRAY';
    $chunk =~ s/\s+ (?: ASC|DESC ) \s* $//ix;

    next if $in_sel_index-&gt;{$chunk};

    $extra_order_sel-&gt;{$chunk} ||= $self-&gt;_quote (
      'ORDER__BY__' . sprintf '%03d', scalar keys %{$extra_order_sel||{}}
    );
  }

  return {
    query_leftover =&gt; $proto_sql,
    (map {( "selection_$_" =&gt; join (', ', @{$sel-&gt;{$_}} ) )} keys %$sel ),
    outer_renames =&gt; $renamed,
    order_supplement =&gt; $extra_order_sel,
  };
}

sub _unqualify_colname {
  my ($self, $fqcn) = @_;
  $fqcn =~ s/ \. /__/xg;
  return $fqcn;
}

1;

=head1 AUTHORS

See L&lt;DBIx::Class/CONTRIBUTORS&gt;.

=head1 LICENSE

You may distribute this code under the same terms as Perl itself.

=cut
</pre></body></html>