Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Checking if the subquery uses the same object as the main query #5743

Merged
merged 2 commits into from
Feb 26, 2022
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
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');
}
}