Skip to content

Commit 8213211

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

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
@@ -1985,7 +1985,7 @@ public function countAll(bool $reset = true)
19851985
}
19861986

19871987
/**
1988-
* Determines whether the current Query Builder conditions match any rows.
1988+
* Determines whether the current Query Builder query would return at least one row.
19891989
*
19901990
* @return bool|string SQL string when test mode is enabled.
19911991
*/
@@ -1997,7 +1997,7 @@ public function exists(bool $reset = true)
19971997
}
19981998

19991999
/**
2000-
* Determines whether the current Query Builder conditions do not match any rows.
2000+
* Determines whether the current Query Builder query would not return any rows.
20012001
*
20022002
* @return bool|string SQL string when test mode is enabled.
20032003
*/
@@ -2053,7 +2053,7 @@ protected function compileExists(): string
20532053
$lockForUpdate = $this->QBLockForUpdate;
20542054
$select = $this->QBSelect;
20552055
$noEscape = $this->QBNoEscape;
2056-
$needsSubquery = $this->QBUnion !== [] || $this->QBGroupBy !== [] || $this->QBHaving !== [] || $this->QBOffset !== false;
2056+
$needsSubquery = $this->QBSelectUsesAggregate || $this->QBUnion !== [] || $this->QBGroupBy !== [] || $this->QBHaving !== [] || $this->QBOffset !== false;
20572057

20582058
$this->QBOrderBy = null;
20592059
$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()
@@ -524,6 +522,40 @@ public function getIdValue($row)
524522
}
525523

526524
public function countAllResults(bool $reset = true, bool $test = false)
525+
{
526+
$this->prepareSoftDeleteQuery($reset);
527+
528+
return $this->builder()->testMode($test)->countAllResults($reset);
529+
}
530+
531+
/**
532+
* Determines whether the current Model query would return at least one row.
533+
*
534+
* @return bool|string Returns a SQL string if in test mode.
535+
*/
536+
public function exists(bool $reset = true, bool $test = false)
537+
{
538+
$this->prepareSoftDeleteQuery($reset);
539+
540+
return $this->builder()->testMode($test)->exists($reset);
541+
}
542+
543+
/**
544+
* Determines whether the current Model query would not return any rows.
545+
*
546+
* @return bool|string Returns a SQL string if in test mode.
547+
*/
548+
public function doesntExist(bool $reset = true, bool $test = false)
549+
{
550+
$this->prepareSoftDeleteQuery($reset);
551+
552+
return $this->builder()->testMode($test)->doesntExist($reset);
553+
}
554+
555+
/**
556+
* Applies the Model soft-delete constraint before terminal Builder operations.
557+
*/
558+
private function prepareSoftDeleteQuery(bool $reset): void
527559
{
528560
if ($this->tempUseSoftDeletes) {
529561
$this->builder()->where($this->table . '.' . $this->deletedField, null);
@@ -535,8 +567,6 @@ public function countAllResults(bool $reset = true, bool $test = false)
535567
$this->tempUseSoftDeletes = $reset
536568
? $this->useSoftDeletes
537569
: ($this->useSoftDeletes ? false : $this->useSoftDeletes);
538-
539-
return $this->builder()->testMode($test)->countAllResults($reset);
540570
}
541571

542572
/**

‎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
@@ -217,7 +217,7 @@ Database
217217
Query Builder
218218
-------------
219219

220-
- Added ``exists()`` and ``doesntExist()`` to Query Builder to check whether the current Query Builder conditions match any rows. See :ref:`query-builder-exists`.
220+
- 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`.
221221
- Added ``whereBetween()``, ``orWhereBetween()``, ``whereNotBetween()``, and ``orWhereNotBetween()`` to Query Builder. See :ref:`query-builder-where-between`.
222222
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.
223223
- 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
@@ -820,23 +820,26 @@ $builder->exists()
820820

821821
.. versionadded:: 4.8.0
822822

823-
Permits you to determine whether the current Query Builder conditions match
824-
any rows:
823+
Permits you to determine whether the current Query Builder query would return
824+
at least one row:
825825

826826
.. literalinclude:: query_builder/128.php
827827

828-
This method returns ``true`` when at least one row exists and ``false`` when no
829-
rows match. It respects any existing ``limit()`` and ``offset()`` clauses, and
830-
resets the current Query Builder state by default. If you need to keep the
831-
current Query Builder state, you can pass ``false`` as the first parameter.
828+
This method returns ``true`` when the query would return at least one row and
829+
``false`` when it would not. It respects any existing ``limit()`` and
830+
``offset()`` clauses, and resets the current Query Builder state by default. If
831+
you need to keep the current Query Builder state, you can pass ``false`` as the
832+
first parameter.
833+
If the existence query fails and ``DBDebug`` is ``false``, both methods return
834+
``false``.
832835

833836
$builder->doesntExist()
834837
-----------------------
835838

836839
.. versionadded:: 4.8.0
837840

838841
This method is identical to ``exists()``, except that it returns ``true`` when
839-
no rows match.
842+
the query would not return any rows.
840843

841844
.. note:: These methods execute the current Query Builder query to check for
842845
rows. To add an SQL ``EXISTS`` predicate to a query, use
@@ -1561,18 +1564,18 @@ Class Reference
15611564
.. php:method:: exists([$reset = true])
15621565
15631566
:param bool $reset: Whether to reset values for SELECTs
1564-
:returns: Whether the query has any matching rows
1567+
:returns: Whether the query would return at least one row
15651568
:rtype: bool
15661569

1567-
Determines whether the current Query Builder conditions match any rows.
1570+
Determines whether the current Query Builder query would return at least one row.
15681571

15691572
.. php:method:: doesntExist([$reset = true])
15701573
15711574
:param bool $reset: Whether to reset values for SELECTs
1572-
:returns: Whether the query has no matching rows
1575+
:returns: Whether the query would not return any rows
15731576
:rtype: bool
15741577

1575-
Determines whether the current Query Builder conditions do not match any rows.
1578+
Determines whether the current Query Builder query would not return any rows.
15761579

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

0 commit comments

Comments
 (0)