Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Dynamic data type #63058

Merged
merged 39 commits into from
May 23, 2024
Merged

Implement Dynamic data type #63058

merged 39 commits into from
May 23, 2024

Conversation

Avogar
Copy link
Member

@Avogar Avogar commented Apr 26, 2024

Changelog category (leave one):

  • New Feature

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

Implement Dynamic data type that allows to store values of any type inside it without knowing all of them in advance.
Dynamic type is available under a setting allow_experimental_dynamic_type.
Reference: #54864

Documentation entry for user-facing changes

Dynamic

This type allows to store values of any type inside it without knowing all of them in advance.

To declare a column of Dynamic type, use the following syntax:

<column_name> Dynamic(max_types=N)

Where N is an optional parameter between 1 and 255 indicating how many different data types can be stored inside a column with type Dynamic across single block of data that is stored separately (for example across single data part for MergeTree table). If this limit is exceeded, all new types will be converted to type String. Default value of max_types is 32.

Creating Dynamic

Using Dynamic type in table column definition:

CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT d, dynamicType(d) FROM test;
┌─d─────────────┬─dynamicType(d)─┐
│ ᴺᵁᴸᴸ          │ None           │
│ 42            │ Int64          │
│ Hello, World! │ String         │
│ [1,2,3]       │ Array(Int64)   │
└───────────────┴────────────────┘

Using CAST from ordinary column:

SELECT 'Hello, World!'::Dynamic as d, dynamicType(d);
┌─d─────────────┬─dynamicType(d)─┐
│ Hello, World! │ String         │
└───────────────┴────────────────┘

Using CAST from Variant column:

SET allow_experimental_variant_type = 1, use_variant_as_common_type = 1;
SELECT multiIf((number % 3) = 0, number, (number % 3) = 1, range(number + 1), NULL)::Dynamic AS d, dynamicType(d) FROM numbers(3)
┌─d─────┬─dynamicType(d)─┐
│ 0     │ UInt64         │
│ [0,1] │ Array(UInt64)  │
│ ᴺᵁᴸᴸ  │ None           │
└───────┴────────────────┘

Reading Dynamic nested types as subcolumns

Dynamic type supports reading a single nested type from a Dynamic column using the type name as a subcolumn.
So, if you have column d Dynamic you can read a subcolumn of any valid type T using syntax d.T,
this subcolumn will have type Nullable(T) if T can be inside Nullable and T otherwise. This subcolumn will
be the same size as original Dynamic column and will contain NULL values (or empty values if T cannot be inside Nullable)
in all rows in which original Dynamic column doesn't have type T.

Dynamic subcolumns can be also read using function dynamicElement(dynamic_column, type_name).

Examples:

CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT d, dynamicType(d), d.String, d.Int64, d.`Array(Int64)`, d.Date, d.`Array(String)` FROM test;
┌─d─────────────┬─dynamicType(d)─┬─d.String──────┬─d.Int64─┬─d.Array(Int64)─┬─d.Date─┬─d.Array(String)─┐
│ ᴺᵁᴸᴸ          │ None           │ ᴺᵁᴸᴸ          │    ᴺᵁᴸᴸ │ []             │   ᴺᵁᴸᴸ │ []              │
│ 42            │ Int64          │ ᴺᵁᴸᴸ          │      42 │ []             │   ᴺᵁᴸᴸ │ []              │
│ Hello, World! │ String         │ Hello, World! │    ᴺᵁᴸᴸ │ []             │   ᴺᵁᴸᴸ │ []              │
│ [1,2,3]       │ Array(Int64)   │ ᴺᵁᴸᴸ          │    ᴺᵁᴸᴸ │ [1,2,3]        │   ᴺᵁᴸᴸ │ []              │
└───────────────┴────────────────┴───────────────┴─────────┴────────────────┴────────┴─────────────────┘
SELECT toTypeName(d.String), toTypeName(d.Int64), toTypeName(d.`Array(Int64)`), toTypeName(d.Date), toTypeName(d.`Array(String)`)  FROM test LIMIT 1;
┌─toTypeName(d.String)─┬─toTypeName(d.Int64)─┬─toTypeName(d.Array(Int64))─┬─toTypeName(d.Date)─┬─toTypeName(d.Array(String))─┐
│ Nullable(String)     │ Nullable(Int64)     │ Array(Int64)               │ Nullable(Date)     │ Array(String)               │
└──────────────────────┴─────────────────────┴────────────────────────────┴────────────────────┴─────────────────────────────┘
SELECT d, dynamicType(d), dynamicElement(d, 'String'), dynamicElement(d, 'Int64'), dynamicElement(d, 'Array(Int64)'), dynamicElement(d, 'Date'), dynamicElement(d, 'Array(String)') FROM test;```
┌─d─────────────┬─dynamicType(d)─┬─dynamicElement(d, 'String')─┬─dynamicElement(d, 'Int64')─┬─dynamicElement(d, 'Array(Int64)')─┬─dynamicElement(d, 'Date')─┬─dynamicElement(d, 'Array(String)')─┐
│ ᴺᵁᴸᴸ          │ None           │ ᴺᵁᴸᴸ                        │                       ᴺᵁᴸᴸ │ []                                │                      ᴺᵁᴸᴸ │ []                                 │
│ 42            │ Int64          │ ᴺᵁᴸᴸ                        │                         42 │ []                                │                      ᴺᵁᴸᴸ │ []                                 │
│ Hello, World! │ String         │ Hello, World!               │                       ᴺᵁᴸᴸ │ []                                │                      ᴺᵁᴸᴸ │ []                                 │
│ [1,2,3]       │ Array(Int64)   │ ᴺᵁᴸᴸ                        │                       ᴺᵁᴸᴸ │ [1,2,3]                           │                      ᴺᵁᴸᴸ │ []                                 │
└───────────────┴────────────────┴─────────────────────────────┴────────────────────────────┴───────────────────────────────────┴───────────────────────────┴────────────────────────────────────┘

To know what variant is stored in each row function dynamicType(dynamic_column) can be used. It returns String with value type name for each row (or 'None' if row is NULL).

Example:

CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (NULL), (42), ('Hello, World!'), ([1, 2, 3]);
SELECT dynamicType(d) from test;
┌─dynamicType(d)─┐
│ None           │
│ Int64          │
│ String         │
│ Array(Int64)   │
└────────────────┘

Reading Dynamic type from the data

All text formats (TSV, CSV, CustomSeparated, Values, JSONEachRow, etc) supports reading Dynamic type. During data parsing ClickHouse tries to infer the type of each value and use it during insertion to Dynamic column.

Example:

SELECT
    d,
    dynamicType(d),
    dynamicElement(d, 'String') AS str,
    dynamicElement(d, 'Int64') AS num,
    dynamicElement(d, 'Float64') AS float,
    dynamicElement(d, 'Date') AS date,
    dynamicElement(d, 'Array(Int64)') AS arr
FROM format(JSONEachRow, 'd Dynamic', $$
{"d" : "Hello, World!"},
{"d" : 42},
{"d" : 42.42},
{"d" : "2020-01-01"},
{"d" : [1, 2, 3]}
$$)
┌─d─────────────┬─dynamicType(d)─┬─str───────────┬──num─┬─float─┬───────date─┬─arr─────┐
│ Hello, World! │ String         │ Hello, World! │ ᴺᵁᴸᴸ │  ᴺᵁᴸᴸ │       ᴺᵁᴸᴸ │ []      │
│ 42            │ Int64          │ ᴺᵁᴸᴸ          │   42 │  ᴺᵁᴸᴸ │       ᴺᵁᴸᴸ │ []      │
│ 42.42         │ Float64        │ ᴺᵁᴸᴸ          │ ᴺᵁᴸᴸ │ 42.42 │       ᴺᵁᴸᴸ │ []      │
│ 2020-01-01    │ Date           │ ᴺᵁᴸᴸ          │ ᴺᵁᴸᴸ │  ᴺᵁᴸᴸ │ 2020-01-01 │ []      │
│ [1,2,3]       │ Array(Int64)   │ ᴺᵁᴸᴸ          │ ᴺᵁᴸᴸ │  ᴺᵁᴸᴸ │       ᴺᵁᴸᴸ │ [1,2,3] │
└───────────────┴────────────────┴───────────────┴──────┴───────┴────────────┴─────────┘
  • Documentation is written (mandatory for new features)

Information about CI checks: https://clickhouse.com/docs/en/development/continuous-integration/

@robot-clickhouse robot-clickhouse added the pr-feature Pull request with new product feature label Apr 26, 2024
@robot-clickhouse
Copy link
Member

robot-clickhouse commented Apr 26, 2024

This is an automated comment for commit 48cab9e with description of existing statuses. It's updated for the latest CI running

❌ Click here to open a full report in a separate page

Check nameDescriptionStatus
A SyncThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS⏳ pending
AST fuzzerRuns randomly generated queries to catch program errors. The build type is optionally given in parenthesis. If it fails, ask a maintainer for help❌ failure
CI runningA meta-check that indicates the running CI. Normally, it's in success or pending state. The failed status indicates some problems with the PR⏳ pending
Flaky testsChecks if new added or modified tests are flaky by running them repeatedly, in parallel, with more randomization. Functional tests are run 100 times with address sanitizer, and additional randomization of thread scheduling. Integrational tests are run up to 10 times. If at least once a new test has failed, or was too long, this check will be red. We don't allow flaky tests, read the doc❌ failure
Integration testsThe integration tests report. In parenthesis the package type is given, and in square brackets are the optional part/total tests❌ failure
Mergeable CheckChecks if all other necessary checks are successful❌ failure
Stateless testsRuns stateless functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc❌ failure
Successful checks
Check nameDescriptionStatus
ClickBenchRuns [ClickBench](https://github.com/ClickHouse/ClickBench/) with instant-attach table✅ success
ClickHouse build checkBuilds ClickHouse in various configurations for use in further steps. You have to fix the builds that fail. Build logs often has enough information to fix the error, but you might have to reproduce the failure locally. The cmake options can be found in the build log, grepping for cmake. Use these options and follow the general build process✅ success
Compatibility checkChecks that clickhouse binary runs on distributions with old libc versions. If it fails, ask a maintainer for help✅ success
Docker keeper imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docker server imageThe check to build and optionally push the mentioned image to docker hub✅ success
Docs checkBuilds and tests the documentation✅ success
Fast testNormally this is the first check that is ran for a PR. It builds ClickHouse and runs most of stateless functional tests, omitting some. If it fails, further checks are not started until it is fixed. Look at the report to see which tests fail, then reproduce the failure locally as described here✅ success
Install packagesChecks that the built packages are installable in a clear environment✅ success
PR CheckThere's no description for the check yet, please add it to tests/ci/ci_config.py:CHECK_DESCRIPTIONS✅ success
Performance ComparisonMeasure changes in query performance. The performance test report is described in detail here. In square brackets are the optional part/total tests✅ success
Stateful testsRuns stateful functional tests for ClickHouse binaries built in various configurations -- release, debug, with sanitizers, etc✅ success
Stress testRuns stateless functional tests concurrently from several clients to detect concurrency-related errors✅ success
Style checkRuns a set of checks to keep the code style clean. If some of tests failed, see the related log from the report✅ success
Unit testsRuns the unit tests for different release types✅ success
Upgrade checkRuns stress tests on server version from last release and then tries to upgrade it to the version from the PR. It checks if the new server can successfully startup without any errors, crashes or sanitizer asserts✅ success

@Avogar Avogar marked this pull request as ready for review April 30, 2024 18:51
@fm4v
Copy link
Member

fm4v commented Apr 30, 2024

SELECT * FROM test hangs with max_types=255 and big number of types (265). Insert is just too long.

time pastila https://pastila.nl/?0006e67d/a572a7de6ab9f44442835cce2da1b056#fphVwtwR/+/3DogkorMtUA== | clickhouse client -n --echo

@Avogar
Copy link
Member Author

Avogar commented Apr 30, 2024

SELECT * FROM test hangs with max_types=255 and big number of types (265):

It works well for me (with release build downloaded from the CI): https://pastila.nl/?00029bb2/ef837fea9f5ea85db2f5edfb5a6f5ab1#YdWQhOS+QIaDkfwyhvftSA==

In interactive mode works too: https://pastila.nl/?0001557a/19a1bd199f27efef1253e18504146390#wVSn7Qee2pJN02q0RTgV6w==

Insert takes around 0.5 sec

@fm4v
Copy link
Member

fm4v commented Apr 30, 2024

It works well for me (with release build downloaded from the CI)

Yes, problem was in debug build

Two things here:

  1. Variant instead of Dynamic in exception message Variant(String)
  2. Which functions will be supported for Dynamic type?
SELECT cityHash64(CAST('Hello, World!', 'Dynamic'))

Received exception from server (version 24.4.1):
Code: 48. DB::Exception: Received from localhost:9000. DB::Exception: Method getDataAt is not supported for Variant(String): In scope SELECT cityHash64(CAST('Hello, World!', 'Dynamic')). (NOT_IMPLEMENTED)

@Avogar
Copy link
Member Author

Avogar commented Apr 30, 2024

Variant instead of Dynamic in exception message Variant(String)

Dynamic stores Variant inside, so we just propogated getDataAt method to nested Variant and it throws excetpion that this method is not supported. It's kind of expected, but better to improve exception message here, agree.

Which functions will be supported for Dynamic type?

Similar to Variant, only few functions can work with Dynamic: CAST/dynamicElement/dynamicType/isNull/isNotNull. More functions can be added later if there will be need for it (if you think that we need to support Variant/Dynamic for some functions, feel free to suggest, I will add support). Types Variant/Dynamic are designed for parsing/storing/extracting values of different types, so it's expected that the user will extract required type before using any functions or cast Dynamic to some type (for example to String, or to numeric type if all stored types are numeric, etc).

@fm4v
Copy link
Member

fm4v commented Apr 30, 2024

Can't filter by int because of types mismatch.

pastila https://pastila.nl/?020c4c9a/70fae8e3f2a3ec6cecfae4f50773aad6#Hwy2AegPJJpwM28TIeWiHg== | clickhouse client -n --echo

SET allow_experimental_dynamic_type=1;
DROP TABLE IF EXISTS test;
CREATE TABLE test (d Dynamic) ENGINE = Memory;
INSERT INTO test VALUES (42);
SELECT d, dynamicType(d) FROM test;
42	Int64
SELECT * FROM test WHERE d == 42;
Received exception from server (version 24.4.1):
Code: 43. DB::Exception: Received from localhost:9000. DB::Exception: Illegal types of arguments (Dynamic, UInt8) of function equals: In scope SELECT * FROM test WHERE d = 42. (ILLEGAL_TYPE_OF_ARGUMENT)
(query: SELECT * FROM test WHERE d == 42;)

@Avogar
Copy link
Member Author

Avogar commented May 1, 2024

Can't filter by int because of types mismatch.

It's expected, value of Dynamic column can be compared only with value of another Dynamic column, otherwise we don't know with wich type to compare. Please, see documentation (there is also a note how to filter):
https://github.com/ClickHouse/ClickHouse/blob/3b9f593524ba27105864464f41d8b3e858d163f9/docs/en/sql-reference/data-types/dynamic.md#comparing-values-of-dynamic-type

@antonio2368 antonio2368 self-assigned this May 1, 2024
src/Columns/ColumnDynamic.cpp Outdated Show resolved Hide resolved
src/Columns/ColumnDynamic.cpp Outdated Show resolved Hide resolved
src/Columns/ColumnDynamic.cpp Outdated Show resolved Hide resolved
src/Columns/ColumnDynamic.cpp Show resolved Hide resolved
src/Columns/ColumnDynamic.cpp Outdated Show resolved Hide resolved
src/Formats/FormatSettings.h Show resolved Hide resolved
src/Interpreters/InterpreterInsertQuery.cpp Outdated Show resolved Hide resolved
tests/queries/0_stateless/02941_variant_type_4.sh Outdated Show resolved Hide resolved
@Avogar Avogar enabled auto-merge May 23, 2024 12:09
@Avogar Avogar disabled auto-merge May 23, 2024 12:17
@Avogar Avogar added this pull request to the merge queue May 23, 2024
Merged via the queue into ClickHouse:master with commit 30dce78 May 23, 2024
224 of 235 checks passed
@Avogar Avogar deleted the dynamic-data-type branch May 23, 2024 14:45
@robot-ch-test-poll2 robot-ch-test-poll2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 23, 2024
robot-clickhouse-ci-1 added a commit that referenced this pull request May 23, 2024
…e4eea94f975a6cb9847d497f0cbd8

Cherry pick #63058 to 24.5: Implement Dynamic data type
alexey-milovidov added a commit that referenced this pull request May 23, 2024
Backport #63058 to 24.5: Implement Dynamic data type
@robot-ch-test-poll4 robot-ch-test-poll4 added pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-backports-created-cloud labels May 23, 2024
baibaichen added a commit to Kyligence/gluten that referenced this pull request May 24, 2024
baibaichen added a commit to apache/incubator-gluten that referenced this pull request May 24, 2024
* [GLUTEN-1632][CH]Daily Update Clickhouse Version (20240524)

* Fix build due to ClickHouse/ClickHouse#63058

---------

Co-authored-by: kyligence-git <gluten@kyligence.io>
Co-authored-by: Chang Chen <baibaichen@gmail.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
pr-backports-created Backport PRs are successfully created, it won't be processed by CI script anymore pr-backports-created-cloud pr-feature Pull request with new product feature pr-synced-to-cloud The PR is synced to the cloud repo v24.5-must-backport
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

9 participants