Skip to content

Commit 07a5b5b

Browse files
committed
feat(database): add query builder between conditions
Add whereBetween(), orWhereBetween(), whereNotBetween(), and orWhereNotBetween() to Query Builder. - Bind lower and upper range values through the existing bind system - Protect identifiers at compile time for alias and prefix correctness - Add Model method annotations, user guide docs, and changelog entry - Cover normal, OR, NOT, grouped, unescaped, aliased, prefixed, and invalid input cases Signed-off-by: memleakd <121398829+memleakd@users.noreply.github.com>
1 parent 8640420 commit 07a5b5b

7 files changed

Lines changed: 385 additions & 1 deletion

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 126 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -828,6 +828,112 @@ private function parseWhereColumnFirst(string $first): array
828828
return [$first, '='];
829829
}
830830

831+
/**
832+
* Generates a WHERE field BETWEEN minimum AND maximum SQL query,
833+
* joined with 'AND' if appropriate.
834+
*
835+
* @param array<array-key, mixed>|null $values The range values searched on
836+
*
837+
* @return $this
838+
*
839+
* @throws InvalidArgumentException
840+
*/
841+
public function whereBetween(?string $key = null, $values = null, ?bool $escape = null): static
842+
{
843+
return $this->whereBetweenHaving('QBWhere', $key, $values, false, 'AND ', $escape);
844+
}
845+
846+
/**
847+
* Generates a WHERE field BETWEEN minimum AND maximum SQL query,
848+
* joined with 'OR' if appropriate.
849+
*
850+
* @param array<array-key, mixed>|null $values The range values searched on
851+
*
852+
* @return $this
853+
*
854+
* @throws InvalidArgumentException
855+
*/
856+
public function orWhereBetween(?string $key = null, $values = null, ?bool $escape = null): static
857+
{
858+
return $this->whereBetweenHaving('QBWhere', $key, $values, false, 'OR ', $escape);
859+
}
860+
861+
/**
862+
* Generates a WHERE field NOT BETWEEN minimum AND maximum SQL query,
863+
* joined with 'AND' if appropriate.
864+
*
865+
* @param array<array-key, mixed>|null $values The range values searched on
866+
*
867+
* @return $this
868+
*
869+
* @throws InvalidArgumentException
870+
*/
871+
public function whereNotBetween(?string $key = null, $values = null, ?bool $escape = null): static
872+
{
873+
return $this->whereBetweenHaving('QBWhere', $key, $values, true, 'AND ', $escape);
874+
}
875+
876+
/**
877+
* Generates a WHERE field NOT BETWEEN minimum AND maximum SQL query,
878+
* joined with 'OR' if appropriate.
879+
*
880+
* @param array<array-key, mixed>|null $values The range values searched on
881+
*
882+
* @return $this
883+
*
884+
* @throws InvalidArgumentException
885+
*/
886+
public function orWhereNotBetween(?string $key = null, $values = null, ?bool $escape = null): static
887+
{
888+
return $this->whereBetweenHaving('QBWhere', $key, $values, true, 'OR ', $escape);
889+
}
890+
891+
/**
892+
* @used-by whereBetween()
893+
* @used-by orWhereBetween()
894+
* @used-by whereNotBetween()
895+
* @used-by orWhereNotBetween()
896+
*
897+
* @param 'QBHaving'|'QBWhere' $qbKey
898+
* @param non-empty-string|null $key
899+
* @param array<array-key, mixed>|null $values The range values searched on
900+
*
901+
* @return $this
902+
*
903+
* @throws InvalidArgumentException
904+
*/
905+
protected function whereBetweenHaving(string $qbKey, ?string $key = null, $values = null, bool $not = false, string $type = 'AND ', ?bool $escape = null): static
906+
{
907+
if ($key === null || $key === '') {
908+
throw new InvalidArgumentException(sprintf('%s() expects $key to be a non-empty string', debug_backtrace(0, 2)[1]['function']));
909+
}
910+
911+
if (! is_array($values) || count($values) !== 2) {
912+
throw new InvalidArgumentException(sprintf('%s() expects $values to be an array containing exactly two values', debug_backtrace(0, 2)[1]['function']));
913+
}
914+
915+
$escape ??= $this->db->protectIdentifiers;
916+
$values = array_values($values);
917+
$ok = $key;
918+
919+
$lowerBind = $this->setBind($ok, $values[0], $escape);
920+
$upperBind = $this->setBind($ok, $values[1], $escape);
921+
$not = $not ? ' NOT' : '';
922+
$prefix = $this->{$qbKey} === [] ? $this->groupGetType('') : $this->groupGetType($type);
923+
924+
$this->{$qbKey}[] = [
925+
'betweenComparison' => true,
926+
'condition' => $prefix,
927+
'escape' => $escape,
928+
'key' => $key,
929+
'lowerBind' => $lowerBind,
930+
'not' => $not,
931+
'upperBind' => $upperBind,
932+
];
933+
934+
return $this;
935+
}
936+
831937
/**
832938
* @used-by where()
833939
* @used-by orWhere()
@@ -3277,6 +3383,12 @@ protected function compileWhereHaving(string $qbKey): string
32773383
continue;
32783384
}
32793385

3386+
if (($qbkey['betweenComparison'] ?? false) === true) {
3387+
$qbkey = $this->compileBetweenComparison($qbkey);
3388+
3389+
continue;
3390+
}
3391+
32803392
if ($qbkey['escape'] === false) {
32813393
$qbkey = $qbkey['condition'];
32823394

@@ -3355,6 +3467,20 @@ private function compileColumnComparison(array $condition): string
33553467
return $condition['condition'] . $condition['first'] . ' ' . $condition['operator'] . ' ' . $condition['second'];
33563468
}
33573469

3470+
/**
3471+
* @used-by compileWhereHaving()
3472+
*
3473+
* @param array{betweenComparison: true, condition: string, escape: bool, key: string, lowerBind: string, not: string, upperBind: string} $condition
3474+
*/
3475+
private function compileBetweenComparison(array $condition): string
3476+
{
3477+
if ($condition['escape']) {
3478+
$condition['key'] = $this->db->protectIdentifiers($condition['key'], false, true);
3479+
}
3480+
3481+
return $condition['condition'] . $condition['key'] . $condition['not'] . ' BETWEEN :' . $condition['lowerBind'] . ': AND :' . $condition['upperBind'] . ':';
3482+
}
3483+
33583484
/**
33593485
* Escapes identifiers in GROUP BY statements at execution time.
33603486
*

‎system/Model.php‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -72,8 +72,10 @@
7272
* @method $this orNotHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
7373
* @method $this orNotLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
7474
* @method $this orWhere($key, $value = null, ?bool $escape = null)
75+
* @method $this orWhereBetween(?string $key = null, $values = null, ?bool $escape = null)
7576
* @method $this orWhereColumn(string $first, string $second, ?bool $escape = null)
7677
* @method $this orWhereIn(?string $key = null, $values = null, ?bool $escape = null)
78+
* @method $this orWhereNotBetween(?string $key = null, $values = null, ?bool $escape = null)
7779
* @method $this orWhereNotIn(?string $key = null, $values = null, ?bool $escape = null)
7880
* @method $this select($select = '*', ?bool $escape = null)
7981
* @method $this selectAvg(string $select = '', string $alias = '')
@@ -84,8 +86,10 @@
8486
* @method $this when($condition, callable $callback, ?callable $defaultCallback = null)
8587
* @method $this whenNot($condition, callable $callback, ?callable $defaultCallback = null)
8688
* @method $this where($key, $value = null, ?bool $escape = null)
89+
* @method $this whereBetween(?string $key = null, $values = null, ?bool $escape = null)
8790
* @method $this whereColumn(string $first, string $second, ?bool $escape = null)
8891
* @method $this whereIn(?string $key = null, $values = null, ?bool $escape = null)
92+
* @method $this whereNotBetween(?string $key = null, $values = null, ?bool $escape = null)
8993
* @method $this whereNotIn(?string $key = null, $values = null, ?bool $escape = null)
9094
*
9195
* @phpstan-method $this when($condition, callable(BaseBuilder, mixed): mixed $callback, (callable(BaseBuilder): mixed)|null $defaultCallback = null)

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,28 @@ public function testPrefixesSetOnTableNamesWithWhereColumnClause(): void
6868
$this->assertSame($expectedBinds, $builder->getBinds());
6969
}
7070

71+
public function testPrefixesSetOnTableNamesWithWhereBetweenClause(): void
72+
{
73+
$builder = $this->db->table('users');
74+
75+
$expectedSQL = 'SELECT * FROM "ci_users" WHERE "ci_users"."created_at" BETWEEN 1 AND 10';
76+
$expectedBinds = [
77+
'users.created_at' => [
78+
1,
79+
true,
80+
],
81+
'users.created_at.1' => [
82+
10,
83+
true,
84+
],
85+
];
86+
87+
$builder->whereBetween('users.created_at', [1, 10]);
88+
89+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
90+
$this->assertSame($expectedBinds, $builder->getBinds());
91+
}
92+
7193
public function testPrefixWithSubquery(): void
7294
{
7395
$expected = <<<'NOWDOC'

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

Lines changed: 147 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,6 +489,153 @@ public static function provideWhereColumnInvalidColumnThrowInvalidArgumentExcept
489489
];
490490
}
491491

492+
#[DataProvider('provideWhereBetweenMethods')]
493+
public function testWhereBetweenMethods(string $method, string $sql): void
494+
{
495+
$builder = $this->db->table('jobs');
496+
497+
$builder->{$method}('created_at', ['2026-01-01', '2026-01-31']);
498+
499+
$expectedSQL = 'SELECT * FROM "jobs" WHERE "created_at" ' . $sql . " '2026-01-01' AND '2026-01-31'";
500+
$expectedBinds = [
501+
'created_at' => [
502+
'2026-01-01',
503+
true,
504+
],
505+
'created_at.1' => [
506+
'2026-01-31',
507+
true,
508+
],
509+
];
510+
511+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
512+
$this->assertSame($expectedBinds, $builder->getBinds());
513+
}
514+
515+
/**
516+
* @return iterable<string, array{string, string}>
517+
*/
518+
public static function provideWhereBetweenMethods(): iterable
519+
{
520+
return [
521+
'between' => ['whereBetween', 'BETWEEN'],
522+
'not between' => ['whereNotBetween', 'NOT BETWEEN'],
523+
];
524+
}
525+
526+
#[DataProvider('provideOrWhereBetweenMethods')]
527+
public function testOrWhereBetweenMethods(string $method, string $sql): void
528+
{
529+
$builder = $this->db->table('jobs');
530+
531+
$builder->where('active', 1)
532+
->{$method}('created_at', ['2026-01-01', '2026-01-31']);
533+
534+
$expectedSQL = 'SELECT * FROM "jobs" WHERE "active" = 1 OR "created_at" ' . $sql . " '2026-01-01' AND '2026-01-31'";
535+
536+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
537+
}
538+
539+
/**
540+
* @return iterable<string, array{string, string}>
541+
*/
542+
public static function provideOrWhereBetweenMethods(): iterable
543+
{
544+
return [
545+
'or between' => ['orWhereBetween', 'BETWEEN'],
546+
'or not between' => ['orWhereNotBetween', 'NOT BETWEEN'],
547+
];
548+
}
549+
550+
public function testWhereBetweenWithGroupedConditions(): void
551+
{
552+
$builder = $this->db->table('jobs');
553+
554+
$builder->groupStart()
555+
->whereBetween('created_at', ['2026-01-01', '2026-01-31'])
556+
->orWhereNotBetween('updated_at', ['2026-02-01', '2026-02-28'])
557+
->groupEnd()
558+
->where('active', 1);
559+
560+
$expectedSQL = 'SELECT * FROM "jobs" WHERE ( "created_at" BETWEEN \'2026-01-01\' AND \'2026-01-31\' OR "updated_at" NOT BETWEEN \'2026-02-01\' AND \'2026-02-28\' ) AND "active" = 1';
561+
562+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
563+
}
564+
565+
public function testWhereBetweenNoEscape(): void
566+
{
567+
$builder = $this->db->table('jobs');
568+
569+
$builder->whereBetween('DATE(created_at)', ['20260101', '20260131'], escape: false);
570+
571+
$expectedSQL = 'SELECT * FROM "jobs" WHERE DATE(created_at) BETWEEN 20260101 AND 20260131';
572+
$expectedBinds = [
573+
'DATE(created_at)' => [
574+
'20260101',
575+
false,
576+
],
577+
'DATE(created_at).1' => [
578+
'20260131',
579+
false,
580+
],
581+
];
582+
583+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
584+
$this->assertSame($expectedBinds, $builder->getBinds());
585+
}
586+
587+
public function testWhereBetweenWithAliasBeforeFrom(): void
588+
{
589+
$builder = $this->db->newQuery();
590+
591+
$builder->whereBetween('u.created_at', ['2026-01-01', '2026-01-31'])
592+
->from('users u');
593+
594+
$expectedSQL = 'SELECT * FROM "users" "u" WHERE "u"."created_at" BETWEEN \'2026-01-01\' AND \'2026-01-31\'';
595+
596+
$this->assertSame($expectedSQL, str_replace("\n", ' ', $builder->getCompiledSelect()));
597+
}
598+
599+
/**
600+
* @param mixed $key
601+
*/
602+
#[DataProvider('provideWhereInvalidKeyThrowInvalidArgumentException')]
603+
public function testWhereBetweenInvalidKeyThrowInvalidArgumentException($key): void
604+
{
605+
$this->expectException(InvalidArgumentException::class);
606+
607+
$builder = $this->db->table('jobs');
608+
$builder->whereBetween($key, ['2026-01-01', '2026-01-31']);
609+
}
610+
611+
/**
612+
* @param mixed $values
613+
*/
614+
#[DataProvider('provideWhereBetweenInvalidValuesThrowInvalidArgumentException')]
615+
public function testWhereBetweenInvalidValuesThrowInvalidArgumentException($values): void
616+
{
617+
$this->expectException(InvalidArgumentException::class);
618+
619+
$builder = $this->db->table('jobs');
620+
$builder->whereBetween('created_at', $values);
621+
}
622+
623+
/**
624+
* @return iterable<string, array{mixed}>
625+
*/
626+
public static function provideWhereBetweenInvalidValuesThrowInvalidArgumentException(): iterable
627+
{
628+
return [
629+
'null' => [null],
630+
'not array' => ['not array'],
631+
'empty array' => [[]],
632+
'one value' => [['2026-01-01']],
633+
'three values' => [
634+
['2026-01-01', '2026-01-31', '2026-02-28'],
635+
],
636+
];
637+
}
638+
492639
public function testWhereIn(): void
493640
{
494641
$builder = $this->db->table('jobs');

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

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -217,8 +217,9 @@ Database
217217
Query Builder
218218
-------------
219219

220-
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.
221220
- Added new ``incrementMany()`` and ``decrementMany()`` methods to ``CodeIgniter\Database\BaseBuilder`` for performing bulk increment/decrement operations.
221+
- Added ``whereBetween()``, ``orWhereBetween()``, ``whereNotBetween()``, and ``orWhereNotBetween()`` to Query Builder. See :ref:`query-builder-where-between`.
222+
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.
222223

223224
Forge
224225
-----

0 commit comments

Comments
 (0)