Skip to content

Commit 944b328

Browse files
authored
feat(database): add Query Builder likeAny helpers (#10261)
1 parent 7ff0f73 commit 944b328

7 files changed

Lines changed: 262 additions & 1 deletion

File tree

‎system/Database/BaseBuilder.php‎

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1397,6 +1397,20 @@ public function like($field, string $match = '', string $side = 'both', ?bool $e
13971397
return $this->_like($field, $match, 'AND ', $side, '', $escape, $insensitiveSearch);
13981398
}
13991399

1400+
/**
1401+
* Generates grouped LIKE portions of the query joined with OR.
1402+
*
1403+
* @param list<non-empty-string|RawSql> $fields
1404+
*
1405+
* @return $this
1406+
*
1407+
* @throws InvalidArgumentException
1408+
*/
1409+
public function likeAny(array $fields, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false): static
1410+
{
1411+
return $this->likeAnyGroup($fields, $match, 'AND ', $side, $escape, $insensitiveSearch, __FUNCTION__);
1412+
}
1413+
14001414
/**
14011415
* Generates a NOT LIKE portion of the query.
14021416
* Separates multiple calls with 'AND'.
@@ -1423,6 +1437,20 @@ public function orLike($field, string $match = '', string $side = 'both', ?bool
14231437
return $this->_like($field, $match, 'OR ', $side, '', $escape, $insensitiveSearch);
14241438
}
14251439

1440+
/**
1441+
* Generates grouped LIKE portions of the query joined with OR.
1442+
*
1443+
* @param list<non-empty-string|RawSql> $fields
1444+
*
1445+
* @return $this
1446+
*
1447+
* @throws InvalidArgumentException
1448+
*/
1449+
public function orLikeAny(array $fields, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false): static
1450+
{
1451+
return $this->likeAnyGroup($fields, $match, 'OR ', $side, $escape, $insensitiveSearch, __FUNCTION__);
1452+
}
1453+
14261454
/**
14271455
* Generates a NOT LIKE portion of the query.
14281456
* Separates multiple calls with 'OR'.
@@ -1488,9 +1516,53 @@ public function orNotHavingLike($field, string $match = '', string $side = 'both
14881516
return $this->_like($field, $match, 'OR ', $side, 'NOT', $escape, $insensitiveSearch, 'QBHaving');
14891517
}
14901518

1519+
/**
1520+
* @param list<non-empty-string|RawSql> $fields
1521+
*
1522+
* @return $this
1523+
*
1524+
* @throws InvalidArgumentException
1525+
*/
1526+
private function likeAnyGroup(array $fields, string $match, string $type, string $side, ?bool $escape, bool $insensitiveSearch, string $caller): static
1527+
{
1528+
$this->validateLikeAnyFields($fields, $caller);
1529+
1530+
$this->groupStartPrepare('', $type);
1531+
1532+
foreach ($fields as $index => $field) {
1533+
$this->_like($field, $match, $index === 0 ? 'AND ' : 'OR ', $side, '', $escape, $insensitiveSearch);
1534+
}
1535+
1536+
return $this->groupEndPrepare();
1537+
}
1538+
1539+
/**
1540+
* @param list<non-empty-string|RawSql> $fields
1541+
*
1542+
* @throws InvalidArgumentException
1543+
*/
1544+
private function validateLikeAnyFields(array $fields, string $caller): void
1545+
{
1546+
if ($fields === [] || ! array_is_list($fields)) {
1547+
throw new InvalidArgumentException(sprintf('%s() expects $fields to be a non-empty list of field names', $caller));
1548+
}
1549+
1550+
foreach ($fields as $field) {
1551+
if ($field instanceof RawSql) {
1552+
continue;
1553+
}
1554+
1555+
if (! is_string($field) || trim($field) === '') {
1556+
throw new InvalidArgumentException(sprintf('%s() expects $fields to contain only non-empty strings or RawSql instances', $caller));
1557+
}
1558+
}
1559+
}
1560+
14911561
/**
14921562
* @used-by like()
1563+
* @used-by likeAny()
14931564
* @used-by orLike()
1565+
* @used-by orLikeAny()
14941566
* @used-by notLike()
14951567
* @used-by orNotLike()
14961568
* @used-by havingLike()

‎system/Model.php‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
use CodeIgniter\Database\Exceptions\DataException;
2323
use CodeIgniter\Database\Exceptions\UniqueConstraintViolationException;
2424
use CodeIgniter\Database\Query;
25+
use CodeIgniter\Database\RawSql;
2526
use CodeIgniter\Entity\Entity;
2627
use CodeIgniter\Exceptions\BadMethodCallException;
2728
use CodeIgniter\Exceptions\InvalidArgumentException;
@@ -57,6 +58,7 @@
5758
* @method $this havingNotIn(?string $key = null, $values = null, ?bool $escape = null)
5859
* @method $this join(string $table, string $cond, string $type = '', ?bool $escape = null)
5960
* @method $this like($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
61+
* @method $this likeAny(list<RawSql|string> $fields, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
6062
* @method $this limit(?int $value = null, ?int $offset = 0)
6163
* @method $this notGroupStart()
6264
* @method $this notHavingGroupStart()
@@ -73,6 +75,7 @@
7375
* @method $this orHavingNotBetween(?string $key = null, $values = null, ?bool $escape = null)
7476
* @method $this orHavingNotIn(?string $key = null, $values = null, ?bool $escape = null)
7577
* @method $this orLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
78+
* @method $this orLikeAny(list<RawSql|string> $fields, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)
7679
* @method $this orNotGroupStart()
7780
* @method $this orNotHavingGroupStart()
7881
* @method $this orNotHavingLike($field, string $match = '', string $side = 'both', ?bool $escape = null, bool $insensitiveSearch = false)

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

Lines changed: 120 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,8 +15,10 @@
1515

1616
use CodeIgniter\Database\BaseBuilder;
1717
use CodeIgniter\Database\RawSql;
18+
use CodeIgniter\Exceptions\InvalidArgumentException;
1819
use CodeIgniter\Test\CIUnitTestCase;
1920
use CodeIgniter\Test\Mock\MockConnection;
21+
use PHPUnit\Framework\Attributes\DataProvider;
2022
use PHPUnit\Framework\Attributes\Group;
2123

2224
/**
@@ -52,6 +54,124 @@ public function testSimpleLike(): void
5254
$this->assertSame($expectedBinds, $builder->getBinds());
5355
}
5456

57+
public function testLikeAny(): void
58+
{
59+
$builder = new BaseBuilder('job', $this->db);
60+
61+
$builder->likeAny(['name', 'description'], 'veloper');
62+
63+
$expectedSQL = 'SELECT * FROM "job" WHERE ( "name" LIKE \'%veloper%\' ESCAPE \'!\' OR "description" LIKE \'%veloper%\' ESCAPE \'!\' )';
64+
$expectedBinds = [
65+
'name' => [
66+
'%veloper%',
67+
true,
68+
],
69+
'description' => [
70+
'%veloper%',
71+
true,
72+
],
73+
];
74+
75+
$this->assertSame($expectedSQL, (string) preg_replace('/\s+/', ' ', trim($builder->getCompiledSelect())));
76+
$this->assertSame($expectedBinds, $builder->getBinds());
77+
}
78+
79+
public function testLikeAnyAfterWhere(): void
80+
{
81+
$builder = new BaseBuilder('job', $this->db);
82+
83+
$builder->where('active', 1)
84+
->likeAny(['name', 'description'], 'veloper');
85+
86+
$expectedSQL = 'SELECT * FROM "job" WHERE "active" = 1 AND ( "name" LIKE \'%veloper%\' ESCAPE \'!\' OR "description" LIKE \'%veloper%\' ESCAPE \'!\' )';
87+
88+
$this->assertSame($expectedSQL, (string) preg_replace('/\s+/', ' ', trim($builder->getCompiledSelect())));
89+
}
90+
91+
public function testOrLikeAnyAfterWhere(): void
92+
{
93+
$builder = new BaseBuilder('job', $this->db);
94+
95+
$builder->where('active', 1)
96+
->orLikeAny(['name', 'description'], 'veloper');
97+
98+
$expectedSQL = 'SELECT * FROM "job" WHERE "active" = 1 OR ( "name" LIKE \'%veloper%\' ESCAPE \'!\' OR "description" LIKE \'%veloper%\' ESCAPE \'!\' )';
99+
100+
$this->assertSame($expectedSQL, (string) preg_replace('/\s+/', ' ', trim($builder->getCompiledSelect())));
101+
}
102+
103+
public function testLikeAnyCaseInsensitiveSearch(): void
104+
{
105+
$builder = new BaseBuilder('job', $this->db);
106+
107+
$builder->likeAny(['name', 'description'], 'VELOPER', 'both', null, true);
108+
109+
$expectedSQL = 'SELECT * FROM "job" WHERE ( LOWER("name") LIKE \'%veloper%\' ESCAPE \'!\' OR LOWER("description") LIKE \'%veloper%\' ESCAPE \'!\' )';
110+
$expectedBinds = [
111+
'name' => [
112+
'%veloper%',
113+
true,
114+
],
115+
'description' => [
116+
'%veloper%',
117+
true,
118+
],
119+
];
120+
121+
$this->assertSame($expectedSQL, (string) preg_replace('/\s+/', ' ', trim($builder->getCompiledSelect())));
122+
$this->assertSame($expectedBinds, $builder->getBinds());
123+
}
124+
125+
public function testLikeAnyWithRawSqlField(): void
126+
{
127+
$builder = new BaseBuilder('job', $this->db);
128+
$rawSql = new RawSql('LOWER(description)');
129+
130+
$builder->likeAny(['name', $rawSql], 'veloper', 'after');
131+
132+
$expectedSQL = 'SELECT * FROM "job" WHERE ( "name" LIKE \'veloper%\' ESCAPE \'!\' OR LOWER(description) LIKE \'veloper%\' ESCAPE \'!\' )';
133+
$expectedBinds = [
134+
'name' => [
135+
'veloper%',
136+
true,
137+
],
138+
$rawSql->getBindingKey() => [
139+
'veloper%',
140+
true,
141+
],
142+
];
143+
144+
$this->assertSame($expectedSQL, (string) preg_replace('/\s+/', ' ', trim($builder->getCompiledSelect())));
145+
$this->assertSame($expectedBinds, $builder->getBinds());
146+
}
147+
148+
/**
149+
* @param mixed $fields
150+
*/
151+
#[DataProvider('provideLikeAnyInvalidFieldsThrowInvalidArgumentException')]
152+
public function testLikeAnyInvalidFieldsThrowInvalidArgumentException($fields): void
153+
{
154+
$this->expectException(InvalidArgumentException::class);
155+
156+
$builder = new BaseBuilder('job', $this->db);
157+
158+
$builder->likeAny($fields, 'veloper');
159+
}
160+
161+
/**
162+
* @return iterable<string, array{mixed}>
163+
*/
164+
public static function provideLikeAnyInvalidFieldsThrowInvalidArgumentException(): iterable
165+
{
166+
return [
167+
'empty list' => [[]],
168+
'assoc array' => [['name' => 'description']],
169+
'empty field' => [['name', '']],
170+
'blank field' => [['name', ' ']],
171+
'int field' => [['name', 1]],
172+
];
173+
}
174+
55175
/**
56176
* @see https://github.com/codeigniter4/CodeIgniter4/issues/3970
57177
*/

‎tests/system/Database/Live/LikeTest.php‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,18 @@ public function testLikeCaseInsensitive(): void
7676
$this->assertSame('Developer', $job->name);
7777
}
7878

79+
public function testLikeAny(): void
80+
{
81+
$jobs = $this->db->table('job')
82+
->likeAny(['name', 'description'], 'bor', 'both', null, true)
83+
->get()
84+
->getResult();
85+
86+
$this->assertCount(2, $jobs);
87+
$this->assertSame('Developer', $jobs[0]->name);
88+
$this->assertSame('Accountant', $jobs[1]->name);
89+
}
90+
7991
#[DataProvider('provideLikeCaseInsensitiveWithMultibyteCharacter')]
8092
public function testLikeCaseInsensitiveWithMultibyteCharacter(string $match, string $result): void
8193
{

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

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,7 @@ Query Builder
226226
- 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`.
227227
- Added ``explain()`` to Query Builder to run execution-plan queries for the current ``SELECT`` query. See :ref:`query-builder-explain`.
228228
- Added ``havingBetween()``, ``orHavingBetween()``, ``havingNotBetween()``, and ``orHavingNotBetween()`` to Query Builder. See :ref:`query-builder-having-between`.
229+
- Added ``likeAny()`` and ``orLikeAny()`` to Query Builder to search one value across multiple fields with grouped ``OR`` ``LIKE`` conditions. See :ref:`query-builder-like-any`.
229230
- Added ``whereBetween()``, ``orWhereBetween()``, ``whereNotBetween()``, and ``orWhereNotBetween()`` to Query Builder. See :ref:`query-builder-where-between`.
230231
- Added ``whereColumn()`` and ``orWhereColumn()`` to compare one column to another column while protecting identifiers by default. See :ref:`query-builder-where-column`.
231232
- 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: 43 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -601,10 +601,28 @@ searches.
601601

602602
.. warning:: When you use ``RawSql``, you MUST escape the values and protect the identifiers manually. Failure to do so could result in SQL injections.
603603

604+
.. _query-builder-like-any:
605+
606+
$builder->likeAny()
607+
-------------------
608+
609+
.. versionadded:: 4.8.0
610+
611+
This method generates a grouped set of **LIKE** clauses joined by **OR**.
612+
Use it when you want to search for one value across multiple fields:
613+
614+
.. literalinclude:: query_builder/130.php
615+
616+
Unlike the associative array form of ``like()``, the field list must be a
617+
non-empty list of field names. The same match value is used for every field.
618+
The field list may also contain ``RawSql`` instances; see :ref:`query-builder-like-rawsql`.
619+
Use ``orLikeAny()`` when the grouped search should be separated from previous
620+
conditions with **OR**.
621+
604622
$builder->orLike()
605623
------------------
606624

607-
This method is identical to the one above, except that multiple
625+
This method is identical to ``like()``, except that multiple
608626
instances are joined by **OR**:
609627

610628
.. literalinclude:: query_builder/042.php
@@ -2002,6 +2020,18 @@ Class Reference
20022020

20032021
Adds a ``LIKE`` clause to a query, separating multiple calls with ``AND``.
20042022

2023+
.. php:method:: likeAny($fields[, $match = ''[, $side = 'both'[, $escape = null[, $insensitiveSearch = false]]]])
2024+
2025+
:param array $fields: List of field names or RawSql instances
2026+
:param string $match: Text portion to match
2027+
:param string $side: Which side of the expression to put the '%' wildcard on
2028+
:param bool $escape: Whether to escape values and identifiers
2029+
:param bool $insensitiveSearch: Whether to force a case-insensitive search
2030+
:returns: ``BaseBuilder`` instance (method chaining)
2031+
:rtype: ``BaseBuilder``
2032+
2033+
Adds grouped ``LIKE`` clauses joined with ``OR``.
2034+
20052035
.. php:method:: orLike($field[, $match = ''[, $side = 'both'[, $escape = null[, $insensitiveSearch = false]]]])
20062036
20072037
:param string $field: Field name
@@ -2014,6 +2044,18 @@ Class Reference
20142044

20152045
Adds a ``LIKE`` clause to a query, separating multiple class with ``OR``.
20162046

2047+
.. php:method:: orLikeAny($fields[, $match = ''[, $side = 'both'[, $escape = null[, $insensitiveSearch = false]]]])
2048+
2049+
:param array $fields: List of field names or RawSql instances
2050+
:param string $match: Text portion to match
2051+
:param string $side: Which side of the expression to put the '%' wildcard on
2052+
:param bool $escape: Whether to escape values and identifiers
2053+
:param bool $insensitiveSearch: Whether to force a case-insensitive search
2054+
:returns: ``BaseBuilder`` instance (method chaining)
2055+
:rtype: ``BaseBuilder``
2056+
2057+
Adds grouped ``LIKE`` clauses joined with ``OR``, separating the group from previous conditions with ``OR``.
2058+
20172059
.. php:method:: notLike($field[, $match = ''[, $side = 'both'[, $escape = null[, $insensitiveSearch = false]]]])
20182060
20192061
:param string $field: Field name
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
<?php
2+
3+
$builder->likeAny(['title', 'body', 'summary'], $match);
4+
5+
/*
6+
* WHERE (
7+
* `title` LIKE '%match%' ESCAPE '!'
8+
* OR `body` LIKE '%match%' ESCAPE '!'
9+
* OR `summary` LIKE '%match%' ESCAPE '!'
10+
* )
11+
*/

0 commit comments

Comments
 (0)