Skip to content

Push Enum constants to external databases in the form ClickHouse compares them - #123843

Merged
alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-external-pushdown-enum-constant
Oct 4, 2026
Merged

alexey-milovidov merged 5 commits into
ClickHouse:masterfrom
groeneai:groeneai/fix-external-pushdown-enum-constant

Conversation

@groeneai

@groeneai groeneai commented Oct 4, 2026 •

Copy link
Copy Markdown
Collaborator

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):

Fixed lost rows when a query over a MySQL, PostgreSQL, SQLite or ODBC/JDBC table compares a column (string, number or Decimal) with an Enum constant (also inside a tuple, an IN list, Nullable, Variant or Dynamic, at any depth): the filter sent to the external database used the Enum's number, while ClickHouse compares a string column with the Enum's name, and PostgreSQL rejected such a query. An IN list or row of Variant or Decimal constants is no longer sent as one quoted string.

Description

On 26.3 and 26.8, SELECT s FROM mysql(...) WHERE s = CAST('7', 'Enum8(\'7\' = 3)') returns no rows, while the same filter over local data returns '7'; postgresql(...) fails with operator does not exist: text = integer. No open issue; found while validating #118988.

Root cause: ClickHouse compares a string with an Enum by its name and a number by its value, but getASTForExternalDatabaseFromQueryTree writes an Enum constant as its number. The pushed filter must select a superset of the local rows, so rows are lost. A Variant(Enum) constant against a number is pushed as the name, and replaceConstantExpressions folds a constant tuple(...) into one string (s IN ('(''7'',''x'')')).

Change:

  • PrepareForExternalDatabaseVisitor: a constant holding an Enum value (plain, in a Tuple, behind Nullable/Variant/Dynamic at any level) becomes, for IN/NOT IN, the members of the set the local query builds; for a comparison, each Enum leaf becomes its name against a string operand and its value against a number.
  • A conjunct that still holds an Enum constant after this (an empty set, a nested tuple key, an Enum column, a non-constant row such as (s, n) < (E, n)) is not pushed down and is applied locally.
  • replaceConstantExpressions keeps a constant tuple(...) and folds its elements one by one. On the AST path (a CHECK constraint subquery) it leaves an Enum constant unfolded, so the condition stays local.

A simpler alternative is to keep every predicate with an Enum constant local (no pushdown for it); I can switch to that if you prefer.

Validation: the new test 05321_sqlite_pushdown_enum_constant (STRICT SQLite table, 39 shapes incl. strict mode) fails on master and passes with the fix (100/100 runs); the SQLite stateless tests and TransformQueryForExternalDatabase gtests pass; checked by hand on MySQL 8.0 and PostgreSQL 16, incl. Decimal keys.


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

Version info

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

groeneai and others added 4 commits October 4, 2026 04:28
…ares them

ClickHouse compares a string with an `Enum` by the Enum's name and a number
by its value, but the analyzer pushdown for external databases
(`getASTForExternalDatabaseFromQueryTree`, `toAST` without casts) writes an
`Enum` constant as its underlying number whatever the column is. The pushed
filter is only a pre-filter and must select a superset of the local rows, so
`s = CAST('7', 'Enum8(\'7\' = 3)')` sent as `s = 3` lost the row '7' on
SQLite and MySQL, and PostgreSQL rejected the query (`text = integer`).
A `Variant(Enum)` constant went the other way (its `_CAST` chain was folded to
the name, wrong against a number).

`PrepareForExternalDatabaseVisitor` now rewrites a constant that holds an
`Enum` value (plain, `Nullable`, in a `Tuple`, active in `Variant`/`Dynamic`):
- for `IN`/`NOT IN` it becomes the members of the set the local query builds,
  `getSetElementsForConstantValue` with the same settings as `CollectSets`,
  so a string key gets the name, a number key the value, and the list/row
  shape follows the left-hand side; a `FixedString` key gets the unpadded
  name (what the remote stores, and a long name cannot throw);
- for a comparison each `Enum` leaf (zipped through tuples) becomes its name
  against a string operand and its value against a number, other leaves keep
  their literal (a strict set conversion would drop `2.5` in
  `(s, n) < (E, 2.5)`). Other operand types are left as before.

The old-analyzer `replaceConstantExpressions` replaced every constant
non-numeric function by its text, including the structural `tuple(...)` the
analyzer writes for an `IN` list or row whose element needs an exact literal
(`Variant`, `Decimal`, ...), so `s IN (V('7'), V('x'))` was pushed as
`s IN ('(''7'',''x'')')` and `(s, f) < (E, toDecimal64(4, 1))` as a row
compared with a string (SQLite: `row value misused`). The matcher now keeps a
`tuple` function and folds its elements one by one (the visitor is
top-to-bottom).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nt tuple keys

Three shapes still fell outside the rewrite and kept the Enum's number:

- A `Decimal` or wide-integer key or operand was neither a string nor a
  native number, so `(s, d) IN ((E, 3))` with `d Decimal(10, 1)` aborted the
  whole `IN` rewrite and pushed `(s, d) IN ((3, 3))`: MySQL returned no rows and
  PostgreSQL rejected `text = integer`. Every number type now counts as a
  number key/operand.
- A tuple behind `Nullable`, `Variant` or `Dynamic` was detected (or, for
  `Dynamic`, not even detected) but not rendered, so
  `(s, n) < toNullable((E, 4))` pushed `(3, 4)` and the `Variant` form was
  folded into one string (`row value misused`). One helper, `unwrapCarrier`,
  now looks through `Nullable` and the active alternative of `Variant` and
  `Dynamic` at every level, for both detection and rendering.
- A one-element tuple key (`tuple(s) IN (tuple(E))`) stays packed in the set
  builder and was rejected as a key type, so the number was pushed. The key
  element is now checked and the set is built with the packed type, as
  `CollectSets` does, and each member's single element is pushed.

A comparison constant without an Enum is left untouched.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Every Enum constant the rewrite does not render keeps the Enum's number
when the filter is written for the external database. That happened for
an empty local set (`(s, n) NOT IN ((E, NULL))`: MySQL dropped rows,
PostgreSQL rejected `text = integer`), a nested tuple key
(`((s, n), d) IN (((E, 3), 3.0))`, pushed to PostgreSQL as `((3, 3), 3.)`),
a key or operand that is neither a string nor a number (an `Enum` column),
and an Enum constant inside a non-constant row (`(s, n) < (E, n)` was
pushed as `(s, n) < (3, n)` and lost the matching row).

After the rewrite, a conjunct of the pushed filter that still holds a
constant with an Enum value is now removed from it, so ClickHouse applies
it locally, as for any predicate it cannot push. The remaining conjuncts
are re-resolved as `removeExpressionsThatDoNotDependOnTableIdentifiers`
does, and it runs after that function, so a predicate over another joined
table is still dropped as foreign first. Under
`external_table_strict_query` such a conjunct is rejected with
`INCORRECT_QUERY`, like the conjuncts `transformQueryForExternalDatabaseImpl`
cannot push.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Shorten the renderEnumLeaves contract to two lines.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@groeneai groeneai added can be tested Allows running workflows for external contributors groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work labels Oct 4, 2026
@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Internal second-model review (3 rounds before publication)

Fixed during review:

  • ❌ r1: a Decimal or 128/256-bit key or operand stopped the Enum rewrite, so a String key in the same tuple still got the number. Every number type is accepted now.
  • ❌ r1: an Enum inside Nullable(Tuple), Variant(Tuple) or Dynamic(Tuple) was not rewritten. One carrier-unwrapping helper handles all of them.
  • ❌ r1: tuple(s) IN (tuple(E)) (one-element tuple key) kept the number. The set is now built with the packed key, and its members are pushed as scalars.
  • ❌ r2: an Enum constant the rewrite cannot write (empty local set, nested tuple key, non-string/number operand, non-constant row such as (s, n) < (E, n)) fell back to its number. Such a conjunct is kept local now.

r3: no new findings. Noted, not blocking:

  • 💡 The branch that re-resolves an and with 2 or more remaining conjuncts was checked by hand, not by a test arm.
  • 💡 An Enum-typed constant against an Enum column declared on the ClickHouse side is now applied locally. Before, it was pushed as the number, which MySQL compares by ENUM index and PostgreSQL rejects.

@groeneai

groeneai commented Oct 4, 2026

Copy link
Copy Markdown
Collaborator Author
Pre-PR validation gate (click to expand)
# Question Answer
a Deterministic repro? Yes. STRICT SQLite table t(s TEXT, n INTEGER, f REAL), SELECT s FROM sqlite(...) WHERE s = CAST('7', 'Enum8(\'7\' = 3)'): master returns no rows and pushes `s` = 3, local data returns 7. No randomness involved.
b Root cause explained? The analyzer pushdown writes an Enum constant as its number whatever the column is, while a string column is compared with an Enum by its name; and replaceConstantExpressions folds a constant tuple(...) (an IN list or row with Variant/Decimal elements) into one string. The pushed filter must select a superset of the local rows, so rows are lost or the remote rejects the query.
c Fix matches root cause? Yes. The constant is rewritten in the typed query tree, the only place that knows both types: IN gets the members of the local set, a comparison gets the name for a string operand and the value for a number. The tuple fold now keeps the structure. A conjunct whose Enum constant cannot be written this way (empty set, nested tuple key, Enum column, non-constant row) is kept local instead of being pushed with the number.
d Test intent preserved / new tests added? New test 05321_sqlite_pushdown_enum_constant (37 shapes incl. external_table_strict_query, rows and pushed SQL). Existing SQLite tests and TransformQueryForExternalDatabase gtests unchanged.
e Both directions demonstrated? Master: the test fails (114 lines differ, plus a SQLite row value misused error). Fix: passes, 100/100 repeated runs (50 randomized). Each of five mutants reddens its own lines.
f Fix is general across code paths? All pushable comparisons with the constant on either side, IN/NOT IN (scalar, list, rows), and every engine using this builder (SQLite, MySQL, PostgreSQL, ODBC/JDBC). The shard-facing literal is intentionally unchanged.
g Fix generalizes across inputs (params/datatypes/wrappers)? Plain, Nullable, Tuple, Variant, Dynamic (also max_types = 0) constants, also nested (Nullable/Variant/Dynamic of a tuple); String, FixedString, Nullable(String), Int64, Float64, Decimal, Bool operands and keys, one-element tuple keys, checked against SQLite, MySQL 8.0 and PostgreSQL 16; mixed lists; a tuple comparison keeps its non-Enum elements as they are.
h Backward compatible? (maintainer-approved exception only) Yes. No setting, format or default change; only the pushed filter text changes, toward the local result.
i Invariants and contracts preserved? The pushed filter stays a superset of the local one: a conjunct is either written in the local comparison's form or not pushed. Strict mode rejects a conjunct it cannot push, as for any other one. Only the cloned tree is rewritten, the local plan is not touched. The set is built with the same function and settings as the local set.

Session id: cron:clickhouse-impl-self-slot-57:20261004-072600

@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [fae62b6]

Summary: ✅


AI Review

Summary

This PR fixes the main Enum pushdown mismatch by rewriting analyzer-side constants into the same domain ClickHouse compares in, and by keeping the old AST path local when it cannot do that rewrite safely. The remaining blocker is that the new carrier-unwrapping helper still stops at LowCardinality, so LowCardinality(Enum) constants can still bypass both protections and reach the external database as the wrong literal.

Findings
  • ❌ Blockers
    • [src/Storages/transformQueryForExternalDatabaseAnalyzer.cpp:57] unwrapCarrier still unwraps only Nullable, Variant and Dynamic, so holdsEnumValue returns false for LowCardinality(Enum) and nested carriers such as Nullable(LowCardinality(Enum)) or Variant(LowCardinality(Enum), ...). That means renderEnumLeaves / renderInSet skip the rewrite, removeConjunctsHoldingEnumConstants does not keep the predicate local, and the shared old AST path in src/Storages/transformQueryForExternalDatabase.cpp:77 also misses it. A query like s = CAST('7', 'LowCardinality(Enum8(\'7\' = 3))') can therefore still be pushed as the enum’s numeric value (or rejected remotely, e.g. by PostgreSQL) instead of following ClickHouse comparison semantics.
    • Suggested fix: unwrap LowCardinality in the same helper before testing isEnum, including the recursive tuple path, or conservatively treat any surviving LowCardinality(Enum) carrier as non-pushable and keep that whole conjunct local. Add a focused case for LowCardinality(Enum) to 05321_sqlite_pushdown_enum_constant once fixed.
Final Verdict

❌ Changes requested.

LLVM Coverage Report

Measured on commit fae62b6.

Metric Baseline Current Δ
Lines 88.20% 88.20% +0.00%
Functions 92.10% 91.80% -0.30%
Branches 79.60% 79.60% +0.00%

Changed lines: Changed C/C++ lines covered: 159/171 (92.98%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-bugfix Pull request with bugfix, not backported by default label Oct 4, 2026
if (column->isNullAt(0))
return std::nullopt;

if (const auto * nullable_type = typeid_cast<const DataTypeNullable *>(type.get()))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This still misses LowCardinality(Enum) carriers. renderEnumLeaves / removeConjunctsHoldingEnumConstants only see what unwrapCarrier exposes, but unwrapCarrier stops before LowCardinality, while comparison semantics themselves strip it with removeLowCardinalityAndNullable. So s = CAST('7', 'LowCardinality(Enum8(\'7\' = 3))') still reaches the remote side as the enum's numeric value instead of '7', and text = integer remains possible in PostgreSQL.

Can we unwrap LowCardinality here as well (including the recursive tuple path), or at least treat it like the other unsupported cases and keep the whole conjunct local?

@clickhouse-gh clickhouse-gh Bot added the comp-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). label Oct 4, 2026
@clickhouse-gh

clickhouse-gh Bot commented Oct 4, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing fae62b658 with master b94acbe31 (stripped binary size, per-symbol sizes and ThinLTO time; object sizes against the warmup build of 37a251ffa; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

5 object files changed (+82.12 KiB total), 0 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Storages/transformQueryForExternalDatabaseAnalyzer.cpp.o 96.46 KiB 177.23 KiB +80.77 KiB (+83.73%)

719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

8 translation units recompiled, 14 s compile time in total, 8 of them have a recent master baseline.

Job report

…uments

Two fixes on top of the Enum constant pushdown:

- The visitor asked every two-argument comparison for its argument types,
  including the `key = value` arguments of a table function, where the key
  is an identifier. `SELECT * FROM mysql(named_collection, table = 't')`
  failed with "Method getResultType is not supported for IDENTIFIER query
  tree node" (the targeted MySQL/PostgreSQL integration tests). Comparisons
  with an untyped argument are now left alone.

- The pushdown from an analyzed AST (still used for the subquery of a
  `CHECK` constraint) turned an `Enum` constant into its name whatever the
  other operand was, so `CHECK n IN (SELECT n FROM <sqlite> WHERE n = E)`
  sent `"n" = '7'` for an integer column and rejected a valid INSERT. Such
  a constant is now left unfolded there, so its condition is evaluated
  locally (strict mode throws INCORRECT_QUERY, as on the query tree path).
  `holdsEnumValue` is shared between the two paths for this.

`LowCardinality(Enum)` needs no handling: the type cannot be created
(Code 43 for every spelling, with or without
`allow_suspicious_low_cardinality_types`).

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.

All good.

@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 2d576bf Oct 4, 2026
149 checks passed
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label Oct 4, 2026
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-foreign-db Connectivity to external databases (ODBC/JDBC, MySQL, PostgreSQL, etc.). groeneai-origin-follow-up PR origin: groeneai's own out-of-scope finding during its PR work 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.

3 participants