Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add pagination to all pages that show past N request #8

Open
lencioni opened this issue Dec 13, 2010 · 1 comment
Open

Add pagination to all pages that show past N request #8

lencioni opened this issue Dec 13, 2010 · 1 comment

Comments

@lencioni
Copy link

It would be nice to have pagination so you are able to browse backward in time. Alternatively, it would be great to be able to specify a date range a la Google Analytics.

@lencioni
Copy link
Author

Pagination in MySQL is very straightforward with the LIMIT syntax, but for MSSQL, things get a bit more complicated.

I've written some functions that work to mimic the limit syntax for MSSQL. They are part of a larger class and a bit on the old side, so they might need some tweaking, but here's the quick copy and paste:

/**
 * @param string $sql
 * @param string $orderBy
 * @return string
 */
final protected static function limitOrderBy($sql, $orderBy = 'ASC')
{
    // get the "order by" statement how we need it
    $r      = preg_replace('/.*?ORDER(.*)/ims', 'ORDER$1', $sql);
    $r      = preg_replace('/[\w]+\.([\[\]\w]+)/', '$1', $r);

    $parts  = explode(',', $r);
    foreach($parts as &$orderPart)
    {
        if (preg_match('/[\s](DE|A)SC[\s]*$/i', $orderPart) === 0)
        {
            $orderPart  .= ' ' . $orderBy;
        }
    }
    return implode(',', $parts);
}

/**
 * @param string $sql
 * @return string
 */
final protected static function stripOrderBy($sql)
{
    return preg_replace('/^(.*?)ORDER.*$/ims', '$1', $sql);
}

/**
 * @param string $sql
 * @param integer $start
 * @param integer $stop
 * @param string $orderBy
 * @return string
 */
final public static function limit($sql, $start, $stop, $orderBy = 'ASC')
{
    // Get the "order by" statement how we need it
    $orderBySql = self::limitOrderBy($sql, $orderBy);
    $sql        = self::stripOrderBy($sql);
    $rows       = $stop - $start + 1;

    return "
    SET ROWCOUNT $rows;
    SELECT TOP $rows * FROM (
        SELECT ROW_NUMBER() OVER ($orderBySql) AS rownumber, sqlQuery.*
        FROM ($sql) AS sqlQuery
    ) AS rowedQuery
    WHERE rownumber >= $start
        AND rownumber <= $stop
    ";
}

dshafik pushed a commit to dshafik/xhprof that referenced this issue Oct 23, 2013
add composer.json (see getcomposer.org / packagist.org)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant