Skip to content

Instantly share code, notes, and snippets.

@datiecher
Created February 5, 2013 19:23
Show Gist options
  • Save datiecher/4716900 to your computer and use it in GitHub Desktop.
Save datiecher/4716900 to your computer and use it in GitHub Desktop.
Quick hack
<?php
protected function doModifyLimitQuery($query, $limit, $offset = null)
{
if ($limit > 0) {
if ($offset == 0) {
$query = preg_replace('/^(SELECT\s(DISTINCT\s)?)/i', '\1TOP ' . $limit . ' ', $query);
$query = preg_replace('/FROM \(SELECT/i', 'FROM (SELECT TOP 2000000000', $query);
} else {
$orderby = stristr($query, 'ORDER BY');
if ( ! $orderby) {
$over = 'ORDER BY (SELECT 0)';
} else {
$over = preg_replace('/\"[^,]*\".\"([^,]*)\"/i', '"inner_tbl"."$1"', $orderby);
}
// Remove ORDER BY clause from $query
$query = preg_replace('/\s+ORDER BY(.*)/', '', $query);
$query = preg_replace('/\sFROM/i', ", ROW_NUMBER() OVER ($over) AS doctrine_rownum FROM", $query);
$start = $offset + 1;
$end = $offset + $limit;
$query = "SELECT * FROM ($query) AS doctrine_tbl WHERE doctrine_rownum BETWEEN $start AND $end";
}
}
return $query;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment