Skip to content

Commit 99f9f92

Browse files
authored
fix: clear bindings after DELETE and COUNT query execution (#10693)
1 parent 0094803 commit 99f9f92

6 files changed

Lines changed: 245 additions & 23 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2385,6 +2385,8 @@ public function countAllResults(bool $reset = true)
23852385

23862386
if ($reset) {
23872387
$this->resetSelect();
2388+
$this->binds = [];
2389+
$this->bindsKeyCount = [];
23882390
} elseif (! isset($this->QBOrderBy)) {
23892391
$this->QBOrderBy = $orderBy;
23902392
}
@@ -3485,7 +3487,18 @@ public function delete($where = '', ?int $limit = null, bool $resetData = true)
34853487
$this->resetWrite();
34863488
}
34873489

3488-
return $this->testMode ? $sql : $this->db->query($sql, $this->binds, false);
3490+
if ($this->testMode) {
3491+
return $sql;
3492+
}
3493+
3494+
$result = $this->db->query($sql, $this->binds, false);
3495+
3496+
if ($resetData) {
3497+
$this->binds = [];
3498+
$this->bindsKeyCount = [];
3499+
}
3500+
3501+
return $result;
34893502
}
34903503

34913504
/**

‎system/Database/SQLSRV/Builder.php‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -582,7 +582,18 @@ public function delete($where = '', ?int $limit = null, bool $resetData = true)
582582
$this->resetWrite();
583583
}
584584

585-
return $this->testMode ? $sql : $this->db->query($sql, $this->binds, false);
585+
if ($this->testMode) {
586+
return $sql;
587+
}
588+
589+
$result = $this->db->query($sql, $this->binds, false);
590+
591+
if ($resetData) {
592+
$this->binds = [];
593+
$this->bindsKeyCount = [];
594+
}
595+
596+
return $result;
586597
}
587598

588599
/**
Lines changed: 186 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,186 @@
1+
<?php
2+
3+
declare(strict_types=1);
4+
5+
/**
6+
* This file is part of CodeIgniter 4 framework.
7+
*
8+
* (c) CodeIgniter Foundation <admin@codeigniter.com>
9+
*
10+
* For the full copyright and license information, please view
11+
* the LICENSE file that was distributed with this source code.
12+
*/
13+
14+
namespace CodeIgniter\Database\Builder;
15+
16+
use CodeIgniter\Database\BaseBuilder;
17+
use CodeIgniter\Database\Query;
18+
use CodeIgniter\Database\SQLSRV\Builder as SQLSRVBuilder;
19+
use CodeIgniter\Test\CIUnitTestCase;
20+
use CodeIgniter\Test\Mock\MockConnection;
21+
use CodeIgniter\Test\Mock\MockResult;
22+
use PHPUnit\Framework\Attributes\DataProvider;
23+
use PHPUnit\Framework\Attributes\Group;
24+
use PHPUnit\Framework\MockObject\MockObject;
25+
26+
/**
27+
* @internal
28+
*/
29+
#[Group('Others')]
30+
final class ExecutionBindingsTest extends CIUnitTestCase
31+
{
32+
#[DataProvider('provideExecution')]
33+
public function testExecutionClearsBindingsOnReset(string $method): void
34+
{
35+
$db = $this->connection();
36+
$builder = new BaseBuilder('jobs', $db);
37+
38+
for ($id = 1; $id <= 3; $id++) {
39+
$result = $builder->where('id >', $id)->where('id <', $id + 10)->{$method}();
40+
41+
$this->assertSame($method === 'delete' ? true : 0, $result);
42+
$this->assertStringContainsString('"id" > ' . $id, $db->lastQuery->getQuery());
43+
$this->assertSame([], $builder->getBinds());
44+
$this->assertSame([], $this->getPrivateProperty($builder, 'bindsKeyCount'));
45+
}
46+
}
47+
48+
#[DataProvider('provideExecution')]
49+
public function testExecutionPreservesBindingsWithoutReset(string $method): void
50+
{
51+
$db = $this->connection();
52+
$builder = new BaseBuilder('jobs', $db);
53+
$builder->where('id', 3);
54+
55+
for ($i = 0; $i < 2; $i++) {
56+
if ($method === 'delete') {
57+
$builder->delete('', null, false);
58+
} else {
59+
$builder->countAllResults(false);
60+
}
61+
62+
$this->assertSame(['id' => [3, true]], $builder->getBinds());
63+
$this->assertStringContainsString('"id" = 3', $db->lastQuery->getQuery());
64+
}
65+
66+
$builder->{$method}();
67+
$this->assertSame([], $builder->getBinds());
68+
}
69+
70+
#[DataProvider('provideExecution')]
71+
public function testFailedExecutionClearsBindingsOnReset(string $method): void
72+
{
73+
$db = $this->connection(false);
74+
$builder = new BaseBuilder('jobs', $db);
75+
$builder->where('id', 3);
76+
77+
$this->assertSame($method === 'delete' ? false : 0, $builder->{$method}());
78+
$this->assertSame([], $builder->getBinds());
79+
$this->assertSameSql('SELECT * FROM "jobs"', $builder->getCompiledSelect(false));
80+
}
81+
82+
#[DataProvider('provideExecution')]
83+
public function testTestModeRetainsBindingsForReturnedPlaceholders(string $method): void
84+
{
85+
$builder = new BaseBuilder('jobs', $this->connection());
86+
$builder->where('id', 3)->testMode();
87+
88+
$sql = $builder->{$method}();
89+
90+
$this->assertIsString($sql);
91+
$this->assertStringContainsString(':id:', $sql);
92+
$this->assertSame(['id' => [3, true]], $builder->getBinds());
93+
}
94+
95+
#[DataProvider('provideExecution')]
96+
public function testExecutionWithSubqueryPreservesInnerBindings(string $method): void
97+
{
98+
$db = $this->connection();
99+
$subquery = (new BaseBuilder('user_jobs', $db))->select('job_id')->where('id', 7);
100+
$builder = (new BaseBuilder('jobs', $db))->whereIn('id', $subquery);
101+
102+
if ($method === 'countAllResults') {
103+
$builder->groupBy('id');
104+
}
105+
106+
$builder->{$method}();
107+
108+
$this->assertStringContainsString('IN (SELECT "job_id" FROM "user_jobs" WHERE "id" = 7)', str_replace("\n", ' ', $db->lastQuery->getQuery()));
109+
$this->assertSame([], $builder->getBinds());
110+
$this->assertSame(['id' => [7, true]], $subquery->getBinds());
111+
112+
if ($method === 'countAllResults') {
113+
$this->assertStringContainsString('CI_count_all_results', $db->lastQuery->getQuery());
114+
}
115+
}
116+
117+
/**
118+
* @return iterable<string, array{string}>
119+
*/
120+
public static function provideExecution(): iterable
121+
{
122+
yield 'delete' => ['delete'];
123+
124+
yield 'count' => ['countAllResults'];
125+
}
126+
127+
public function testCompiledDeleteKeepsBindingsUntilFinalCompilation(): void
128+
{
129+
$builder = new BaseBuilder('jobs', $this->connection());
130+
$builder->where('id', 3);
131+
132+
$this->assertSameSql('DELETE FROM "jobs" WHERE "id" = 3', $builder->getCompiledDelete(false));
133+
$this->assertSame(['id' => [3, true]], $builder->getBinds());
134+
$this->assertSameSql('DELETE FROM "jobs" WHERE "id" = 3', $builder->getCompiledDelete());
135+
$this->assertSame([], $builder->getBinds());
136+
}
137+
138+
public function testSQLSRVDeleteClearsBindingsAfterExecution(): void
139+
{
140+
foreach ([true, false] as $success) {
141+
$db = $this->connection($success);
142+
$builder = new SQLSRVBuilder('jobs', $db);
143+
144+
for ($id = 1; $id <= 3; $id++) {
145+
$this->assertSame($success, $builder->where('id', $id)->delete());
146+
$this->assertSame([], $builder->getBinds());
147+
$this->assertStringContainsString('"id" = ' . $id, $db->lastQuery->getQuery());
148+
}
149+
}
150+
}
151+
152+
public function testSQLSRVDeletePreservesBindingsWhenNeeded(): void
153+
{
154+
$builder = new SQLSRVBuilder('jobs', $this->connection());
155+
$builder->where('id', 3)->delete('', null, false);
156+
157+
$this->assertSame(['id' => [3, true]], $builder->getBinds());
158+
$sql = $builder->getCompiledDelete(false);
159+
$this->assertStringContainsString('"id" = 3', $sql);
160+
$this->assertSame(['id' => [3, true]], $builder->getBinds());
161+
$this->assertSame($sql, $builder->getCompiledDelete());
162+
$this->assertSame([], $builder->getBinds());
163+
}
164+
165+
private function connection(bool $success = true): MockConnection
166+
{
167+
$result = $this->createMock(MockResult::class);
168+
$result->method('getRow')->willReturn((object) ['numrows' => 0]);
169+
170+
$db = $this->getMockBuilder(MockConnection::class)
171+
->setConstructorArgs([[]])
172+
->onlyMethods(['query'])
173+
->getMock();
174+
175+
$db->method('query')->willReturnCallback(static function (string $sql, array $binds, bool $setEscapeFlags) use ($db, $result, $success): bool|MockObject {
176+
$query = new Query($db);
177+
$query->setQuery($sql, $binds, $setEscapeFlags);
178+
$query->getQuery();
179+
$db->lastQuery = $query;
180+
181+
return $success ? ($query->isWriteType() ? true : $result) : false;
182+
});
183+
184+
return $db;
185+
}
186+
}

‎user_guide_src/source/changelogs/v4.8.0.rst‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ Behavior Changes
7373
- **Config:** ``BaseConfig`` now scans the environment once instead of checking every property against it, which makes building config classes
7474
several times faster without config caching and in Worker Mode. As a result, a bare ``putenv()`` call (adding, changing, or removing a variable) made
7575
after the first config class was built may not be seen until ``BaseConfig::reset()`` runs, including in later requests in Worker Mode. See :ref:`upgrade-480-config-env-lookups`.
76-
- **Database:** ``BaseBuilder::getCompiledSelect()``, ``getCompiledInsert()``, ``getCompiledUpdate()`` and ``getCompiledDelete()`` now clear bindings and binding counters after compilation when ``$reset = true`` (the default), preventing binding accumulation when a builder is reused. ``getBinds()`` now returns an empty array after these calls. This aligns ``getCompiledSelect()`` with its documented reset behavior, which should match ``get()``. Pass ``false`` to retain the query and its bindings. See :ref:`upgrade-480-query-builder-bindings`.
76+
- **Database:** ``BaseBuilder::getCompiledSelect()``, ``getCompiledInsert()``, ``getCompiledUpdate()``, ``getCompiledDelete()``, ``delete()`` and ``countAllResults()`` now clear bindings and binding counters after compilation or execution when their reset parameter is enabled (the default). This prevents accumulation when a builder is reused, but ``getBinds()`` now returns an empty array after these calls. This also aligns ``getCompiledSelect()`` with its documented reset behavior, which should match ``get()``. Pass ``false`` for the reset parameter to retain the query and its bindings. Test mode retains bindings needed by its returned raw SQL. See :ref:`upgrade-480-query-builder-bindings`.
7777
- **Database:** The Postgre driver's ``$db->error()['code']`` previously always returned ``''``. It now returns the 5-character SQLSTATE string for query and transaction failures (e.g., ``'42P01'``), or ``'08006'`` for connection-level failures. Code that relied on ``$db->error()['code'] === ''`` will need updating.
7878
- **Debug:** ``CodeIgniter\Debug\Toolbar\Collectors\BaseCollector`` is now ``abstract``. Custom toolbar collectors must extend it; code that instantiated it directly with ``new BaseCollector()`` will now throw an ``Error``.
7979
- **Filters:** HTTP method matching for method-based filters is now case-sensitive. The keys in ``Config\Filters::$methods`` must exactly match the request method

‎user_guide_src/source/database/query_builder.rst‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -913,6 +913,12 @@ first parameter.
913913

914914
.. literalinclude:: query_builder/073.php
915915

916+
.. note::
917+
**Changed in version 4.8.0.** With ``$reset = true`` (the default), bindings and
918+
binding counters are cleared after execution, so ``getBinds()`` returns an empty
919+
array. Pass ``false`` to retain the query conditions and bindings. Test mode
920+
retains bindings for the placeholders in its returned SQL.
921+
916922
.. _query-builder-exists:
917923

918924
$builder->exists()
@@ -1654,6 +1660,12 @@ the data to the first parameter of the method:
16541660
If you want to delete all data from a table, you can use the ``truncate()``
16551661
method, or ``emptyTable()``.
16561662

1663+
.. note::
1664+
**Changed in version 4.8.0.** With ``$resetData = true`` (the default), bindings
1665+
and binding counters are cleared after execution, so ``getBinds()`` returns an
1666+
empty array. Pass ``false`` as the third argument to retain the query conditions
1667+
and bindings. Test mode retains bindings for the placeholders in its returned SQL.
1668+
16571669
$builder->getCompiledDelete()
16581670
-----------------------------
16591671

‎user_guide_src/source/installation/upgrade_480.rst‎

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -22,33 +22,33 @@ Breaking Changes
2222

2323
.. _upgrade-480-query-builder-bindings:
2424

25-
Compiled Query Builder Bindings
26-
===============================
25+
Query Builder Bindings
26+
======================
2727

28-
``getCompiledSelect()``, ``getCompiledInsert()``, ``getCompiledUpdate()`` and
29-
``getCompiledDelete()`` now clear their bindings and binding counters after
30-
compilation when ``$reset = true`` (the default). Previously, these methods
31-
reset the query clauses but retained the bindings, which accumulated when the
32-
same builder was reused and made subsequent query compilation increasingly
33-
expensive.
28+
``getCompiledSelect()``, ``getCompiledInsert()``, ``getCompiledUpdate()``,
29+
``getCompiledDelete()``, ``delete()`` and ``countAllResults()`` now clear their
30+
bindings and binding counters after compilation or execution when their reset
31+
parameter is enabled (the default). This prevents accumulation when a builder
32+
is reused, but ``getBinds()`` now returns an empty array after these calls.
33+
Bindings are also cleared when the database query returns ``false``.
3434

3535
The :ref:`getCompiledSelect() documentation <query-builder-get-compiled-select>`
3636
already states that the default reset should work just like ``get()``.
37-
Clearing the bindings corrects that inconsistency, but changes the result of
38-
``getBinds()`` after compilation: it now returns an empty array.
39-
40-
If your application reads the bindings after compilation or reuses the query,
41-
pass ``false`` to preserve them:
37+
Clearing the bindings corrects that inconsistency while changing the observable
38+
result of ``getBinds()``.
4239

43-
.. code-block:: php
40+
To retain the query and its bindings, pass ``false`` as the first argument to
41+
any of the compiled methods or ``countAllResults()``, or as the third argument
42+
to ``delete()``: ``$builder->delete('', null, false)``. This also retains query
43+
clauses such as WHERE and LIMIT.
4444

45-
$sql = $builder->getCompiledSelect(false);
46-
$binds = $builder->getBinds();
45+
If you only need a snapshot of the bindings, read them before compilation or
46+
execution instead. When passing conditions directly to ``delete()``, move them
47+
into ``where()`` first so their bindings are available before execution.
4748

48-
Passing ``false`` also retains the query clauses, including WHERE and LIMIT.
49-
If you only need a snapshot of the bindings while retaining the default reset
50-
behavior, call ``getBinds()`` before compiling the query instead.
51-
The same migration applies to the compiled INSERT, UPDATE and DELETE methods.
49+
Test mode retains bindings needed by the placeholders in its returned raw SQL.
50+
In particular, ``getCompiledDelete()`` needs these bindings to finish compilation
51+
and clears them afterwards according to its own reset parameter.
5252

5353
Query Builder JOIN Overrides
5454
============================

0 commit comments

Comments
 (0)