Skip to content

Commit

Permalink
Merge pull request #3 from dscone/3.1
Browse files Browse the repository at this point in the history
allow multiple ORDER BY clauses within a query to be correctly processed...
  • Loading branch information
xrado committed Aug 17, 2012
2 parents d22d2dd + 8d77c5b commit 345f50b
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions classes/kohana/database/mssql.php
Expand Up @@ -32,20 +32,22 @@ public function query($type, $sql, $as_object = FALSE, array $params = NULL)
}
else
{
$orderby = stristr($sql, 'ORDER BY');
$ob_count = (int)preg_match_all('/ORDER BY/i',$sql,$ob_matches,PREG_OFFSET_CAPTURE);

if (!$orderby)
if($ob_count < 1)
{
$over = 'ORDER BY (SELECT 0)';
}
else
{
$ob_last = array_pop($ob_matches[0]);
$orderby = strrchr($sql, $ob_last[0]);
$over = preg_replace('/[^,\s]*\.([^,\s]*)/i', 'inner_tbl.$1', $orderby);

// Remove ORDER BY clause from $sql
$sql = substr($sql, 0, $ob_last[1]);
}

// Remove ORDER BY clause from $sql
$sql = preg_replace('/\s+ORDER BY(.*)/', '', $sql);

// Add ORDER BY clause as an argument for ROW_NUMBER()
$sql = "SELECT ROW_NUMBER() OVER ($over) AS KOHANA_DB_ROWNUM, * FROM ($sql) AS inner_tbl";

Expand Down Expand Up @@ -75,7 +77,7 @@ public function query($type, $sql, $as_object = FALSE, array $params = NULL)
}

// Convert the exception in a database exception
throw new Database_Exception($e->getCode(), '[:code] :error ( :query )', array(
throw new Database_Exception('[:code] :error ( :query )', array(
':code' => $e->getMessage(),
':error' => $e->getCode(),
':query' => $sql,
Expand Down

0 comments on commit 345f50b

Please sign in to comment.