Skip to content

Commit

Permalink
Merge pull request #5156 from morozov/ibm-db2-limit
Browse files Browse the repository at this point in the history
Use native IBM DB2 11 syntax for Top-N queries
  • Loading branch information
morozov authored Jan 5, 2022
2 parents c5154dc + 48ead93 commit 27a7c5b
Show file tree
Hide file tree
Showing 2 changed files with 3 additions and 42 deletions.
17 changes: 3 additions & 14 deletions src/Platforms/DB2Platform.php
Original file line number Diff line number Diff line change
Expand Up @@ -643,26 +643,15 @@ public function getTemporaryTableName(string $tableName): string

protected function doModifyLimitQuery(string $query, ?int $limit, int $offset): string
{
$where = [];

if ($offset > 0) {
$where[] = sprintf('db22.DC_ROWNUM >= %d', $offset + 1);
$query .= sprintf(' OFFSET %d ROWS', $offset);
}

if ($limit !== null) {
$where[] = sprintf('db22.DC_ROWNUM <= %d', $offset + $limit);
}

if (empty($where)) {
return $query;
$query .= sprintf(' FETCH NEXT %d ROWS ONLY', $limit);
}

// Todo OVER() needs ORDER BY data!
return sprintf(
'SELECT db22.* FROM (SELECT db21.*, ROW_NUMBER() OVER() AS DC_ROWNUM FROM (%s) db21) db22 WHERE %s',
$query,
implode(' AND ', $where)
);
return $query;
}

public function getLocateExpression(string $string, string $substring, ?string $start = null): string
Expand Down
28 changes: 0 additions & 28 deletions tests/Platforms/DB2PlatformTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -392,34 +392,6 @@ public function testGeneratesSQLSnippets(): void
self::assertEquals('SUBSTR(column, 5, 2)', $this->platform->getSubstringExpression('column', '5', '2'));
}

public function testModifiesLimitQuery(): void
{
self::assertEquals(
'SELECT * FROM user',
$this->platform->modifyLimitQuery('SELECT * FROM user', null, 0)
);

self::assertEquals(
'SELECT db22.* FROM ('
. 'SELECT db21.*, ROW_NUMBER() OVER() AS DC_ROWNUM FROM (SELECT * FROM user) db21'
. ') db22 WHERE db22.DC_ROWNUM <= 10',
$this->platform->modifyLimitQuery('SELECT * FROM user', 10)
);

self::assertEquals(
'SELECT db22.* FROM (SELECT db21.*, ROW_NUMBER() OVER() AS DC_ROWNUM FROM ('
. 'SELECT * FROM user) db21'
. ') db22 WHERE db22.DC_ROWNUM >= 6 AND db22.DC_ROWNUM <= 15',
$this->platform->modifyLimitQuery('SELECT * FROM user', 10, 5)
);
self::assertEquals(
'SELECT db22.* FROM ('
. 'SELECT db21.*, ROW_NUMBER() OVER() AS DC_ROWNUM FROM (SELECT * FROM user) db21'
. ') db22 WHERE db22.DC_ROWNUM >= 6 AND db22.DC_ROWNUM <= 5',
$this->platform->modifyLimitQuery('SELECT * FROM user', 0, 5)
);
}

public function testSupportsIdentityColumns(): void
{
self::assertTrue($this->platform->supportsIdentityColumns());
Expand Down

0 comments on commit 27a7c5b

Please sign in to comment.