Skip to content

Support constant haystack with non-constant needle in LIKE/ILIKE/match - #100479

Merged
alexey-milovidov merged 30 commits into
ClickHouse:masterfrom
Onyx2406:fix/like-constant-haystack-nonconstant-needle
Jun 14, 2026
Merged

alexey-milovidov merged 30 commits into
ClickHouse:masterfrom
Onyx2406:fix/like-constant-haystack-nonconstant-needle

Conversation

@Onyx2406

@Onyx2406 Onyx2406 commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • Bug Fix (user-visible misbehavior in an official stable release)

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

Functions like, ilike, notLike, notILike, and match now support constant haystack with non-constant needle (e.g. 'foo' LIKE pattern_column), which previously threw ILLEGAL_COLUMN.

Documentation entry for user-facing changes

  • Documentation is not required (bug fix restoring expected SQL behavior)

What this PR does

The (I)LIKE and match functions threw an exception when the haystack (first argument) was a constant string and the needle/pattern (second argument) came from a column:

SELECT * FROM t WHERE 'foo' ILIKE concat('%', col, '%');
-- Code: 44. DB::Exception: Function 'ilike' doesn't support search with
-- non-constant needles in constant haystack

This is valid SQL and works in other databases. The constantVector method in MatchImpl was a stub that unconditionally threw. This PR implements it.

Root cause

MatchImpl::constantVector in src/Functions/MatchImpl.h was:

template <typename... Args>
static void constantVector(Args &&...) {
    throw Exception(..., "doesn't support non-constant needles in constant haystack");
}

The other argument combinations (vectorConstant, vectorVector, vectorFixedVector) were all implemented — only constantVector was missing.

Fix

Implements constantVector following the same logic as the existing vectorVector path:

  • For each row, extract the needle pattern from the column
  • Fast path: if the LIKE pattern reduces to %substring%, use Volnitsky string search
  • Slow path: compile to regexp via the per-thread LocalCacheTable cache, pre-filter with required substring, then run RE2 match

The haystack is constant across all rows, so it is read once and reused.

Test plan

New stateless test 04053_like_constant_haystack_nonconstant_needle.sql:

  • LIKE, ILIKE, NOT LIKE, NOT ILIKE with constant haystack
  • match() with constant haystack
  • Needle patterns from table column
  • Edge cases: empty strings, single-char strings, escaped wildcards

Fixes #84187

Version info

  • Merged into: 26.6.1.785

The `like`, `ilike`, `notLike`, `notILike`, and `match` functions
previously threw an exception when the haystack (first argument) was
a constant and the needle (second argument) came from a column:

    SELECT * FROM t WHERE 'foo' ILIKE concat('%', col, '%');
    -- Error: doesn't support non-constant needles in constant haystack

This implements the `constantVector` method in `MatchImpl` following
the same logic as the existing `vectorVector` path: per-row pattern
compilation with substring fast-path and regexp cache.

Fixes ClickHouse#84187
@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 23, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [38d0e35]

Summary: ✅


AI Review

Summary

This PR implements non-constant needle support for constant haystacks in LIKE, ILIKE, NOT LIKE, NOT ILIKE, and match, and updates the match source documentation plus stateless coverage. The current code addresses the prior review threads around trivial %/%% patterns, keeps the non-constant-needle paths unified through matchOneRow, and I did not find any remaining correctness, compatibility, or documentation issue that needs an inline comment.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Mar 23, 2026
Comment thread src/Functions/MatchImpl.h Resolved
- Remove unused `ErrorCodes::ILLEGAL_COLUMN` declaration from
  `MatchImpl.h` (style check failure).
- Update `03278_enum_string_functions` test: constant LIKE with
  `randomString(0)` no longer throws, it returns 0.
- Simplify `04053` test reference and remove ambiguous edge cases.
ClickHouse's LIKE treats '%%' differently from '%' — fix the
expected output for the empty-string edge case.
@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

Copy link
Copy Markdown
Member

The flaky check failure is fixed in #102148, let's update the branch.

Comment thread src/Functions/MatchImpl.h Resolved
`vectorConstant` and `vectorFixedConstant` already short-circuit
`needle == '%' || needle == '%%'` (for `LIKE`) and `needle == '.*' ||
needle == '.*?'` (for `match`) to `!negate` independently of the
haystack. `constantVector` was missing the same shortcut, so
`'' LIKE '%%'` fell through `likePatternIsSubstring` into a Volnitsky
search with an empty required substring on an empty haystack, which
returns `haystack_end` and therefore `0` — inconsistent with the
column ⇒ const direction and with SQL semantics.

Adds the shortcut and updates the reference for
`'' LIKE '%%'` from `0` to `1`.

Addresses review comment on PR ClickHouse#100479.
Comment thread src/Functions/MatchImpl.h Resolved
…rFixedVector`

`constantVector` (and `vectorConstant`/`vectorFixedConstant`) already
short-circuit `needle == '%' || needle == '%%'` (for `LIKE`) and
`needle == '.*' || needle == '.*?'` (for `match`) to `!negate`
independently of the haystack. `vectorVector` and `vectorFixedVector`
were missing the same shortcut, so when both the haystack and the
needle came from columns and a row had `needle == '%%'`, that row
fell through `likePatternIsSubstring` into a Volnitsky search with
an empty `required_substr` and returned `0` for an empty haystack —
inconsistent with the column ⇒ const direction (which the prior
`705aef7d474` fixed) and with SQL semantics.

Adds the shortcut and extends `04053_like_constant_haystack_nonconstant_needle`
to cover the column-column path for both `String` and `FixedString`
haystacks, and the `match` `.*` / `.*?` shortcut across all four
argument-shape combinations.

Addresses follow-up review comment on PR ClickHouse#100479.
The merge brought in updated `.github/workflows/*` and `ci/workflows/*` from
master, which the fork-push OAuth token cannot push. Restore those paths to
the PR-branch's pre-merge state so the PR keeps its own workflow snapshot
and the push succeeds.
@clickhouse-gh clickhouse-gh Bot added the manual approve Manual approve required to run CI label May 24, 2026
These changes to CI workflow / infrastructure files were unrelated to the
purpose of this pull request and were introduced accidentally (stale base
branch). Restoring them to match `master`.
@alexey-milovidov alexey-milovidov removed the manual approve Manual approve required to run CI label May 31, 2026
alexey-milovidov and others added 3 commits June 1, 2026 23:26
The merge with master pulled in many tests using the 04053 prefix, so
the new test is renumbered to the next available number.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ctor`

Master enabled the `cppcoreguidelines-init-variables` clang-tidy check.
Initialize these locals to `false` as in the other `MatchImpl` paths.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
alexey-milovidov and others added 2 commits June 6, 2026 17:57
…-pattern shortcut

Addresses @antaljanosbenjamin's review on `MatchImpl.h`:

- The per-row matching logic was duplicated three times (in `vectorVector`,
  `vectorFixedVector` and `constantVector`). Extracted it into a single
  `matchOneRow` helper so the three non-constant-needle paths stay in sync.
- `matchOneRow` takes the needle as a `std::string_view` instead of copying it
  into a `String` on every row; a `String` is only materialized on the slow
  path when populating the per-thread regexp cache (`getOrSet`).
- Generalized the "matches everything" trivial-pattern check: instead of only
  recognizing `%` and `%%`, the new `impl::likePatternMatchesEverything` treats
  any non-empty run of `%` (e.g. `%%%`, `%%%%%%`) as matching every haystack.
  Applied consistently across all argument shapes (`vectorConstant`,
  `vectorFixedConstant`, and the three non-constant-needle paths).

Extended `04309_like_constant_haystack_nonconstant_needle` to cover longer runs
of `%` as a needle in both the constant-haystack and column-column directions.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged master (was ~487 commits behind) and addressed the three open review comments from @antaljanosbenjamin in 511e19a:

  • Unified the per-row matching logic that was duplicated across vectorVector, vectorFixedVector and constantVector into a single matchOneRow helper (net −234/+89 lines).
  • The helper takes the needle as a std::string_view; a String is only materialized on the slow path for the regexp cache.
  • Generalized the trivial-pattern shortcut into impl::likePatternMatchesEverything so any non-empty run of % (%%%, %%%%%%, …) is recognized as "matches everything", applied across all argument shapes.

Verified locally against the freshly built binary: 04309_like_constant_haystack_nonconstant_needle and 03278_enum_string_functions both pass. The 5 translation units (like/ilike/notLike/notILike/match) compile clean.

The remaining red checks are unrelated to this PR:

@groeneai, could you take a look at the arrayRemove AST-fuzzer failure (STID 2508-1fb5, e.g. https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100479&sha=843e8461c44fb4d216eb5b67cd3aa332014bc024&name_0=PR&name_1=AST%20fuzzer%20%28amd_debug%2C%20targeted%29) and provide a fix in a separate PR if one isn't already in progress?

Comment thread src/Functions/MatchImpl.h Resolved
alexey-milovidov and others added 2 commits June 8, 2026 11:43
…able

The `match` function now supports a non-constant needle (pattern from a
column), so its embedded documentation should no longer advertise the
`pattern` argument as `const String`. Change the argument type to
`String` and note that it can be a constant or come from a column.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

CI status update

Merged master (was 337 commits behind) and addressed the remaining open review thread.

Review feedback

  • Resolved the last open thread (match.cpp argument doc): 0a2bf393f49 changes the pattern argument type from const String to String and notes it can be a constant or come from a column, so generated docs no longer advertise the now-supported match('foo', pattern_column) shape as invalid. The like/ilike/notLike/notILike docs already used String.

CI failures — all unrelated to this PR

The only red checks are the targeted AST fuzzer jobs (amd_debug, targeted and amd_debug, targeted, old_compatibility). Both crash on the same fuzzer-mutated query that has nothing to do with LIKE/match:

SELECT arrayRemove([[[isNotDistinctFrom(16, ...)]], ...], [[arrayRemove(['hello', 'world'], concat('a', 1, equals(16, isNullable(8)))), ...]])

It aborts in FunctionIf::executeGeneric → IColumn::insertFrom → IColumn::assertTypeEquality (if.cpp:907), i.e. the getDataType() == rhs.getDataType() logical error. This is a pre-existing bug in FunctionIf with nested arrays — CIDB shows the same logical error firing on 6 different PRs over the last 30 days (#94517, #106026, #99740, #98607, #106073, and this one). It does not exercise any code touched by this PR.

@groeneai, could you investigate the FunctionIf::executeGeneric / assertTypeEquality logical error (STID: 2508-1fb5) and provide a fix in a separate PR? If a fix is already in progress, please link it here.

Verified locally: the new test 04309_like_constant_haystack_nonconstant_needle passes against a freshly built binary (LIKE/ILIKE/NOT LIKE/NOT ILIKE/match, column and FixedString haystacks, empty-block / partial-result path).

@groeneai

groeneai commented Jun 8, 2026

Copy link
Copy Markdown
Collaborator

@alexey-milovidov, the fix is open and approved: #105248 "Fix arrayRemove logical error when comparing incompatible Variant types". State: MERGEABLE, BLOCKED, approved by antaljanosbenjamin on 2026-06-05, last push 2026-06-03 (2006f54c). Issue #95839 is the tracking issue.

Same root cause covers all 6 sub-STIDs you listed (1fb5 / 3a34 / 42b3 / 3f35 / 30fe + the new 2508-30fe on amd_tsan): arrayRemove produces a ColumnNothing while declaring its result type as UInt8, so the FunctionIf typed path bypasses dispatch and insertFrom then trips assertTypeEquality. Fix substitutes a constant-zero UInt8 column when the underlying equality column is not UInt8 (src/Functions/array/arrayIndex.h).

CIDB 30d for the exact STID 2508-1fb5: 0 master hits, 46 total (38x #94517 + 14x this PR). Broader FunctionIf::executeGeneric + assertTypeEquality shape across the 6 PRs you cited: 51 hits, all PR-only. The 1fb5 shape last hit master 0 times in 30d.

The PR is not stuck on us; it has been approved and is just waiting for a final merge step (looks like the BLOCKED state is the standard second-reviewer gate, not a CI/code blocker). Happy to close+reopen or rebase if that helps unblock.

Session: cron:clickhouse-ci-task-worker:20260608-133300

alexey-milovidov and others added 2 commits June 9, 2026 22:10
After merging master, the number `04309` is now also used by
`04309_distributed_aggregation_persisted_exchange` and
`04309_explain_insert_format`. Renumber to the next free prefix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master into the branch (it was ~894 commits behind and red). No conflicts. Also:

  • Renumbered the new stateless test 04309_* → 04327_like_constant_haystack_nonconstant_needle to avoid a prefix collision introduced by master (two other 04309_* tests now exist).
  • Rebuilt clickhouse (clean) and re-ran the tests against the new binary: 04327_like_constant_haystack_nonconstant_needle and 03278_enum_string_functions both pass. The original issue repro SELECT 'foo' ILIKE concat('%', 'o', '%') now returns 1.

CI failures — all unrelated to this change

  • Stateless tests (amd_debug, parallel): Virtual row boundary violated in MergingSortedAlgorithm (STID: 2651-3359) and Server died — known read-in-order virtual-row flake (#106740), fixed on master by 28c01518689, now pulled into the branch via the merge.
  • AST fuzzer (amd_debug, targeted) and (…, old_compatibility): Logical error: '(isConst() || … ) ? getDataType() == rhs.getDataType() : typeid(*this) == typeid(rhs)' (STID: 2508-1fb5) — pre-existing fuzzer crash in nested arrayRemove/if type handling, with no like/ilike/match anywhere in the reproducer. Tracked as #95839 (closed, but still recurring); CIDB shows the same STID failing on unrelated PR Enable optimize_or_like_chain by default. #94517 (base master) across 25+ days.

@groeneai, please investigate the AST fuzzer failure (STID: 2508-1fb5, #95839, a nested arrayRemove/if column-type-mismatch crash unrelated to this PR) and provide a fix in a separate PR. If a fix is already in progress, please link it here.

@alexey-milovidov

Copy link
Copy Markdown
Member

CI status on current head 8fc389fcbc7 (after the 2026-06-09 master merge): 142/162 checks passed; the only 2 failures are AST fuzzer (amd_debug, targeted) and AST fuzzer (amd_debug, targeted, old_compatibility), both the same known pre-existing logical error (STID 2508-1fb5): arrayRemove building an internal if that hits IColumn::assertTypeEquality in FunctionIf::executeGeneric. I verified the reproducer query from the fuzzer log — it contains no like/ilike/match and no MatchImpl frames in the stack, so it is unrelated to this PR.

Fix is already open and approved: #105248 (tracking issue #95839).

No unresolved review threads, approved by @antaljanosbenjamin — this is ready to merge.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest `master` (the branch was ~1002 commits behind and red); the merge was conflict-free and master had not touched src/Functions/MatchImpl.h or src/Functions/match.cpp, so it is purely additive. Pushed as 8d039abdfc3.

The only remaining non-sync failures are the two AST fuzzer (amd_debug, targeted[, old_compatibility]) jobs, both the same pre-existing arrayRemove/Variant logical error (STID 2508-1fb5) that is unrelated to this change and tracked by #105248. The CH Inc sync failure was against the stale head and re-runs fresh against this merge.

@alexey-milovidov

Copy link
Copy Markdown
Member

Merged latest master (pushed as 38d0e3535d5). Conflict-free and purely additive — master did not touch src/Functions/MatchImpl.h or src/Functions/match.cpp, and the PR's own diff vs master is unchanged (MatchImpl.h, match.cpp, 03278_enum_string_functions, and the new 04327_like_constant_haystack_nonconstant_needle test).

The reason for this re-merge: the only remaining red checks were the two AST fuzzer (amd_debug, targeted[, old_compatibility]) jobs, both hitting the known pre-existing arrayRemove/Variant logical error (STID 2508-1fb5, tracked in #95839). The fix for it — #105248 (Fix arrayRemove logical error when comparing incompatible Variant types) — was merged into master on 2026-06-13 21:23 UTC, which is after this branch's previous merge-base. This re-merge pulls that fix in (8427ed3d375, modifying src/Functions/array/arrayRemove.cpp), so the targeted AST fuzzer should now pass on a fresh run.

No unresolved review threads; approved by @antaljanosbenjamin. Ready to merge once CI is green.

@clickhouse-gh

clickhouse-gh Bot commented Jun 14, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.80% 84.70% -0.10%
Functions 92.40% 92.40% +0.00%
Branches 77.30% 77.30% +0.00%

Changed lines: Changed C/C++ lines covered by tests: 89/91 (97.80%) | Lost baseline coverage: none · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue Jun 14, 2026
Merged via the queue into ClickHouse:master with commit b4f0960 Jun 14, 2026
166 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 14, 2026
@clickgapai

Copy link
Copy Markdown
Contributor

Hi @Onyx2406 @alexey-milovidov @antaljanosbenjamin — while reviewing this PR I found the following:

Could you review the test PR and add the can be tested label if it looks good?
Happy to discuss — close anything that's wrong or already addressed.

alexey-milovidov added a commit that referenced this pull request Jun 27, 2026
`MatchImpl` supports a constant haystack with a non-constant needle (since the
merge of #100479 into `master`), so the earlier exclusion of `LIKE`, `ILIKE`,
`NOT LIKE`, `NOT ILIKE`, and `REGEXP` from the `SOME` / `ALL` array quantifier
no longer applies: `'abc' LIKE SOME(['a%', 'b%'])` rewrites to
`arrayExists(x -> 'abc' LIKE x, ['a%', 'b%'])` and evaluates without throwing.

Route these predicates through the same `arrayExists` / `arrayAll` lambda
rewrite as the keyword comparison predicates, correct the now-false parser
comment and the operator documentation, and replace the `UNKNOWN_FUNCTION`
assertion in the test with positive coverage (`LIKE` / `ILIKE` / `NOT LIKE` /
`NOT ILIKE` / `REGEXP` with `SOME` / `ALL`, including `NULL` patterns and
equivalence to the explicit lambda form).

Review addressed: #107454 (comment)

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
`MatchImpl` supports a constant haystack with a non-constant needle (since the
merge of ClickHouse#100479 into `master`), so the earlier exclusion of `LIKE`, `ILIKE`,
`NOT LIKE`, `NOT ILIKE`, and `REGEXP` from the `SOME` / `ALL` array quantifier
no longer applies: `'abc' LIKE SOME(['a%', 'b%'])` rewrites to
`arrayExists(x -> 'abc' LIKE x, ['a%', 'b%'])` and evaluates without throwing.

Route these predicates through the same `arrayExists` / `arrayAll` lambda
rewrite as the keyword comparison predicates, correct the now-false parser
comment and the operator documentation, and replace the `UNKNOWN_FUNCTION`
assertion in the test with positive coverage (`LIKE` / `ILIKE` / `NOT LIKE` /
`NOT ILIKE` / `REGEXP` with `SOME` / `ALL`, including `NULL` patterns and
equivalence to the explicit lambda form).

Review addressed: ClickHouse#107454 (comment)

Co-Authored-By: Claude Opus 4.8 (1M context) <[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 pr-bugfix Pull request with bugfix, not backported by default 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.

Occurs error when (I)LIKE doesn't support search with-non-constant needles in constant haystack when left side is constant

6 participants