diff --git a/CHANGELOG.md b/CHANGELOG.md index 56ecdb4..e10cbf5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,17 @@ All notable changes to `laravel-sql-dialect` will be documented in this file. +## Unreleased + +### Starts with search + +`LikeOperator` gains a prefix search with the same shape as the contains family. Wildcards in the term are literal, the term is always bound, and the operator and `ESCAPE` clause are picked per driver. + +- `startsWithPattern()` returns the escaped `term%` pattern. +- `applyStartsWith()`, `orApplyStartsWith()`, `applyNotStartsWith()` and `orApplyNotStartsWith()` mirror `applyContains()` and its variants. + +No breaking changes. The existing methods behave exactly as before. + ## v1.2.0 - Laravel Boost guidelines - 2026-10-02 ### Laravel Boost guidelines diff --git a/README.md b/README.md index dbb5ea8..feb97c1 100644 --- a/README.md +++ b/README.md @@ -91,6 +91,27 @@ $query->where(function (Builder $query) { }); ``` +### Starts with + +`applyStartsWith()` matches rows whose column begins with the term, for example an autocomplete where typing "ro" should list "Roma" and "Rovigo" but not "Monterotondo". It takes the same arguments as `applyContains()`, escapes the term the same way and binds it, but builds the pattern with `LikeOperator::startsWithPattern()` (`term%` instead of `%term%`). It type hints `Illuminate\Database\Eloquent\Builder` like the contains family, and it is case insensitive wherever `applyContains()` is. + +| Method | Clause added | +| --- | --- | +| `applyStartsWith($query, $column, $term)` | `and LIKE ?` | +| `orApplyStartsWith($query, $column, $term)` | `or LIKE ?` | +| `applyNotStartsWith($query, $column, $term)` | `and NOT LIKE ?` | +| `orApplyNotStartsWith($query, $column, $term)` | `or NOT LIKE ?` | + +```php +use PlinCode\SqlDialect\LikeOperator; + +$towns = Town::query(); +LikeOperator::applyStartsWith($towns, 'name', $term); +$towns->limit(20)->get(); +``` + +As with `applyContains()`, an empty term matches every row whose column is not `NULL`, and a `NULL` column never matches, negated or not. + ### Escaping `containsPattern()` (and the `escapeWildcards()` it calls) neutralise `%`, `_` and `\` in the search term with `addcslashes()`, so a term containing those characters is matched literally instead of being interpreted as a wildcard. That is why `applyContains()` always appends an `ESCAPE` clause: it tells the driver which character in the pattern is the escape character it just used. diff --git a/resources/boost/guidelines/core.blade.php b/resources/boost/guidelines/core.blade.php index a375d40..9932e60 100644 --- a/resources/boost/guidelines/core.blade.php +++ b/resources/boost/guidelines/core.blade.php @@ -21,10 +21,11 @@ @endverbatim - Variants: `LikeOperator::orApplyContains()`, `LikeOperator::applyNotContains()`, `LikeOperator::orApplyNotContains()`. Wrap OR clauses in a closure so they do not leak into the rest of the query. A `NULL` column matches neither the positive nor the negated form. +- Prefix search (autocomplete): `LikeOperator::applyStartsWith()`, with the same `or`, `not` and `or not` variants as `applyContains()` (`orApplyStartsWith()`, `applyNotStartsWith()`, `orApplyNotStartsWith()`). Do not hand write `LIKE 'term%'`. - `LikeOperator::applyContainsOnDate()` matches a partial date by casting the column to text first, instead of a hand written `CAST(... AS CHAR)` or `::text`. - These methods take `Illuminate\Database\Eloquent\Builder` only, not `Illuminate\Database\Query\Builder` (so not inside `whereExists()` or `orWhereIn()` closures). - `$column` is interpolated into raw SQL: pass a column name from your code, never request input. The term is always bound. -- Building SQL by hand: `LikeOperator::for()` returns the operator, `LikeOperator::containsPattern()` the escaped `%term%` pattern. +- Building SQL by hand: `LikeOperator::for()` returns the operator, `LikeOperator::containsPattern()` the escaped `%term%` pattern and `LikeOperator::startsWithPattern()` the escaped `term%` pattern. ### Year of a date column diff --git a/src/LikeOperator.php b/src/LikeOperator.php index d948aee..c80dc84 100644 --- a/src/LikeOperator.php +++ b/src/LikeOperator.php @@ -31,6 +31,11 @@ public static function containsPattern(string $term): string return '%'.self::escapeWildcards($term).'%'; } + public static function startsWithPattern(string $term): string + { + return self::escapeWildcards($term).'%'; + } + /** * Adds `column LIKE '%term%'` (ILIKE on PostgreSQL) to the query. * @@ -45,7 +50,7 @@ public static function applyContains(Builder $query, string $column, string $ter { $wrappedColumn = $query->getGrammar()->wrap($column); - self::applyPattern($query, $wrappedColumn, $term, $boolean, $not); + self::applyPattern($query, $wrappedColumn, self::containsPattern($term), $boolean, $not); } /** @@ -72,6 +77,45 @@ public static function orApplyNotContains(Builder $query, string $column, string self::applyContains($query, $column, $term, 'or', true); } + /** + * Adds `column LIKE 'term%'` (ILIKE on PostgreSQL) to the query. + * + * `$boolean` and `$not` behave as in `applyContains()`. + * + * @param Builder $query + * @param 'and'|'or' $boolean + */ + public static function applyStartsWith(Builder $query, string $column, string $term, string $boolean = 'and', bool $not = false): void + { + $wrappedColumn = $query->getGrammar()->wrap($column); + + self::applyPattern($query, $wrappedColumn, self::startsWithPattern($term), $boolean, $not); + } + + /** + * @param Builder $query + */ + public static function orApplyStartsWith(Builder $query, string $column, string $term): void + { + self::applyStartsWith($query, $column, $term, 'or'); + } + + /** + * @param Builder $query + */ + public static function applyNotStartsWith(Builder $query, string $column, string $term): void + { + self::applyStartsWith($query, $column, $term, 'and', true); + } + + /** + * @param Builder $query + */ + public static function orApplyNotStartsWith(Builder $query, string $column, string $term): void + { + self::applyStartsWith($query, $column, $term, 'or', true); + } + /** * @param Builder $query * @param 'and'|'or' $boolean @@ -88,13 +132,13 @@ public static function applyContainsOnDate(Builder $query, string $column, strin default => "CAST({$wrappedColumn} AS TEXT)", }; - self::applyPattern($query, $expression, $term, $boolean, $not); + self::applyPattern($query, $expression, self::containsPattern($term), $boolean, $not); } /** * @param Builder $query */ - private static function applyPattern(Builder $query, string $expression, string $term, string $boolean, bool $not): void + private static function applyPattern(Builder $query, string $expression, string $pattern, string $boolean, bool $not): void { $boolean = strtolower($boolean); @@ -107,7 +151,7 @@ private static function applyPattern(Builder $query, string $expression, string $operator = ($not ? 'NOT ' : '').self::for($query); $escape = self::escapeClause($connection->getDriverName()); - $query->whereRaw("{$expression} {$operator} ? {$escape}", [self::containsPattern($term)], $boolean); + $query->whereRaw("{$expression} {$operator} ? {$escape}", [$pattern], $boolean); } /** diff --git a/tests/LikeOperatorTest.php b/tests/LikeOperatorTest.php index 8fa8df6..c68230c 100644 --- a/tests/LikeOperatorTest.php +++ b/tests/LikeOperatorTest.php @@ -22,6 +22,12 @@ expect(LikeOperator::containsPattern('50%'))->toBe('%50\\%%'); }); +it('wraps an escaped term in a starts with pattern', function (): void { + expect(LikeOperator::startsWithPattern('50%'))->toBe('50\\%%') + ->and(LikeOperator::startsWithPattern('a_b\\c'))->toBe('a\\_b\\\\c%') + ->and(LikeOperator::startsWithPattern(''))->toBe('%'); +}); + it('picks the operator for the driver', function (): void { $expected = driver() === 'pgsql' ? 'ILIKE' : 'LIKE'; @@ -266,3 +272,189 @@ it('rejects a boolean other than and or or', function (): void { LikeOperator::applyContains(Document::query(), 'title', 'x', 'xor'); })->throws(InvalidArgumentException::class, "The boolean must be 'and' or 'or', got 'xor'."); + +it('finds rows starting with the term', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Rovigo']); + Document::create(['title' => 'Verona']); + Document::create(['title' => 'Bergamo']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'Ro'); + + expect($query->orderBy('id')->pluck('title')->all())->toBe(['Roma', 'Rovigo']); +})->group('integration'); + +it('does not match the term in the middle or at the end', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Monterotondo']); + Document::create(['title' => 'Bro']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'ro'); + + expect($query->pluck('title')->all())->toBe(['Roma']); +})->group('integration'); + +it('ignores the case of ascii letters in a starts with clause', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Verona']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'rOM'); + + expect($query->pluck('title')->all())->toBe(['Roma']); +})->group('integration'); + +it('treats a percent sign in the term as a literal in a starts with clause', function (): void { + Document::create(['title' => '100% remote']); + Document::create(['title' => '1000 remote']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', '100%'); + + expect($query->pluck('title')->all())->toBe(['100% remote']); +})->group('integration'); + +it('treats an underscore in the term as a literal in a starts with clause', function (): void { + Document::create(['title' => 'a_b c']); + Document::create(['title' => 'axb c']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'a_b'); + + expect($query->pluck('title')->all())->toBe(['a_b c']); +})->group('integration'); + +it('treats a backslash in the term as a literal in a starts with clause', function (): void { + Document::create(['title' => 'path\\to']); + Document::create(['title' => 'pathto']); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'path\\'); + + expect($query->pluck('title')->all())->toBe(['path\\to']); +})->group('integration'); + +it('matches every non null row for an empty term in a starts with clause', function (): void { + Document::create(['title' => 'a', 'summary' => 'x']); + Document::create(['title' => 'b', 'summary' => '']); + Document::create(['title' => 'c', 'summary' => null]); + + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'summary', ''); + + expect($query->orderBy('id')->pluck('title')->all())->toBe(['a', 'b']); +})->group('integration'); + +it('adds a starts with clause with or instead of and', function (): void { + Document::create(['title' => 'Roma', 'summary' => 'keep']); + Document::create(['title' => 'Verona', 'summary' => 'keep']); + Document::create(['title' => 'Padova', 'summary' => 'keep']); + Document::create(['title' => 'Roma', 'summary' => 'drop']); + + $query = Document::query() + ->where('summary', 'keep') + ->where(function (Builder $query): void { + LikeOperator::orApplyStartsWith($query, 'title', 'Ro'); + LikeOperator::orApplyStartsWith($query, 'title', 'Ver'); + }); + + expect($query->orderBy('id')->pluck('title')->all())->toBe(['Roma', 'Verona']); +})->group('integration'); + +it('excludes rows starting with the term', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Rovigo']); + Document::create(['title' => 'Verona']); + + $query = Document::query(); + LikeOperator::applyNotStartsWith($query, 'title', 'Ro'); + + expect($query->pluck('title')->all())->toBe(['Verona']); +})->group('integration'); + +it('keeps a row containing but not starting with the term in a not starts with clause', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Monterotondo']); + + $query = Document::query(); + LikeOperator::applyNotStartsWith($query, 'title', 'ro'); + + expect($query->pluck('title')->all())->toBe(['Monterotondo']); +})->group('integration'); + +it('treats a percent sign as a literal in a not starts with clause', function (): void { + Document::create(['title' => '100% remote']); + Document::create(['title' => '1000 remote']); + + $query = Document::query(); + LikeOperator::applyNotStartsWith($query, 'title', '100%'); + + expect($query->pluck('title')->all())->toBe(['1000 remote']); +})->group('integration'); + +it('ands consecutive not starts with clauses', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Verona']); + Document::create(['title' => 'Padova']); + + $query = Document::query(); + LikeOperator::applyNotStartsWith($query, 'title', 'Ro'); + LikeOperator::applyNotStartsWith($query, 'title', 'Ver'); + + expect($query->pluck('title')->all())->toBe(['Padova']); +})->group('integration'); + +it('excludes a null column from a not starts with clause', function (): void { + Document::create(['title' => 'a', 'summary' => null]); + Document::create(['title' => 'b', 'summary' => 'remote']); + Document::create(['title' => 'c', 'summary' => 'office']); + + $query = Document::query(); + LikeOperator::applyNotStartsWith($query, 'summary', 'rem'); + + expect($query->pluck('title')->all())->toBe(['c']); +})->group('integration'); + +it('adds a not starts with clause with or instead of and', function (): void { + Document::create(['title' => 'Roma', 'summary' => 'keep']); + Document::create(['title' => 'Roma', 'summary' => 'drop']); + Document::create(['title' => 'Verona', 'summary' => 'drop']); + + $query = Document::query()->where(function (Builder $query): void { + $query->where('summary', 'keep'); + LikeOperator::orApplyNotStartsWith($query, 'title', 'Ro'); + }); + + expect($query->orderBy('id')->pluck('title')->all())->toBe(['Roma', 'Verona']) + ->and($query->pluck('summary')->sort()->values()->all())->toBe(['drop', 'keep']); +})->group('integration'); + +it('accepts the boolean and the negation as arguments of starts with', function (): void { + Document::create(['title' => 'Roma']); + Document::create(['title' => 'Rovigo']); + Document::create(['title' => 'Verona']); + + $query = Document::query()->where(function (Builder $query): void { + LikeOperator::applyStartsWith($query, 'title', 'Ro', 'or', true); + LikeOperator::applyStartsWith($query, 'title', 'Rov', 'or'); + }); + + expect($query->orderBy('id')->pluck('title')->all())->toBe(['Rovigo', 'Verona']); +})->group('integration'); + +it('binds the term and writes the operator and escape clause for the driver', function (): void { + $query = Document::query(); + LikeOperator::applyStartsWith($query, 'title', 'Ro%'); + + $operator = driver() === 'pgsql' ? 'ILIKE' : 'LIKE'; + $escape = in_array(driver(), ['mysql', 'mariadb'], true) ? "ESCAPE '\\\\'" : "ESCAPE '\\'"; + + expect($query->toRawSql())->toContain($operator)->toContain($escape) + ->and($query->getBindings())->toBe(['Ro\\%%']); +})->group('integration'); + +it('rejects a boolean other than and or or in a starts with clause', function (): void { + LikeOperator::applyStartsWith(Document::query(), 'title', 'x', 'xor'); +})->throws(InvalidArgumentException::class, "The boolean must be 'and' or 'or', got 'xor'.");