Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## 1.0.1 under development

- Enh #146: Explicitly import `SORT_ASC` constant in `QueryDataReader` (@vjik)
- Enh #147: Omit `ASC` in `ORDER BY` for sort fields mapped to expressions (@vjik)

## 1.0.0 December 13, 2025

Expand Down
7 changes: 3 additions & 4 deletions src/QueryDataReader.php
Original file line number Diff line number Diff line change
Expand Up @@ -345,10 +345,9 @@ private function convertSortToOrderBy(Sort $sort): array
if (is_string($field)) {
$result[$field] = $direction;
} else {
$result[] = new CompositeExpression([
$field,
$direction === SORT_ASC ? 'ASC' : 'DESC',
]);
$result[] = $direction === SORT_ASC
? $field
: new CompositeExpression([$field, 'DESC']);
}
}
return $result;
Expand Down
21 changes: 21 additions & 0 deletions tests/Sqlite/QueryDataReader/QueryDataReaderTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,12 @@

namespace Yiisoft\Data\Db\Tests\Sqlite\QueryDataReader;

use PHPUnit\Framework\Attributes\DataProvider;
use Yiisoft\Data\Db\QueryDataReader;
use Yiisoft\Data\Db\Tests\Base\BaseQueryDataReaderTestCase;
use Yiisoft\Data\Db\Tests\Sqlite\DatabaseTrait;
use Yiisoft\Data\Reader\Sort;
use Yiisoft\Db\Expression\Expression;
use Yiisoft\Db\Query\Query;
use Yiisoft\Test\Support\Log\SimpleLogger;

Expand Down Expand Up @@ -105,4 +107,23 @@ public function testCountQuery(): void
$messages[0]['message'],
);
}

public static function dataSortWithFieldMappedToExpression(): iterable
{
yield 'asc' => ['asc', 'LOWER(name)'];
yield 'desc' => ['desc', 'LOWER(name) DESC'];
}

#[DataProvider('dataSortWithFieldMappedToExpression')]
public function testSortWithFieldMappedToExpression(string $direction, string $expectedOrderBy): void
{
$query = (new Query($this->getConnection()))->from('customer');
$dataReader = (new QueryDataReader($query, fieldMapper: ['userName' => new Expression('LOWER(name)')]))
->withSort(Sort::any()->withOrder(['userName' => $direction]));

$this->assertSame(
'SELECT * FROM "customer" ORDER BY ' . $expectedOrderBy,
$dataReader->getPreparedQuery()->createCommand()->getRawSql(),
);
}
}
Loading