Skip to content

User defined types - #80373

Open
cucumber95 wants to merge 60 commits into
ClickHouse:masterfrom
cucumber95:user-defined-types
Open

cucumber95 wants to merge 60 commits into
ClickHouse:masterfrom
cucumber95:user-defined-types

Conversation

@cucumber95

@cucumber95 cucumber95 commented May 16, 2025 •

Copy link
Copy Markdown
Contributor

Changelog category (leave one):

  • New Feature

Changelog entry (a user-readable short description of the changes that goes to CHANGELOG.md):

Adding the ability to create custom types

Documentation entry for user-facing changes

Usage examples:

  • CREATE TYPE [IF NOT EXISTS] [OR REPLACE] CustomType(T, U) AS Tuple(T, Array(U))
  • DROP TYPE [IF EXISTS] CustomType
  • SHOW TYPES
  • SHOW TYPE CustomType

You can see more examples in the tests


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

@vitlibar vitlibar self-assigned this May 16, 2025
@vitlibar

Copy link
Copy Markdown
Member

Can you please give an example SQL how this user-defined type will be used?

@alexey-milovidov

Copy link
Copy Markdown
Member

Please edit the description using the template: https://raw.githubusercontent.com/ClickHouse/ClickHouse/refs/heads/master/.github/PULL_REQUEST_TEMPLATE.md

The CI is not smart; it parses only the template.

@alexey-milovidov

Copy link
Copy Markdown
Member

Needs tests. Needs docs.
Please resolve a conflict.

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label May 26, 2025
@clickhouse-gh

clickhouse-gh Bot commented May 26, 2025

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [18e87fa]

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label May 26, 2025
Comment thread src/DataTypes/UserDefinedTypeFactory.h Resolved

@vitlibar vitlibar left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Please fix persistent storing of user-defined types (see) and add some documentation.

@clickhouse-gh

clickhouse-gh Bot commented Jul 8, 2025

Copy link
Copy Markdown
Contributor

Dear @vitlibar, this PR hasn't been updated for a while. You will be unassigned. Will you continue working on it? If so, please feel free to reassign yourself.

@ilejn

ilejn commented Aug 26, 2025

Copy link
Copy Markdown
Contributor

Hello @cucumber95 ,
do you plan to continue working on this PR ?

The thing looks interesting and useful, would be nice to have it in ClickHouse.

alexey-milovidov and others added 7 commits June 29, 2026 14:44
Resolve conflicts in the feature's integration points:
- `src/Common/ErrorCodes.cpp`: renumber the new `TYPE_ALREADY_EXISTS` and
  `CANNOT_REMOVE_TYPE` error codes to 779/780 (747/748 are now taken on master).
- `src/DataTypes/DataTypeFactory.cpp`: keep the hoisted `query_context` lookup
  used for user-defined type resolution, switch it to the non-throwing
  `CurrentThread::tryGetQueryContext` (`getQueryContext` was removed on master),
  and keep both new includes.
- `src/Interpreters/InterpreterFactory.cpp`, `src/Interpreters/registerInterpreters.cpp`,
  `src/Parsers/ParserQuery.cpp`, `src/Storages/System/attachSystemTables.cpp`:
  keep both the feature's and master's additions (interpreters, parsers, system tables).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Document `CREATE TYPE`, `DROP TYPE`, `SHOW TYPES`/`SHOW TYPE`, and the
`system.user_defined_types` table, as requested in review. Only the
behavior that is actually implemented is documented: a user-defined type
is a named, optionally parameterized alias that is expanded to its
definition when used (for example as a column type). The `INPUT`,
`OUTPUT`, and `DEFAULT` clauses are currently only recorded as metadata
(visible in `system.user_defined_types`) and are intentionally not
advertised as functional.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The branch predates several master refactors; adapt the feature so it
compiles against current `master`:

- Remove the obsolete AST highlighting in `formatImpl`/`formatQueryImpl`
  (`hilite`, `hilite_keyword`, `hilite_none`, `hilite_identifier` no
  longer exist in `IAST::FormatSettings`) and write the keywords directly,
  in `ASTCreateTypeQuery`, `ASTDropTypeQuery`, `ASTShowTypeQuery`,
  `ASTShowTypesQuery`.
- `IAST::FormatSettings`' second positional argument is now an
  `IdentifierQuotingRule`, not a `hilite` bool, so drop it in
  `InterpreterCreateTypeQuery`.
- `SourceFromSingleChunk` now takes a `SharedHeader`
  (`std::shared_ptr<const Block>`) instead of a `Block`; wrap the result
  block accordingly in `InterpreterShowTypesQuery` and
  `InterpreterShowTypeQuery`.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
- Remove unused `extern const int` error-code declarations that fail the
  "defined but not used" style check: `CANNOT_PARSE_TEXT`, `BAD_ARGUMENTS`,
  `TABLE_ALREADY_EXISTS`, `UNKNOWN_DATABASE` in `UserDefinedTypeFactory`,
  `ACCESS_DENIED`/`BAD_ARGUMENTS` in `InterpreterCreateTypeQuery`, and the
  whole dead `ErrorCodes` block in `InterpreterDropTypeQuery` (which also
  removes the non-English comments flagged in review).
- Drop the now-unreferenced `CANNOT_REMOVE_TYPE` error code; it was never
  thrown. `TYPE_ALREADY_EXISTS` keeps code 779.
- Document the `UserDefinedTypeFactory::TypeInfo` fields with a worked
  example, as requested in review, and note that `INPUT`/`OUTPUT`/`DEFAULT`
  are currently recorded as metadata only.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The feature sources contained pervasive trailing whitespace, which fails
the `Style check`. Remove it across the new and modified files.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The feature adds three access types (`SHOW_USER_DEFINED_TYPES`,
`CREATE_TYPE`, `DROP_TYPE`) but the `SHOW PRIVILEGES` snapshot test was
not updated, so it would fail. Add the corresponding rows in enum order.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Jun 29, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca49c70]

Summary: ❌

job_name test_name status info comment
Style check FAIL
cpp FAIL cidb
Build (arm_tidy, 1/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 2/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 3/4) FAIL
Build ClickHouse FAIL cidb
Build (arm_tidy, 4/4) FAIL
Build ClickHouse FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL
Code Review DROPPED
Build (amd_asan_ubsan) DROPPED
Build (arm_asan_ubsan) DROPPED
Integration tests (amd_asan_ubsan, db disk, targeted) DROPPED

Comment thread src/Parsers/ParserCreateTypeQuery.cpp Resolved
alexey-milovidov and others added 2 commits October 9, 2026 13:54
…ents, support backup

- The walker over the type references of a definition visited every identifier, so the aggregate function of
  `AggregateFunction(sum, UInt64)` / `SimpleAggregateFunction(sum, UInt64)` and settings like
  `Dynamic(max_types = 10)` were rejected as unknown types. It now visits only the positions that hold types.
- `CREATE TYPE OR REPLACE` only checked that the dependent types use the replaced type with the right number
  of arguments. Now every dependent type (directly or through other types) is expanded with the new definition
  in place, so `CREATE TYPE A(T) AS Array(T); CREATE TYPE B AS A(UInt8); CREATE TYPE OR REPLACE A(T) AS Map(T)`
  is rejected instead of leaving `B` unusable.
- `system.user_defined_types` overrides `backupData` / `restoreDataFromBackup` like `system.functions`.
  The restored types are registered after the types they are defined through, `create_function` decides what
  happens to existing ones, and `RESTORE` requires `CREATE TYPE` (and `DROP TYPE` in 'replace' mode).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
alexey-milovidov and others added 2 commits October 17, 2026 18:38
Resolve conflict in `ErrorCodes.cpp`: master took code 786 for `BAD_FUNCTION_SIGNATURE`, so `TYPE_ALREADY_EXISTS` moves to 787.
… restores

A parameterized definition was only checked by the names of the type families it
uses, so `CREATE TYPE Broken(T) AS Map(T)` and `CREATE TYPE Broken(T) AS Map(String)`
were accepted and failed only when the type was used. Now such a definition is
instantiated with every combination of a few probe arguments (types and values, so
that `FixedString(N)` and `DateTime64(P, TZ)` are accepted), and is rejected if none
of them gives a valid type.

`RESTORE ... SETTINGS create_function = 'replace'` validated every restored
definition against the types it replaced, one at a time, so a backup in which a type
and its dependent both change their shape could not be restored. The pending
definition that `tryGet` returns in place of the stored one is generalized to a set
of definitions, and `restore` sets all the restored definitions, so each one is
validated against the set of types after the restore.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/DataTypes/DataTypeFactory.cpp Resolved
auto & storage = current_context->getUserDefinedTypesStorage();

/// Dropping a type another type is defined through would leave that type registered but unusable.
auto dependent_uses = findDependentUses(storage, type_name);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Make dependency validation atomic with the metadata change

findDependentUses, definition validation, and cycle checking run outside the storage lock; storeObject and removeObject acquire it only for the eventual write. For example, with A AS UInt8, DROP TYPE A can observe no dependents, another session can finish validating/storing B AS A, and the first session can then remove A. Both statements succeed and leave persisted B unusable. Concurrent replacements can likewise close a cycle after both cycle checks pass.

Please serialize validation and mutation over one consistent registry state. The ZooKeeper mode also needs coordination/version checks: another server's local cache can miss a dependent even after its creation has completed, so a process-local lock alone does not enforce this invariant. Cover conflicting DDL locally and across the two replicated nodes.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Partially addressed in 28ee762.

  • Within one server: CREATE TYPE, DROP TYPE and the restore of types now hold one mutex (UserDefinedTypeFactory::ddl_mutex) across validation and the write. So DROP TYPE A and CREATE TYPE B AS A can no longer interleave, and concurrent replacements can no longer close a cycle.
  • Across servers (ZooKeeper storage): under that mutex, each server now re-reads the definitions from ZooKeeper (reloadObjects) before validating, so it no longer checks against a lagging local cache. test_replicated_user_defined_types now checks that a type used on node1 cannot be dropped on node2 right away.

Not fixed: truly concurrent DDL on two servers. This does not make the check linearizable across servers. Two servers that run the conflicting statements at the same moment can both pass validation. Closing that gap needs coordination in the storage itself, e.g. a version node that every type DDL bumps in the same multi request as the object write, with the whole validation retried on ZBADVERSION. That changes the storage shared with user-defined functions, so I'm leaving the design decision to a human reviewer and keeping this thread open.

Comment on lines +761 to +762
for (const auto & [type_name, create_type_query] : restored_types)
registerType(restore_context, type_name, create_type_query, throw_if_exists, replace_if_exists);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Publish mutually dependent restore replacements together

The pending definitions make validation see the final snapshot, but this loop still publishes and persists each replacement separately. In the new regression's example, after A(T) AS Array(T) has been replaced by A(K, V) AS Map(K, V) and before B is replaced, every other thread still sees the old B AS A(UInt8) and its expansion fails. If writing B throws, the guard unwinds without rolling back A, so the broken pair remains on disk and survives restart.

Please make publication of the replacement set consistent for ordinary readers and preserve a valid persisted set on failure, rather than relying on an overlay visible only to the restore thread. Add a focused failure case after the first replacement and verify that the pre-existing dependent remains usable.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Partially addressed in 28ee762.

  • Validate first: restore now validates the whole set of restored definitions (against the final snapshot) before storing any of them.
  • Revert on failure: if storing one of them fails, the definitions already stored are reverted in reverse order. Each replaced type gets its previous definition back and each created type is removed, so a valid persisted set is kept. The new test 05449_user_defined_types_restore_rollback makes the second store fail after the first type has been stored, then checks that the first type is removed and the pre-existing type is unchanged and still usable.
  • Readers during the restore: they can still see the intermediate state while the types are being stored one by one. The storage interface only stores single objects, and the ZooKeeper storage republishes each object into its in-memory map as it writes it. Making the whole set visible at once would need a batch store API in IUserDefinedSQLObjectsStorage (a multi request in ZooKeeper, one map swap in memory), which is shared with user-defined functions. I'm keeping this thread open for that design decision.

Comment thread src/Parsers/ParserCreateTypeQuery.cpp Resolved
alexey-milovidov and others added 4 commits October 25, 2026 02:39
# Conflicts:
#	src/Storages/System/attachSystemTables.cpp
Master now declares 256 access types, and the `CREATE TYPE`, `DROP TYPE` and
`SHOW USER DEFINED TYPES` privileges added by this PR no longer fit into the
`uint8_t` underlying type (`enumerator value 256 is not representable`).
The bitset of `AccessFlags` is widened accordingly.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`CREATE TYPE` accepted any quoted identifier, e.g. `` `Type-With-Dashes` `` or
`` `тип_utf8` ``, but `ParserDataType` rejects such names even when quoted, so
the type could not be used in a column declaration or `CAST`. The name of the
type and the names of its parameters are now checked with the same rule
(`isValidDataTypeName`), and the test instantiates a quoted name that is valid.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…store rollback

- `substituteTypeParameters` (moved from `DataTypeFactory`) keeps the named
  fields of `ASTNameTypePair`, `ASTObjectTypedPathArgument`,
  `ASTObjectTypeArgument` and `ASTFunction` in sync with the substituted
  children. Before, `Nested(x T)` and `JSON(a.b T)` aliases kept `T`, and a
  parameter shadowing a built-in type (`N(UInt8) AS Nested(x UInt8)`) silently
  expanded to the wrong type.
- A parameterized definition is no longer required to be valid for one of a
  few sample arguments, which rejected valid definitions like
  `Decimal(P, 2)` and skipped definitions with more than four parameters.
  Instead, each use of a built-in family is instantiated on its own with
  sample arguments, and only a wrong number of arguments (which does not
  depend on the values) is rejected, for any number of parameters.
- `CREATE TYPE`, `DROP TYPE` and the restore of types are serialized with the
  validation they depend on, and with a replicated storage the definitions are
  re-read from ZooKeeper first, so `DROP TYPE A` can no longer race with
  `CREATE TYPE B AS A`.
- `RESTORE` validates all definitions before storing any of them and reverts
  the already stored ones if storing another one fails.
- Fix the `cert-err09-cpp` / `bugprone-exception-copy-constructor-throws`
  clang-tidy errors: the stored exception is rethrown with
  `std::rethrow_exception`.

CI report: https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=80373&sha=d84122817f8301d96dff98c02d36f4395f5e9f17&name_0=PR&name_1=Build%20%28arm_tidy%2C%203%2F4%29
PR: ClickHouse#80373

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@mintlify

mintlify Bot commented Oct 25, 2026 •

Copy link
Copy Markdown
Contributor

Preview approval required

This pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit ca49c70.

Approve preview

Comment thread programs/server/Server.cpp Resolved
backQuote(type_name), new_num_parameters, backQuote(use.dependent_type_name), use.num_arguments);
}

checkDependentsAfterReplacement(storage, type_name, normalized_query);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

[P1] Preserve the resolved types of persisted key expressions

The replacement checks only dependencies between user-defined types, but table expressions retain alias names. This sequence reproduces an unreadable primary index on the PR-head binary:

CREATE TYPE ReviewKey AS UInt64;
CREATE TABLE key_table (x UInt8) ENGINE = MergeTree
ORDER BY CAST(x, 'ReviewKey') SETTINGS index_granularity = 1;
INSERT INTO key_table VALUES (2), (10);
CREATE TYPE OR REPLACE ReviewKey AS String;
DETACH TABLE key_table;
ATTACH TABLE key_table;
SELECT * FROM key_table WHERE CAST(x, 'ReviewKey') = '10';

The final read fails with EXPECTED_END_OF_FILE because primary.cidx was serialized as UInt64 and is now interpreted as String. DROP TYPE likewise leaves the persisted cast unresolvable. Please expand alias targets in persisted expressions, or track their table dependencies and reject destructive type changes; checking other type definitions alone does not preserve the table's storage contract.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Agreed, this is real, but I'm leaving it open as a design decision for a human reviewer. There are two possible fixes and they have different semantics:

  1. Expand alias targets in persisted table expressions when a table is created (rewrite CAST(x, 'ReviewKey') to CAST(x, 'UInt64')). Persisted tables would then never depend on a type by name. But the stored SHOW CREATE TABLE would no longer match what the user wrote, and the type name would have to be found in string literals (CAST, ::, toTypeName-style arguments, DEFAULT expressions, projections, skipping indexes, TTL ...).
  2. Track table → type dependencies (like DatabaseCatalog's referential dependencies for dictionaries), and reject DROP TYPE and incompatible CREATE OR REPLACE TYPE while a table refers to the type.

Column types are not affected, because they are stored expanded. This only concerns type names inside expressions. User-defined SQL functions have the same issue in persisted expressions today. Which contract we want for types should be decided before more code is written here.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

🕵 Correction to my previous reply: user-defined SQL functions do not have this issue. They are inlined into persisted expressions: CREATE TABLE ut (x UInt8) ENGINE = MergeTree ORDER BY udfk(x) is stored as ORDER BY x + 1, so DROP FUNCTION udfk does not affect the table. Option 1 (expand type names in persisted expressions when the table is created) would follow that precedent. The difficulty is that type names appear inside string literals (CAST(x, 'T')), not as AST nodes, so it is a design choice. I'm still leaving the thread open for a reviewer to pick the approach.

@maxknv maxknv added the external Author is not a member of the ClickHouse organization label Nov 2, 2026
alexey-milovidov and others added 4 commits November 3, 2026 12:50
# Conflicts:
#	src/Backups/RestorerFromBackup.cpp
Persisted table expressions can refer to a user-defined type by name, e.g.
`ORDER BY CAST(x, 'MyType')`. The types were loaded after `loadMetadata`, so
attaching such a table on restart failed with `UNKNOWN_TYPE` (or raced with
asynchronous table loading). Load them before the system and user databases,
in both the server and `clickhouse-local`, and cover it in the persistence test.

Address review: ClickHouse#80373 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The storages of user-defined functions and types share the ZooKeeper session,
and `createWatchFromRawCallback` reuses the callback registered under the same
id. The id of an object watch contained only the name, so with a function and a
type of the same name the changes of one were reported to the queue of the
other, and the replacement was not propagated to other replicas.

Address review: ClickHouse#80373 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`dependsOnParameters` used the type-reference walker, which skips the
arguments of aggregate functions, so a parameter used as in
`AggregateFunction(quantiles(Q), UInt8)` was not detected. Replacing a type
such a definition was passed to then tried to instantiate the unresolved `Q`
and failed even for an identical definition. Check every identifier instead.

Address review: ClickHouse#80373 (comment)

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
@clickhouse-gh clickhouse-gh Bot added comp-data-types Type system & core datatypes used across query planning/execution. and removed comp-datatype-wrapper Type modifiers/wrappers (Nullable, LowCardinality, etc.). labels Nov 3, 2026
alexey-milovidov and others added 4 commits November 11, 2026 22:00
Resolve the conflict in `src/Common/ErrorCodes.cpp`: master took code 787 for
`UNKNOWN_DISTRIBUTED_ASYNC_INSERT_FORMAT_VERSION`, so `TYPE_ALREADY_EXISTS`
moves to 788.
… built-ins

`ParserDataType` parses every spelling of `Array` and `Map` followed by arguments as the built-in type,
so `CREATE TYPE array(T) AS Tuple(T)` succeeded, but `array(UInt8)` in a column declaration still
meant `Array(UInt8)`. The normalization is now in `getCanonicalNameOfDataTypeWithArguments`, which
`CREATE TYPE` uses to reject such names.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
`clickhouse-local` loaded the user-defined types only when the default `<path>/user_defined`
directory existed, so types stored under a custom `user_defined_path` were not loaded by the next
invocation. Always load the configured storage: it does nothing when there is nothing to load.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The persisted expressions of tables can refer to user-defined types by name
(`ORDER BY CAST(x, 'T')`), but `system.user_defined_types` was restored in the data-restoration
stage, after the tables were created, so restoring a backup with both a table and its types to an
empty registry failed with `UNKNOWN_TYPE`. Restore the types at the end of the
`CHECKING_ACCESS_RIGHTS` stage, like named collections, and with a replicated storage reload them
on every host after the stage barrier.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Backups/RestorerFromBackup.cpp Resolved
alexey-milovidov and others added 3 commits November 23, 2026 13:07
Conflicts, both sides kept in each:
- `src/Access/Common/AccessType.h`: `CREATE_TYPE` and `DROP_TYPE` next to the regrouped workload and resource grants.
- `src/Access/ContextAccess.cpp`: `type_ddl` next to `named_collection_ddl`.
- `src/Common/ErrorCodes.cpp`: `TYPE_ALREADY_EXISTS` renumbered to 789 (788 was taken by `CANNOT_CONNECT_PULSAR`).
- `src/Parsers/ParserDataType.cpp`: the new rejection of bareword literals moved into `isValidDataTypeName`.
- `tests/queries/0_stateless/01271_show_privileges.reference`.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
`system.privileges` has a new column on master; the three lines of the type privileges kept in the merge lacked it.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…sions

- `RESTORE` restores the types whenever `system.user_defined_types` is selected, also with `structure_only` and
  `restore_table_data = false`: tables are still created with these settings, and their persisted expressions can
  refer to the types by name. The access check follows the same rule.
- With a replicated storage of types, every host of a `RESTORE ON CLUSTER` registers the directory of the backup it
  would restore the types from, and the one host that restores them reads the directories of all hosts sharing the
  storage. Identical definitions collapse into one, different definitions of the same type are rejected. A host whose
  part of the backup has no types reloads the types restored by another host. Before, the types of the other source
  hosts were silently lost when a backup of servers with separate disk storages was restored into a shared one.
- An internal restore refuses to restore the types if the initiator of the `ON CLUSTER` query is too old to require
  `CREATE TYPE` and `DROP TYPE` of the initiating user (coordination version 4).
- `CREATE TYPE` rejects every spelling of a built-in type name, whatever the case: `ParserDataType` recognizes
  `enum8('a' = 1)` and `uint8(1)` as built-in types although these names are registered case-sensitively.
- `DataTypeFactory::get` is `nodiscard` on master.

The test `05623_user_defined_types_backup_with_tables` failed in the stateless tests with `DatabaseReplicated`: the
other replicas of the database are separate servers without the type, so they cannot create a table that refers to it
by name. It is tagged `no-replicated-database`.
https://s3.amazonaws.com/clickhouse-test-reports/praktika.html?PR=80373&sha=0f248a568ef8685fce02dec3aa54689cc5958fa9&name_0=PR&name_1=Stateless%20tests%20%28arm_binary%2C%20s3%20storage%2C%20DBReplicated%2C%20sequential%29
ClickHouse#80373

Co-Authored-By: Claude Fable 5.2 <[email protected]>
@alexey-milovidov

Copy link
Copy Markdown
Member

🕵 Merged current master (518ceb96315) and pushed ca49c70a1a7f.

Merge. Five conflicts, both sides kept in each: AccessType.h and ContextAccess.cpp (type grants next to the regrouped workload / named-collection grants), ErrorCodes.cpp (TYPE_ALREADY_EXISTS is now 789; 788 was taken by CANNOT_CONNECT_PULSAR), ParserDataType.cpp (the new rejection of bareword literals moved into isValidDataTypeName), and the 01271_show_privileges reference. DataTypeFactory::get became nodiscard on master, so four validation calls needed std::ignore.

CI of the previous run.

  • 05623_user_defined_types_backup_with_tables failed in Stateless tests (arm_binary, s3 storage, DBReplicated, sequential): the other replicas of the Replicated database are separate servers without the type, so they cannot create a table that refers to it by name. The test is now tagged no-replicated-database.
  • All six Performance Comparison (arm_release, master_head) shards failed with test selection unavailable: GitHub API 403 ... rate limit exceeded. That is unrelated to this PR and fixed on master by Read sources for performance test selection from git, not the GitHub API #131332, which this merge brings in.

Review threads addressed in this push (replies are on the threads):

  • Types are restored with structure_only = 1 and restore_table_data = 0 too.
  • In RESTORE ON CLUSTER into a shared Keeper storage, the elected host restores the source directories of all hosts; conflicting definitions fail the restore.
  • An internal restore refuses to store types when the initiator is too old to check CREATE TYPE / DROP TYPE (coordination version 4).
  • CREATE TYPE rejects every case variant of a built-in name (enum8, uint8, ...).

Verification. clickhouse builds. Locally all 20 *user_defined_types* stateless tests, 01271_show_privileges and 01999_grant_with_replace pass, and so does test_replicated_user_defined_types with a new RESTORE ... ON CLUSTER case. Not covered by tests: restoring a backup of disk-storage servers with different types into shared Keeper, and the mixed-version guard.

Still open, need a reviewer's decision (unchanged, see the threads):

  • Linearizable dependency checks for truly concurrent type DDL on two servers (needs a versioned multi in the storage shared with user-defined functions).
  • Publishing a set of restored replacements atomically for concurrent readers (needs a batch store API in IUserDefinedSQLObjectsStorage).
  • Type names in persisted table expressions (ORDER BY CAST(x, 'T')): expand them at CREATE TABLE, or track table → type dependencies and reject DROP TYPE / incompatible replacement.

@vitlibar, your CHANGES_REQUESTED review still needs a re-review of the UserDefinedSQLObjectsStorage-based persistence.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

can be tested Allows running workflows for external contributors comp-data-types Type system & core datatypes used across query planning/execution. external Author is not a member of the ClickHouse organization pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants