Repository navigation
Introduce NumberLiteral Field type for precision-preserving numeric literals - #102646
Algunenano wants to merge 98 commits into
Conversation
When a numeric literal overflows Int64/UInt64 (e.g. 100000000000000000000000), store it as a `NumberLiteral` (unparsed string) instead of Float64 which loses precision. The actual parsing to a concrete type (UInt128/Int128/UInt256/Int256) is deferred to when the target type is known. This fixes silent precision loss in queries like: WHERE action_id BETWEEN 100000000000000000000000 AND 100000000000000000000500
- Add `writeText` overload for `NumberLiteral` in Field.cpp (fixes `fieldToString`) - Guard `convertNumberLiteralToType` with `if constexpr` for float vs int - Remove heavy IO includes from `FieldVisitorConvertToNumber.h`; throw instead of parsing (the real conversion is in `convertFieldToType`) - Add explicit `safeGet<NumberLiteral>` template instantiation - Revert unneeded protocol version bump (query is sent as SQL text, server re-parses)
Tests that integer literals exceeding UInt64 range are parsed as UInt128/Int128 instead of Float64, preserving precision for BETWEEN queries and arithmetic.
Extend `NumberLiteral` to also store decimal-point and exponent literals (3.14, 1e10) instead of eagerly parsing to Float64. The default type from `FieldToDataType` is still Float64 for backward compat, but the original text is preserved on `ConstantNode` so that `castNodeToType` can convert directly from string to the target type (e.g. Decimal) without Float64 precision loss. Changes: - Parser: `try_read_float` stores regular numbers as `NumberLiteral` (NaN/Inf stay as Float64) - `FieldToDataType`: returns Float64 for decimal-looking NumberLiterals, UInt128/Int128 for integers - `ConstantNode`: saves `number_literal_text` when constructed from a NumberLiteral field - `castNodeToType`: when source is a NumberLiteral constant, casts from string text directly - `SettingsFields`: handle NumberLiteral field in settings conversion
Store `NumberLiteral` as String in `ConstantNode` (no Float64 intermediate). In `resolveFunction`, before function resolution, replace `NumberLiteral` constants with properly typed values based on the other arguments: - If comparing with a Decimal column, parse text directly to Decimal - If comparing with a UInt128 column, parse text to UInt128 - If the value doesn't fit the reference type, use the intrinsic type - If no reference type, use `FieldToDataType` default (Float64/UInt128) This fixes precision loss in comparisons like `WHERE decimal_col = 3.14` where the literal was previously converted Float64 → Decimal, losing trailing digits.
Store ALL non-special float literals as NumberLiteral (not just integer overflow). Handle NumberLiteral comprehensively: - Field::resolveNumberLiteral: converts to Float64 (for decimal) or UInt128/Int128/etc (for big integers) - Field::safeGet<T>: auto-resolves NumberLiteral when accessed as a concrete numeric type — this is the systemic fix that handles all code paths (settings, index params, background tasks, etc.) - convertFieldToTypeImpl: resolves NumberLiteral before conversion - FieldToDataType: delegates to resolveNumberLiteral then infers type - getFieldFromIndexArgumentAST: resolves before returning - Analyzer resolveFunction: replaces NumberLiteral constants with properly typed constants based on context (Decimal, big int, etc.) - ConstantNode: saves number_literal_text for Analyzer deferred parsing - SettingsFields: handles NumberLiteral field type
When a NumberLiteral constant has no reference type (e.g. standalone SELECT 3.14), reference_type is null. Guard WhichDataType construction against null by using default_type as fallback.
When resolveNumberLiteral encounters a pure-integer string that doesn't fit in any wide integer type (e.g. a 309-digit number), fall back to Float64 via strtod instead of throwing. This preserves the old behavior for extremely large integer literals.
tryReadIntText silently wraps on overflow for wide integer types. Verify correctness by roundtrip: parse → writeText → compare with original digits. This correctly handles boundary values like UInt128 max+1, UInt256 max+1, and numbers too large for any integer type.
Add comprehensive test cases: - UInt64/Int64 boundary (max, max+1) - UInt128/Int128 boundary (max, max+1, min, min-1) - UInt256 boundary (max, max+1 → Float64) - Negative big integers - Numbers exceeding all integer types → Float64 fallback - Decimal precision via deferred parsing - Positive and negative value preservation - Int128 column comparisons with big literals Fix overflow detection: verify wide integer parsing via roundtrip (parse → writeText → compare) since tryReadIntText silently wraps.
- In resolveFunction, use resolveNumberLiteral (strtod) for non-Decimal targets, and String→Decimal direct conversion for Decimal targets. This fixes subnormal floats (4.9E-324) which strtod handles but readFloatText does not. - Update 02428_decimal_in_floating_point_literal reference: Decimal IN with float literals now uses exact string parsing, fixing false positives from Float64 precision loss. - Update 02124_comparison_betwwen_decimal_and_float reference: same improvement in Decimal vs literal comparison precision.
When DataTypeAggregateFunction parses parameters like meanZTest(1., 1., 0.95), the float literals are now NumberLiteral. Call resolveNumberLiteral before passing to the aggregate function factory which calls safeGet<Float64>.
When resolveFunction converts a NumberLiteral to a Decimal reference type, check if the literal has more decimal digits than the reference scale. If so, use Decimal256 with the literal's full scale to avoid truncation that causes false IN matches (e.g. 1.5551 truncated to 1.555). Restore original reference for 02428_decimal_in_floating_point_literal (behavior now matches master exactly). Update 02124_comparison_betwwen_decimal_and_float line 18: the query 0.1000000000000000055511151231257827021181583404541015625::Decimal256(70) = 0.1 now correctly returns 0 (the exact decimal 0.1 differs from the Float64 approximation). Previously both sides went through Float64 imprecision. Fix aggregate function parameters: resolve NumberLiteral in DataTypeAggregateFunction parameter extraction.
The shared helper parseAggregateFunctionParameters (used by arrayReduce, initializeAggregation, Graphite) extracts literal values from AST for aggregate function parameters. Call resolveNumberLiteral so float parameters like aggThrow(0.0001) work correctly.
|
Workflow [PR], commit [0239e91] Summary: ❌
AI ReviewSummaryThis PR introduces deferred Findings
💡 Nits
Final Verdict
|
Add NumberLiteral resolution in ActionsVisitor for the old analyzer path: - Before addFunction, check AST arguments for NumberLiteral fields - When a sibling argument has Decimal type, re-resolve the NumberLiteral as Decimal with proper scale (same logic as new analyzer) - Skip IN/NOT IN functions (second argument is a Set, not a scalar) - Resolve NumberLiteral in function parameter extraction - Also resolve in parseAggregateFunctionParameters shared helper Both old and new analyzers now produce identical results for Decimal precision tests.
FieldVisitorConvertToNumber, dictionary params, and workload settings - ConstantExpressionTemplate: resolve NumberLiteral to default type before setting data type (fixes 12 VALUES template failures) - SettingsFields: resolve NumberLiteral via resolveNumberLiteral (not stringToNumber) so scientific notation like 1e9 works for int settings - FieldVisitorConvertToNumber: resolve via strtod+Float64 path instead of throwing (fixes Buffer engine params like 1e6) - Dictionary layout params: resolve before type check - WorkloadSettings: resolve before safeGet<Float64> - Old analyzer ActionsVisitor: resolve for function parameters
dictionary params, Decimal scale, and update test references Core fixes: - ConstantExpressionTemplate: handle Number field type (12 VALUES failures) - SettingsFields: resolve via resolveNumberLiteral (13 settings failures) - FieldVisitorConvertToNumber: resolve via strtod (5 Buffer engine failures) - Dictionary layout params: resolve before type check - WorkloadSettings: resolve before safeGet - Restrict Decimal conversion to comparison functions only (equals, less, etc.) to avoid scale overflow in arithmetic (Decimal32(5) * 1.5) Test updates (use explicit types to preserve original test intent): - 01065_if_not_finite: toUInt64/toFloat64 for incompatible type test - 03667_accurate_cast_datetime_overflow: toFloat64 for overflow test - 01666_gcd_ubsan: toFloat64/toInt128 chain for Float64-approximated values Reference updates for expected behavioral changes: - 03456_wide_integer_cross_platform_consistency: Int128 precision - 03371_dynamic_values_parsing_templates: big numbers as UInt128 - 04098_number_literal_type: regenerated
…nction - Fix verifyRoundtrip in resolveNumberLiteral: compare the full signed string representation instead of negating the value (which overflows for Int128_min and Int256_min) - Resolve NumberLiteral in SimpleAggregateFunction parameter parsing for parity with AggregateFunction and parseAggregateFunctionParameters. No supported SimpleAggregateFunction currently takes float params, so this is a preventive fix. - Add regression tests for exact Int128_min and Int256_min literals
FieldVisitorConvertToNumber, dictionary params, Decimal scale, and update test references Core fixes: - ConstantExpressionTemplate: handle Number field type - SettingsFields: resolve via resolveNumberLiteral (handles 1e9 for int settings) - FieldVisitorConvertToNumber: resolve via strtod instead of throwing - Dictionary layout params: resolve before type check - WorkloadSettings: resolve before safeGet - Restrict Decimal conversion to comparison functions only, and skip scientific notation (e.g. 1e-2) since scale cannot be derived from exponent form - Old analyzer: implement deferred parsing in ActionsVisitor with same comparison-only restriction, skip IN functions Test updates (use explicit types to preserve original test intent): - 01065_if_not_finite: use toUInt64/toFloat64 for type mismatch test - 03667_accurate_cast_datetime_overflow: use toFloat64 for overflow test - 01666_gcd_ubsan, 01666_lcm_ubsan: use toFloat64/toInt128 chain Reference updates: - 02740_hashed_dictionary_load_factor_smoke: SHOW CREATE now preserves the original literal text (0.90 stays as 0.90 instead of being normalized to 0.9 through Float64 roundtrip) - 03456_wide_integer_cross_platform_consistency: Int128 precision - 03371_dynamic_values_parsing_templates: big numbers as UInt128 - 03978_alter_table_execute_expire_snapshots_parse: AST dump shows Number_ prefix instead of Float64_ - 04098_number_literal_type: added scientific notation Decimal test
Update docs/en/sql-reference/syntax.md to document the numeric literal parsing changes introduced in version 25.5. The docs now clearly separate pre-25.5 and post-25.5 behavior: - Wide integer literals (>UInt64) are now parsed as UInt128/Int128/ UInt256/Int256 natively, without requiring string-based conversion - Decimal-point literals use deferred type resolution for exact Decimal comparisons Each change is explicitly tagged with version numbers so readers on older versions understand which behavior applies to them.
dictionary params, Decimal scale, and update test references Core fixes: - ConstantExpressionTemplate: handle Number field type - SettingsFields: resolve via resolveNumberLiteral for both typed and custom settings (fixes custom_c showing Number_98.11 instead of Float64_98.11 in system.settings) - FieldVisitorConvertToNumber: resolve via strtod instead of throwing - Dictionary layout params: resolve before type check - WorkloadSettings: resolve before safeGet - Restrict Decimal conversion to comparison functions only, and skip scientific notation (e.g. 1e-2) since scale cannot be derived from exponent form - Old analyzer: implement deferred parsing in ActionsVisitor with same restrictions, skip IN functions Test updates (use explicit types to preserve original test intent): - 01065_if_not_finite: use toUInt64/toFloat64 for type mismatch test - 03667_accurate_cast_datetime_overflow: use toFloat64 for overflow test - 01666_gcd_ubsan, 01666_lcm_ubsan: use toFloat64/toInt128 chain - 00972_geohashesInBox: use toFloat64 for mixed Float32/Float64 test Reference updates for expected behavioral changes: - 02740_hashed_dictionary_load_factor_smoke: SHOW CREATE preserves original literal text (0.90 stays as 0.90, not normalized to 0.9) - 03456_wide_integer_cross_platform_consistency: Int128 precision - 03371_dynamic_values_parsing_templates: big numbers as UInt128 - 03978_alter_table_execute_expire_snapshots_parse: AST dump shows Number_ prefix - 03777_highlight_digit_groups_in_format: 123456e78 preserved as-is - 04098_number_literal_type: added scientific notation Decimal test
fix custom settings, fix geohashesInBox, fix highlight test - Extract NumberLiteral-to-typed-Field resolution into shared resolveNumberLiteral.h/cpp, used by both new and old analyzers. Eliminates duplicated logic for Decimal scale computation, type family matching, and fallback handling. - Guard against Decimal256 scale overflow for literals with >76 fractional digits (falls back to default Float64 resolution). - Fix SettingFieldCustom to resolve NumberLiteral on store, so system.settings shows Float64_98.11 not Number_98.11. - Fix 00972_geohashesInBox: use explicit toFloat64 for mixed-type test. - Fix 03777_highlight_digit_groups_in_format: 123456e78 preserved as-is.
A literal too wide for `Decimal256` now compares through `Float64` in every spelling; a wide integer kept `UInt256` and threw `DECIMAL_OVERFLOW`. In a comparison the literal keeps its own scale but takes the `Decimal` supertype precision instead of always 76, so it is no wider than needed and the rescale cannot overflow. The common-type check moves to each literal, so a mismatched key in a tuple compared with IN no longer drops the exact type of a `Decimal` position. Co-Authored-By: Claude Opus 5.5 <[email protected]>
# Conflicts: # src/Interpreters/executeQuery.cpp
When disabled, every `NumberLiteral` is resolved to the `Float64` the parser produced before, so the context typing does not apply. Tests changed by the literal typing now run the old query with the setting disabled, followed by the new or adjusted query. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
📊 Cloud Performance Report ✅ AI verdict: no significant changes detected. K_source=6 K_base=30 flagged=0/65 clickbench🟢 No significant changes tpch_adapted_1_official🟢 No significant changes Debug info
|
…syntax docs Co-Authored-By: Claude Opus 5.5 <[email protected]>
yakov-olkhovskiy
left a comment
There was a problem hiding this comment.
Analyzed by Cursor Agent:
I tested the build_amd_release binary of b557d7ac against the master build of the merge base 252b266b. The later commits only add the enable_context_typed_number_literals gate, which is on by default, so the default behavior is the same as the current head 5509b004.
❌ Blockers
1. Existing table definitions change meaning on upgrade
The description says the old-analyzer path (ActionsVisitor) is "still used by mutations, TTL and DEFAULT expressions" and keeps the previous Float64 semantics. That is not what happens:
DEFAULT/MATERIALIZEDvalues are computed atINSERT(and at read time for columns missing from a part) bycreateExpressionsAnalyzerinsrc/Interpreters/inplaceBlockConversions.cpp, which runsQueryAnalyzer.- Mutations (
ALTER UPDATE,MATERIALIZE COLUMN) also produce the new results.
So stored expressions of existing tables pick up the new Decimal semantics after a routine upgrade with default settings.
How I reproduced it: I created the tables with master and inserted a row, then opened the same data directory with the PR build.
-- created with master
CREATE TABLE d.t (price Decimal64(2), r Float64 DEFAULT price / 3.0, a Float64 ALIAS price / 3.0) ENGINE = MergeTree ORDER BY tuple();
CREATE TABLE d.t32 (p Decimal32(5), r Float64 MATERIALIZED p / 1.5) ENGINE = MergeTree ORDER BY tuple();
INSERT INTO d.t (price) VALUES (1);
INSERT INTO d.t32 (p) VALUES (1);
-- then, with the PR binary on the same data directory
INSERT INTO d.t (price) VALUES (1);
SELECT price, r, a FROM d.t ORDER BY r;
INSERT INTO d.t32 (p) VALUES (1);| Case | master | PR, after upgrade |
|---|---|---|
r Float64 DEFAULT price / 3.0 |
0.3333333333333333 |
new rows get 0.33; old rows keep 0.3333… in the same column |
a Float64 ALIAS price / 3.0 |
0.3333333333333333 |
0.33, for old rows too |
r Float64 MATERIALIZED p / 1.5, p Decimal32(5) |
INSERT works |
every INSERT fails with DECIMAL_OVERFLOW |
z Float64 DEFAULT price / 0.0 |
inf |
INSERT fails with ILLEGAL_DIVISION |
ALTER UPDATE u = price / 3.0, MATERIALIZE COLUMN m (m DEFAULT price / 3.0) |
0.333… |
0.33 |
So one column ends up holding values computed two different ways, the results of ALIAS columns change for data already stored, and INSERTs into existing tables can start failing after the upgrade. Materialized views and row policies take the same path; I did not test them.
Possible fixes:
- Record the literal semantics when an object is created and use them when it is loaded (resolve its literals as
Float64for objects created before 26.10). - Or, as the description already promises, do not apply the non-comparison retargeting to stored table expressions (
DEFAULT/MATERIALIZED/ALIAS, mutations, TTL).
Either way, please add a regression test for these expressions.
2. Primary key and skip index pruning stops working for expressions with a decimal literal next to a Decimal column
KeyDescription and IndicesDescription still build their expressions through TreeRewriter/ExpressionAnalyzer, where the literal stays Float64. The query goes through the analyzer, where the same literal becomes a Decimal. The two expressions no longer match, so the index is skipped. This also happens on freshly created tables, not only after an upgrade.
CREATE TABLE t (price Decimal64(2)) ENGINE = MergeTree ORDER BY toInt64(price * 100.0) SETTINGS index_granularity = 2;
INSERT INTO t SELECT number FROM numbers(20);
EXPLAIN indexes = 1 SELECT count() FROM t WHERE toInt64(price * 100.0) = 500;
-- master: Condition: (toInt64(multiply(price, 100.)) in [500, 500]), Granules: 1/10
-- PR: Condition: true, Granules: 10/10The same happens with a skip index such as INDEX idx price / 3.0 TYPE minmax GRANULARITY 1: master uses it for WHERE price / 3.0 > 5, but on the PR it is missing from EXPLAIN indexes = 1.
It does not happen for the Float32 narrowing (ORDER BY toInt64(f * 0.5)) or for wide-integer key expressions; both still prune. Partition-key minmax pruning and projection matching probably have the same problem, but I did not verify them.
The result is a silent switch to full scans on tables whose key or index expression contains such a literal. The key and index description paths should type literals the same way the query does. Please add a test with EXPLAIN indexes = 1.
⚠️ Majors
3. Division by a literal next to a Decimal now loses precision
Decimal division keeps the scale of the dividend. Writing / 7.0 instead of / 7 is a common way to force floating-point division, and it now truncates:
SELECT toDecimal64(1, 2) / 3.0; -- master: 0.3333333333333333 (Float64); PR: 0.33 (Decimal(18, 2))
SELECT sum(toDecimal64(number, 2)) / 7.0 FROM numbers(3); -- master: 0.42857142857142855; PR: 0.42
SELECT toDecimal64(1, 2) / 0.0; -- master: inf; PR: ILLEGAL_DIVISION
SELECT toDecimal32(1, 5) / 1.5; -- master: 0.6666666666666666; PR: DECIMAL_OVERFLOWThis goes against the "precision-preserving" promise in the title. 05243_number_literal_sibling_family_arithmetic pins these results as intended. I'd suggest excluding divide (and probably intDiv/modulo) from the non-comparison retargeting. If the current behavior stays, the changelog entry should state the truncation and the new exceptions explicitly. Right now it only mentions "overflow errors".
4. The description and docs contradict the code in places
- The
ActionsVisitorclaim about mutations andDEFAULTexpressions (see Blocker 1). - "Overflowing binary (
0b) literals stayFloat64": they are a syntax error on both master and this PR.syntax.mdxalready says this correctly. syntax.mdxsays "a literal used with non-Decimalarguments are stillFloat64". Butgreatest(toFloat32(x), 1.5)isFloat32(while1.1staysFloat64), as05242_number_literal_mixed_numeric_siblingsshows.- The changelog entry should also say that existing
DEFAULT/MATERIALIZED/ALIASexpressions, materialized views and mutations pick up the new semantics after an upgrade, and how to keep the old behavior: setenable_context_typed_number_literals = 0in the default profile, which also covers mutations because they use the default.
Thanks a lot for the reviews. About the issues:
It's not an issue, because it respects compatibility:
Agree, this is incorrect. I think it comes from the beginning of the PR, when analyzer wasn't still being used for mutations. Will fix.
Agree. If using compatibility it will keep working exactly as now, but when not using it then the index analysis and the query analysis disagree, because KeyDescription (primary/sorting/partition keys), IndicesDescription (skip indices) and TTLDescription still build their expressions with the old analyzer. I can either teach the old analyzer the new way of handling, or try migrating these modes to the new one. Both have issues (indices created with one meaning, changing to another one). Will have a look at both. In addition, there is a bug where
Agree, but also respects compatibility and it doesn't "lose precision", instead it changes the the where operations are done to decimal division, because both values are decimal. This is also how other databases work.
Good points. Will fix. |
The analyzer rebuilt the AST of table function arguments it does not analyze (`view`, `viewIfPermitted`, `viewExplain`) from the query tree, which wrote untyped number literals as `Float64` values. The table function then analyzed them with the previous typing: `view` returned different results than the same query, `viewIfPermitted` rejected its `ELSE` structure, and `SELECT * FROM (EXPLAIN ...)` showed a plan that differed from the executed one. Keep the original literal text for these arguments. Co-Authored-By: Claude Opus 5.5 <[email protected]>
Only a comparison with a `Decimal` argument now parses a number literal into a wide `Decimal`. In arithmetic the literal stays a `Float64`, as before. Keys, skip indices and projections are built by the old analyzer with `Float64` literals, so a `Decimal` literal in the query never matched them and they were not used; stored `DEFAULT`, `ALIAS` and `MATERIALIZED` expressions, materialized views and mutations of existing tables changed their results; and division by a literal truncated to the scale of the dividend or threw instead of returning `inf`. Restore the tests that pinned the `Decimal` arithmetic to their master versions and add tests for the stored expressions and index usage. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
@yakov-olkhovskiy After iterating and trying to find a good way to handle indices, projections, etc on table definitions I didn't see a simple way forward that doesn't involve a huge refactor or a major headache for everyone, so I've decided to limit the scope of this PR instead and keep the usage of NumberLiteral only for We can do that in the future if we need to, probably requiring MT settings, a deprecated old analyzer or some other ideas on how to handle compatibility. Points 1 and 3 from the issues and my responses no longer apply, since the behaviour is fully reverted back. I'm fixing the other findings, updating description and adding tests that verify the behaviour that works now and would have been broken by the changes if introduced. |
…_countmin_numeric_types The test covers `countmin` statistics on a `Float32` column compared with a `Float64` constant. Number literals are now typed by context also in an `EXPLAIN` subquery, so `1.5` next to a `Float32` column became `Float32` and the test no longer compared against a `Float64` value. Cast the literal to `Float64` explicitly to keep the original test case. Co-Authored-By: Claude Opus 5.5 <[email protected]>
…seQueryToJSON` Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
|
||
| /// Only a comparison is retargeted to `Decimal`. Arithmetic keeps `Float64`, so a stored expression | ||
| /// (`DEFAULT price / 3.0`) and a key built by the old analyzer compute the same value as before. | ||
| if (isDecimal(*ref) && is_comparison) |
There was a problem hiding this comment.
This still leaves table-definition expressions that are analyzed through the legacy ExpressionAnalyzer out of sync for comparison / IN expressions themselves.
KeyDescription, IndicesDescription, and projection key expressions are still built through TreeRewriter + ExpressionAnalyzer, so a definition like INDEX idx (price = 1.1) or ORDER BY (price IN (1.1, 2.2)) keeps the RHS on the old Float64 path there. The same predicate in a query now comes through this exact-Decimal retargeting branch, so the stored expression and the query expression no longer match even though 05341 now covers the arithmetic cases.
That means pruning / projection matching can still silently stop for tables whose stored expression itself is one of these exact-comparison forms. I think this either needs the same exact-literal handling on the DDL side before enabling comparisons here, or this branch needs to stay on the old Float64 semantics for expressions that must agree with old-analyzer table metadata.
|
🤖 Blocked by #125612. Projections, skip indices and keys don't follow the settings that change function results: projection data is computed with the settings of the session that inserts it, and a query uses a projection, skip index or key even when its session computes the expression differently.
This needs a global fix for all such settings, not a special case (a new file in the part) for this one, so this PR waits for it. |
|
Closing for now to reduce noise |
Numeric literals that overflow
Int64/UInt64(e.g.100000000000000000000000) were silently parsed asFloat64, losing precision. Decimal-point literals like3.14also went throughFloat64, preventing exact comparisons withDecimalcolumns.The
NumberLiteralFieldtype from #121554 stores the original text of such a literal. This PR makes the parser produce it and defers parsing to a concrete type until the context is known. The spelling of a literal decides its value; the arguments it is used with decide its type:Int64/UInt64resolves to the smallest fitting wide integer (UInt128/Int128/UInt256/Int256), falling back toFloat64only beyondInt256/UInt256. Overflowing hexadecimal (0x) literals stayFloat64for compatibility; overflowing binary (0b) literals are a syntax error, as before.Decimalargument, the literal is parsed from its text into a wideDecimal, so the comparison is exact. This covers=,<and friends,INsets, and literals nested in tuples, arrays and maps.Decimalargument, such as arithmetic, the literal stays aFloat64, as before:price * 1.1withprice Decimal64(2)is still aFloat64,toDecimal64(1, 2) / 3.0is still0.3333333333333333, and/ 0.0is stillinf. So the expressions stored in tables (DEFAULT,MATERIALIZEDandALIAScolumns, keys, skip indices, projections, TTL, mutations and materialized views) compute the same values as before. Keys, skip indices and projections are built by the old analyzer, which also types these literals asFloat64, so they keep matching the same expression in a query.Float64, including an integer literal too large forUInt64(toFloat64(x) + 100000000000000000000000keeps working), and so is such an integer next to aDecimal. Next toFloat32arguments a literal that is exact inFloat32is aFloat32(greatest(toFloat32(x), 1.5)isFloat32, while1.1staysFloat64). Next to integer arguments an integer literal takes their type when it fits.NumberLiteral::toFloat64(readFloatTextPrecise, deterministic and locale-independent;strtodonly for hex floats).The Analyzer's
resolveFunctionre-typesNumberLiteralconstants from the sibling arguments before function resolution. Table functions that analyze their own arguments (view,viewIfPermitted, andviewExplainbehindSELECT * FROM (EXPLAIN ...)) receive the literal text, so they type literals the same way as the query. Paths that take a literal as a plain value (settings, aggregate function parameters, index and codec arguments, dictionary layout parameters,SYSTEM INSTRUMENT) callField::resolveNumberLiteral, andconvertFieldToTypedoes the same for anything else.A wide integer that ends up as a setting or config value is now written without quotes (
FieldVisitorToSettingValueString): a setting value is not a SQL literal, and the quoted form re-parsed as aString.The
clickhouse_jsondialect carries the literal text verbatim and only accepts text thatParserNumberreads as one deferred literal.A literal that takes a wide integer type inherits the limits of that type, exactly as an explicit constant would:
100000000000000000000000 OR 0fails liketoUInt128(1) OR 0. Fixing those limits belongs to the types themselves, not to the literals.In existing tables, a comparison with a
Decimalcolumn in a stored expression (a materialized viewWHERE, aDEFAULT price > 0.1) becomes exact after the upgrade, so its result changes only whereFloat64used to round. A key or skip index built on such a comparison is not used by queries, as before.The new behavior is controlled by the setting
enable_context_typed_number_literals, enabled by default. Disabling it (orcompatibilitybelow 26.10) resolves every literal that is not a plainInt64/UInt64toFloat64, as before. It applies to the queries of the session (SELECT,INSERTincluding theDEFAULTandMATERIALIZEDexpressions it computes,EXPLAIN), to stored views and other definitions when the session reads them, to theValuesinput format, and toformatQuery,parseQueryToJSONandclickhouse-format. It does not cover:SHOW CREATEshows0.90, not0.9, and a view keeps the column types it was created with.CASTof a literal in brackets or in hexadecimal is decided in the parser, soCAST((0.10000000000000000000001) AS Decimal256(76))keeps every digit either way.UInt64is a wide integer either way.Closes: #74312
Related: #121554
Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Numeric literals are now typed by the context they are used in instead of by their spelling. A decimal integer literal that doesn't fit
Int64/UInt64becomes a big integer (UInt128/Int128/UInt256/Int256) instead ofFloat64, or aFloat64when used with floating-point orDecimalarguments. A literal compared with aDecimalcolumn is parsed exactly from its text, sodecimal_col = 1.123456789012345678anddecimal_col IN (...)compare exactly instead of throughFloat64, and an equality likedecimal_col = 1.1can now use a primary key on that column. Arithmetic with aDecimalcolumn still treats the literal as aFloat64. This may change result types and results of queries that relied onFloat64behavior for numeric literals. The behavior is controlled by the new settingenable_context_typed_number_literals(enabled by default); disable it to restore the previousFloat64typing.Workflow [PR]
Sync PR [sync-upstream/pr/102646]