Skip to content

Commit 90818ff

Browse files
committed
refactor(query-builder): address review feedbacks
Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 0a75b7b commit 90818ff

6 files changed

Lines changed: 112 additions & 19 deletions

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2049,7 +2049,7 @@ public function countAll(bool $reset = true)
20492049
}
20502050

20512051
/**
2052-
* Determines whether the current Query Builder conditions match any rows.
2052+
* Determines whether the current Query Builder query would return at least one row.
20532053
*
20542054
* @return bool|string SQL string when test mode is enabled.
20552055
*/
@@ -2061,7 +2061,7 @@ public function exists(bool $reset = true)
20612061
}
20622062

20632063
/**
2064-
* Determines whether the current Query Builder conditions do not match any rows.
2064+
* Determines whether the current Query Builder query would not return any rows.
20652065
*
20662066
* @return bool|string SQL string when test mode is enabled.
20672067
*/
@@ -2117,7 +2117,7 @@ protected function compileExists(): string
21172117
$lockForUpdate = $this->QBLockForUpdate;
21182118
$select = $this->QBSelect;
21192119
$noEscape = $this->QBNoEscape;
2120-
$needsSubquery = $this->QBUnion !== [] || $this->QBGroupBy !== [] || $this->QBHaving !== [] || $this->QBOffset !== false;
2120+
$needsSubquery = $this->QBSelectUsesAggregate || $this->QBUnion !== [] || $this->QBGroupBy !== [] || $this->QBHaving !== [] || $this->QBOffset !== false;
21212121

21222122
$this->QBOrderBy = null;
21232123
$this->QBLockForUpdate = false;

‎system/Model.php‎

Lines changed: 34 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -42,8 +42,6 @@
4242
*
4343
* @property-read BaseConnection $db
4444
*
45-
* @method bool doesntExist(bool $reset = true)
46-
* @method bool exists(bool $reset = true)
4745
* @method $this groupBy($by, ?bool $escape = null)
4846
* @method $this groupEnd()
4947
* @method $this groupStart()
@@ -528,6 +526,40 @@ public function getIdValue($row)
528526
}
529527

530528
public function countAllResults(bool $reset = true, bool $test = false)
529+
{
530+
$this->prepareSoftDeleteQuery($reset);
531+
532+
return $this->builder()->testMode($test)->countAllResults($reset);
533+
}
534+
535+
/**
536+
* Determines whether the current Model query would return at least one row.
537+
*
538+
* @return bool|string Returns a SQL string if in test mode.
539+
*/
540+
public function exists(bool $reset = true, bool $test = false)
541+
{
542+
$this->prepareSoftDeleteQuery($reset);
543+
544+
return $this->builder()->testMode($test)->exists($reset);
545+
}
546+
547+
/**
548+
* Determines whether the current Model query would not return any rows.
549+
*
550+
* @return bool|string Returns a SQL string if in test mode.
551+
*/
552+
public function doesntExist(bool $reset = true, bool $test = false)
553+
{
554+
$this->prepareSoftDeleteQuery($reset);
555+
556+
return $this->builder()->testMode($test)->doesntExist($reset);
557+
}
558+
559+
/**
560+
* Applies the Model soft-delete constraint before terminal Builder operations.
561+
*/
562+
private function prepareSoftDeleteQuery(bool $reset): void
531563
{
532564
if ($this->tempUseSoftDeletes) {
533565
$this->builder()->where($this->table . '.' . $this->deletedField, null);
@@ -539,8 +571,6 @@ public function countAllResults(bool $reset = true, bool $test = false)
539571
$this->tempUseSoftDeletes = $reset
540572
? $this->useSoftDeletes
541573
: ($this->useSoftDeletes ? false : $this->useSoftDeletes);
542-
543-
return $this->builder()->testMode($test)->countAllResults($reset);
544574
}
545575

546576
/**

‎tests/system/Database/Builder/ExistsTest.php‎

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,24 @@ public function testExistsWithGroupByAndHaving(): void
157157
);
158158
}
159159

160+
public function testExistsWithAggregateSelection(): void
161+
{
162+
$builder = new BaseBuilder('jobs', $this->db);
163+
$builder->testMode();
164+
165+
$answer = $builder->selectCount('id', 'total')
166+
->where('id >', 3)
167+
->exists(false);
168+
169+
$expectedSQL = 'SELECT 1 FROM ( SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > :id: ) CI_exists LIMIT 1';
170+
171+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $answer));
172+
$this->assertSame(
173+
'SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > 3',
174+
str_replace("\n", ' ', $builder->getCompiledSelect(false)),
175+
);
176+
}
177+
160178
public function testExistsWithUnion(): void
161179
{
162180
$builder = new BaseBuilder('jobs', $this->db);
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
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 ExistsModelTest extends LiveModelTestCase
24+
{
25+
public function testExistsRespectsSoftDeletes(): void
26+
{
27+
$this->createModel(UserModel::class);
28+
$this->model->delete(1);
29+
30+
$this->assertFalse($this->model->where('id', 1)->exists());
31+
$this->assertTrue($this->model->withDeleted()->where('id', 1)->exists());
32+
}
33+
34+
public function testDoesntExistRespectsSoftDeletes(): void
35+
{
36+
$this->createModel(UserModel::class);
37+
$this->model->delete(1);
38+
39+
$this->assertTrue($this->model->where('id', 1)->doesntExist());
40+
$this->assertFalse($this->model->withDeleted()->where('id', 1)->doesntExist());
41+
}
42+
}

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -218,8 +218,8 @@ Database
218218
Query Builder
219219
-------------
220220

221+
- 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`.
221222
- Added ``havingBetween()``, ``orHavingBetween()``, ``havingNotBetween()``, and ``orHavingNotBetween()`` to Query Builder. See :ref:`query-builder-having-between`.
222-
- Added ``exists()`` and ``doesntExist()`` to Query Builder to check whether the current Query Builder conditions match any rows. See :ref:`query-builder-exists`.
223223
- Added ``whereBetween()``, ``orWhereBetween()``, ``whereNotBetween()``, and ``orWhereNotBetween()`` to Query Builder. See :ref:`query-builder-where-between`.
224224
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.
225225
- Added ``whereExists()``, ``orWhereExists()``, ``whereNotExists()``, and ``orWhereNotExists()`` to add ``EXISTS`` and ``NOT EXISTS`` subquery conditions. See :ref:`query-builder-where-exists`.

‎user_guide_src/source/database/query_builder.rst‎

Lines changed: 14 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -858,23 +858,26 @@ $builder->exists()
858858

859859
.. versionadded:: 4.8.0
860860

861-
Permits you to determine whether the current Query Builder conditions match
862-
any rows:
861+
Permits you to determine whether the current Query Builder query would return
862+
at least one row:
863863

864864
.. literalinclude:: query_builder/128.php
865865

866-
This method returns ``true`` when at least one row exists and ``false`` when no
867-
rows match. It respects any existing ``limit()`` and ``offset()`` clauses, and
868-
resets the current Query Builder state by default. If you need to keep the
869-
current Query Builder state, you can pass ``false`` as the first parameter.
866+
This method returns ``true`` when the query would return at least one row and
867+
``false`` when it would not. It respects any existing ``limit()`` and
868+
``offset()`` clauses, and resets the current Query Builder state by default. If
869+
you need to keep the current Query Builder state, you can pass ``false`` as the
870+
first parameter.
871+
If the existence query fails and ``DBDebug`` is ``false``, both methods return
872+
``false``.
870873

871874
$builder->doesntExist()
872875
-----------------------
873876

874877
.. versionadded:: 4.8.0
875878

876879
This method is identical to ``exists()``, except that it returns ``true`` when
877-
no rows match.
880+
the query would not return any rows.
878881

879882
.. note:: These methods execute the current Query Builder query to check for
880883
rows. To add an SQL ``EXISTS`` predicate to a query, use
@@ -1599,18 +1602,18 @@ Class Reference
15991602
.. php:method:: exists([$reset = true])
16001603
16011604
:param bool $reset: Whether to reset values for SELECTs
1602-
:returns: Whether the query has any matching rows
1605+
:returns: Whether the query would return at least one row
16031606
:rtype: bool
16041607

1605-
Determines whether the current Query Builder conditions match any rows.
1608+
Determines whether the current Query Builder query would return at least one row.
16061609

16071610
.. php:method:: doesntExist([$reset = true])
16081611
16091612
:param bool $reset: Whether to reset values for SELECTs
1610-
:returns: Whether the query has no matching rows
1613+
:returns: Whether the query would not return any rows
16111614
:rtype: bool
16121615

1613-
Determines whether the current Query Builder conditions do not match any rows.
1616+
Determines whether the current Query Builder query would not return any rows.
16141617

16151618
.. php:method:: get([$limit = null[, $offset = null[, $reset = true]]]])
16161619

0 commit comments

Comments
 (0)