Repository navigation
Push Enum constants to external databases in the form ClickHouse compares them - #123843
Conversation
…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]>
Internal second-model review (3 rounds before publication)Fixed during review:
r3: no new findings. Noted, not blocking:
|
Pre-PR validation gate (click to expand)
Session id: cron:clickhouse-impl-self-slot-57:20261004-072600 |
|
Workflow [PR], commit [fae62b6] Summary: ✅
AI ReviewSummaryThis PR fixes the main Findings
Final Verdict❌ Changes requested. LLVM Coverage ReportMeasured on commit fae62b6.
Changed lines: Changed C/C++ lines covered: 159/171 (92.98%) · Uncovered code |
| if (column->isNullAt(0)) | ||
| return std::nullopt; | ||
|
|
||
| if (const auto * nullable_type = typeid_cast<const DataTypeNullable *>(type.get())) |
There was a problem hiding this comment.
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?
Build profile diff (arm_release)Comparing ✅ No significant changes. Binary sizes
The official master build is compiled with Object file sizes5 object files changed (+82.12 KiB total), 0 added.
719 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only Compile time of recompiled translation units8 translation units recompiled, 14 s compile time in total, 8 of them have a recent master baseline. |
…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]>
Changelog category (leave one):
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,SQLiteor ODBC/JDBC table compares a column (string, number orDecimal) with anEnumconstant (also inside a tuple, anINlist,Nullable,VariantorDynamic, 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, andPostgreSQLrejected such a query. AnINlist or row ofVariantorDecimalconstants 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 withoperator does not exist: text = integer. No open issue; found while validating #118988.Root cause: ClickHouse compares a string with an
Enumby its name and a number by its value, butgetASTForExternalDatabaseFromQueryTreewrites anEnumconstant as its number. The pushed filter must select a superset of the local rows, so rows are lost. AVariant(Enum)constant against a number is pushed as the name, andreplaceConstantExpressionsfolds a constanttuple(...)into one string (s IN ('(''7'',''x'')')).Change:
PrepareForExternalDatabaseVisitor: a constant holding anEnumvalue (plain, in aTuple, behindNullable/Variant/Dynamicat any level) becomes, forIN/NOT IN, the members of the set the local query builds; for a comparison, eachEnumleaf becomes its name against a string operand and its value against a number.Enumconstant after this (an empty set, a nested tuple key, anEnumcolumn, a non-constant row such as(s, n) < (E, n)) is not pushed down and is applied locally.replaceConstantExpressionskeeps a constanttuple(...)and folds its elements one by one. On the AST path (aCHECKconstraint subquery) it leaves anEnumconstant unfolded, so the condition stays local.A simpler alternative is to keep every predicate with an
Enumconstant 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 andTransformQueryForExternalDatabasegtests pass; checked by hand on MySQL 8.0 and PostgreSQL 16, incl.Decimalkeys.Workflow [PR]
Sync PR [sync-upstream/pr/123843]
Version info
26.10.1.1523-master(included in26.10and later)