From 7e710c5bdf2778e4745d24e5bd0ffa3ac72d7695 Mon Sep 17 00:00:00 2001 From: juanmacias Date: Thu, 2 Apr 2026 10:56:40 +0200 Subject: [PATCH 1/2] Fix queryScalar() state mutation by using clone instead of save/restore queryScalar() was manually saving and restoring select, orderBy, limit, and offset properties around createCommand(). This is fragile: if createCommand() throws, the original state is never restored. It is also not safe if properties are referenced elsewhere. Replace with clone $this, which is already the pattern used in the else branch (line 856) and in withTypecasting(). Co-Authored-By: Claude Opus 4.6 (1M context) --- src/Query/Query.php | 23 ++++++----------------- 1 file changed, 6 insertions(+), 17 deletions(-) diff --git a/src/Query/Query.php b/src/Query/Query.php index f499893f5..81dfa7b73 100644 --- a/src/Query/Query.php +++ b/src/Query/Query.php @@ -833,24 +833,13 @@ protected function queryScalar(string|ExpressionInterface $selectExpression): bo && empty($this->having) && empty($this->union) ) { - $select = $this->select; - $order = $this->orderBy; - $limit = $this->limit; - $offset = $this->offset; + $query = clone $this; + $query->select = [$selectExpression]; + $query->orderBy = []; + $query->limit = null; + $query->offset = null; - $this->select = [$selectExpression]; - $this->orderBy = []; - $this->limit = null; - $this->offset = null; - - $command = $this->createCommand(); - - $this->select = $select; - $this->orderBy = $order; - $this->limit = $limit; - $this->offset = $offset; - - return $command->queryScalar(); + return $query->createCommand()->queryScalar(); } $query = (new self($this->db))->select($selectExpression)->from(['c' => $this]); From ada8b40bee0c3df0a24eb85f9d1cbfeba75347b9 Mon Sep 17 00:00:00 2001 From: Sergei Tigrov Date: Mon, 20 Apr 2026 12:09:29 +0700 Subject: [PATCH 2/2] Update CHANGELOG [skip ci] --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 957cb6fd1..75e0d939f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,7 +2,7 @@ ## 2.0.2 under development -- no changes in this release. +- Enh #1172: Refactor `Query::queryScalar()` to use a cloned `Query` object (@darkspock) ## 2.0.1 February 09, 2026