Repository navigation
User defined types - #80373
User defined types#80373cucumber95 wants to merge 60 commits into
Conversation
|
Can you please give an example SQL how this user-defined type will be used? |
|
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. |
|
Needs tests. Needs docs. |
|
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. |
|
Hello @cucumber95 , The thing looks interesting and useful, would be nice to have it in ClickHouse. |
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]>
|
Workflow [PR], commit [ca49c70] Summary: ❌
|
…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]>
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]>
| 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); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 Partially addressed in 28ee762.
- Within one server:
CREATE TYPE,DROP TYPEand the restore of types now hold one mutex (UserDefinedTypeFactory::ddl_mutex) across validation and the write. SoDROP TYPE AandCREATE TYPE B AS Acan 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_typesnow checks that a type used onnode1cannot be dropped onnode2right 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.
| for (const auto & [type_name, create_type_query] : restored_types) | ||
| registerType(restore_context, type_name, create_type_query, throw_if_exists, replace_if_exists); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 Partially addressed in 28ee762.
- Validate first:
restorenow 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_rollbackmakes 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(amultirequest in ZooKeeper, one map swap in memory), which is shared with user-defined functions. I'm keeping this thread open for that design decision.
# 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]>
Preview approval requiredThis pull request comes from a fork, so Mintlify won't build a preview until someone with write access approves commit |
| backQuote(type_name), new_num_parameters, backQuote(use.dependent_type_name), use.num_arguments); | ||
| } | ||
|
|
||
| checkDependentsAfterReplacement(storage, type_name, normalized_query); |
There was a problem hiding this comment.
[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.
There was a problem hiding this comment.
🕵 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:
- Expand alias targets in persisted table expressions when a table is created (rewrite
CAST(x, 'ReviewKey')toCAST(x, 'UInt64')). Persisted tables would then never depend on a type by name. But the storedSHOW CREATE TABLEwould no longer match what the user wrote, and the type name would have to be found in string literals (CAST,::,toTypeName-style arguments,DEFAULTexpressions, projections, skipping indexes, TTL ...). - Track table → type dependencies (like
DatabaseCatalog's referential dependencies for dictionaries), and rejectDROP TYPEand incompatibleCREATE OR REPLACE TYPEwhile 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.
There was a problem hiding this comment.
🕵 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.
# 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]>
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]>
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]>
|
🕵 Merged current Merge. Five conflicts, both sides kept in each: CI of the previous run.
Review threads addressed in this push (replies are on the threads):
Verification. Still open, need a reviewer's decision (unchanged, see the threads):
@vitlibar, your |
Changelog category (leave one):
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:
You can see more examples in the tests
Workflow [PR]
Sync PR [sync-upstream/pr/80373]