Repository navigation
Remove Field from constant-expression evaluation (table functions + column-native coercion) - #110945
Merged
Merged
Conversation
`evaluateConstantExpression` already builds a size-1 `ColumnConst` internally,
then discards it by returning `(*result_column)[0]` as a `Field` — which both
allocates and collapses the exact SQL type through `Field`'s `NearestFieldType`
mapping (`UInt8`->`UInt64`, `Float32`->`Float64`, `DateTime64`->`Decimal`, ...).
Add `evaluateConstantExpressionAsColumn` (and `tryEvaluateConstantExpressionAsColumn`)
returning the value as `{ColumnPtr /*size 1*/, DataTypePtr}`, preserving the exact
type and avoiding the `Field`. The existing `Field`-returning functions become thin
shims over it, so behavior is unchanged for callers not yet migrated.
Migrate the plain `String` literal arguments of `prometheusQuery`/`prometheusQueryRange`
(`StoragePrometheusQuery`) and `timeSeriesSelector` (`StorageTimeSeriesSelector`) to the
new API, reading the value with `IColumn::getDataAt` instead of materializing a `Field`
and calling `safeGet<String>`.
This is the first step of reducing `DB::Field` usage; no behavior change.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…egation)
Introduce `convertColumnToTypeOrNull` / `tryConvertColumnToTypeOrNull` /
`convertColumnToTypeOrThrow`, the column-native counterpart of `convertFieldToType`:
convert a single value (row 0 of a size-1 column of type `from`) into type `to`,
returning a size-1 column of `to`, or a null `ColumnPtr{}` when the value is not
representable (the twin of a Null `Field`).
The goal is to coerce constants without materializing a `Field`. This first step
implements the facility by delegating to `convertFieldToType` (so behavior is exactly
preserved); `gtest_convert_column_to_type` pins the result against `convertFieldToType`
across numerics, float modes, Bool, Decimal, String<->number, Date/DateTime, Nullable,
LowCardinality, Array and Tuple. Column-native fast paths (numeric, ...) that actually
avoid the `Field` will replace the delegation incrementally in the same effort, guarded
by that test.
Part of the effort to remove `DB::Field`. No behavior change.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Contributor
|
Workflow [PR], commit [211a606] Summary: ✅
AI ReviewSummaryThis PR moves the reviewed constant-expression paths from Final VerdictStatus: ✅ Approve |
The style check rejects a bare catch(...) that swallows exceptions; use the project's `// Ok: ...` suppression idiom (as tryConvertFieldToType does), since this is an intentional try-pattern. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Addresses automated review on #110944: the exact-type column API narrowed the accepted argument types. The previous `Field`-based code read the value via `operator[]`, which flattens wrappers, so a non-NULL `Nullable(String)` / `LowCardinality(String)` constant passed the `Field::Types::String` check. Unwrap via `removeLowCardinalityAndNullable` before the String kind check to keep those accepted, and add an explicit `isNullAt` check so a NULL value is still rejected as before. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…(review fix) Addresses automated review on #110945: convertFieldToType returns a Null Field both for a legitimate NULL result (NULL input into a nullable-capable type) and for "not representable". The first version collapsed both into ColumnPtr{}, so `NULL :: Nullable(Int32) -> Nullable(Int64)` could not be represented, and convertColumnToTypeOrThrow diverged from convertFieldToTypeOrThrow (threw on a valid NULL, and threw the wrong exception for NULL -> non-nullable). Now a valid NULL result becomes a size-1 column holding NULL, while ColumnPtr{} means only "not representable". convertColumnToTypeOrThrow mirrors convertFieldToTypeOrThrow: TYPE_MISMATCH for NULL into a non-nullable target, ARGUMENT_OUT_OF_BOUND for a non-NULL value that does not fit. Extends the differential test with the nullable/NULL cases. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Add the first Field-free fast path: plain numeric-to-numeric in the default mode now converts via castColumnAccurateOrNull instead of materializing a Field. It uses the same accurate numeric conversion (accurate::convertNumeric, strict) as convertFieldToType's default path, so out-of-range / inexact-narrowing still yield 'not representable'. Excluded (still delegate to convertFieldToType): strict / convert_inexact_floats modes, Bool (clamp semantics), and anything non-native-numeric (Decimal/Date/Enum/String/wrappers/composite). The API now takes 'from'/'to' as DataTypePtr (needed for castColumn; no external callers yet). The differential test against convertFieldToType (numeric widening/ narrowing/overflow, float modes, ...) stays green, pinning equivalence. Part of removing DB::Field. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…nvert-column-to-type
Migrate the numeric argument evaluation of the numbers, primes and generateSeries table functions off Field end-to-end: evaluateConstantExpressionAsColumn + convertColumnToTypeOrNull + IColumn::getUInt/getInt, instead of evaluateConstantExpression + convertFieldToType + Field::safeGet. The happy path no longer materializes a Field (a Field is only built on the error path, to format the offending value). Also make convertColumnToTypeOrNull robust to ColumnConst input (what evaluateConstantExpressionAsColumn returns) by operating on the full column, and cover ColumnConst input in the differential test. Part of removing DB::Field. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
1 task
Belt-and-suspenders for the automated review on #110945: even though callers already unwrap the input before the numeric fast path (so castColumnAccurateOrNull gets a full column and returns a non-const result), unwrap the cast result too, so the assert_cast<ColumnNullable> is locally correct regardless of the argument's constness (ExecutableFunctionCast wraps const results). The ColumnConst regression test already covers this input shape. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate LIMIT/OFFSET/LIMIT BY value evaluation off Field on both the analyzer and the legacy paths: - Planner::getLimitOffsetValue now takes the ConstantNode and reads its column (getColumn) + convertColumnToTypeOrNull, instead of ConstantNode::getValue() (a Field) + convertFieldToType. - InterpreterSelectQuery::getLimitOffsetValue uses evaluateConstantExpressionAsColumn + convertColumnToTypeOrNull + IColumn typed getters. - QueryAnalyzer::convertLimitOffsetExpression converts the constant column-natively and rebuilds the ConstantNode from the resulting column (via ConstantValue), avoiding both the getValue() Field and the ConstantNode(Field) re-conversion. The UInt64 -> Int64 -> Float64 order and the negative/fractional-limit handling are unchanged; a Field is only materialized on the error path (to format the bad value). Smoke-tested LIMIT/OFFSET/LIMIT BY, positive/negative/fractional, analyzer + legacy. Part of removing DB::Field. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Migrate the remaining LIMIT/OFFSET ConstantNode reads off Field: - PlannerJoinTree: the 'is the limit/offset a non-negative UInt64' checks used for limit pushdown now read the ConstantNode's column (getColumn) + convertColumnToTypeOrNull instead of getValue() + convertFieldToType, and take the value from the converted column. - OptimizeTrivialGroupByLimitPass::tryGetNonNegativeUInt64 now takes the ConstantNode and converts column-natively. Same non-negative-UInt64 semantics (negative/fractional -> skip optimization); no Field on the happy path. Smoke-tested limit pushdown and the group-by-limit optimization. Part of removing DB::Field. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review flagged that the `Field`-returning `evaluateConstantExpression` can return nested `Field` tags collapsed (e.g. `Bool` elements of a literal `array(...)` / `tuple(...)` come back as `UInt64`), because the value is produced as a size-1 column and read back with `operator[]`, which re-canonicalizes tags through the column implementation. This is not a user-reachable bug: strict `Bool` consumers read via `evaluateConstantExpressionAsLiteral` (which returns literal nodes verbatim, bypassing this path) or via `Array(Variant)` (which is per-element type-aware), and tolerant consumers pass the value through `convertFieldToType`. It is inherent to the `Field` representation and is one of the reasons `Field` is being removed. Rather than add a backward-compatibility path that materializes a `Field` for literals (which would move against removing `Field`), the behavior is left as is and pinned by a gtest, alongside a test showing the column API (`evaluateConstantExpressionAsColumn`) keeps the exact SQL type (`Array(Bool)`) - the type-faithful replacement callers should migrate to. Part of removing DB::Field. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review noted that `convertColumnToTypeOrNull` is documented as a generic column twin of `convertFieldToType`, but the delegation path is not faithful for every type: it does `IColumn::get(0, field)` to reconstruct a `Field`, and `get` canonicalizes tags. For a `DataTypeBool` source (backed by `ColumnUInt8`) the reconstructed `Field` is `UInt64`, so `Bool -> String` yields `'1'`/`'0'` instead of `convertFieldToType`'s `'true'`/`'false'` (same for nested `Array(Bool)` / `Tuple(Bool)`). This does not affect any current caller: they all convert to numeric types, and a `Bool`-source into a numeric `to` is value-preserving (verified by the differential test). Rather than reintroduce a `Field` into the API (against the goal of removing `Field`) or enumerate every tag-sensitive type in the fallback, narrow the documented contract to the faithful scope and record the `Bool`-to-textual gap explicitly in `convertColumnToType.h`. The gap disappears as the `convertFieldToType` delegation is replaced by column-native paths. Adjust `gtest_convert_column_to_type` to cover `Bool`-source into numeric targets (faithful) and document why `Bool -> String` is not asserted. Part of removing DB::Field. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ression
Phase B reimplemented `evaluateConstantExpression` on top of a size-1 column. For a
literal node the `Field`-returning API then produced its `Field` by reading the value
back with `operator[]`, which canonicalizes nested/scalar `Field` tags through the
column implementation (`Bool` -> `UInt64`, since a `DataTypeBool` column is a plain
`ColumnUInt8`). Callers that still convert the returned `Field` observed a real change:
`values('x String', true)` returned `'1'` instead of `'true'` (verified). This is a
user-facing regression introduced within this effort.
Restore the pre-Phase-B behavior: the `Field`-returning entry points take a
tag-preserving fast path for literal nodes (return `convertFieldToType(literal->value,
type)` directly) instead of round-tripping through the column. The non-literal path is
unchanged - it still returns `(*result_column)[0]`, so its long-standing behavior (a
computed `Array(Bool)` yields `UInt64` elements) is preserved.
This fast path re-adds a `Field` materialization, which is a temporary compatibility
bridge, not the end state: it is removed together with the `Field`-returning
`evaluateConstantExpression` once its callers migrate to the column API (tracked as
bridge B1 in the project notes). The `array(...)` / `tuple(...)` literal case is
unaffected here because the analyzer wraps those as `_CAST(...)` (a non-literal), which
behaves as on master.
Covered by a stateless test (`values(...)` with `Bool` into `String`/`Nullable(String)`,
plus a numeric sanity case) and a gtest asserting the `Field` API preserves nested `Bool`
tags for literal `array`/`tuple`, while the column API keeps the exact `Array(Bool)` type.
Part of removing DB::Field.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
…ppers
`prometheusQuery` / `timeSeriesSelector` read their String arguments via
`evaluateConstantExpressionAsColumn` (no `Field`). A review noted the compatibility
contract - accept a non-NULL `Nullable(String)` / `LowCardinality(String)` constant
(the previous `Field`-based code unwrapped these), still reject `NULL` - was only
asserted by a comment. Add a stateless test on both public entry points covering
`CAST('ts', 'Nullable(String)')`, `toLowCardinality('ts')`, a `Nullable(String)`
promql/selector, and `CAST(NULL, 'Nullable(String)')` (rejected with `BAD_ARGUMENTS`).
Part of removing DB::Field.
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The literal fast path (bridge B1) only preserved `Field` tags when the original node was already an
`ASTLiteral`. But `evaluateConstantExpressionAsColumnImpl` has a second literal site: the non-analyzer
path where `TreeRewriter::analyze` folds a non-literal into an `ASTLiteral` (e.g. a SQL UDF returning a
literal). That site still went through `getColumnAndDataTypeFromLiteral` + `materializeToField`, so the
legacy `Field` API re-canonicalized `Bool` back to `UInt64` and `values('x String', udf_returning_true())`
returned `'1'` instead of `'true'`.
Handle both literal sites with one mechanism: a `from_literal` helper plus a `literal_out` out-param.
When the `Field`-returning API is calling, a literal (original or rewrite-folded) is returned through
`literal_out` as its tag-preserving `Field` and no column is built; when the column API is calling, the
size-1 column is built as before. This also removes the earlier duplicated literal short-circuit in the
entry points.
Verified the fix is load-bearing (temporarily gating it off makes the cases return `'1'`). Extended the
regression test with a SQL UDF folded to a `Bool` literal, checked with `enable_analyzer` = 1 and 0.
Part of removing DB::Field. Transitional bridge B1 (removed with the `Field` API).
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The rewrite-to-literal case in this test creates a SQL UDF (a global object). The CI flaky check runs
the changed test many times concurrently against one server, so a fixed function name collided
(`DROP`/`CREATE` racing) and every run failed. Mark the test `no-parallel` so its copies run serially;
the function name stays unique in time. Only the tag changed - the reference is unaffected because the
tag line precedes `-- { echo }`.
CI: #110945
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
A review noted the code/test comments referenced `.cursor/projects/valueref-pilot/BRIDGES.md` and a `bridge B1` label, but that ledger file is intentionally git-excluded (local project notes), so the reference was dead in-tree and the removal condition undocumented for readers of the branch. Rewrite the comments to be self-contained: describe the shim and its removal condition inline (delete together with the `Field`-returning `evaluateConstantExpression` once callers move to `evaluateConstantExpressionAsColumn`), and cross-reference the sibling function instead of an external path. No behavior change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Contributor
LLVM Coverage Report
Changed lines: Changed C/C++ lines covered: 353/373 (94.64%) · Uncovered code |
yakov-olkhovskiy
marked this pull request as ready for review
July 25, 2026 08:01
KochetovNicolai
approved these changes
Jul 27, 2026
scanhex12
pushed a commit
to scanhex12/ClickHouse
that referenced
this pull request
Jul 29, 2026
…(review fix) Addresses automated review on ClickHouse#110945: convertFieldToType returns a Null Field both for a legitimate NULL result (NULL input into a nullable-capable type) and for "not representable". The first version collapsed both into ColumnPtr{}, so `NULL :: Nullable(Int32) -> Nullable(Int64)` could not be represented, and convertColumnToTypeOrThrow diverged from convertFieldToTypeOrThrow (threw on a valid NULL, and threw the wrong exception for NULL -> non-nullable). Now a valid NULL result becomes a size-1 column holding NULL, while ColumnPtr{} means only "not representable". convertColumnToTypeOrThrow mirrors convertFieldToTypeOrThrow: TYPE_MISMATCH for NULL into a non-nullable target, ARGUMENT_OUT_OF_BOUND for a non-NULL value that does not fit. Extends the differential test with the nullable/NULL cases. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
scanhex12
pushed a commit
to scanhex12/ClickHouse
that referenced
this pull request
Jul 29, 2026
Belt-and-suspenders for the automated review on ClickHouse#110945: even though callers already unwrap the input before the numeric fast path (so castColumnAccurateOrNull gets a full column and returns a non-const result), unwrap the cast result too, so the assert_cast<ColumnNullable> is locally correct regardless of the argument's constness (ExecutableFunctionCast wraps const results). The ColumnConst regression test already covers this input shape. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
scanhex12
pushed a commit
to scanhex12/ClickHouse
that referenced
this pull request
Jul 29, 2026
The rewrite-to-literal case in this test creates a SQL UDF (a global object). The CI flaky check runs
the changed test many times concurrently against one server, so a fixed function name collided
(`DROP`/`CREATE` racing) and every run failed. Mark the test `no-parallel` so its copies run serially;
the function name stays unique in time. Only the tag changed - the reference is unaffected because the
tag line precedes `-- { echo }`.
CI: ClickHouse#110945
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Part of a larger effort to eliminate
DB::FieldOngoing effort to remove
DB::Fieldfrom the ClickHouse server, replacing it with type-consistent, copy-free representations.Field's type tags don't map to ClickHouse SQL types (NearestFieldTypecollapsesUInt8→UInt64,Float32→Float64,DateTime64→Decimal, ...), and it forces copies of data that already lives in columns.This PR takes one self-contained flow — constant-expression evaluation for numeric table-function arguments — all the way from
Fieldto column-native, and provides the two reusable pieces the rest of the effort needs.What's here
1. Producer — evaluate a constant as a column (
evaluateConstantExpression.{h,cpp})evaluateConstantExpressionalready builds a size-1ColumnConstinternally, then discards it via(*result_column)[0]as aField(which also collapses the exact type). NewevaluateConstantExpressionAsColumn/tryEvaluateConstantExpressionAsColumnreturn{ColumnPtr /*size 1*/, DataTypePtr}instead; theField-returning functions become thin shims, so un-migrated callers are unaffected.2. Coercion — column-native
convertFieldToType(convertColumnToType.{h,cpp})convertColumnToTypeOrNull/try…/…OrThrowconvert a single value (row 0 of a size-1 column) into a target type, returning a size-1 column (orColumnPtr{}when not representable; a valid NULL result is a column holding NULL). Plain numeric→numeric in the default mode is done column-natively viacastColumnAccurateOrNull(sameaccurate::convertNumericasconvertFieldToType); other cases delegate toconvertFieldToTypefor now. Pinned by a differential test (gtest_convert_column_to_type) againstconvertFieldToTypeacross numerics/float-modes/Bool/Decimal/String↔number/Date/Nullable/LowCardinality/Array/Tuple/ColumnConst, incl. the NULL-vs-not-representable distinction.3. Actual
Fieldremoval — table functionsnumbers,primes,generateSeriesargument evaluation, and theStringarguments ofprometheusQuery/prometheusQueryRange/timeSeriesSelector, now read their constant as a column and coerce column-natively instead of materializing aFieldand callingsafeGet. The happy path no longer builds aField(aFieldis only formatted on the error path).No user-facing behavior change (smoke-tested:
numbers/primes/generate_seriesresults and error messages preserved;Nullable/LowCardinalitystring args and NULL handling preserved).Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Internal refactor to reduce
DB::Fieldusage in constant-expression evaluation. No user-facing change.Documentation entry for user-facing changes
🤖 Generated with Claude Code
Version info
26.8.1.210(included in26.8and later)