-
Notifications
You must be signed in to change notification settings - Fork 2k
feat: add Query Builder exists and doesntExist methods #10215
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
memleakd
wants to merge
3
commits into
codeigniter4:4.8
Choose a base branch
from
memleakd:feat/exists-query-builder
base: 4.8
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,229 @@ | ||
| <?php | ||
|
|
||
| declare(strict_types=1); | ||
|
|
||
| /** | ||
| * This file is part of CodeIgniter 4 framework. | ||
| * | ||
| * (c) CodeIgniter Foundation <admin@codeigniter.com> | ||
| * | ||
| * For the full copyright and license information, please view | ||
| * the LICENSE file that was distributed with this source code. | ||
| */ | ||
|
|
||
| namespace CodeIgniter\Database\Builder; | ||
|
|
||
| use CodeIgniter\Database\BaseBuilder; | ||
| use CodeIgniter\Database\SQLSRV\Builder as SQLSRVBuilder; | ||
| use CodeIgniter\Test\CIUnitTestCase; | ||
| use CodeIgniter\Test\Mock\MockConnection; | ||
| use Config\Feature; | ||
| use PHPUnit\Framework\Attributes\Group; | ||
|
|
||
| /** | ||
| * @internal | ||
| */ | ||
| #[Group('Others')] | ||
| final class ExistsTest extends CIUnitTestCase | ||
| { | ||
| protected function setUp(): void | ||
| { | ||
| parent::setUp(); | ||
|
|
||
| $this->db = new MockConnection([]); | ||
| } | ||
|
|
||
| public function testExistsReturnsSqlInTestMode(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3)->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM "jobs" WHERE "id" > :id: LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| } | ||
|
|
||
| public function testDoesntExistReturnsSqlInTestMode(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3)->doesntExist(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM "jobs" WHERE "id" > :id: LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| } | ||
|
|
||
| public function testExistsDoesNotUseOrderByOrLockForUpdate(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3) | ||
| ->orderBy('id', 'DESC') | ||
| ->lockForUpdate() | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM "jobs" WHERE "id" > :id: LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT * FROM "jobs" WHERE "id" > 3 ORDER BY "id" DESC FOR UPDATE', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsWithSQLSRVDoesNotUseOrderByOrLockForUpdate(): void | ||
| { | ||
| $this->db = new MockConnection(['DBDriver' => 'SQLSRV', 'database' => 'test', 'schema' => 'dbo']); | ||
|
|
||
| $builder = new SQLSRVBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3) | ||
| ->orderBy('id', 'DESC') | ||
| ->lockForUpdate() | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM "test"."dbo"."jobs" WHERE "id" > :id: ORDER BY (SELECT NULL) OFFSET 0 ROWS FETCH NEXT 1 ROWS ONLY '; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT * FROM "test"."dbo"."jobs" WITH (UPDLOCK, ROWLOCK) WHERE "id" > 3 ORDER BY "id" DESC', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsHonorsExistingLimitAndOffset(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3) | ||
| ->limit(10, 20) | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM ( SELECT * FROM "jobs" WHERE "id" > :id: LIMIT 20, 10 ) CI_exists LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT * FROM "jobs" WHERE "id" > 3 LIMIT 20, 10', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsHonorsLimitZero(): void | ||
| { | ||
| $config = config(Feature::class); | ||
| $limitZeroAsAll = $config->limitZeroAsAll; | ||
| $config->limitZeroAsAll = false; | ||
|
|
||
| try { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->where('id >', 3) | ||
| ->limit(0) | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM "jobs" WHERE "id" > :id: LIMIT 0'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| } finally { | ||
| $config->limitZeroAsAll = $limitZeroAsAll; | ||
| } | ||
| } | ||
|
|
||
| public function testExistsWithGroupByAndHaving(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->selectCount('id', 'total') | ||
| ->where('id >', 3) | ||
| ->groupBy('id') | ||
| ->having('total >', 1) | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM ( SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > :id: GROUP BY "id" HAVING "total" > :total: ) CI_exists LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > 3 GROUP BY "id" HAVING "total" > 1', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsWithAggregateSelection(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->selectCount('id', 'total') | ||
| ->where('id >', 3) | ||
| ->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM ( SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > :id: ) CI_exists LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT COUNT("id") AS "total" FROM "jobs" WHERE "id" > 3', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsWithUnion(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $answer = $builder->union($this->db->table('jobs'))->exists(false); | ||
|
|
||
| $expectedSQL = 'SELECT 1 FROM ( SELECT * FROM (SELECT * FROM "jobs") "uwrp0" UNION SELECT * FROM (SELECT * FROM "jobs") "uwrp1" ) CI_exists LIMIT 1'; | ||
|
|
||
| $this->assertSame($expectedSQL, str_replace("\n", ' ', $answer)); | ||
| $this->assertSame( | ||
| 'SELECT * FROM (SELECT * FROM "jobs") "uwrp0" UNION SELECT * FROM (SELECT * FROM "jobs") "uwrp1"', | ||
| str_replace("\n", ' ', $builder->getCompiledSelect(false)), | ||
| ); | ||
| } | ||
|
|
||
| public function testExistsResetsByDefault(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $builder->where('id >', 3)->exists(); | ||
|
|
||
| $this->assertSame('SELECT * FROM "jobs"', str_replace("\n", ' ', $builder->getCompiledSelect(false))); | ||
| $this->assertSame([], $builder->getBinds()); | ||
| } | ||
|
|
||
| public function testExistsHonorsResetFalse(): void | ||
| { | ||
| $builder = new BaseBuilder('jobs', $this->db); | ||
| $builder->testMode(); | ||
|
|
||
| $builder->where('id >', 3)->exists(false); | ||
|
|
||
| $this->assertSame('SELECT * FROM "jobs" WHERE "id" > 3', str_replace("\n", ' ', $builder->getCompiledSelect(false))); | ||
| $this->assertSame([ | ||
| 'id' => [ | ||
| 3, | ||
| true, | ||
| ], | ||
| ], $builder->getBinds()); | ||
| } | ||
|
|
||
| public function testExistsMethodsReturnFalseWhenQueryFails(): void | ||
| { | ||
| $db = new MockConnection([]); | ||
| $db->shouldReturn('execute', false); | ||
|
|
||
| $this->assertFalse((new BaseBuilder('jobs', $db))->exists()); | ||
| $this->assertFalse((new BaseBuilder('jobs', $db))->doesntExist()); | ||
| } | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Naming-wise, I wonder whether
hasRows()/hasNoRows()would fit this behavior better thanexists()/doesntExist(). Since the method checks whether the current Query Builder would return a row, and we already havewhereExists()for SQLEXISTSpredicates,hasRows()feels less ambiguous to me. EventuallyhasResults()/hasNoResults()?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I thought about this a bit more, and I still slightly lean toward
exists()/doesntExist()from a DX point of view.The main reason is familiarity.
Existsis already common vocabulary in SQL, but it's also used across many ecosystems and frameworks. Laravel hasexists(), Rails hasexists?, Django hasexists(), and many developers coming from ORM/query builder backgrounds are already used to that wording.So if I were asking "does this query return anything?",
exists()would probably be one of the first method names I'd try or search for.hasRows()/hasNoRows()is clear too, so I don't think it's a bad option. It just feels a bit more CI-specific to me, whileexists()feels closer to the common vocabulary developers already bring from SQL and other ecosystems. I also like that it sits naturally next towhereExists(), even though one executes the query and the other only adds a predicate.That said, this is just my preference. I'd be happy to follow whatever the team feels is the better fit.