Skip to content

Add --dump-schema option to clickhouse-client and clickhouse-local - #117784

Open
valerypetrov wants to merge 215 commits into
ClickHouse:masterfrom
valerypetrov:dump-database-schema
Open

valerypetrov wants to merge 215 commits into
ClickHouse:masterfrom
valerypetrov:dump-database-schema

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Sep 2, 2026 •

Copy link
Copy Markdown
Contributor

Supersedes #114098.

Closes: #60681

clickhouse-client and clickhouse-local get a --dump-schema option that prints the CREATE statements of databases and their tables, views, materialized views and dictionaries, each after the objects it depends on, so the output replays into another server: clickhouse-client --dump-schema=shop > shop.sql. With no value it dumps all user databases. --dump-schema-exclude=db1,db2 leaves some out, and --dump-schema-dir=<path> writes one <database>.sql file per database and prints the order to replay them in.

The dump starts with SET lines for only the settings its statements need, such as one allowing an experimental type. The server's own checks decide this, for example type and codec validation, or the source server's analyzer for a materialized view. When a check cannot decide, the setting is kept.

Named collections are not dumped, since their values can be credentials. Objects using one get a warning, as do objects with secrets masked as [HIDDEN] and dependencies on databases left out. The source server must be 26.6 or newer.

Changelog category (leave one):

  • New Feature

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

Added a --dump-schema option to clickhouse-client and clickhouse-local that prints the CREATE statements of databases and everything in them in an order that can be replayed into another server, similar to pg_dump --schema-only.

🤖 Generated with Claude Code


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

Rebased on latest master. All PR changes including:
- SchemaDumper.{cpp,h}: schema dump with dependency ordering, replay prelude,
  and ambiguity detection for database-less references
- enableAllExperimentalSettings: restructured to expose allExperimentalSettingNames()
- ClientBase/Client/LocalServer/ClientEmbedded: --dump-schema option wiring
- Chime uses clientElapsedSeconds() not server-reported elapsedSeconds()
- Tests and documentation

Replay prelude: shared experimental settings emitted unconditionally (CREATE
replay re-enters many of them); dump-specific gates (Ordinary, Replicated,
TimeSeries, Kafka, etc.) are gated by AST analysis. Dead settings (window
functions, hash functions, simdjson) excluded.

Undumped database rebinding: unqualified references and merge('', ...) checked
against undumped databases, not just dumped ones.

Round-trip tests: UniqueMergeTree replay, MATERIALIZED expression replay,
shared settings presence verification.

Co-authored-by: factory-droid[bot] <138933559+factory-droid[bot]@users.noreply.github.com>
valerypetrov and others added 4 commits September 4, 2026 08:58
The dump-schema change accidentally deleted seven lines of an unrelated
comment explaining why the chime threshold uses the client's own clock.
Put them back so the PR diff only touches what it is about.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Client.cpp now calls registerTableFunctions() so the schema dumper can
ask TableFunctionFactory about nested table functions. Only the unified
binary resolved that symbol through clickhouse-local-lib; link the
library explicitly, as clickhouse-local and clickhouse-format do.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
The masked-credentials section created an S3 table, but the fast test
builds with ENABLE_LIBRARIES=0, where the S3 engine does not exist, so
the CREATE failed and both counters came out 0. Use a dictionary whose
CLICKHOUSE source carries a PASSWORD: it is masked as [HIDDEN] through
the same show_secrets path and is always built.

The case-collision check grepped for 'would all be written to the same
file', while SchemaDumper.cpp says 'would be written to the same file',
so the grep printed nothing and the reference line never matched.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Two blank lines before the new test and the connect() call on one line,
as black (pinned in pyproject.toml) formats it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
@clickhouse-gh clickhouse-gh Bot added the comp-cli clickhouse-client (interactive CLI) and client library. label Sep 4, 2026
@shankar-iyer shankar-iyer added the can be tested Allows running workflows for external contributors label Sep 7, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [48239a2]

Summary: ❌

job_name test_name status info comment
Stateless tests (amd_asan_ubsan, db disk, distributed plan, targeted) FAIL
04836_client_dump_schema_7 FAIL cidb
04836_client_dump_schema_7 FAIL cidb
04836_client_dump_schema_7 FAIL cidb
Finish Workflow FAIL
python3 ./ci/jobs/scripts/workflow_hooks/can_be_merged.py --review-threads FAIL

AI Review

Summary

The PR adds schema DDL export to clickhouse-client and clickhouse-local, including dependency ordering, directory output, replay settings, and passive loading of a local data path. Changes are still needed: computed remote addresses can lose replay prerequisites, and two expression-evaluation paths can run external commands during export. Reviewed PR head: 48239a26aa0fec82ec3589550e72b8395c060e67.

Findings

⚠️ Majors

  • src/Client/SchemaDumper.cpp:994–996: Computed local addresses lose dependencies. A nested remote(concat('127.', '0.0.1'), 'd', 'zzz_src') is classified as remote because its address is not a literal. remoteFunctionArgumentsToSkip then discards its arguments. A persisted local Remote table wrapping this query in view can consequently precede zzz_src, causing replay to fail. Safely fold stable constant addresses before classification and refuse unresolved addresses. Existing finding remains open.

  • src/Databases/DatabaseOnDisk.cpp:158–159: Constant predictions bypass passive attachment. runsWhenFolded omits predictXGBoost. A persisted TTL ts DELETE WHERE k < predictXGBoost('d.model', toFloat64(1)) therefore reaches constant folding while loading the source. The prediction explicitly loads the model dictionary, whose constructor trains through its source's loadAll; an executable source runs its command. Disabling automatic dictionary loading does not prevent this. Enforce passive evaluation at a shared folding boundary or cover all dictionary-loading functions. New inline finding.

  • src/Client/SchemaDumper.cpp:5397–5400: Structure strings hide executable expressions from passive checks. A materialized view joining url with structure x UInt64 DEFAULT dictGetUInt64('d.rules', 'v', toUInt64(1)) passes the static-structure checks. The export's EXPLAIN QUERY TREE parses that structure in CREATE mode and folds the default, loading the dictionary and potentially running its executable source. Persisted AS url attachment also reparses the opaque structure despite cached columns. Validate parsed structure expressions before permitting either path, including generator structures. New inline finding.

Tests
  • ⚠️ Add a round trip with a computed loopback address whose source sorts after its consumer. Add command-marker preservation cases for constant model predictions and for dictionary lookups inside structure strings, covering both source-side probes and local attachment.
  • ⚠️ Fast test succeeded, but current-head stateless checks are skipped and the new schema tests are marked no-fasttest. A completed stateless run covering these cases is needed; no local tests were run in this CI review job. Current CI report.
Final Verdict

Status: ⚠️ Request changes

Preserve computed local dependencies and close both passive-evaluation gaps, with focused regression coverage.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Sep 7, 2026
Comment thread src/Client/SchemaDumper.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Sep 7, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 18ff102c9 with master f50e9454c (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

⚠️ Significant changes: object file sizes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes ⚠️

51 object files changed (+1.67 MiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Client/SchemaDumper.cpp.o new 1.57 MiB +1.57 MiB
src/CMakeFiles/dbms.dir/Databases/DatabaseOnDisk.cpp.o 509.05 KiB 528.35 KiB +19.30 KiB (+3.79%)
programs/local/CMakeFiles/clickhouse-local-lib.dir/LocalServer.cpp.o 858.82 KiB 874.84 KiB +16.03 KiB (+1.87%)

711 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.

Slowest function optimization changes (ThinLTO)

Median per-function time ratio to the master baseline: programs/clickhouse ×0.55, programs/clickhouse-keeper ×0.78 (each binary is linked separately, on a different machine and with different build flags); deltas below are relative to it.

Binary Function Master PR Δ vs median
programs/clickhouse _ZN6detail10static_forITk7is_enumN2DB23AttributeUnderlyingTypeEZNS1_29callOnDictionaryAttributeType… 3.6 s 7.0 s +5.0 s (+251%)
Compile time of recompiled translation units

335 translation units recompiled, 3420 s compile time in total, 334 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Client/SchemaDumper.cpp: 15.3 s

Job report

Commit 03bbab9 replaced it with a dictionary source password, on the
premise that Fast test (the only ENABLE_LIBRARIES=0 build) would fail the
S3 CREATE. That premise is wrong: the test is tagged `long` and Fast test
runs clickhouse-test with --no-long, so it never runs there at all.

Restore the S3 engine fixture, which is the form 04510 already asserts
[HIDDEN] for, and drop the comment that stated the false constraint. The
grep-pattern fix from the same commit is correct and is kept.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
@CLAassistant

CLAassistant commented Sep 10, 2026 •

Copy link
Copy Markdown

CLA assistant check
All committers have signed the CLA.

valerypetrov and others added 2 commits September 10, 2026 08:06
A database-less `joinGet('jj', ...)` can only bind a Join table and
`dictionary('d')`/`dictGet('d', ...)` only a dictionary, but the scan for
a competing binding keyed on the object name alone. A same-named
MergeTree table or view in another dumped or omitted database therefore
made the dump fail even though nothing could rebind on replay.

Carry the expected reference kind out of collectFunctionArgumentReferences
and skip candidates whose `system.tables.engine` cannot satisfy it; the
omitted-database lookup now fetches the engine as well.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Resolved src/Databases/enableAllExperimentalSettings.cpp: kept the PR's
allExperimentalSettingNames() list and added master's allow_experimental_trino_dialect to it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 2 commits September 11, 2026 05:48
The dumper skipped the whole argument list of remote()/remoteSecure()
unconditionally, but parseRemoteFunctionArguments marks loopback
replicas on the server's own port as local and TableFunctionRemote then
reads their tables (or the wrapped merge()) from the local catalog. A
view over remote('127.0.0.1', db, t) therefore got no edge to t and
could be emitted before it.

Classify remote*/cluster* calls through one predicate: an identifier
first argument names a configured cluster and reuses the cluster
locality, a literal pattern is expanded like the server does and a
replica is local when its host is loopback (by the same value rule as
isLocalAddress) and its port is the server's tcpPort() (tcp_port_secure
for remoteSecure, fetched lazily), except in clickhouse-local, which
treats any explicit port as remote. Local calls feed the same argument
and merge() walkers as local cluster() calls; other hosts stay remote,
as DDLDependencyVisitor already assumes.

Regression: views and a materialized view over loopback remote() with
and without an explicit port, and over remote('localhost', merge(...)),
must be dumped after their source.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
The materialized view read a dumped table in its FROM, which already put
it one dependency level above zzz_remote_src; levels are emitted in
order, so it came after its remote() source even when no remote() edge
was recorded. Read system.one instead (outside the dump set, so no
edge), leaving the remote() reference as the MV's only in-dump
dependency: without it the MV sits at level 0 and sorts before
zzz_remote_src, so the ordering assertion now exercises the fix.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
Claude-Session: https://claude.ai/code/session_01ScfL2iRpXjAYmAMoDLCmqY
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 3 commits September 16, 2026 16:54
Conflict in src/Databases/enableAllExperimentalSettings.cpp: kept this
branch's allExperimentalSettingNames() list and applied master's three
edits to it (drop allow_experimental_trino_dialect, renamed with no alias;
drop the two Iceberg compaction gates; add allow_delta_lake_create_table).

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
fetchStringColumn cast the result column to ColumnString directly, but the
queries it runs are constant-folded, and only the native protocol materializes
a constant on its way to the client. Over a local connection the block arrives
as a ColumnConst, so every clickhouse-local dump raised LOGICAL_ERROR: a plain
exception and an empty dump in release, an abort in debug and sanitizer builds.
The column is materialized before the cast, which also covers the two other
constant-folded queries.

The TimeSeries helper names also need the table version now, since a version
below the one that renamed the metric-families target still spells it `metrics`.
The dump asks for the current names and treats each older spelling the way it
already treats the legacy samples name: implicit only while the modern one is
absent, so a user table carrying that name stays in the dump.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
The test starts 130 clickhouse-local instances, and a sanitizer build spends
several seconds on each before any work happens, so the file cannot finish
inside the 600-second per-test deadline however fast the dump itself is. The
`long` tag does not extend that deadline; it only exempts a test from the
flaky check's runtime warning. The sections are split across three files with
every assertion kept, and the concatenated parts reproduce the original script
and reference byte for byte.

One section is dropped rather than moved: it created a UniqueMergeTree table,
an engine no open-source build registers, so the fixture failed with an unknown
engine before the section could test anything. The guarantee it checked, that
the emitted prelude carries the gates a replay needs, is already covered by the
TimeSeries and Ordinary section.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
Comment thread src/Client/SchemaDumper.cpp Resolved
The merge() ambiguity assertion greps for "more than one dumped database", but
the merge path prints "more than one database": that message also lists omitted
databases, tagged "(omitted)", so the broader wording is deliberate and it is
the grep that was wrong. The dump was refused all along.

The omitted-database reference assertion set up a plain unqualified table name
in a view body, but CREATE stamps the session database onto those identifiers
before storing the SELECT, so the stored reference is already unambiguous and
there is nothing to refuse. Use joinGet(), whose table argument is stored
verbatim, for the refusal, and assert separately that the plain-identifier shape
keeps its binding to the omitted database and reports it instead of rebinding.

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_01QtEKPyQDMCBZfJkiJcs789
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Databases/DatabaseOnDisk.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 2 commits November 13, 2026 12:28
…d reserved column names

A secondary index analyzed under the client's typing settings could throw and abort the whole dump, although the
server's own settings accept it; the analysis failure now decides nothing and the typing discovery picks the settings.
A sorting key probe that analyzed to a Variant was taken as proof, so the dump set the lossy numeric supertype off and
the replayed CREATE failed; the key probes now fail on a Variant, Dynamic or JSON key type.
Constraint subqueries now keep the correlated-subquery gate of their nested subqueries and the Dynamic join gate of a
JOIN in a query that `eval` generates. The table form of a local CLICKHOUSE dictionary source contributes its WHERE
dependencies to the creation order. Master added `allow_reserved_column_names`; a MergeTree column whose name starts
with `_` now carries it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 4 commits November 15, 2026 16:35
…ema_2

master reverted ClickHouse#114923, so CREATE no longer stores the joinGet table name
with the session database. The stored name is database-less again, and
--dump-schema refuses it like a database-less dictionary() reference, because
it would rebind on replay. The test expected the qualified name and failed
on every job.

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

A minmax index such as `if(a > 0, toDecimal64(a, 2), 0.5)` is a `Float64`
on a source with `allow_lossy_numeric_supertype = 1`, but a client on default
settings analyzed it as a `Variant` and refused the dump before the typing
settings were picked. The early check now passes an index that fits under
some combination of the typing settings, and the typing probe of a minmax
index fails on `Variant` and `Dynamic`, so the dump picks the setting.

A dictionary source `QUERY` with the `{condition}` placeholder did not
parse, so the tables it reads were not ordered before an eager dictionary.
The placeholder is removed before parsing, like the source does at load.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Master now makes the system database of clickhouse-local persistent when
system logs are configured, so a dump created metadata/system.sql and
data/system in the source it reads (04836_client_dump_schema_19). A dump
starts no system logs, so it keeps the in-memory system database.

Master also refuses CREATE TABLE ... AS loop(...), so the ordering case of
04836_client_dump_schema_13 uses merge() instead.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread programs/local/LocalServer.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
…running dictionary commands

A database loaded with load_tables_readonly has no replication handler, so
reading the definition of a MaterializedPostgreSQL table dereferenced a null
pointer. The stored definition is returned instead.

A TTL or a projection that calls a dictionary function on constants is folded
when the table is attached, which loads the dictionary and runs the command of
an executable source. Such a table is refused like a stored table function
argument already is.

The table form of a dictionary source selects the attribute expressions too, so
an eager dictionary now comes after the objects those expressions read.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Databases/DatabaseOnDisk.cpp Resolved
# Conflicts:
#	programs/client/Client.cpp
#	src/Databases/PostgreSQL/DatabaseMaterializedPostgreSQL.cpp
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 4 commits November 22, 2026 18:10
`clickhouse-local --path <source> --dump-schema` attaches the stored tables with `load_tables_readonly` and must run no stored command. Three places still did:

- A `CONSTRAINT` was analyzed at attach, which runs its scalar subqueries (and folds a `dictGet` on constants inside them), so a subquery over an `Executable` table or a dictionary with an executable source ran its command. With `load_tables_readonly` the stored constraints are now taken as they are, without the analysis. A table whose constraint subquery calls a table function could not be loaded this way at all (`THERE_IS_NO_QUERY`), and is dumped now.
- A scalar subquery in an argument of an engine or of an `AS` table function that is folded at attach, such as `url((SELECT ...), ...)`, ran. Such a table is now refused with `NOT_IMPLEMENTED`, like an argument that loads a dictionary. The table function that `remote`, `cluster` and the `Remote` engine read through, and a query inside an argument such as the one of `view`, are not run at attach and stay loadable.
- The key and the assignments of a TTL `GROUP BY ... SET` are kept outside the children of `ASTTTLElement`, so a `dictGet` on constants there was not seen by the check that refuses it in the TTL expression itself.

The dump itself also folded the table function nested in `remote` as if it were a table name, which ran the scalar subqueries of `view(SELECT (SELECT ...))` in the dumping process. It is no longer folded.

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

The solver of the typing settings made the probe of an index expression
fail on a `Variant` or `Dynamic` result only for a minmax index. An
expression such as `if(a > 0, toDecimal64(a, 2), 0.5)` analyzes with
`allow_lossy_numeric_supertype = 0` too, as a `Variant`, so for a
bloom_filter or vector_similarity index the dump carried
`SET allow_lossy_numeric_supertype = 0` and no warning that the storage
expressions need the setting in the replaying server's profile, although
the validators of these indexes refuse such a type and the CREATE fails
without it.

The probe now does the same for every index type whose validator refuses
a `Variant`: minmax, bloom_filter, ngrambf_v1, tokenbf_v1, sparse_grams,
vector_similarity and text. The validator of a set index checks no type,
so its probe stays as it was.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
…a` like the server does

An eager dictionary runs the query of its local `CLICKHOUSE` source at CREATE, so the dump has to put what the query reads before the dictionary. Two cases were missed, and the dump could not be replayed.

The source was taken as local only when `HOST` was exactly `localhost`, `127.0.0.1` or `::1`. The server resolves the host and compares the port, so `HOST 'LOCALHOST'` or the server's own host name is local too, and `localhost` with a port that is not the server's is not. The host now goes through `remoteAddressLocality`, the metadata-only check that `remote` addresses use, and an explicit `PORT` is compared with the server's port, the secure one under `SECURE 1`. A host that is not shown to be this server still gives no dependency, and no host is contacted.

The source query was only parsed, so a table named only inside a setting such as `filter` stayed a string. The server runs the query through `executeQuery`, which turns such settings into query text. The query is now parsed by `parseSelectWithConstructionSettings`, the code `eval` already used for the same purpose.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Databases/DatabaseOnDisk.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 3 commits November 23, 2026 22:36
With `load_tables_readonly`, `checkExpressionsLoadPassively` walked the
table TTL, the column TTLs and the projections, but not the secondary
indexes, and it looked only for calls that load a dictionary or run a
user-defined function.

A secondary index such as `INDEX i k + dictGetUInt64('d.rules', 'v', toUInt64(1))`
is rejected by `CREATE`, but a table attached with its full definition can
hold one. Loading it folded the call, which loaded the dictionary and ran
the command of its source, before `--dump-schema` refused the table for
its non-deterministic index. The index expressions are now walked too, so
the table is refused before anything runs. A call that reads a column is
not folded and still passes the load, as for a TTL.

A subquery in `TTL ... DELETE WHERE` or in a projection, scalar or under
`IN`, is accepted by `CREATE` and was run when the table was loaded, so
`--dump-schema` of a data path ran an `Executable` table it read. Such a
subquery is now refused the same way as one in the engine arguments.

The server path without `load_tables_readonly` is unchanged.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
… in `--dump-schema`

`--dump-schema` orders an eager dictionary after the tables its local
`CLICKHOUSE` source query reads. Four forms of the source were still read
differently from how the server reads them, so the dump put the dictionary
before a table it needs and the replay failed:

- A quoted flag or port, such as `SECURE 'false'` or `PORT '9000'`, and a
  boolean literal. The source reads both from the text of the value
  (`getBool`, `getUInt`), so the same spellings are accepted now. A value
  that cannot be read still counts as not shown to be this server.
- A repeated key, such as two `QUERY` pairs. The source reads the first one,
  the dump read the last one.
- A construction setting (`select`, `filter`, `order`, `sort`) in the
  dictionary's own `SETTINGS`. The source runs its query under these
  settings, so they are passed to `parseSelectWithConstructionSettings` as
  the settings around the query; a `SETTINGS` clause of the query itself
  overrides them as it does on the server.
- A host that the server's metadata does not show to be this server, such as
  an interface address. The source query was skipped without a word. Now it
  is read as for a `remote` call with such an address: a table of the dump
  it names gives a warning, no order and no refusal. A foreign port still
  gives neither.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 4 commits November 24, 2026 09:25
…-schema`

The walker that finds what a stored CREATE reads at CREATE visited only
`children`, but a TTL element keeps its `GROUP BY` keys and `SET`
assignments apart from them. A table with

    TTL ts GROUP BY k SET y = max(predictXGBoost('d.zzz_model', x1, x2))

lost its dependency on the model dictionary and was dumped before it. CREATE
analyzes the assignment and `predictXGBoost` resolves the dictionary then, so
the replay failed. The walker now visits the keys and assignments too, as
`forEachNode` does.

04836_client_dump_schema_48 replays such a table with the model fixture of
04836_client_dump_schema_41.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
… leaking, in `--dump-schema`

`--dump-schema` collected the typing settings carried by the tables a CREATE
reads only for constraint subqueries. A materialized view selecting an ALIAS
column, which CREATE expands with the session's settings, got no settings
before it, so it ran with whatever an earlier table of the dump had set:

    SET allow_lossy_numeric_supertype = 1;
    CREATE TABLE d.b_lossy (... DEFAULT arraySum([toDecimal64(a, 2), 0.5]));
    CREATE MATERIALIZED VIEW d.mv ENGINE = Memory AS SELECT v FROM d.a_src;

where `v` is `toString(variantType(if(a > 0, toDecimal64(a, 2), 0.5)))`, and
the replay failed in `variantType`.

- The settings that the ALIAS columns of the tables a materialized view's
  SELECT names carry are now its settings too. The probe of the view
  analyzes its SELECT, which expands those columns as CREATE does, so they
  take the probed values, not the dump session's. A view it reads is
  expanded neither by CREATE nor by the probe, so it adds nothing.
- A typing setting that an earlier CREATE's prefix set and the next CREATE
  does not pick is set back to the dump session's value, the value the dump
  keeps for what it cannot tell, before that CREATE. The analyzer gates are
  not reset: they only allow more, and the prelude may set them.

04836_client_dump_schema_49 replays the three objects dumped from the
default session and from a session with numeric promotion, and a table
whose constraint subquery reads the ALIAS column through `merge`, which the
dump does not see, so it picks no typing setting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…--dump-schema`

The named collection scan parsed the raw `QUERY`, `WHERE` and
`invalidate_query` strings of a `CLICKHOUSE` dictionary source. It did not
expand the query construction settings, of the query itself or of the
dictionary's `SETTINGS`, under which the source runs its query, so a
collection read only through one, as in

    QUERY 'SELECT ... SETTINGS filter = ''id IN (SELECT id FROM url(nc))'''

was not reported, and an eager dictionary failed on replay without a word.

The query the source runs is now read once, by `readDictionarySourceQuery`,
for both the table order and the named collection scan: the first of
repeated keys, the table form with its `WHERE`, without `{condition}`, and
with the construction settings expanded. `invalidate_query` is parsed under
the dictionary's settings too.

04836_client_dump_schema_50 covers a collection read through a setting of the
source query and through a setting of the dictionary.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment thread src/Databases/DatabaseOnDisk.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
valerypetrov and others added 2 commits November 24, 2026 14:45
The guard that refuses a table whose TTL, projection or secondary index
would load a dictionary when its expressions are folded looked only at the
raw expressions. A projection or an index analyzes an `ALIAS` column it
reads in its place, so a constant lookup behind one, as in

    a UInt64 ALIAS dictGetUInt64('d.rules', 'v', toUInt64(1)),
    PROJECTION p (SELECT x + a ORDER BY x)

passed the guard and ran the dictionary's source during the dump. The
guard now follows `ALIAS` columns, both into the checked expressions and
when it decides whether a lookup key reads a column.

A dictionary key built through a lambda is not folded when the table is
loaded, so it runs nothing; the test covers that too.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A dictionary attribute `EXPRESSION` can be a string holding SQL, which the
source runs unquoted. The query synthesized for the table form of a
`CLICKHOUSE` source kept the quotes, so a dependency or a named collection
read only inside such an expression, as in

    v UInt64 EXPRESSION '(SELECT max(id) FROM d.zzz_src)'

was missed, and an eager dictionary was emitted before what it reads.
`getAttributeExpression` of the dictionary configuration is now shared and
used for it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Comment on lines +158 to +159
return Poco::toLower(call.name).starts_with("dict") || UserDefinedSQLFunctionFactory::instance().has(call.name)
|| UserDefinedExecutableFunctionFactory::has(call.name, context);

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.

[Major] Keep constant predictXGBoost calls out of passive attachment.

This predicate omits predictXGBoost, although folding it loads a dictionary. With enable_xgboost = 1 and an executable-source XGBOOST dictionary d.model with one feature, this is a valid persisted table:

CREATE TABLE d.t
(
    ts DateTime,
    k UInt64,
    dep UInt8 DEFAULT dictHas('d.model', k)
)
ENGINE = MergeTree ORDER BY k
TTL ts DELETE WHERE k < predictXGBoost('d.model', toFloat64(1));

The typed, nonconstant default establishes the dictionary's loading dependency without evaluating it during attachment. The TTL prediction passes this guard, then TTLDescription::getTTLFromAST builds its actions. predictXGBoost permits constant folding, and its default dry-run implementation calls executeImpl; the constant arguments give it one row, so it calls getDictionary. Constructing XGBoostDictionary trains the model through its source's loadAll.

Consequently, clickhouse-local --path <source> --enable_xgboost=1 --dump-schema=d can execute the dictionary's command and change the source before the first export query, despite automatic dictionary loading being disabled. Please enforce passive evaluation at a shared folding boundary, or include every dictionary-loading function in this guard, and add a command-marker preservation case for a constant prediction.

Comment on lines +5397 to +5400
}
/// Virtual columns of MergeTree start with `_`; a fresh CREATE refuses such a column name without the gate.
for (const auto & column : columns)
needs.reserved_column_names |=

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.

[Major] Inspect structure expressions before treating a table function as passive.

A nonempty literal structure can contain executable expressions. For example, this stored materialized view passes the static-structure and passive-analysis checks:

CREATE MATERIALIZED VIEW d.mv ENGINE = Memory AS
SELECT s.x AS x
FROM d.src AS s
INNER JOIN url('http://127.0.0.1:1/unused', 'TSV',
    'x UInt64 DEFAULT dictGetUInt64(''d.rules'', ''v'', toUInt64(1))') AS u
ON s.x = u.x;

The walkers see only the structure's string literal, so the dump sends EXPLAIN QUERY TREE. Resolving url calls parseColumnsListFromString, which calls getColumnsDescription in CREATE mode and validates/folds the default. The constant lookup explicitly loads d.rules; after restart with a lazy dictionary, that can contact its external source or run its executable command during the schema export. The endpoint in the URL itself need not be read.

The same opaque structure also passes checkArgumentsLoadPassively for a persisted CREATE TABLE ... AS url(...); ITableFunction::execute checks the actual static structure even with cached columns, so local attachment has the same hole.

Please apply passive-expression validation to parsed structure declarations wherever they are consumed, including generator structures, before allowing either path. Add command-marker cases proving that both exports leave an unloaded executable dictionary unloaded.

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-cli clickhouse-client (interactive CLI) and client library. external Author is not a member of the ClickHouse organization manual approve Manual approve required to run CI pr-feature Pull request with new product feature

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Command to dump database schema

5 participants