Skip to content

Support SIMILAR TO pattern matching predicate - #101514

Merged
alexey-milovidov merged 84 commits into
ClickHouse:masterfrom
zheguang:zheguang-99608-similar-to
Oct 4, 2026
Merged

alexey-milovidov merged 84 commits into
ClickHouse:masterfrom
zheguang:zheguang-99608-similar-to

Conversation

@zheguang

@zheguang zheguang commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

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

Support SIMILAR TO pattern matching predicate

Documentation entry for user-facing changes

  • [ x ] Documentation is written (mandatory for new features)
  • Motivation:
    SQL standard has SIMILAR TO predicate that combines SQL LIKE wildcards (%, _) with regular expression metacharacters |, *, +, ?, [...], {m,n}, (...). Note that excluded are ^, $, ..
    It is supported by PostgreSQL and others. See the PostgreSQL documentation on pattern matching for reference.

I also added: negation and substring pattern shortcut. Syntax highlighting is also hooked in to highlight the metacharacters.

  • Parameters:
    None.

  • Example use:

SELECT similarTo('ClickHouse', 'Cl_ck[hH]ouse');  -- Returns: 1
SELECT 'ClickHouse' NOT SIMILAR TO 'Cl%ck[0-9]ouse'; -- Returns: 1
  • Corner cases
    • Character class inside bracket expression.
    • Bracket expressions don't nest. So [[:a]] is invalid, but up to RE2 to process.

Addresses #99608.


Note

Medium Risk
Adds new SQL operator/function surface area and a new pattern-to-regexp translator, which can affect query parsing and string filtering semantics; risk is moderate due to edge cases in escaping/bracket handling and regex compilation paths.

Overview
Adds SQL-standard SIMILAR TO pattern matching (and NOT SIMILAR TO) implemented via new similarToPatternToRegexp() conversion and new similarTo/notSimilarTo functions wired into MatchImpl/Regexps::createRegexp.

Extends the parser to recognize and pretty-print SIMILAR TO / NOT SIMILAR TO, updates CNF NOT-pushing inversions, and adds syntax-highlighting support for SIMILAR TO metacharacters.

Updates call sites to the new Regexps::createRegexp<like, similar_to, ...> template signature and expands query fuzzer swap sets plus a new stateless test suite covering SIMILAR TO behavior and corner cases.

Reviewed by Cursor Bugbot for commit e17d9fd. Bugbot is set up for automated code reviews on this repo. Configure here.


Workflow [PR]
Sync PR [sync-upstream/pr/101514]

Version info

  • Merged into: 26.10.1.1492-master (included in 26.10 and later)

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Apr 1, 2026
@clickhouse-gh

clickhouse-gh Bot commented Apr 1, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [2d1b654]

Summary: ✅


AI Review

Summary

This PR adds SIMILAR TO / NOT SIMILAR TO end to end: parser and formatter support, execution via a dedicated SIMILAR TO-to-RE2 translator, ESCAPE handling (including SOME / ALL array-quantifier forms), analyzer/CNF normalization, documentation, and focused stateless regressions. I did not find any remaining correctness, safety, or contract issues in the current code.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 2d1b654.

Metric Baseline Current Δ
Lines 88.10% 88.10% +0.00%
Functions 92.10% 92.10% +0.00%
Branches 79.60% 79.50% -0.10%

Changed lines: Changed C/C++ lines covered: 562/595 (94.45%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Apr 1, 2026
Comment thread src/Common/likePatternToRegexp.cpp Resolved
@zheguang
zheguang marked this pull request as draft April 1, 2026 23:14
@zheguang
zheguang marked this pull request as ready for review April 2, 2026 01:08
Comment thread src/Common/likePatternToRegexp.cpp Resolved
@zheguang

zheguang commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor Author

❌ Blockers

[src/Common/likePatternToRegexp.cpp:126] similarToPatternToRegexp can leave bracket context too early when parsing patterns like [[:digit:]] / [[:digit:]%]. After closing [:digit:], _ / % may be treated as outside-bracket and translated as wildcards (. / .*), changing matching semantics and producing incorrect query results.
Suggested fix: keep outer bracket state separate from POSIX class state, and only exit in_bracket on the outer ]. Add regression tests for SELECT '
' SIMILAR TO '[[:digit:]_]' and SELECT '%' SIMILAR TO '[[:digit:]%]'.

@clickhouse-gh's s suggestion seems off? Lookahead would be an overkill here for a thin layer of translating SQL metacharacters into RE2. We just need to figure out "maybe it's a class expression" or not. Also, bracket expressions don't nest in SQL standards and RE2. The translation layer shouldn't do too much here...

Added test cases to show the suggested bug doesn't exist:

SELECT '-- Metacharacter before/after class in bracket expression';
SELECT '_' SIMILAR TO '[_[:digit:]]';              -- Returns: 1
SELECT '5' SIMILAR TO '[_[:digit:]]';              -- Returns: 1
SELECT 'a' SIMILAR TO '[_[:digit:]]';              -- Returns: 0

SELECT '%' SIMILAR TO '[[:digit:]%]';              -- Returns: 1
SELECT '5' SIMILAR TO '[[:digit:]%]';              -- Returns: 1
SELECT 'a' SIMILAR TO '[[:digit:]%]';              -- Returns: 0

@zheguang

zheguang commented Apr 2, 2026 •

Copy link
Copy Markdown
Contributor Author

I think I see where the AI got wrong:

  • Concrete trace for pattern [[:digit:]_]:

    • At first [ (pos[1] == ':'): maybe_in_class=true, in_bracket remains false.

At first [, should be pos[1] == '['...
Then in_bracket is set to true in the default case:
https://github.com/zheguang/ClickHouse/blob/4f430004345ad8f95ad9f6a359654ac6d100986f/src/Common/likePatternToRegexp.cpp#L138

The test case actually passed... 🤣

SELECT '_' SIMILAR TO '[[:digit:]_]';         -- Returns: 1
SELECT 'a' SIMILAR TO '[[:digit:]_]';         -- Returns: 0
SELECT 'a' SIMILAR TO '[[:digit:]%]';              -- Returns: 0

https://github.com/zheguang/ClickHouse/blob/4f430004345ad8f95ad9f6a359654ac6d100986f/tests/queries/0_stateless/04051_similar_to.sql#L91
https://github.com/zheguang/ClickHouse/blob/4f430004345ad8f95ad9f6a359654ac6d100986f/tests/queries/0_stateless/04051_similar_to.sql#L127

How do I ... debug AI? 🤔

Comment thread src/Client/ClientBaseHelpers.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.

Comment thread docs/reference/operators/index.mdx Resolved
The docs claimed that `^` is always a literal character in a `SIMILAR TO`
pattern, but a leading `^` inside a bracket expression still negates the
class (as `04051_similar_to` already tests). Qualify the statement in
`docs/reference/operators/index.mdx` and mirror it in the `similarTo` and
`notSimilarTo` function documentation.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label Aug 20, 2026
…lar-to

# Conflicts:
#	docs/reference/operators/index.mdx
#	src/Parsers/ExpressionListParsers.cpp
…lar-to

Two conflicts, both in `Common/likePatternToRegexp.{h,cpp}`, where `master`
added `likePatternHasUnknownBackslashEscape` for the text/bloom-filter text
indexes right next to this PR's `similarToPatternWithCustomEscapeToSimilarToPattern`.
Resolved as a union of both declarations and definitions.

Also fixed two things that auto-merged without a textual conflict:
- `master` added a new 3-argument `Regexps::createRegexp` call site in
  `ITokenizer.cpp` (this PR widens the template to 4 arguments); made it
  4-argument.
- `introduced_in` for `similarTo` / `notSimilarTo` bumped `{26, 8}` -> `{26, 9}`
  to match `master`'s `VERSION_MINOR`.

Restored the `contrib/llvm-project` and `contrib/musl` gitlinks to `master`'s
values - an earlier criss-cross merge had reverted them on the branch.
Comment thread src/Functions/similarTo.cpp Resolved
@abashkeev abashkeev added the comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... label Sep 4, 2026
…lar-to

Conflict in `src/Interpreters/ITokenizer.cpp`: `master` reworked
`SplitByRegexpTokenizer` to build its `OptimizedRegularExpression`
directly instead of going through `Regexps::createRegexp`, so the
4-argument `createRegexp` adaptation this branch had applied there is
no longer needed - took `master`'s version wholesale.
…ualify the `ESCAPE` prose

Two unresolved review threads:

1. The \`SIMILAR TO\` additions to \`docs/reference/statements/select/where.mdx\`
   sat inside the file's \`AUTOGENERATED_START\`/\`AUTOGENERATED_END\` region, so
   \`check_autogenerated_regions\` rejected them. That region is a verbatim copy
   of the \`.description\` raw string of \`factory.registerStatement("WHERE", ...)\`
   in \`src/Parsers/ParserSelectQuery.cpp\`, so the content now lives there and the
   generated page is left untouched for the docs autogeneration job to refresh.

2. The \`ESCAPE\` prose claimed that an escape followed by an ordinary character is
   always an error. That holds only for a *custom* escape character: the default
   backslash keeps the legacy \`LIKE\` behaviour and denotes a literal backslash, as
   \`04051_similar_to.sql\` pins (\`SELECT '\\\\mabc' SIMILAR TO '%\\\\mabc%'\` returns 1).
   Qualified in \`src/Functions/similarTo.cpp\` and \`docs/reference/operators/index.mdx\`.
Comment thread src/Common/likePatternToRegexp.cpp Resolved
alexey-milovidov and others added 2 commits September 16, 2026 23:02
…lar-to

# Conflicts:
#	src/Storages/MergeTree/MergeTreeIndexConditionText.cpp
… backslash in `SIMILAR TO`

`similarToPatternWithCustomEscapeToSimilarToPattern` still accepted the
custom escape character before `^`, `$`, `.` and `\`, silently rewriting
`a#.b` (under `ESCAPE '#'`) to the same meaning as `a.b`. The documented
`SIMILAR TO` contract describes these characters as ordinary literals
outside bracket expressions and says that escaping an ordinary character
is an error, so the validator now accepts only the characters that are
special in the `SIMILAR TO` grammar (`%`, `_`, `|`, `*`, `+`, `?`, `{`,
`}`, `(`, `)`, `[`, `]`) and the escape character itself, consistent with
`LIKE ... ESCAPE`.

Adds focused regressions for `a#.b`, `a#^b`, `a#$b` and `a#\b`, and
spells the rule out in the `similarTo` documentation and the operators
reference.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Comment thread src/Parsers/ParserSelectQuery.cpp Resolved
alexey-milovidov and others added 2 commits October 3, 2026 03:46
…lar-to

# Conflicts:
#	src/Common/QueryFuzzer.cpp
#	src/Functions/Regexps.h
…cs tables

Inside a Markdown table the `|` has to be written as `\|`, which readers
can mistake for a ClickHouse string escape. Use examples that need no
escaping instead.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

@alexey-milovidov alexey-milovidov left a comment

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.

The implementation is straightforward. Thanks!

@alexey-milovidov alexey-milovidov self-assigned this Oct 4, 2026
@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Oct 4, 2026
Merged via the queue into ClickHouse:master with commit 37a251f Oct 4, 2026
149 checks passed
@robot-ch-test-poll3 robot-ch-test-poll3 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 4, 2026
Master (ClickHouse#101514) added a similar_to template parameter to createRegexp,
so the two LIKE-pattern calls of this branch no longer compiled after
the master merge.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
valerypetrov added a commit to valerypetrov/ClickHouse that referenced this pull request Oct 4, 2026
Master added the pattern bypass cache (ClickHouse#113572), which conflicted in
ProfileEvents.cpp and MergeTreeIndexText.cpp; both sides' events are kept.
Its key does not hold text_index_like_max_matched_tokens, which can decide
the bypass for hasTokenPrefix, hasTokenLike and hasTokenMatch, so a query
with those patterns skips the cache.

Master (ClickHouse#101514) also added a similar_to parameter to createRegexp; the
branch's calls pass it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-regular-function Regular scalar functions: string processing, data conversion, arithmetic, math, comparison, condi... manual approve Manual approve required to run CI 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.

4 participants