From e7cd0c62015170a87b8cf037a998e8711f1a40a9 Mon Sep 17 00:00:00 2001 From: Andrey Pyzhikov <5071@mail.ru> Date: Fri, 25 Feb 2022 08:46:03 +0800 Subject: [PATCH 1/2] Checking if the subquery uses the same object as the main query Signed-off-by: Andrey Pyzhikov <5071@mail.ru> --- system/Database/BaseBuilder.php | 4 ++++ tests/system/Database/Builder/BaseTest.php | 12 ++++++++++++ 2 files changed, 16 insertions(+) diff --git a/system/Database/BaseBuilder.php b/system/Database/BaseBuilder.php index ccfa5bd9d8bb..842aae3c8a29 100644 --- a/system/Database/BaseBuilder.php +++ b/system/Database/BaseBuilder.php @@ -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) { diff --git a/tests/system/Database/Builder/BaseTest.php b/tests/system/Database/Builder/BaseTest.php index 1390e4668200..5a2a4f1578db 100644 --- a/tests/system/Database/Builder/BaseTest.php +++ b/tests/system/Database/Builder/BaseTest.php @@ -11,6 +11,7 @@ namespace CodeIgniter\Database\Builder; +use CodeIgniter\Database\Exceptions\DatabaseException; use CodeIgniter\Test\CIUnitTestCase; use CodeIgniter\Test\Mock\MockConnection; @@ -53,4 +54,15 @@ 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'); + $builder->getCompiledSelect(); + } } From e5bc03d8037fc1791ef912a85938fd0dabdfd00c Mon Sep 17 00:00:00 2001 From: Andrey Pyzhikov <5071@mail.ru> Date: Sat, 26 Feb 2022 07:59:09 +0800 Subject: [PATCH 2/2] Update tests/system/Database/Builder/BaseTest.php Co-authored-by: kenjis --- tests/system/Database/Builder/BaseTest.php | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/system/Database/Builder/BaseTest.php b/tests/system/Database/Builder/BaseTest.php index 5a2a4f1578db..c7386066aa74 100644 --- a/tests/system/Database/Builder/BaseTest.php +++ b/tests/system/Database/Builder/BaseTest.php @@ -63,6 +63,5 @@ public function testSubquerySameBaseBuilderObject() $builder = $this->db->table('users'); $builder->fromSubquery($builder, 'sub'); - $builder->getCompiledSelect(); } }