Skip to content

Commit b14c450

Browse files
authored
feat: add Query Builder explain() (#10238)
1 parent be70740 commit b14c450

11 files changed

Lines changed: 381 additions & 0 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2055,6 +2055,47 @@ public function get(?int $limit = null, int $offset = 0, bool $reset = true)
20552055
return $result;
20562056
}
20572057

2058+
/**
2059+
* Explains the select statement based on the other functions called
2060+
* and runs the query.
2061+
*
2062+
* @return BaseResult|false|Query|string SQL string when test mode is enabled.
2063+
*/
2064+
public function explain(bool $reset = true)
2065+
{
2066+
$this->assertExplainSupported();
2067+
2068+
$sql = $this->compileExplain($this->compileSelect());
2069+
2070+
$result = $this->testMode
2071+
? $this->compileFinalQuery($sql)
2072+
: $this->db->query($sql, $this->binds, false);
2073+
2074+
if ($reset) {
2075+
$this->resetSelect();
2076+
2077+
// Clear our binds so we don't eat up memory
2078+
$this->binds = [];
2079+
}
2080+
2081+
return $result;
2082+
}
2083+
2084+
/**
2085+
* Ensures the current driver supports explaining Query Builder selects.
2086+
*/
2087+
protected function assertExplainSupported(): void
2088+
{
2089+
}
2090+
2091+
/**
2092+
* Compiles an execution-plan query for the current SELECT query.
2093+
*/
2094+
protected function compileExplain(string $sql): string
2095+
{
2096+
return 'EXPLAIN ' . $sql;
2097+
}
2098+
20582099
/**
20592100
* Generates a platform-specific query string that counts all records in
20602101
* the particular table

‎system/Database/OCI8/Builder.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,14 @@ protected function compileLockForUpdate(): string
233233
return parent::compileLockForUpdate();
234234
}
235235

236+
/**
237+
* Ensures the current driver supports explaining Query Builder selects.
238+
*/
239+
protected function assertExplainSupported(): never
240+
{
241+
throw new DatabaseException('OCI8 does not support explain().');
242+
}
243+
236244
/**
237245
* Generates a platform-specific batch update string from the supplied data
238246
*/

‎system/Database/SQLSRV/Builder.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -646,6 +646,14 @@ protected function compileLockForUpdate(): string
646646
return '';
647647
}
648648

649+
/**
650+
* Ensures the current driver supports explaining Query Builder selects.
651+
*/
652+
protected function assertExplainSupported(): never
653+
{
654+
throw new DatabaseException('SQLSRV does not support explain().');
655+
}
656+
649657
/**
650658
* Compiles the select statement based on the other functions called
651659
* and runs the query

‎system/Database/SQLite3/Builder.php‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,14 @@ protected function compileLockForUpdate(): string
6767
return '';
6868
}
6969

70+
/**
71+
* Compiles an execution-plan query for the current SELECT query.
72+
*/
73+
protected function compileExplain(string $sql): string
74+
{
75+
return 'EXPLAIN QUERY PLAN ' . $sql;
76+
}
77+
7078
/**
7179
* Replace statement
7280
*

‎system/Model.php‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,10 +16,12 @@
1616
use Closure;
1717
use CodeIgniter\Database\BaseBuilder;
1818
use CodeIgniter\Database\BaseConnection;
19+
use CodeIgniter\Database\BaseResult;
1920
use CodeIgniter\Database\ConnectionInterface;
2021
use CodeIgniter\Database\Exceptions\DatabaseException;
2122
use CodeIgniter\Database\Exceptions\DataException;
2223
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
24+
use CodeIgniter\Database\Query;
2325
use CodeIgniter\Entity\Entity;
2426
use CodeIgniter\Exceptions\BadMethodCallException;
2527
use CodeIgniter\Exceptions\InvalidArgumentException;
@@ -532,6 +534,18 @@ public function countAllResults(bool $reset = true, bool $test = false)
532534
return $this->builder()->testMode($test)->countAllResults($reset);
533535
}
534536

537+
/**
538+
* Explains the current Model query.
539+
*
540+
* @return BaseResult|false|Query|string Returns a SQL string if in test mode.
541+
*/
542+
public function explain(bool $reset = true, bool $test = false)
543+
{
544+
$this->prepareSoftDeleteQuery($reset);
545+
546+
return $this->builder()->testMode($test)->explain($reset);
547+
}
548+
535549
/**
536550
* Determines whether the current Model query would return at least one row.
537551
*
Lines changed: 143 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,143 @@
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\Exceptions\DatabaseException;
18+
use CodeIgniter\Database\OCI8\Builder as OCI8Builder;
19+
use CodeIgniter\Database\SQLite3\Builder as SQLite3Builder;
20+
use CodeIgniter\Database\SQLSRV\Builder as SQLSRVBuilder;
21+
use CodeIgniter\Test\CIUnitTestCase;
22+
use CodeIgniter\Test\Mock\MockConnection;
23+
use PHPUnit\Framework\Attributes\Group;
24+
25+
/**
26+
* @internal
27+
*/
28+
#[Group('Others')]
29+
final class ExplainTest extends CIUnitTestCase
30+
{
31+
protected $db;
32+
33+
protected function setUp(): void
34+
{
35+
parent::setUp();
36+
37+
$this->db = new MockConnection([]);
38+
}
39+
40+
public function testExplainReturnsSqlInTestMode(): void
41+
{
42+
$builder = new BaseBuilder('jobs', $this->db);
43+
$builder->testMode();
44+
45+
$answer = $builder->where('id >', 3)->explain(false);
46+
47+
$expectedSQL = 'EXPLAIN SELECT * FROM "jobs" WHERE "id" > 3';
48+
49+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
50+
}
51+
52+
public function testSQLiteExplainUsesQueryPlanInTestMode(): void
53+
{
54+
$builder = new SQLite3Builder('jobs', $this->db);
55+
$builder->testMode();
56+
57+
$answer = $builder->where('id >', 3)->explain(false);
58+
59+
$expectedSQL = 'EXPLAIN QUERY PLAN SELECT * FROM "jobs" WHERE "id" > 3';
60+
61+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
62+
}
63+
64+
public function testExplainResetsByDefault(): void
65+
{
66+
$builder = new BaseBuilder('jobs', $this->db);
67+
$builder->testMode();
68+
69+
$builder->where('id >', 3)->explain();
70+
71+
$this->assertSame('SELECT * FROM "jobs"', str_replace("\n", ' ', $builder->getCompiledSelect(false)));
72+
$this->assertSame([], $builder->getBinds());
73+
}
74+
75+
public function testExplainHonorsResetFalse(): void
76+
{
77+
$builder = new BaseBuilder('jobs', $this->db);
78+
$builder->testMode();
79+
80+
$builder->where('id >', 3)->explain(false);
81+
82+
$this->assertSame('SELECT * FROM "jobs" WHERE "id" > 3', str_replace("\n", ' ', $builder->getCompiledSelect(false)));
83+
$this->assertSame([
84+
'id' => [
85+
3,
86+
true,
87+
],
88+
], $builder->getBinds());
89+
}
90+
91+
public function testExplainReturnsFalseWhenQueryFails(): void
92+
{
93+
$db = new MockConnection([]);
94+
$db->shouldReturn('execute', false);
95+
96+
$builder = new BaseBuilder('jobs', $db);
97+
98+
$this->assertFalse($builder->where('id >', 3)->explain());
99+
$this->assertSame('SELECT * FROM "jobs"', str_replace("\n", ' ', $builder->getCompiledSelect(false)));
100+
$this->assertSame([], $builder->getBinds());
101+
}
102+
103+
public function testSQLSRVExplainIsNotSupported(): void
104+
{
105+
$builder = new SQLSRVBuilder('jobs', new MockConnection([
106+
'DBDriver' => 'SQLSRV',
107+
'database' => 'test',
108+
'schema' => 'dbo',
109+
]));
110+
111+
$this->expectException(DatabaseException::class);
112+
$this->expectExceptionMessage('SQLSRV does not support explain().');
113+
114+
$builder->explain();
115+
}
116+
117+
public function testSQLSRVExplainChecksSupportBeforeCompilingSelect(): void
118+
{
119+
$db = new MockConnection([
120+
'DBDriver' => 'SQLSRV',
121+
'database' => 'test',
122+
'schema' => 'dbo',
123+
]);
124+
125+
$builder = new SQLSRVBuilder('jobs', $db);
126+
$builder->union(new SQLSRVBuilder('jobs', $db))->lockForUpdate();
127+
128+
$this->expectException(DatabaseException::class);
129+
$this->expectExceptionMessage('SQLSRV does not support explain().');
130+
131+
$builder->explain();
132+
}
133+
134+
public function testOCI8ExplainIsNotSupported(): void
135+
{
136+
$builder = new OCI8Builder('jobs', new MockConnection(['DBDriver' => 'OCI8']));
137+
138+
$this->expectException(DatabaseException::class);
139+
$this->expectExceptionMessage('OCI8 does not support explain().');
140+
141+
$builder->explain();
142+
}
143+
}
Lines changed: 66 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
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\Live;
15+
16+
use CodeIgniter\Database\Exceptions\DatabaseException;
17+
use CodeIgniter\Database\ResultInterface;
18+
use CodeIgniter\Test\CIUnitTestCase;
19+
use CodeIgniter\Test\DatabaseTestTrait;
20+
use PHPUnit\Framework\Attributes\Group;
21+
use Tests\Support\Database\Seeds\CITestSeeder;
22+
23+
/**
24+
* @internal
25+
*/
26+
#[Group('DatabaseLive')]
27+
final class ExplainTest extends CIUnitTestCase
28+
{
29+
use DatabaseTestTrait;
30+
31+
protected $refresh = true;
32+
protected $seed = CITestSeeder::class;
33+
34+
public function testExplainReturnsResultForSupportedDrivers(): void
35+
{
36+
if (in_array($this->db->DBDriver, ['OCI8', 'SQLSRV'], true)) {
37+
$this->markTestSkipped($this->db->DBDriver . ' does not support explain().');
38+
}
39+
40+
$result = $this->db->table('job')
41+
->where('name', 'Developer')
42+
->explain();
43+
44+
$this->assertInstanceOf(ResultInterface::class, $result);
45+
46+
$expectedPrefix = $this->db->DBDriver === 'SQLite3'
47+
? 'EXPLAIN QUERY PLAN SELECT'
48+
: 'EXPLAIN SELECT';
49+
50+
$this->assertStringStartsWith(
51+
$expectedPrefix,
52+
str_replace("\n", ' ', (string) $this->db->getLastQuery()),
53+
);
54+
}
55+
56+
public function testExplainThrowsForUnsupportedDrivers(): void
57+
{
58+
if (! in_array($this->db->DBDriver, ['OCI8', 'SQLSRV'], true)) {
59+
$this->markTestSkipped($this->db->DBDriver . ' supports explain().');
60+
}
61+
62+
$this->expectException(DatabaseException::class);
63+
64+
$this->db->table('job')->explain();
65+
}
66+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
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\Models;
15+
16+
use PHPUnit\Framework\Attributes\Group;
17+
use Tests\Support\Models\UserModel;
18+
19+
/**
20+
* @internal
21+
*/
22+
#[Group('DatabaseLive')]
23+
final class ExplainModelTest extends LiveModelTestCase
24+
{
25+
public function testExplainRespectsSoftDeletesInTestMode(): void
26+
{
27+
if (in_array($this->db->DBDriver, ['OCI8', 'SQLSRV'], true)) {
28+
$this->markTestSkipped($this->db->DBDriver . ' does not support explain().');
29+
}
30+
31+
$this->createModel(UserModel::class);
32+
33+
$sql = $this->model->where('id', 1)->explain(test: true);
34+
35+
$expectedPrefix = $this->db->DBDriver === 'SQLite3'
36+
? 'EXPLAIN QUERY PLAN SELECT'
37+
: 'EXPLAIN SELECT';
38+
39+
$this->assertStringStartsWith($expectedPrefix, str_replace("\n", ' ', (string) $sql));
40+
$this->assertStringContainsString('deleted_at', (string) $sql);
41+
}
42+
43+
public function testExplainWithDeletedOmitsSoftDeleteConstraintInTestMode(): void
44+
{
45+
if (in_array($this->db->DBDriver, ['OCI8', 'SQLSRV'], true)) {
46+
$this->markTestSkipped($this->db->DBDriver . ' does not support explain().');
47+
}
48+
49+
$this->createModel(UserModel::class);
50+
51+
$sql = $this->model->withDeleted()->where('id', 1)->explain(test: true);
52+
53+
$this->assertStringNotContainsString('deleted_at', (string) $sql);
54+
}
55+
}

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -219,6 +219,7 @@ Query Builder
219219
-------------
220220

221221
- Added ``exists()`` and ``doesntExist()`` to Query Builder to check whether the current Query Builder query would return at least one row. See :ref:`query-builder-exists`.
222+
- Added ``explain()`` to Query Builder to run execution-plan queries for the current ``SELECT`` query. See :ref:`query-builder-explain`.
222223
- Added ``havingBetween()``, ``orHavingBetween()``, ``havingNotBetween()``, and ``orHavingNotBetween()`` to Query Builder. See :ref:`query-builder-having-between`.
223224
- Added ``whereBetween()``, ``orWhereBetween()``, ``whereNotBetween()``, and ``orWhereNotBetween()`` to Query Builder. See :ref:`query-builder-where-between`.
224225
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.

0 commit comments

Comments
 (0)