diff options
author | Aleksander Machniak <alec@alec.pl> | 2013-03-11 08:35:21 +0100 |
---|---|---|
committer | Aleksander Machniak <alec@alec.pl> | 2013-03-11 08:35:21 +0100 |
commit | ec6a77bab27984ce05b003af07ac9f42ca410d94 (patch) | |
tree | b8f167e4626bec86f2cb8ec3d2c06e6f6aff3445 /program/lib/Roundcube/rcube_db_sqlsrv.php | |
parent | 65de0018c8e34a24167a2cc5a46a72981886362a (diff) |
Fix LIMIT/OFFSET queries handling on MS SQL Server (#1488984) - require version 2005+
Diffstat (limited to 'program/lib/Roundcube/rcube_db_sqlsrv.php')
-rw-r--r-- | program/lib/Roundcube/rcube_db_sqlsrv.php | 28 |
1 files changed, 16 insertions, 12 deletions
diff --git a/program/lib/Roundcube/rcube_db_sqlsrv.php b/program/lib/Roundcube/rcube_db_sqlsrv.php index e69678025..e5dfb1154 100644 --- a/program/lib/Roundcube/rcube_db_sqlsrv.php +++ b/program/lib/Roundcube/rcube_db_sqlsrv.php @@ -100,26 +100,30 @@ class rcube_db_sqlsrv extends rcube_db { $limit = intval($limit); $offset = intval($offset); + $end = $offset + $limit; - $orderby = stristr($query, 'ORDER BY'); - if ($orderby !== false) { - $sort = (stripos($orderby, ' desc') !== false) ? 'desc' : 'asc'; - $order = str_ireplace('ORDER BY', '', $orderby); - $order = trim(preg_replace('/\bASC\b|\bDESC\b/i', '', $order)); + // query without OFFSET + if (!$offset) { + $query = preg_replace('/^SELECT\s/i', "SELECT TOP $limit ", $query); + return $query; } - $query = preg_replace('/^SELECT\s/i', 'SELECT TOP ' . ($limit + $offset) . ' ', $query); + $orderby = stristr($query, 'ORDER BY'); + $offset += 1; - $query = 'SELECT * FROM (SELECT TOP ' . $limit . ' * FROM (' . $query . ') AS inner_tbl'; if ($orderby !== false) { - $query .= ' ORDER BY ' . $order . ' '; - $query .= (stripos($sort, 'asc') !== false) ? 'DESC' : 'ASC'; + $query = trim(substr($query, 0, -1 * strlen($orderby))); } - $query .= ') AS outer_tbl'; - if ($orderby !== false) { - $query .= ' ORDER BY ' . $order . ' ' . $sort; + else { + // it shouldn't happen, paging without sorting has not much sense + // @FIXME: I don't know how to build paging query without ORDER BY + $orderby = "ORDER BY 1"; } + $query = preg_replace('/^SELECT\s/i', '', $query); + $query = "WITH paging AS (SELECT ROW_NUMBER() OVER ($orderby) AS [RowNumber], $query)" + . " SELECT * FROM paging WHERE [RowNumber] BETWEEN $offset AND $end ORDER BY [RowNumber]"; + return $query; } |