Skip to content

Support for LIKE ... ESCAPE ... clause - #99774

Merged
alexey-milovidov merged 19 commits into
masterfrom
like-escape-clause
May 25, 2026
Merged

alexey-milovidov merged 19 commits into
masterfrom
like-escape-clause

Conversation

@qoega

@qoega qoega commented Mar 17, 2026 •

Copy link
Copy Markdown
Member

Resolves #99599

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Added ESCAPE syntax that defines a custom escape character in a LIKE pattern, allowing you to treat % and _ as literal characters instead of wildcards.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

Version info

  • Merged into: 26.6.1.123

qoega and others added 2 commits March 17, 2026 13:29
Implements the SQL-standard ESCAPE clause for LIKE, ILIKE, NOT LIKE,
and NOT ILIKE expressions. This allows users to specify a custom escape
character for matching literal `%` and `_` wildcards in patterns.

Examples:
  SELECT '10%' LIKE '10|%' ESCAPE '|'     -- returns 1
  SELECT '50%off' LIKE '50#%off' ESCAPE '#' -- returns 1

The implementation:
- Adds ESCAPE keyword to the parser
- Parses `expr LIKE pattern ESCAPE char` into a 3-argument `like` function
- Rewrites the pattern at execution time from custom escape to standard
  backslash escapes, so the core matching logic is unchanged
- Supports both operator syntax (LIKE ... ESCAPE) and functional syntax
  (like(haystack, pattern, escape_char))
- Handles round-trip formatting (parse -> format -> parse)

Closes #99599

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
- Parser: clarify pop/push-back logic with explicit `popped` flag
- ASTFunction: remove redundant `is_like_operator` variable, reuse `is_like_with_escape`
- Error messages: explain what escape sequences are valid after the escape character
- FunctionsStringSearch: wrap ESCAPE handling in `if constexpr` to avoid dead code
  in non-LIKE instantiations; add comment explaining `ImplIsLike` SFINAE trait
- Documentation: update `like`, `notLike`, `ilike`, `notILike` function docs with
  ESCAPE clause description, syntax, and examples
- Tests: add coverage for functional syntax, non-constant needle, ILIKE with case
  difference, empty/multi-char escape errors, subquery, and `formatQuery` round-trip

Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [aa72411]

Summary: ✅


AI Review

Summary

This PR adds LIKE/ILIKE/NOT LIKE/NOT ILIKE support for the ESCAPE clause, including parser, formatter, execution, and stateless tests. Core implementation is mostly solid, but one cross-component correctness regression remains in system.zookeeper path pruning for 3-argument like expressions.

Findings

❌ Blockers

  • [src/Parsers/ExpressionListParsers.cpp:3410] LIKE ... ESCAPE now produces 3-argument like, but StorageSystemZooKeeper::extractPathImpl still assumes 2-argument/default-backslash semantics when deriving path prefixes. With custom escape characters this can compute the wrong prefix and skip matching ZooKeeper paths (false negatives). Example: path LIKE '/x|_%' ESCAPE '|' should match /x_..., but current prefix extraction can derive /x|.
  • Suggested fix: in StorageSystemZooKeeper::extractPathImpl, either skip LIKE path optimization when like has 3 args (fail-closed to broader scan), or normalize the pattern with the explicit escape character before prefix extraction.
Final Verdict

Status: ⚠️ Request changes

Minimum required actions:

  1. Make system.zookeeper path pruning semantics-correct for 3-argument like generated by ESCAPE.
  2. Add a focused regression test covering path LIKE ... ESCAPE ... with a non-backslash escape character.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 17, 2026
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@rschu1ze rschu1ze self-assigned this Mar 17, 2026
@rschu1ze

This comment was marked as resolved.

@rschu1ze

Copy link
Copy Markdown
Member

I am 99% sure that the failure in AST fuzzer (amd_debug, targeted, old_compatibility) is related.

qoega and others added 2 commits March 27, 2026 20:24
Two bugs caused the AST fuzzer crash (PODArray assertion in debug
build via the format-parse-format round-trip check):

1. Formatter: ASTFunction always formatted 3-arg LIKE as operator
   syntax (x LIKE y ESCAPE z), even when the 3rd argument was not a
   string literal (e.g. after fuzzer mutation). The parser only accepts
   a string literal after ESCAPE, so the round-trip failed. Now only
   uses operator syntax when the escape argument is a string literal;
   otherwise falls back to functional syntax like(x, y, z).

2. Parser: When ESCAPE was followed by a non-string-literal, the LIKE
   operator was popped from the stack and the position advanced past
   ESCAPE, but neither was restored on failure. Now saves position
   before consuming ESCAPE and restores both pos and operator stack
   on any failure in the ESCAPE clause.

Made-with: Cursor
Comment thread src/Functions/FunctionsStringSearch.h Resolved
Comment thread src/Functions/FunctionsStringSearch.h Resolved
Comment thread src/Common/likePatternToRegexp.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix.

alexey-milovidov and others added 5 commits April 6, 2026 17:48
* In likePatternWithCustomEscapeToLikePattern, preserve legacy LIKE
  behavior when the explicit escape character is backslash: unknown
  escape sequences are kept as literal backslash + next character
  rather than throwing CANNOT_PARSE_ESCAPE_SEQUENCE. This makes
  LIKE p and LIKE p ESCAPE '\\' behaviorally equivalent for queries
  that worked before users added the explicit ESCAPE clause. Other
  escape characters keep the strict validation.

* Enforce that the ESCAPE argument in the functional form is a single
  ASCII character (high bit clear), matching the documentation.
  Previously only the byte length was checked, allowing non-ASCII
  single-byte values to pass.

* Replace the partial specialization of ImplIsLike on MatchImpl with
  a trait detection on Impl::is_like and drop the MatchImpl.h include
  from FunctionsStringSearch.h, removing transitive compile-time
  fanout of regex/match machinery into every consumer of the header.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
# Conflicts:
#	src/Functions/FunctionsStringSearch.h
The previous test used `unhex('FF')` after `ESCAPE`, but the parser
only accepts a string literal there, so the query failed with a
syntax error before reaching the runtime ASCII validation.

Use `'\xff'` instead, which is a single-byte string literal with the
high bit set and exercises the new ASCII check in
`FunctionsStringSearch.h`.
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

This was fixed by #105146. Let's update the branch.

The previous implementation handled `ESCAPE` only when the immediate top
operator was `like` / `ilike` / `notLike` / `notILike`. Patterns that
included higher-priority operators (e.g. concatenation in
`'ab' LIKE 'a' || 'b' ESCAPE '#'`) left the top operator as something
other than a LIKE-family op, so the `ESCAPE` keyword was not consumed
and parsing stopped at `ESCAPE`.

Fold operators with priority strictly higher than `LIKE` (priority 9)
before checking the top, so the corresponding `LIKE` becomes accessible.
This is a precedence-correct reduction that `mergeElement` would
perform anyway later, so it does not change the semantics of any
existing expression.

Adds tests covering `LIKE`, `NOT LIKE`, `ILIKE`, and `NOT ILIKE` with
`ESCAPE` after concatenation and function-call sub-expressions.
… test

In `04040_like_escape.sql`, `'a\b'` is the backspace character in ClickHouse
string literals, so the two checks under "Backslash is literal when custom
escape is used" did not actually exercise that contract. Switch the payload
to `'a\\b'` (a literal backslash) so the regression path is covered.

The expected results stay the same:
- `'a\\b' LIKE 'a\\b' ESCAPE '|'` — strings are identical → 1
- `'a\\b' LIKE 'a|%b' ESCAPE '|'` — pattern becomes literal `a%b` → 0
Comment thread src/Parsers/ExpressionListParsers.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented May 21, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.40% 91.40% +0.00%
Branches 76.50% 76.60% +0.10%

Changed lines: 89.52% (188/210) | lost baseline coverage: 4 line(s) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 25, 2026
Merged via the queue into master with commit b184287 May 25, 2026
166 checks passed
@alexey-milovidov
alexey-milovidov deleted the like-escape-clause branch May 25, 2026 05:36
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 25, 2026

-- NOT ILIKE with ESCAPE
SELECT '10%' NOT ILIKE '10|%' ESCAPE '|';

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@groeneai can you add a test case showing ClickHouse's text index is still used with a LIKE ESCAPE clause?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Filed as #105848.

While writing the test I realized the text index was actually being bypassed for LIKE pattern ESCAPE 'c' queries — MergeTreeIndexConditionText::traverseAtomNode rejected the 3-arg like(col, pattern, escape_char) form before the LIKE handler could run (it had arguments_size != 2 -> return false). Result correctness was always fine because FunctionsStringSearch::executeImpl already normalizes the pattern with likePatternWithCustomEscapeToLikePattern at execution time; only the index path was missing the same fold.

#105848 applies the same fold at index-condition time, and the new test 04277_text_index_function_like_escape.sql uses EXPLAIN indexes = 1 to assert that the index narrows reads (1 part / 1024 granules out of 4 / 4096 for %World%) under both LIKE ... ESCAPE and ILIKE ... ESCAPE. It FAILS on master and PASSES with the fix.

@clickgapai

Copy link
Copy Markdown
Contributor

Hi @qoega @alexey-milovidov @rschu1ze — while reviewing this PR I found the following:

Happy to discuss — close anything that's wrong or already addressed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Support ESCAPE clause in LIKE patterns

7 participants