Repository navigation
Conversation
The `TTL` of a table is evaluated by background merges, which do not have the session, so with `session_timezone` set a `DateTime` string literal in it, as in `TTL event + INTERVAL 1 DAY DELETE WHERE event = '2020-01-01 00:00:00'`, was read in the server time zone, and the rule deleted other rows than it named, both after `CREATE TABLE` and after `ALTER TABLE ... MODIFY TTL`. Wrap such literals with `toDateTime(..., '<session time zone>')` in the stored definition, as `InterpreterAlterQuery` already does for the predicates of mutations, with a new overload of `rewriteDateTimeLiteralsWithTimezone` that rewrites one expression in place. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Workflow [PR], commit [a6cf089] Summary: ❌
AI ReviewSummaryThe PR preserves Consumers checked include The Fast test report confirms all 16 added regression tests and the existing datetime-literal mutation test passed. Validation used the PR's CI reports; no local tests were run. All review threads are resolved. Final VerdictStatus: ✅ Approve |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| Object file | Master | PR | Δ |
|---|---|---|---|
src/CMakeFiles/dbms.dir/Interpreters/MutationsDateTimeLiteralVisitor.cpp.o |
95.21 KiB | 353.75 KiB | +258.55 KiB (+271.56%) |
716 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
860 translation units recompiled, 5414 s compile time in total, 860 of them have a recent master baseline.
… at its place in the `ALTER`
The rewrite of the `TTL` in `CREATE TABLE` ran after
`getTablePropertiesAndNormalizeCreateQuery` had copied the storage
definition of the source table, so `CREATE TABLE ... AS` rewrote an
inherited `TTL` with the session time zone of the copy, which then deleted
other rows than in the source. `CLONE AS` was exempt as a whole, so a `TTL`
that the clone gave itself kept its raw literal. Now only a `TTL` that the
query gives itself is rewritten, also for `CLONE AS`, recorded before the
definition of the source is copied.
`MODIFY TTL` looked up the types of the columns in the schema from before
the statement, so `MODIFY COLUMN event DateTime('UTC'), MODIFY TTL ...`
wrapped a literal of the now `UTC` column with the session time zone, and a
preceding `ADD COLUMN` or `RENAME COLUMN` made the lookup miss. Now the
preceding column commands of the statement are applied to a copy of the
metadata as the statement is parsed, and each `MODIFY TTL` is rewritten
against the columns at its place.
Found by the AI review of the PR.
Related: ClickHouse#123959
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…TER`, and rewrite its `GROUP BY ... SET` too `parseAlterCommandSegments` applied the preceding column commands of the statement to a copy of the metadata with `AlterCommand::apply`, before `AlterCommands::validate` checks them. An `ADD COLUMN x DEFAULT 0` without a type then built a column with a null type, and `ColumnsDescription::addSubcolumns` dereferenced it: the server crashed on a statement that is rejected with `BAD_ARGUMENTS`. Now only the names and types of the columns are tracked, in a copy of `ColumnsDescription`, for `ADD COLUMN` and `MODIFY COLUMN` with a type, `RENAME COLUMN` and `DROP COLUMN`, and everything else is left to the validation. The rewrite of a `TTL` visited only the children of its elements, so the assignments of `TTL ... GROUP BY ... SET`, which are stored apart, kept a raw literal, as in `SET value = sumIf(value, event = '2020-01-01 00:00:00')`. Now they are rewritten too, for `CREATE TABLE` and `MODIFY TTL`. Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…a `Replicated` database A `Replicated` database does not support `CREATE ... CLONE AS`, so the case failed the `DBReplicated` stateless job with `SUPPORT_IS_DISABLED`. It is now `05480_ttl_datetime_literal_session_timezone_clone_as` with the `no-replicated-database` tag, as the other `CLONE AS` tests, and the rest of `05459` keeps running in a `Replicated` database. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
In a `Replicated` database, and for `ON CLUSTER` with the default `distributed_ddl_entry_format_version`, the initiator normalizes the query, which copies the `TTL` of the source of `CREATE TABLE ... AS` into it, and the query runs again from the DDL log. There the copied `TTL` looked like the query's own and was rewritten with the session time zone, so the copy deleted other rows than the source, as `05459_ttl_datetime_literal_session_timezone` shows in a `Replicated` database. The initiator already rewrote the query's own `TTL` before sending it, so a DDL worker (`isDDLOrOnClusterInternal`) does not rewrite it again, as `getColumnsDescription` skips the transforms that the initiator applied. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nitiator, and keep a cleared column for `MODIFY TTL` The previous commit skips the rewrite on a DDL worker, as the initiator already rewrote the `TTL`. The `TTL` of a materialized view is in its inner engine (`create.targets`), not in `create.storage`, so the initiator did not rewrite it, and the worker creates the inner table by another `InterpreterCreateQuery` in its own context, which skipped it too: `CREATE MATERIALIZED VIEW ... ENGINE = MergeTree ... TTL ... AS SELECT ...` in a `Replicated` database or `ON CLUSTER` stored the raw literal. Now the initiator rewrites the `TTL` of the inner engine as well. `CLEAR COLUMN` is a `DROP_COLUMN` command with `clear` set, which keeps the column, but the copy of the columns that `MODIFY TTL` is rewritten against removed it, so `CLEAR COLUMN event, MODIFY TTL ...` kept a raw literal. Now the column is removed from the copy only when `AlterCommand::apply` removes it (`!clear && !partition`). Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…iteral rewrite
The rewrite of `DateTime` string literals took every identifier for a table
column, including a lambda parameter of the same name. With `session_timezone`
set, `TTL event + INTERVAL 1 SECOND DELETE WHERE arrayExists(event -> event =
'keep', tags)` became `event = toDateTime('keep', ...)`, and `CREATE TABLE`
and `MODIFY TTL` failed with `CANNOT_PARSE_DATETIME`. The mutations share the
rewrite, so `ALTER TABLE ... DELETE WHERE` with such a lambda failed the same
way. The visitor now visits the body of a lambda itself, with its parameters
shadowing the columns of the same names, and an element of a parameter, such
as `n.event` in `n -> n.event = '...'`, shadowing a column with that compound
name.
Found by the AI review of the PR.
Related: ClickHouse#123959
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… literal rewrite The previous commit kept every lambda parameter out of the rewrite of `DateTime` string literals, also one whose type is a `DateTime` without a time zone. `ALTER TABLE ... DELETE WHERE arrayExists(event -> event = '2020-01-01 00:00:00', arr)` with `arr Array(DateTime)` and `session_timezone` set then stored the string as written, and the background mutation deleted another row, as did such a `TTL ... DELETE WHERE`; before it, the parameter got the time zone because a column with its name was a `DateTime`. The visitor now visits the body of a lambda from the higher-order function it is an argument of, and gives each parameter the type of what it is bound to when that is a column, a subcolumn or a parameter of an enclosing lambda with a known type: the element of an array, the key and the value of a map (`mapFilter((k, v) -> ...)` and the other functions of a map), and the initial accumulator of `arrayFold`. A parameter of a `DateTime` type without a time zone gets the time zone whatever its name, as in `arrayExists(x -> x = '...', arr)`, an element of a `Tuple` parameter, such as `n.event`, gets the type of the element, and a parameter of another type keeps the string. The type of a parameter bound to an expression is not known, and the parameter is matched with the columns by its name, as before the previous commit. Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
… and similar functions The previous commit bound the parameters of a lambda to the arguments right after it. `arrayPartialSort`, `arrayPartialReverseSort`, `arrayTopK`, `arrayBottomK`, `mapPartialSort` and `mapPartialReverseSort` have a fixed limit or count there, so in `arrayPartialSort((x, y) -> y = 'keep', 1, arr, tags)` the parameter `y` got the element type of `arr`, a `DateTime`, instead of that of `tags`, and `CREATE TABLE` and `MODIFY TTL` with `session_timezone` set failed with `CANNOT_PARSE_DATETIME`. These functions now bind the parameters to the arguments after the fixed one, and the parameters of any function get types only when the arguments bound to them are one array for each parameter, or one map for a key and a value; otherwise their types are not known, and they are matched with the columns by their names. Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…umentTypes` in the literal rewrite The rewrite of `DateTime` string literals gave a lambda parameter its type from a hand-written copy of the binding rules of the higher-order functions, which missed an array of tuples unpacked into several parameters, as in `arrayExists((event, tag) -> event = '2020-01-01 00:00:00', arr)` over `Array(Tuple(DateTime, String))`, and the fixed argument of `arrayPackBitsToFixedString` and the other `arrayPackBit*` functions. The parameter got the type of the whole tuple, its comparison kept the raw string, and a mutation or a `TTL` with `session_timezone` deleted other rows than it named. The parameters now get the types that the function itself binds them to, by `getLambdaArgumentTypes` with the types of the other arguments, as the analyzer calls it: fixed arguments, unpacked tuples, maps and `arrayFold` come from the function. This needs the types of all the other arguments: when one of them is not known, such as the type of an expression, the parameters are matched with the columns by their names, as before this PR. The hand-written list of functions with a fixed argument is removed. An identifier that names an alias of the expression, such as `c` in `has([1, 2] AS c, 1) AND arrayExists(x -> x = 1, c)`, is not taken for the column with its name any more, as the analyzer resolves it to the aliased expression: its type is not known, so the function is not asked to bind the parameters with the column's type, which made such a valid mutation fail, and a string compared with it keeps its string. Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nder the locks of the `ALTER`
The `TTL` of `MODIFY TTL` was rewritten against a snapshot of the metadata
taken when the statement was parsed, before the DDL guard and the alter lock.
A concurrent `ALTER` that changed a column from `DateTime` to
`DateTime('UTC')` could commit in between, and the literal stayed pinned to
the session time zone while the column had its own.
The rewrite now runs in `runCommandSegments`, after the locks of the commands
are taken and the metadata cache is cleared, against the metadata the commands
are then validated and applied to, with the preceding commands of the segment
applied to a copy of its columns as before. The commands of an earlier segment
of the statement are committed by then.
Found by the AI review of the PR.
Related: ClickHouse#123959
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… not in the internal `CREATE` of the inner table The inner tables of a `TimeSeries` table are created by an internal `InterpreterCreateQuery`, which took the `TTL` of the inner engine for its own and rewrote it, also when `CREATE TABLE ... AS` had copied it from a source `TimeSeries` table: the copy deleted other samples than the source. The definition of the `TimeSeries` table kept the raw literal for a `TTL` of its own, so it did not match its inner table, and in a `Replicated` database the `TTL` was not rewritten at all, as the internal query ran on a DDL worker. The query records which inner engines have a `TTL` of their own before the definition of the source is copied, and rewrites those in its own definition, against the columns of the inner table that the definition lists for a `TimeSeries` table, as it already did for the inner engine of a materialized view. An internal `CREATE`, of an inner table, of a restored table or of a system log, no longer rewrites a `TTL`. Found by the AI review of the PR. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eral rewrite The rewrite treated every identifier that names an alias as of unknown type, so `ALTER TABLE t DELETE WHERE isNotNull(identity(event) AS event) AND event = '2020-01-01 00:00:00'` kept the literal in the server time zone, and deleted another row than the same `SELECT` returned in the session. The aliases of the mutation now get their types from the analyzer, which resolves the predicate and the values of the assignments against the table, as `MutationsInterpreter` does: `identity(event) AS event` is a `DateTime`, so the literal gets the time zone of the session, and `[1, 2] AS c` is an array, so it does not, and the parameter of a lambda over `c` gets its element type. The analysis uses the settings of the query, as the validation of the mutation does, so it rejects only what the validation rejects. The mutation itself may run with other settings, such as a background mutation of `MergeTree`, which runs with those of the server, so an identifier may name an alias there and the column with its name here, or the other way round with `prefer_column_name_to_alias`. With that setting in the query, the analyzer gives the identifier the type of the column, so the aliases keep unknown types; otherwise, if there is a column with the name of the alias, the type is known only if the column has the same type, so a wrapped literal is valid whichever of the two the identifier names. A `TTL`, which does not allow aliases, is not analyzed. Aliases are also scoped as the analyzer scopes them. An alias inside a lambda or a subquery made every identifier with its name unknown, so in `arrayExists(x -> (x AS event) = 1, [1]) AND event = '...'` or `id IN (SELECT 3 AS event) AND event = '...'` the comparison with the column kept its string. Now an alias inside a subquery is not seen outside it, while the alias of the subquery itself, as in `(SELECT ...) AS s`, is, and gets the type of the scalar subquery; the alias of a lambda, which names a function, is not an alias of an expression; and an alias in the body of a lambda shadows the columns with its name only in the body, where its type stays unknown. Found by the AI review of the PR. PR: ClickHouse#127982 Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…the column with its name An alias with the name of a column got a type in the literal rewrite of a mutation only if the column had the same type, so `toNullable(event) AS event`, `assumeNotNull(n) AS n` of a `Nullable(DateTime)` column and `toDateTime64(event, 3) AS event` kept the bare string, which the background mutation read in the server time zone and deleted another row. The literal is now rewritten if both the alias and the column are a `DateTime` or `DateTime64` without a time zone: it is then compared as the session compares the string whichever of the two the identifier names with the settings the mutation runs with. A lambda parameter still gets its type from an alias only if the column has the same type. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…nalyze the aliases inside lambdas
A literal compared with an alias of a column of another precision was read with the highest precision, `DateTime64(9)`,
and cast to the type of the identifier. That narrowed the range to the year 2262, so `event = '2290-01-01 00:00:00.000'`
failed with `DECIMAL_OVERFLOW`, and it rounded an instant before 1970 toward zero instead of down, so with
`event = '1960-01-01 00:00:00.123456'` the mutation deleted another row than the session selects. Now the literal is read
in the time zone of the session with the precision of each of the two, and the one of the type that the identifier has
where the mutation runs is taken, `if(toTypeName(event) = 'DateTime64(3)', toDateTime64('...', 3, 'tz'), toDateTime64('...',
6, 'tz'))`, which reads it as the comparison of the string does.
An alias inside the body of a lambda had an unknown type, so a literal compared with it kept its string, which a background
mutation of `MergeTree` reads in the time zone of the server: `arrayExists(x -> isNotNull(identity(event) AS event) AND
event = '2020-01-01 00:00:00', [1])` deleted another row than the session selects. Now such an alias gets the type of its
expression against the table, as an alias outside the lambdas, if the expression uses only columns of the table; a `String`
alias keeps the string, and an alias whose expression uses a parameter, another alias or the alias of a lambda still has an
unknown type.
Related: ClickHouse#123959
Related: ClickHouse#127982 (comment)
Related: ClickHouse#127982 (comment)
Related: ClickHouse#127982 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ateTime` and `DateTime64(0)` The alias and the column with its name were compared by their scales, so a `DateTime` alias of a `DateTime64(0)` column took the alias's type, although their ranges differ: with `prefer_column_name_to_alias = 1`, `ALTER TABLE t DELETE WHERE isNotNull(toDateTime(event) AS event) AND event = '1960-01-01 00:00:00'` deleted another row than the session selects. Now they are compared by their types, so the literal is read with the type of whichever the identifier names. An alias inside a lambda whose expression invokes the alias of a lambda, as `f(id) AS z` with `(y -> y = 1) AS f`, was analyzed without the lambda and failed the mutation with `UNKNOWN_FUNCTION`. Now its type is not known, as for the other expressions that do not use only columns of the table. Related: ClickHouse#123959 Related: ClickHouse#127982 (comment) Related: ClickHouse#127982 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…through another alias of it An alias inside a lambda whose expression invokes a lambda through another alias of it, such as `g(id) AS z` with `(y -> y = 1) AS f` and `f AS g`, was analyzed alone against the table, because only the aliases of lambdas themselves were skipped, so the mutation failed with `UNKNOWN_FUNCTION` when `session_timezone` was set. Now the aliases through which a function may invoke a lambda are the aliases of lambdas and, repeatedly, the aliases of identifiers that name one of them (`f AS g`, `g AS h`), and an expression that invokes one of them is not analyzed alone, so its type stays unknown, as for `f(id)`. Another alias, such as `toString(id) AS identity`, does not count, so `identity(event) AS event` still gets the type of the column and the literal compared with it the time zone of the session. Related: ClickHouse#123959 Related: ClickHouse#127982 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
…f matching names in the AST The visitor that rewrites the string literals of a mutation or a `TTL` with `session_timezone` resolved by hand which identifiers name columns, aliases and lambda parameters, and every such rule missed a combination of scopes: a lambda alias in another scope named like a function stopped the conversion of an alias of a `DateTime` expression, an alias of the alias of a lambda, `f AS g`, was rejected with `UNKNOWN_IDENTIFIER`, and a parameter of a lambda over an expression, such as `arrayMap(t -> t, tags)`, was matched with the column with its name, so a `TTL` failed with `CANNOT_PARSE_DATETIME` and a mutation deleted the wrong row. Now the expressions are resolved by the analyzer, against the table for a mutation and against a table with the columns for a `TTL`, and the resolved query tree is walked: each node keeps the AST it was built from, also in the copies for an alias and for each invocation of a lambda, so a literal is converted if every evaluation at its own position reads it as the same `DateTime` or `DateTime64` without a time zone, compared with an identifier, as an element of the tuple of `IN` with an identifier on the left, also where the analyzer rewrites it into `has` and casts the elements, or assigned to a column. With an alias, the expressions are analyzed with the other value of `prefer_column_name_to_alias` too, as before. A comparison in a subquery is converted too. Related: ClickHouse#127982 (comment) Related: ClickHouse#127982 (comment) Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A stored `TTL` is validated and evaluated with the server settings, so a setting of the session that changes the types of its expressions does not change which `TTL` an `ALTER` accepts (05293). The rewrite of its literals for `session_timezone` analyzed it with the settings of the query instead, so with `enable_extended_results_for_datetime_functions = 1` the `MODIFY TTL` of `tumbleStart(toStartOfHour(ts), ...)` over a `DateTime64` column was rejected with `ILLEGAL_TYPE_OF_ARGUMENT`. Now it uses `getTTLExpressionContext`, which the validation of the `TTL` uses, so it binds the identifiers as the merges do. CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127982&sha=5cc69f2ebeffe03a112eacf6fe5989d4a35d7952&name_0=PR&name_1=Fast%20test Related: ClickHouse#127982 Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…imezone-literals-123959 # Conflicts: # src/Interpreters/InterpreterCreateQuery.cpp
…napshot The merged master has ClickHouse#130322, which refreshes the shared snapshot of the query between the segments of an `ALTER`, so 05483 no longer needs `enable_shared_storage_snapshot_in_query = 0`. Related: ClickHouse#123959 Related: ClickHouse#130110 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…N` operand of a generated cast
With `session_timezone`, the expressions of a mutation are analyzed to convert their `DateTime` literals. The command
comes from `MutationCommand::ast`, which parses its stored text again and leaves the set operations of its subqueries not
normalized, so `buildQueryTree` refused them with `UNION mode UNION_DEFAULT must be normalized` and every such mutation
failed. They are now normalized as `MutationsInterpreter` normalizes them.
An expression that cannot be analyzed alone, such as the value of an `UPDATE ... WHERE NULL`, which the mutation analyzes as
a branch of `if` that is never resolved, or an invalid `TTL`, which its validation reports afterwards, no longer fails the
statement: then no literal is converted, as before the conversion, and the statement is accepted or rejected there with its
own error.
The analyzer rewrites `event IN tuple('...', x)` with an element that is not a constant into `has`, casting the elements
without an AST. The literal of such a cast now keeps the identifier `event` and its type, as a comparison does, so if
`event` names an alias of another temporal type than the column with its name, the literal is converted for the type it has
with each value of `prefer_column_name_to_alias`.
Tests `05768_mutation_datetime_literal_set_operation_subquery` and `05769_mutation_datetime_literal_in_nonconstant_tuple_alias`.
Related: ClickHouse#123959
Related: ClickHouse#127982 (comment)
Related: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=127982&sha=d15699cd4989c211aee787f63bdacdef37640e13&name_0=PR
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…eave the statement as it is When the expressions of a mutation or of a `TTL` cannot be analyzed alone, their `DateTime` literals are not converted; this is now logged with the error, so that a statement accepted without the conversion can be told from one that needed none. New test `05770_mutation_datetime_literal_not_analyzed_alone`, with an explicit `session_timezone`: an `UPDATE ... WHERE NULL` whose value does not resolve alone is accepted, and an invalid `TTL` of `ALTER TABLE ... MODIFY TTL` and of `CREATE TABLE` is rejected by its own validation, with its own error. `05769_mutation_datetime_literal_in_nonconstant_tuple_alias` now sets `prefer_column_name_to_alias = 0` in its first part explicitly. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
A converted literal keeps its alias, so that an identifier naming the alias elsewhere still names the string, and such an
evaluation did not count. So in `event = ('2020-01-01 00:00:00' AS lit) AND other = lit` only the first comparison read the
string in the session time zone, and the second one in the server time zone, and `UPDATE d1 = ('...' AS lit), d2 = lit` gave
the two columns values nine hours apart. Now the evaluation of such an identifier, in a comparison or as the value of an
assignment, counts for the identifier itself, which is converted at its own position: `other = toDateTime(lit, '...')`, while
`s = lit` with a `String` column is left as it is. If the identifier names something else with the other value of
`prefer_column_name_to_alias`, such as a column with its name, it is left as it is.
Test `05771_mutation_datetime_literal_alias_reference`.
Related: ClickHouse#123959
Related: ClickHouse#127982 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…d like a column `05771_mutation_datetime_literal_alias_reference` now also checks that an identifier naming the alias of a literal is converted in a constant tuple of `IN`, and that one whose alias is named like a column, so that it names the column with the other value of `prefer_column_name_to_alias`, is left as it is while the literal itself is converted. Related: ClickHouse#123959 Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ecedence of the analyzer The literals of a mutation were analyzed also with the other value of `prefer_column_name_to_alias`, since the mutation may run with other settings than the query, but not with the other value of `analyzer_compatibility_prefer_alias_over_subcolumn`, which decides whether a compound identifier such as `t.event` names the column `event` of the table `t` or the subcolumn `event` of a column `t`. With it in the session, a background mutation of `MergeTree` compared a `DateTime64(3)` subcolumn with a literal converted as the `DateTime` column, which dropped its fraction of a second and deleted another row, and with a `String` subcolumn it failed with `NO_COMMON_TYPE`. The expressions are now analyzed with the other values of both settings, of the second if they have a compound identifier, and the conversion that chooses the reading by the type of the identifier takes several types. A literal that another analysis does not read as a `DateTime` keeps its string. `05816_mutation_datetime_literal_subcolumn_precedence` checks a `DateTime64(3)` and a `String` subcolumn in a background mutation and a `Memory` mutation, which runs in the session. ClickHouse#127982 (comment) Related: ClickHouse#123959 Related: ClickHouse#127982 Co-Authored-By: Claude Opus 5.5 <[email protected]>
With `transform_null_in = 1`, the analyzer resolves `in`, `notIn`, `globalIn` and `globalNotIn` to `nullIn`, `notNullIn`, `globalNullIn` and `globalNotNullIn`. `MutationsDateTimeLiteralVisitor` recognized only the first four names, so a string literal in the tuple of such an `IN` with a `DateTime` column on the left was stored without `session_timezone`, and the background mutation read it in the time zone of the server. Recognize every function of `IN` with `isNameOfInFunction`, in the query tree and in the AST. Related: ClickHouse#123959 Related: ClickHouse#127982 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
`TTLDescription` analyzes the expression of a `TTL`, which merges evaluate to
get the time, with `Date` and `DateTime` columns widened to `Date32` and
`DateTime64(0)`, or with the original columns if a function there rejects the
widened types, and its `WHERE` and the assignments of its `GROUP BY` with the
original columns. The rewrite analyzed all of them with the original columns,
so a literal compared with a `DateTime` column in the expression was stored as
`toDateTime('...', '<time zone>')`, which clamps `1960-01-01` to the start of
1970, and the `TTL` deleted the row stored then.
Analyze each expression of a `TTL` alone, with the widened columns, or with the
original ones if that fails, so such a literal is stored as
`toDateTime64('...', 0, '<time zone>')`. For that, `widenTemporalType` can keep
a `DateTime` without an explicit time zone without one
(`widenTemporalColumnsForTTLAnalysis`).
Related: ClickHouse#123959
Related: ClickHouse#127982 (comment)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
AI review of a later commit does not approve the PR, see the AI Review comment.
…imezone-literals-123959 # Conflicts: # src/Interpreters/MutationsDateTimeLiteralVisitor.cpp
… its literals `TTLDescription` analyzes each `WHERE` of a `TTL` rule and each value of its `GROUP BY ... SET` alone, so the conversion of the `DateTime` literals analyzes them the same way, as it already analyzes each `TTL` expression, rather than all of them in one scope where an alias of one of them could bind an identifier of another one. Such an alias is rejected in a new `TTL` since e43d200, also by `MODIFY TTL`, and an alias in a subquery is local to it, so no definition that the conversion receives is converted differently now, and there is no test for it. Related: ClickHouse#123959 Related: ClickHouse#127982 (comment) Co-Authored-By: Claude Opus 5.5 <[email protected]>
Closes: #123959
Related: #130110
With
session_timezoneset, aDateTimestring literal in theTTLof a table, as inTTL event + INTERVAL 1 SECOND DELETE WHERE event = '2020-01-01 00:00:00', was stored as written. TheTTLis evaluated by background merges, which do not have the session, so the literal was read in the server time zone, and the rule deleted other rows than it named: withSET session_timezone = 'Asia/Tokyo'on a server whose time zone is UTC+0 on that date (Europe/Lisbonhere), the row thatWHERE event = '2020-01-01 00:00:00'selects in the session was kept, and the row stored nine hours later was deleted.ALTER TABLE ... MODIFY TTLbehaved the same. Mutations do not have this problem:InterpreterAlterQueryalready rewrites such literals in their predicates (rewriteDateTimeLiteralsWithTimezone).The same rewrite is now applied to the table
TTL: whensession_timezoneis set, a string literal compared with aDateTimeorDateTime64column without an explicit time zone becomestoDateTime('...', '<session time zone>')(ortoDateTime64) in the stored definition.SHOW CREATE TABLEshows the rewritten form. It runs inInterpreterCreateQuerynext to theuse_legacy_to_timerewrite (not for the shortATTACHorRESTORE), only for aTTLthat the query gives itself: aTTLthatCREATE TABLE ... ASorCLONE AScopies from the source table keeps the meaning it has there, while aTTLthatCLONE ASgives the clone is rewritten. InInterpreterAlterQuery, eachMODIFY TTLis rewritten under the DDL guard and the alter lock of its commands, after they are validated and prepared and beforecheckAlterIsPossible, against the committed metadata as the preceding commands of the statement leave it, such asMODIFY COLUMN event DateTime('UTC')orADD COLUMN: the precedingADD,DROP,MODIFYandRENAME COLUMNcommands are applied to a copy of the metadata byAlterCommand::apply, as theALTERapplies them, so also to the flattened columns of aNestedcolumn, such asn.tswhenDROP COLUMN n, ADD COLUMN n Nested(ts DateTime)changes its type, and not those thatpreparemarked to ignore. Both use a new overload ofrewriteDateTimeLiteralsWithTimezonethat rewrites one expression in place, including the assignments ofTTL ... GROUP BY ... SET. The shared visitor now converts a literal by the type of what the identifier compared with it is bound to, as the analyzer binds it, rather than by matching names by hand: the predicate and the values of the assignments of a mutation are resolved together against the table, asMutationsInterpreterresolves them, the expressions of aTTLagainst a table with its columns and with the server settings, as the validation of theTTLand the merges analyze it (so a session setting such asenable_extended_results_for_datetime_functionsdoes not reject it, 05293), and the resolved query tree is walked for the string literals. Each node keeps the AST it was built from, also in the copies that the analyzer makes for an alias and for each invocation of a lambda, so a literal is converted if every evaluation at its own position reads it as the sameDateTimeorDateTime64without a time zone: compared with an identifier of such a type (a column, a subcolumn such asn.tsofn Tuple(ts DateTime), an alias, or a lambda parameter, in its scope), also as an element of the tuple ofINwith such an identifier on the left, also where the analyzer rewrites anINwith an element that is not a constant intohasand casts the elements, or assigned to such a column byUPDATEorTTL ... GROUP BY ... SET. So a lambda parameter has the type that the higher-order function binds it to, also after a fixed argument such as the limit ofarrayPartialSortand over an expression such asarrayMap(t -> t, tags), and aStringparameter named like aDateTimecolumn keeps its string (arrayExists(event -> event = 'keep', tags)failed withCANNOT_PARSE_DATETIME, in a mutation on master too); an alias has the type of its expression, such asidentity(event) AS event; the alias of a lambda in another scope does not change what a function with its name is; and an alias of the alias of a lambda,f AS g, is accepted. A literal in the body of a lambda that is invoked through its alias with arrays of different types, as inarrayExists((x -> x = '...') AS f, arr) OR arrayExists(f, utc), keeps its string, as on master, while one invoked with arrays of the same type gets the time zone. A converted literal keeps its alias, so an identifier that names the alias elsewhere still names the string. A comparison in a subquery, as inid IN (SELECT id FROM other WHERE ts = '...'), is converted too, since the background mutation evaluates it as well. A comparison with an expression rather than an identifier, such astoStartOfDay(event) = '...'ortoStartOfDay(event) IN tuple('...', x), is not: the function itself would still use the time zone of the server there. The literals of a mutation are rewritten when its segment is submitted, under its share lock and against the metadata that it is validated with (for a lightweight update, just before it), rather than while the whole statement is parsed, so they see the columns that the preceding commands of the statement add: otherwise the analysis of the aliases rejectedADD COLUMN c UInt8, UPDATE c = 1 WHERE isNotNull(identity(c) AS v)withUNKNOWN_IDENTIFIER, and a comparison with aDateTimecolumn that the statement adds kept the server time zone, on master too. (With the defaultenable_shared_storage_snapshot_in_query = 1, such a statement also failed withoutsession_timezone, since the shared snapshot of the query was not refreshed between the segments of the statement, #130110; #130322 fixed it in master, which is merged into this branch.) The mutation itself may run with other settings than the query (a background mutation ofMergeTreeruns with those of the server), whereprefer_column_name_to_aliasmay bind an identifier with the name of an alias to the column with that name, andanalyzer_compatibility_prefer_alias_over_subcolumna compound identifier such ast.eventto the columneventof the tabletrather than to the subcolumneventof a columnt, so the expressions are analyzed with the other values of these settings too (of the first if they have an alias, of the second if they have a compound identifier), and a literal is converted only if all the analyses read it the same way, or as aDateTimeorDateTime64of different types through the same identifier, as fortoDateTime64(event, 3) AS eventof aDateTimecolumn,toDateTime(event) AS eventof aDateTime64(0)column, which has the same precision but another range,n.tsofCAST(n, 'Tuple(ts DateTime)') AS novern Tuple(ts DateTime64(3)), ort.eventof aDateTimecolumneventand aDateTime64(3)subcolumn of a columnt: then it becomesif(toTypeName(event) = 'DateTime', toDateTime('...', '<time zone>'), toDateTime64('...', 3, '<time zone>'))(with a nestediffor each further type), read in the session time zone with the type of whichever the identifier names where the mutation runs, so with the same range and rounding, also before 1970. A literal that another analysis does not read as aDateTimeat all, as whent.eventnames aStringsubcolumn there, keeps its string. If the expressions cannot be analyzed with some of the other values, the mutation fails wherever it runs with them, so only the other analyses count. On a DDL worker (ON CLUSTER, or aReplicateddatabase) the query was normalized on the initiator, which already rewrote its ownTTLand copied there theTTLof the source ofCREATE TABLE ... AS, so it is not rewritten again, asgetColumnsDescriptionskips the transforms the initiator applied; the initiator also rewrites theTTLof an inner engine of a materialized view or aTimeSeriestable that the query gives itself, in the definition of the view or the table, against the columns of the inner table, while the internal query that creates the inner table (or restores a table) does not rewrite it, so aTTLthatCREATE TABLE ... AScopies from aTimeSeriestable keeps its meaning and the stored definition matches the inner table; withdistributed_ddl_entry_format_versionbelow 3 (the default is 5) the initiator does not normalize the query, so neither rewrites it. The inner tables of a materialized view and of aTimeSeriestable are covered. The stored form,toDateTime(string, time zone), is understood by older versions.05459_ttl_datetime_literal_session_timezonecreates a table with such aTTL, and another one withMODIFY TTL, inserts the two rows withsession_timezone = 'Asia/Tokyo', and merges withOPTIMIZE ... FINAL SETTINGS session_timezone = '', like a background merge; it checks which row is left and that the stored definition has the explicit time zone. It also checks thatCREATE TABLE ... ASkeeps the raw literal of a source created without a session time zone, theALTERstatementsMODIFY COLUMN event DateTime('UTC'), MODIFY TTL ...andADD COLUMN event DateTime, MODIFY TTL ...andCLEAR COLUMN event, MODIFY TTL ..., aNestedcolumnnreplaced byDROP COLUMN n, ADD COLUMN n Nested(...)in both directions, so thatn.tschanges betweenStringandDateTime(theTTLdeletes the right row, andx = 'keep'over aStringn.tsis not rejected), also byADD COLUMN n Nested(ts DateTime), MODIFY COLUMN n.ts Array(String), aTTLover the elementn.tsof aTuplecolumn forCREATEandMODIFY TTL, and aDELETEmutation over it, which delete the right row, thatADD COLUMN x DEFAULT 0, MODIFY TTL ...is still rejected withBAD_ARGUMENTS, and that the assignments ofTTL ... GROUP BY ... SETare stored with the time zone forCREATEandMODIFY TTL(only the stored definition: a merge with such a rollup fails before the time zone matters, on master too, #128596), and lambda parameters: aStringparameter named like the column, or aStringelement of aTupleparameter, keeps its string forCREATE,MODIFY TTLand aDELETEmutation, and aDateTimeparameter over an array, a map,arrayFold, a parameter of an enclosing lambda, an array of tuples unpacked into the parameters, or after the fixed argument ofarrayPartialSort,arrayTopKorarrayPackBitsToFixedStringgets the time zone, also in aDELETEmutation, which then removes the right row. ADELETEmutation over an alias that shadows a column, an arraycor aStringevent, removes its rows; one over an alias of aDateTimeexpression with the name of the column,identity(event) AS event, also one that changes the nullability or the precision (toNullable(event),assumeNotNull(n)of aNullable(DateTime)column,toDateTime64(event, 3)), gets the time zone and removes the right row, as does one over the element oftoNullable(n) AS nor of a lambda parameter over[toNullable(n)] AS arr, and one over an alias with another precision than the column with its name, or than its element, is cast to the type of the identifier; and withprefer_column_name_to_alias = 1, theStringaliastoString(event) AS eventof aDateTimecolumn keeps its string, so the mutation, which runs with the settings of the server, completes, and a valid mutation of aMemorytable underprefer_column_name_to_alias = 1, run in the session, is not rejected; an alias inside a lambda or a subquery does not stop the comparison with the column outside from getting the time zone, while one in the body of the lambda keeps its string, and the comparison with the alias of a scalar subqueryStringnamed like aDateTimecolumn keeps its string.05480_ttl_datetime_literal_session_timezone_clone_aschecks that an explicitTTLofCLONE ASis rewritten; it does not run in aReplicateddatabase, which does not supportCLONE AS.05481_ttl_datetime_literal_session_timezone_materialized_viewchecks the inner table of a materialized view created locally and in aReplicateddatabase.05482_ttl_datetime_literal_session_timezone_time_serieschecks the definition and the inner table of samples of aTimeSeriestable: a source created without a session time zone, its copy byCREATE TABLE ... AS, which keeps the raw literal, and a table with its ownTTL, locally and in aReplicateddatabase. On master both tables keep the wrong row.05483_mutation_datetime_literal_after_preceding_alterchecks a mutation after anADD COLUMNof the same statement: an alias of the added column, and a comparison with an addedDateTimecolumn, which gets the time zone; it does not run in aReplicateddatabase, which rejectsALTERcommands of different types in one query, with the defaultenable_shared_storage_snapshot_in_query.05484_mutation_datetime_literal_lambda_aliaschecks aDELETEmutation through a lambda alias invoked over a zoneless array and over an array ofDateTime('UTC')orString, also with a parameter named like aDateTimecolumn and with a lambda inside the shared body, which removes the right rows, and that a lambda alias that nothing invokes still gets the time zone.05485_mutation_datetime_literal_alias_prefer_column_namechecks that withprefer_column_name_to_alias = 1the comparison withidentity(event) AS eventgets the time zone and the mutation removes the right row, and that an alias that refers to another alias with the name of a column keeps its string, so the background mutation does not fail withNO_COMMON_TYPEas on master; it also checksMemorymutations through an alias with another precision than the column, aDateTimealias of aDateTime64(3)column and the reverse, with=and!=and a fractional literal, which remove the rows that the same condition selects in the session, a background mutation ofMergeTreethrough aDateTime64(3)alias of aDateTimecolumn, which reads the literal in the session time zone, and theDateTime64(3)element of aTuplecolumn through aCASTof the tuple with aDateTimeelement, also ofMergeTree, a literal of the year 2290, beyond the range ofDateTime64(9), and a literal with microseconds before 1970 through aDateTime64(6)alias of aDateTime64(3)column, a literal before 1970 through aDateTimealias of aDateTime64(0)column and of such an element of a tuple, and aliases defined and used inside a lambda and a scalar subquery of such an alias, which remove the right rows.05816_mutation_datetime_literal_subcolumn_precedencechecks the same withanalyzer_compatibility_prefer_alias_over_subcolumn = 1: a background mutation ofMergeTreethrought.event, which names aDateTimecolumn in the query and aDateTime64(3)subcolumn in the background, removes the row whose subcolumn matches the fractional literal, one through aStringsubcolumn keeps its string and does not fail withNO_COMMON_TYPE, and aMemorymutation removes the row that the same condition selects in the session.05569_mutation_datetime_literal_lambda_body_aliaschecks that a comparison with aDateTimealias inside a lambda,identity(event) AS event, gets the time zone in the stored command and the background mutation removes the right row, that an alias inside a lambda that names or calls the alias of a lambda (f(id) AS z) is accepted, and that aStringalias inside a lambda keeps its string.05570_mutation_datetime_literal_analyzer_bindingschecks the bindings of the analyzer: a lambda alias in another scope named like the functionidentity, an alias of the alias of a lambda, a lambda over an expression in aTTLand in a mutation, a lambda alias invoked with arrays of the same type, a literal with an alias that is also used as a string, anINwith an element that is not a constant, also with an expression on the left, whose literal keeps its string, a comparison in a subquery, and an alias that does not resolve with the other value ofprefer_column_name_to_alias; the mutations remove the right rows.The command of a mutation comes from
MutationCommand::ast, which parses its stored text again, so its set operations are normalized before it is analyzed, asMutationsInterpreternormalizes them; otherwise a mutation with a set operation in a subquery failed withUNION mode UNION_DEFAULT must be normalized(05768_mutation_datetime_literal_set_operation_subquery). An expression that cannot be analyzed alone, such as the value of anUPDATE ... WHERE NULL, which the mutation analyzes as a branch ofifthat is never resolved, or an invalidTTL, which its validation reports afterwards, is left as it is, as before this change, so the statement is accepted or rejected with its own error; the skipped analysis is logged (05770_mutation_datetime_literal_not_analyzed_alone). Inevent IN tuple('...', x)with an element that is not a constant, which the analyzer rewrites intohaswith casts of the elements, the literal keeps the identifiereventand its type, so it is converted for the type thateventhas with each value ofprefer_column_name_to_alias, as in a comparison (05769_mutation_datetime_literal_in_nonconstant_tuple_alias). Withtransform_null_in = 1, the analyzer resolvesIN,NOT INandGLOBAL INtonullIn,notNullInandglobalNullIn, which are recognized asINtoo (05817_mutation_datetime_literal_transform_null_in). An identifier that names the alias of a literal, such aslitinevent = ('...' AS lit) AND other = litorUPDATE d1 = ('...' AS lit), d2 = lit, is converted at its own position where it is compared with or assigned to such a column, so the alias keeps naming the string for its other uses (05771_mutation_datetime_literal_alias_reference, also in a constant tuple ofIN; an alias named like a column, which names the column with the other value ofprefer_column_name_to_alias, is left as it is).The expression of each
TTL, which merges evaluate to get the time, is analyzed alone and withDateandDateTimecolumns widened toDate32andDateTime64(0), asTTLDescriptionanalyzes it (or with the original columns if a function there, such astumbleStart, rejects the widened types), while itsWHEREand the assignments of itsGROUP BYare analyzed with the original columns. So a literal compared with aDateTimecolumn in the expression is stored astoDateTime64('...', 0, '<time zone>'), which keeps a value before 1970 thattoDateTimewould clamp (05818_ttl_datetime_literal_widened_time_expression, forCREATE,MODIFY TTLand an element of aTuplecolumn).Reproduced on the official builds of release 26.10.2.103 and master 26.11.1.782.
Not covered: an
INlist of such literals, as inWHERE event IN ('2020-01-01 00:00:00'). The shared visitor does not rewrite its folded forms, for mutations either (#121991); #122136 adds them to the visitor, and theTTLgets them with it. Also not covered: an identifier that names the alias of such a literal in a tuple ofINwith an element that is not a constant, as inevent = ('...' AS lit) AND other IN tuple(lit, x): the analyzer casts the elements without an AST, so the position of the identifier is not known, and neither the literal nor the identifier is converted (#132434). Also not covered: theTTLof a column. A columnTTLsuch asif(event = '2020-01-01 00:00:00', event + INTERVAL 1 SECOND, ...)resets the right row on master even when the merge runs without the session time zone, so it is left as it is.Changelog category (leave one):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
A
DateTimestring literal in theTTLof a table, as inTTL ... DELETE WHERE event = '2020-01-01 00:00:00', is now interpreted insession_timezonewhen it is set, as in mutations. It used to be read in the server time zone by background merges, so the rule could delete other rows than it named. In mutations, a lambda parameter is now treated by its own type whensession_timezoneis set: one named like aDateTimecolumn but of another type, as inALTER TABLE ... DELETE WHERE arrayExists(event -> event = 'keep', tags), no longer fails withCANNOT_PARSE_DATETIME, and aDateTimeparameter, as inarrayExists(x -> x = '2020-01-01 00:00:00', arr), is interpreted insession_timezonetoo. A literal compared with a subcolumn, such asn.tsof aTuplecolumn, is interpreted insession_timezonetoo, in aTTLand in mutations.🤖 Generated with Claude Code
Workflow [PR]
Sync PR [sync-upstream/pr/127982]