Skip to content

Commit

Permalink
Merge pull request #5743 from iRedds/subquery-same-object
Browse files Browse the repository at this point in the history
Checking if the subquery uses the same object as the main query
  • Loading branch information
samsonasik authored Feb 26, 2022
2 parents 196d759 + e5bc03d commit 64b6f48
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
4 changes: 4 additions & 0 deletions system/Database/BaseBuilder.php
Original file line number Diff line number Diff line change
Expand Up @@ -2763,6 +2763,10 @@ protected function buildSubquery($builder, bool $wrapped = false, string $alias
$builder($builder = $this->db->newQuery());
}

if ($builder === $this) {
throw new DatabaseException('The subquery cannot be the same object as the main query object.');
}

$subquery = strtr($builder->getCompiledSelect(), "\n", ' ');

if ($wrapped) {
Expand Down
11 changes: 11 additions & 0 deletions tests/system/Database/Builder/BaseTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@

namespace CodeIgniter\Database\Builder;

use CodeIgniter\Database\Exceptions\DatabaseException;
use CodeIgniter\Test\CIUnitTestCase;
use CodeIgniter\Test\Mock\MockConnection;

Expand Down Expand Up @@ -53,4 +54,14 @@ public function testGetTableIgnoresFrom()
$result = $builder->getTable();
$this->assertSame('jobs', $result);
}

public function testSubquerySameBaseBuilderObject()
{
$this->expectException(DatabaseException::class);
$this->expectExceptionMessage('The subquery cannot be the same object as the main query object.');

$builder = $this->db->table('users');

$builder->fromSubquery($builder, 'sub');
}
}

0 comments on commit 64b6f48

Please sign in to comment.