Fix #18552: Fix bug with yii\data\SqlDataProvider not properly handling SQL with ORDER BY clause

This commit is contained in:
Bizley
2021-03-10 21:28:45 +01:00
committed by GitHub
parent 7f6671cdfc
commit bd2b1f25f0
3 changed files with 34 additions and 2 deletions

View File

@ -4,7 +4,7 @@ Yii Framework 2 Change Log
2.0.42 under development
------------------------
- no changes in this release.
- Bug #18552: Fix bug with `yii\data\SqlDataProvider` not properly handling SQL with `ORDER BY` clause (bizley)
2.0.41.1 March 04, 2021

View File

@ -119,7 +119,7 @@ class SqlDataProvider extends BaseDataProvider
if ($sort !== false) {
$orders = $sort->getOrders();
$pattern = '/\s+order\s+by\s+([\w\s,\.]+)$/i';
$pattern = '/\s+order\s+by\s+([\w\s,\."`\[\]]+)$/i';
if (preg_match($pattern, $sql, $matches)) {
array_unshift($orders, new Expression($matches[1]));
$sql = preg_replace($pattern, '', $sql);

View File

@ -46,4 +46,36 @@ class SqlDataProviderTest extends DatabaseTestCase
]);
$this->assertEquals(3, $dataProvider->getTotalCount());
}
public function providerForOrderByColumn()
{
return [
'no marks' => ['name'],
'no marks dot' => ['customer.name'],
'mysql' => ['`name`'],
'mysql dot' => ['`customer`.`name`'],
'sqlite, pgsql, oracle, mysql ansi quotes' => ['"name"'],
'sqlite, pgsql, oracle, mysql ansi quotes dot' => ['"customer"."name"'],
'mssql' => ['[name]'],
'mssql dot' => ['[customer].[name]'],
];
}
/**
* @dataProvider providerForOrderByColumn
* @see https://github.com/yiisoft/yii2/issues/18552
*/
public function testRemovingOrderBy($column)
{
$dataProvider = new SqlDataProvider([
'sql' => 'select * from `customer` order by ' . $column . ' desc',
'db' => $this->getConnection(),
'sort' => [
'attributes' => ['email'],
'params' => ['sort' => '-email']
],
]);
$modelsSorted = $dataProvider->getModels();
$this->assertSame('user3', $modelsSorted[0]['name']);
}
}