Skip to content

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

Closed
valerypetrov wants to merge 1 commit into
ClickHouse:masterfrom
valerypetrov:dump-database-schema
Closed

valerypetrov wants to merge 1 commit into
ClickHouse:masterfrom
valerypetrov:dump-database-schema

Conversation

@valerypetrov

@valerypetrov valerypetrov commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor

Closes: #60681

Adds a --dump-schema[=<db1,db2,...>] option that dumps CREATE DATABASE/CREATE TABLE/CREATE DICTIONARY/CREATE MATERIALIZED VIEW/CREATE VIEW statements for one or more databases, or all non-system user databases if no value is given, to stdout, then exits — similar to pg_dump --schema-only.

Tables are ordered (via TablesDependencyGraph, the same class DatabaseCatalog uses to load tables at startup and backups use to order their restore; ties within a level broken by (database, name) for determinism) using every dependency signal system.tables exposes, combined: loading_dependencies_* (dictionaries), inverted dependencies_* (a materialized view's source — recorded only on the source row, not the view), target_database/target_table (a materialized view's TO target, explicit or implicit), and — since the server tracks none of this for plain views at all (DROP TABLE on a view's source succeeds even with the view still referencing it) — a best-effort scan of each view's stored, server-formatted SELECT text for other dumped tables' names. A genuine dependency cycle is a clear error rather than being silently reordered.

This is entirely a client-side feature: system.tables.create_table_query and SHOW CREATE DATABASE already give the server-computed DDL text, so no server-side or wire-protocol changes are needed — the new code (src/Client/SchemaDumper.{h,cpp}) just issues a couple of queries over the existing connection (same pattern as Suggest.cpp) and prints the results in dependency order.

--dump-schema also accepts a comma-separated database list (--dump-schema=db1,db2), and two modifiers:

  • --dump-schema-exclude=db1,db2 dumps all user databases except the listed ones (rejected if combined with an explicit database list — the two are mutually exclusive ways of selecting the same thing).
  • --dump-schema-dir=<path> writes one <database>.sql file per dumped database into that directory (created if it doesn't exist, e.g. mkdir clickhouse-lab && clickhouse-client --dump-schema --dump-schema-exclude=... --dump-schema-dir=clickhouse-lab) instead of writing everything to stdout. Database names are escaped with escapeForFileName before being used as filenames; two target databases whose escaped names collide case-insensitively are rejected unconditionally (regardless of the destination filesystem's actual case sensitivity — reliably probing that portably isn't worth it when the point of a dump is to be replayed somewhere else later anyway), rather than one silently overwriting the other's file. Per-database write failures are detected instead of reported as success, and when a table in one dumped database depends on a table in another, the files (and their confirmation lines) are ordered — and a note printed — so replaying them in the printed order works; a database-level circular dependency (distinct from, and not implied by, a table-level cycle) is rejected with a clear error since no file order could satisfy it.

A few things worth calling out for review:

  • Implicit materialized-view storage tables are excluded from the dump (recreated automatically by their owning CREATE MATERIALIZED VIEW statement) — but only when confirmed to be a live materialized view's own target with the generated-name shape (.inner_id.*/.inner.*), not merely name-shaped like one, so a real user table literally named `.inner.foo` stays in the dump. Orphaned mid-refresh leftovers (.tmp.inner_id.*/.tmp.inner.*) are filtered by name, since they're never any live target.
  • --dump-schema forces non-interactive mode (like --query/--queries-file) and is rejected if combined with either of them, so its stdout is never mixed with an interactive banner, warnings, or another query's output. For clickhouse-local, it's also rejected combined with --file/--structure. --dump-schema-exclude/--dump-schema-dir are rejected if --dump-schema itself isn't given — all validated in processConfig(), before connect(), so a plain argument mistake fails fast instead of after a connection attempt (which could otherwise block on an interactive password prompt).
  • Verified end-to-end via real replays into a fresh clickhouse-local instance: a source table with a materialized view (implicit storage), a dictionary, a plain view, a view-on-view chain, and an explicit TO target, named so that alphabetical order alone would produce an unreplayable dump without the fix; single/list/exclude/all-databases selection; --dump-schema-dir output with a genuine cross-database dependency; the case-insensitive filename collision guard (using a case-sensitive APFS volume to stand in for a Linux source, confirming both that Foo/foo coexist there and that the guard fires when dumping them); and all the rejection cases (unknown database, combined with --query/--file/--structure, list + exclude together, dir without --dump-schema).

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[=<db1,db2,...>] option to clickhouse-client and clickhouse-local that dumps CREATE DATABASE/CREATE TABLE/CREATE DICTIONARY/CREATE MATERIALIZED VIEW/CREATE VIEW statements for the given database(s), or all user databases if no value is given, to stdout in dependency order, then exits — similar to pg_dump --schema-only. --dump-schema-exclude=<db1,db2,...> skips the listed databases when dumping all of them, and --dump-schema-dir=<path> writes one <database>.sql file per dumped database into that directory instead of stdout.


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

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai, please check this one. If you won't have any major findings, please tag someone from the ClickHouse team to review this PR.

@groeneai

Copy link
Copy Markdown
Collaborator

Reviewed. One blocker, then some smaller notes.

Blocker: views and materialized views are not dependency-ordered, so the dump does not replay

orderTablesByDependencies orders by system.tables.loading_dependencies_*, but that column is empty for View and MaterializedView. The view-to-source edge is only recorded in the reverse direction, on the source table's dependencies_table. So every view lands in dependency level 0 alongside its own source table, and the (database, name) tie-break decides the output order. Whenever a view sorts before its source table by name, the dump is emitted in an unreplayable order.

Reproduced on master (26.8.1.1), realistic names, no cycle involved:

CREATE DATABASE analytics;
CREATE TABLE analytics.raw_events (ts DateTime, uid UInt64) ENGINE = MergeTree ORDER BY ts;
CREATE MATERIALIZED VIEW analytics.daily_agg (day Date, cnt UInt64) ENGINE = SummingMergeTree ORDER BY day
    AS SELECT toDate(ts) AS day, count() AS cnt FROM analytics.raw_events GROUP BY day;

loading_dependencies_table is [] for both daily_agg and raw_events; raw_events.dependencies_table is ['daily_agg']. d sorts before r, so the dump emits CREATE MATERIALIZED VIEW analytics.daily_agg first, and replaying it into a fresh instance gives:

Code: 60. DB::Exception: Unknown table expression identifier 'analytics.raw_events'
in scope SELECT toDate(ts) AS day, count() AS cnt FROM analytics.raw_events GROUP BY day. (UNKNOWN_TABLE)

Same failure for a plain CREATE VIEW whose source sorts after it. Ordering base tables before views fixes it: I replayed a fixture with an inner-table MV, a TO MV and a plain view in that order and it applied cleanly, with SELECT returning correct rows through all three.

Two things fall out of this:

  • The TO target is not covered by either dependency column. For CREATE MATERIALIZED VIEW ... TO tgt, both loading_dependencies_table and dependencies_table are empty on the view and on tgt, so nothing orders the view after its target, and replaying the view first fails with Table d.z_target does not exist. system.tables.target_database/target_table do carry it, so that edge is available.
  • The test passes by name luck, not by dependency tracking. In 04836, the fixture is base, mv, dict. mv has empty loading_dependencies_table, so it sits in level 0 with base, and base happens to sort first alphabetically, which satisfies the base_line -lt mv_line assertion. Rename base to z_base (or the MV to a_mv) and the assertion fails. dict is the only table in the fixture whose ordering is actually exercised, since a dictionary is the one object type here that does populate loading_dependencies_*. Worth adding a case where the view sorts before its source.

Smaller notes

  • A user table literally named .inner.foo is silently dropped from the dump. CREATE TABLE d.\.inner.mytable` (...)succeeds on master, and theNOT startsWith(name, '.inner.')filter then excludes it, so the dump is quietly incomplete rather than wrong. Matching the implicit-storage naming more precisely (the real inner tables are.inner_id., and .inner.` only for the pre-UUID form) would narrow it. Low priority, but it is a silent omission.
  • The test only ever invokes $CLICKHOUSE_LOCAL, never $CLICKHOUSE_CLIENT, so the programs/client/Client.cpp path and its processConfig() validation are untested. The two entry points have separately written validation blocks, so a divergence between them would not be caught.
  • On the case-insensitive-filesystem guard you flagged: escapeForFileName percent-escapes every non-word-character byte but leaves ASCII letters as-is, so db and DB do collide after escaping and the guard is doing real work. It reads correct to me.

Given the blocker I have not tagged a reviewer yet. Ping me once the ordering is fixed and I will route it.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai Fixed, thanks for the very thorough repro — I reproduced your exact case locally (analytics.raw_events/analytics.daily_agg) and confirmed both the failure before the fix and a clean replay after it.

Root cause was exactly what you found: loading_dependencies_* is empty for View/MaterializedView, so both landed in dependency level 0. The fix combines every dependency signal system.tables exposes — loading_dependencies_* (dictionaries), inverted dependencies_* (a materialized view's source, recorded only on the source row), target_database/target_table (the TO target you flagged as uncovered, explicit or implicit), and — since the server doesn't track this for plain views at all (confirmed: DROP TABLE on a view's source succeeds even with the view still referencing it) — a best-effort scan of each view's stored SELECT text for other dumped tables' names.

Also fixed the .inner.foo false-positive you flagged: a table is now only excluded when it's confirmed to be a live materialized view's own target with the generated-name shape, not merely name-shaped like one.

Test (04836_client_dump_schema.sh) is substantially strengthened: renamed the fixture so alphabetical order can't accidentally pass the assertion, added plain views, a view-on-view chain, an explicit TO target, the .inner.foo case, and a clickhouse-client invocation alongside the existing clickhouse-local ones (your test-coverage note). Each new case is round-tripped through an actual replay, not just checked for line order.

One thing I want to flag rather than claim silently: for plain-view-on-plain-view (and view-on-table) ordering, there's no server-tracked signal at all, so I'm relying on a text scan of the resolved, server-formatted SELECT (which is reliably fully-qualified even when the CREATE VIEW wasn't). It's reliable for straightforward FROM/JOIN references but can in principle miss one hidden behind a subquery, CTE, or table function — happy to discuss if you'd rather that residual case fail loudly instead of best-effort.

@valerypetrov

valerypetrov commented Aug 10, 2026 •

Copy link
Copy Markdown
Contributor Author

Correction to my earlier caveat: I did reproduce the case-collision guard — mounted a case-sensitive APFS volume to stand in for a Linux source, created Foo/foo there, dumped with --dump-schema-dir:

Code: 36. DB::Exception: Cannot dump to `--dump-schema-dir`: databases Foo, foo would all be written to the same file on a case-insensitive filesystem. (BAD_ARGUMENTS)

Note: the guard isn't destination-aware — it fires unconditionally regardless of the actual target filesystem, by design (portably detecting case-sensitivity isn't worth it for a dump meant to be replayed elsewhere anyway).

@groeneai

Copy link
Copy Markdown
Collaborator

Answering your question directly: I would not pick either contract, because the text scan does not only under-collect. It also over-collects, and that direction is worse: a spurious edge fabricates a dependency cycle, and checkNoCyclicDependencies() then aborts the entire dump with INFINITE_LOOP for a schema that has no cycle at all. So the current behaviour is not "graceful in the miss direction"; it can refuse to dump a perfectly ordinary database.

Two distinct false-positive classes, both reproduced on master (26.8.1.1) by running the predicate at SchemaDumper.cpp:262 against real server-produced as_select text.

1. Substring, not identifier, matching. find(qualified_name) matches inside a longer identifier, so any table whose qualified name is a prefix of another's yields a bogus edge. Ordinary names are enough:

CREATE TABLE analytics.metrics_source    (a UInt64) ENGINE=MergeTree ORDER BY a;
CREATE TABLE analytics.metrics_daily_raw (a UInt64) ENGINE=MergeTree ORDER BY a;
CREATE VIEW  analytics.metrics       AS SELECT * FROM analytics.metrics_daily_raw;
CREATE VIEW  analytics.metrics_daily AS SELECT * FROM analytics.metrics_source;

metrics matches analytics.metrics_daily inside its own SELECT, and metrics_daily matches analytics.metrics inside its own SELECT, so the two views become mutually dependent and the dump fails. Neither view references the other. Confirmed against the server's own text rather than a reimplementation:

SELECT v.name, o.name FROM system.tables v CROSS JOIN system.tables o
WHERE v.engine='View' AND NOT (v.name=o.name)
  AND position(v.as_select, concat(o.database,'.',o.name)) > 0

metrics         metrics_daily        <-- bogus
metrics         metrics_daily_raw
metrics_daily   metrics              <-- bogus
metrics_daily   metrics_source

2. String literals. A qualified name inside a literal matches too, and this class survives any word-boundary tightening, so tightening the match is not a fix:

CREATE VIEW d.audit_orders AS SELECT a, 'd.audit_users'  AS src FROM d.orders;
CREATE VIEW d.audit_users  AS SELECT a, 'd.audit_orders' AS src FROM d.users;

Same outcome: fake mutual dependency, whole dump refused.

Suggested direction, which removes your question rather than answering it: collect referenced tables from the parsed AST instead of the text. ClientBase.cpp already includes the parsers, and an ASTTableIdentifier walk resolves exactly the cases the scan cannot see. Verified with EXPLAIN AST:

SELECT * FROM (SELECT * FROM d.base2)             -> TableIdentifier d.base2
WITH c AS (SELECT * FROM d.base2) SELECT * FROM c -> TableIdentifier d.base2
SELECT a, 'd.audit_users' AS src FROM d.orders    -> Literal, not an identifier

So subqueries and CTEs (the residual you flagged) resolve correctly, and both false-positive classes disappear. Better still, getDependenciesFromCreateQuery in src/Databases/DDLDependencyVisitor.h is the extractor the server itself uses for this purpose, and it also covers table functions and dictGet; it takes a ContextPtr, so if that is awkward for a client talking to a remote server, a local identifier walk is the fallback. One caveat if you hand-roll it: a CTE alias also parses as a TableIdentifier (WITH orders AS (SELECT 1) SELECT * FROM orders gives TableIdentifier orders), so skip names bound by an enclosing WITH, or you reintroduce a spurious edge.

Smaller notes:

  • The test cannot catch either class today: every fixture name is aaa_*/zzz_*, so no qualified name is a substring of another, and there is no literal case. A prefix-collision pair like the one above is worth adding, since the suite currently passes with this present.
  • Same shape as the .inner. case you fixed: .tmp.inner. is still filtered by name at SchemaDumper.cpp:189, and a user table named .tmp.inner.x is creatable on master (verified), so it would be silently dropped from the dump.

Thanks for the ordering and .inner.foo fixes, and for confirming the case-collision guard. Since this one blocks a plain dump, I am holding off on tagging a ClickHouse team reviewer again; ping me once it is resolved and I will route it.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai Fixed — you're right that the substring scan was worse than the original bug, and your two repro classes were exactly the right proof. Replaced it with a proper parse: as_select is reparsed with ParserSelectWithUnionQuery (same grammar the server used to produce it), and every ASTTableIdentifier in the resulting tree is matched against the known table set by (database, name) equality instead of text search.

Your CTE-alias caveat turned out to be free: I confirmed empirically that a CTE alias reference stays unqualified in server-formatted SQL (WITH c AS (SELECT * FROM d.base2) SELECT * FROM c stores as_select with FROM c untouched, while d.base2 is fully qualified), so filtering to identifiers with a non-empty database part excludes CTE aliases without needing to track WITH-bound names separately — that alone also kills the string-literal false positive, since a literal parses as ASTLiteral, never ASTTableIdentifier.

Went with the local AST-walk fallback you flagged, not getDependenciesFromCreateQuery — confirmed it takes a ContextPtr, which a remote clickhouse-client connection doesn't have.

Verified against both your exact repros (metrics/metrics_daily_raw prefix collision, audit_orders/audit_users literal collision) directly against the built binary — both now dump cleanly with no INFINITE_LOOP, correct ordering preserved for the genuine dependencies. Also fixed .tmp.inner_id.*/.tmp.inner.* the same way as the .inner.foo case: only excluded when traceable to a live materialized view's own uuid/name via system.tables.uuid, so a literal user table with that prefix stays in the dump.

Test now covers both false-positive classes, a genuine view-on-view/view-on-table chain (round-tripped through actual replay), and the .tmp.inner. literal case.

@groeneai

Copy link
Copy Markdown
Collaborator

The AST walk is the right call, and I verified all three things you claimed. The empty-database-part filter (SchemaDumper.cpp:321) does make the CTE-alias case free. getDependenciesFromCreateQuery does take a ContextPtr (DDLDependencyVisitor.h:26), so the local walk is correct for a remote client. Both of my round-2 false-positive classes are now dead by construction.

One new blocker, same class as round 1.

A materialized view with two or more sources is ordered by only one of them.

The AST scan is gated if (row.engine != "View") continue; (SchemaDumper.cpp:302), so MV rows never reach it, and an MV's ordering rests entirely on the inverted dependents edge. That edge carries at most one source, because the server records mv_from_dependency as a single std::optional<StorageID> (DDLDependencyVisitor.h:18), not a set.

Measured on master 26.8.1.1:

CREATE VIEW d.zzz_view AS SELECT id, b FROM d.base;
CREATE MATERIALIZED VIEW d.aaa_join_mv ENGINE = MergeTree ORDER BY id AS
  SELECT s.id AS id, s.a AS a, v.b AS b FROM d.src AS s INNER JOIN d.zzz_view AS v ON s.id = v.id;

dependencies_table is ['aaa_join_mv'] on d.src only; d.zzz_view gets no edge. MV and view both land in level 1, the (database, name) tie-break emits aaa_join_mv first, and replay fails:

Code: 60. DB::Exception: Unknown table expression identifier 'd.zzz_view' ... (UNKNOWN_TABLE)

Emitting the view first replays cleanly and data flows through the MV, so it is the ordering and not the fixture. Reproduces the same way with UNION ALL instead of the join, and with a TO-target MV.

Two precisions so you do not over-fix, both measured:

  • It is specifically the second and later sources. A single-source MV reading a view does get its edge, so the tracked-source path is fine.
  • It only bites when the untracked source outranks level 0. An MV over two plain tables replays fine, since both sources sort into level 0 anyway. The shape that breaks is: two or more sources, at least one of them a view (or anything else carrying its own dependencies) that sorts after the MV by name.

Fix direction: the scan you already wrote is the right tool, just gated too narrowly. Dropping the engine != "View" gate so MV rows are scanned too gives the MV its missing edge from its own as_select, which is populated for MVs including TO-target ones (I checked that on every shape above). The known_tables and self-reference guards at SchemaDumper.cpp:324 already cover the spurious-edge classes, and the TO-target edge is separate and already correct.

The test cannot catch this: 04836_client_dump_schema.sh has no JOIN and no UNION, and every MV in it reads zzz_source, a plain MergeTree table. Worth adding an MV that joins a table and a view, and one over UNION ALL with a view, each with the second source named so it sorts after the MV, round-tripped through an actual replay. Both should fail against the current head.

Holding the reviewer routing one more round, since your condition was no major findings. Ping me once this is in and I will route it.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai Fixed — good catch, and the precision on when it does/doesn't bite (second-and-later sources, only when the untracked one outranks level 0) made this trivial to scope correctly.

Went with your exact fix direction: widened the if (row.engine != "View") gate to also let MaterializedView rows through the AST scan. Confirmed empirically before touching anything: as_select for an MV never mentions its own name, implicit storage, or TO target (verified on a TO-target MV too — identical as_select to the non-TO case), so there's no conflict with the already-correct target_database/target_table edge. A duplicate edge to the already-tracked single source is harmless — TablesDependencyGraph::addDependencies collects into an unordered_set before storing.

Verified against your exact JOIN repro (d.src/d.zzz_view/d.aaa_join_mv) directly against the built binary: zzz_view now dumps before aaa_join_mv, replay succeeds. Test now covers both the JOIN and UNION ALL shapes, each with the untracked source named to sort after the MV, round-tripped through an actual insert+select (confirmed the UNION ALL view-sourced branch not firing on insert is a separate, pre-existing ClickHouse MV limitation — only the table-sourced branch is expected to populate — not something this fix touches).

@groeneai

Copy link
Copy Markdown
Collaborator

Round-4 blocker is discharged. I verified the widened gate at SchemaDumper.cpp:302 against my exact JOIN repro and the UNION-with-a-view shape: zzz_view now lands at level 1 and both MVs at level 2, the dump replays with RC=0, and data flows through both MVs. Negative control: restoring the old engine != "View" gate puts both MVs back at level 1 next to zzz_view and replay fails Code: 60 ... Unknown table expression identifier 'd.zzz_view'. Your dedup reasoning is right (TablesDependencyGraph.cpp:114-116 collects into an unordered_set before comparing). I also re-ran both round-2 false-positive classes in their MV form (mutual 'd.mv_users' literals, and a mtr/mtr_daily prefix collision) and neither fabricates a cycle now that MVs go through the same parse.

One more blocker in the same place, though.

collectTableIdentifiers only picks up ASTTableIdentifier, so a reference the grammar puts in a function ARGUMENT is invisible. Two forms, both reproduced end to end for MVs:

  1. dictGet. SELECT id, dictGet('d.zzz_dict','val',id) AS v FROM d.base parses the dictionary as Literal 'd.zzz_dict', never a TableIdentifier. loading_dependencies_table is [] on the MV and the dictionary gets no dependent edge, so MV and dictionary both land at level 1 and the name tie-break emits the MV first. Replay: Code: 36. DB::Exception: Dictionary (d.zzz_dict) not found. (BAD_ARGUMENTS).

  2. IN. SELECT id FROM d.base WHERE id IN d.zzz_inview is stored as ... IN (d.zzz_inview) and parses as a plain Identifier, not a TableIdentifier. Replay: Code: 47 ... Unknown expression or table expression identifier 'd.zzz_inview'. (UNKNOWN_IDENTIFIER).

Negative control for both: emit the missed object first and replay is RC=0 with data flowing (MV_ROWS 7 seven, IN_MV_ROWS 3). So it is the ordering, not the fixture.

Two precisions, since they scope it:

  • It bites materialized views, not plain views. A dumped CREATE VIEW carries an explicit column list, and with one the server accepts a view over a missing dictionary or table (verified, RC=0), so a plain view still replays. An MV validates its SELECT regardless of the column list, which is what makes this one hard-fail.
  • Like the round-4 case, it needs the missed object to sit at level 1 or above and to sort after the MV. For dictGet that is the ordinary case rather than an exotic one: a dictionary whose source table is in the same dump is always at level 1, so only the name decides. Renaming zzz_dict to aaa_dict makes the identical schema replay cleanly.

The test cannot catch either. dictGet appears once in 04836, in a post-replay probe at line 115, never inside a dumped view or MV SELECT; joinGet and IN <table> do not appear at all.

Fix direction, verified only to this depth: the server's own extractor already handles exactly these argument positions in visitFunction (src/Databases/DDLDependencyVisitor.cpp:312-329) -- argument 0 for functionIsDictGet / functionIsJoinGet and for dictionary(...), argument 1 for functionIsInOrGlobalInOperator. Those predicates are header-only inline functions over std::string in src/Interpreters/misc.h and take no ContextPtr, so the local walk can reuse them: when a node is an ASTFunction, read the relevant argument as a string literal (dictGet / joinGet / dictionary) or as an ASTIdentifier (IN), and match it against known_tables exactly as now. joinGet over a Join-engine table is the same shape and worth covering in the same pass.

Holding the reviewer routing one more round, for the same reason as before. Ping me once this is in and I will route it.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

@groeneai Fixed. Went further than the two cases you'd verified — audited DDLDependencyVisitor.cpp's full visitFunction to catch the whole class rather than patch two instances: dictGet/dictHas/dictIsIn/naiveBayesClassifier*/joinGet/joinGetOrNull (arg 0), the dictionary() table function (arg 0, confirmed empirically it's an ASTIdentifier not a literal — different shape from dictGet), and the full IN/GLOBAL IN family including notIn/globalNotIn/etc. (arg 1).

Deliberately excluded remote()/cluster() and non-literal argument evaluation (e.g. dictGet(concat(...), ...)) — both need a live Context this client-side tool doesn't have, and for remote()/cluster() specifically, blindly extracting the argument text risks a spurious dependency between genuinely unrelated servers, which is worse than the original bug since a false cycle aborts the whole dump.

Given the pattern of this review (a new gap in the same mechanism each round), I ran this one through a fuller pipeline before pushing: architect audited the full extractor and verified every case empirically, a dev implementation, then a senior-style review (confirmed no correctness bugs, and — critically — empirically confirmed each new test case actually forces the target and its referencing MV to the same dependency level, so the fix is what's deciding the order, not an unrelated level gap that would pass either way), and an adversarial pass specifically hunting for what a round 5 would find: tested NOT IN/GLOBAL NOT IN, a UNION ALL mixing a dictGet branch with a plain FROM branch, DEFAULT-column expressions referencing dictGet (confirmed already covered — loading_dependencies_* walks the full CREATE query, not just as_select), and merge()/view() table functions (merge() isn't tracked, but confirmed it resolves lazily at query time rather than CREATE time, so dump order doesn't affect whether it replays — consistent with the server's own tracker also not tracking it).

Your exact dictGet/IN repros verified directly against the built binary, plus the dictionary() case.

@groeneai

Copy link
Copy Markdown
Collaborator

Verified at af8d5b0. collectFunctionArgumentReferences reads the same argument positions as visitFunction and reuses the misc.h predicates, so the dictGet/dictHas/dictIsIn/naiveBayesClassifier*/joinGet family (arg 0), dictionary() (arg 0) and the IN/GLOBAL IN family (arg 1) are all covered. Round-5 blocker discharged.

The arm discriminates, which is the part the previous rounds' suites failed. Restoring the old ASTTableIdentifier-only collector reddens: Code: 36 ... Dictionary (d.zzz_dict) not found for the dictGet MV, Code: 47 UNKNOWN_IDENTIFIER for IN (d.zzz_inview). Ran your new fixture through both collectors: at head the four new MVs sit one level above their targets and replay RC=0; with the narrow collector aaa_mv_inref drops to zzz_inview_tbl's level and replay fails. So ordering is what the fix decides.

I also checked the widening for a round-2 style false cycle, since arg 0 of dictGet is a string literal and a literal is again being read as an object name. Could not construct one: the server refuses a mutual IN 'db.tbl' pair at CREATE (Code: 269 INFINITE_LOOP) and refuses dictGet('d.some_view', ...) outright (Code: 36), so the shapes that would fabricate an edge cannot exist in a dumpable catalog. Unqualified literals are stored already qualified in as_select, so there is no current-database gap. Your dictionary()-vs-dictGet shape claim and the DEFAULT dictGet coverage claim both check out.

One correction, not a blocker. merge() is not resolved lazily, it resolves at CREATE. An MV cannot be created directly from a table function (Code: 397), but it can hold one in a JOIN, and there dump order does matter:

CREATE MATERIALIZED VIEW d.aaa_mv_mergejoin TO d.sink AS
  SELECT s.id AS id, s.val AS val, m.w AS w FROM d.src AS s
  LEFT JOIN merge('d','^zzz_merge_view$') AS m ON s.id = m.id;

With zzz_merge_view a view over a base table, it and the MV are both level 1, aaa_* sorts first, and replaying that order fails Code: 636 CANNOT_EXTRACT_TABLE_STRUCTURE; emitting the view first replays RC=0 with data flowing. loop(d.zzz_loop_view) is the same shape (Code: 60 UNKNOWN_TABLE) and holds arg 0 as a plain Identifier, so it is the extraction path dictionary() already uses. merge() would need its regexp matched against the table list, which is a larger call, and the server tracks neither. Documenting both as limitations is defensible; I would just state the reason as resolved-at-CREATE-but-untracked rather than lazy.

cc @azat @yakov-olkhovskiy, could you review this? It adds a client-side --dump-schema to clickhouse-client and clickhouse-local that prints CREATE statements in dependency order, ordering views and materialized views by parsing their stored SELECT text since the server tracks no dependencies for plain views.

@nikitamikhaylov nikitamikhaylov added the can be tested Allows running workflows for external contributors label Aug 16, 2026
@clickhouse-gh

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [675b6bd]


AI Review

Summary

This PR adds --dump-schema to clickhouse-client and clickhouse-local, with dependency ordering, per-database output, and a replay prelude for create-time settings. The current head is still not safe to merge: two earlier replay-prelude fixes have regressed, and the omitted-database ambiguity scan is still incomplete for external databases.

Findings

❌ Blockers

  • [src/Client/SchemaDumper.cpp:1485-1487] replaySettingsPrelude() is back to emitting every name from allExperimentalSettingNames() unconditionally. That means a plain same-version dump still aborts before the first CREATE under any profile that marks an unrelated setting like database_replicated_allow_explicit_uuid readonly / CONST, which breaks the advertised replay contract for ordinary schemas.
    Suggested fix: restore the narrowed contract from the earlier review and emit only the smallest unavoidable undecidable subset of shared gates, not the full list.

  • [src/Client/SchemaDumper.cpp:1429-1444] database_replicated_allow_heavy_create has fallen back out of dump_specific, but InterpreterCreateQuery still rejects CREATE ... POPULATE in Replicated databases without it at src/Interpreters/InterpreterCreateQuery.cpp:2010-2024. A dump taken from a valid Replicated database can therefore replay as invalid SQL again.
    Suggested fix: add database_replicated_allow_heavy_create back to the replay prelude when the dumped CREATE statements prove it is needed, or fail-close on that shape instead of emitting broken SQL.

  • [src/Client/SchemaDumper.cpp:1160, 648-656, 1053-1067] undumped_table_names_by_db is populated from plain system.tables, but unlike the main table scan it never enables show_data_lake_catalogs_in_system_tables or show_remote_databases_in_system_tables. system.databases still enumerates those omitted external databases, so subset dumps can miss an external table that satisfied an unqualified dictionary() / joinGet() / loop() / merge('', ...) reference at CREATE time and silently rebind the recreated object to the owning database instead of refusing the unsound dump.
    Suggested fix: populate the omitted-database map with the same external-database visibility handling as fetchRawRows(), or stop relying on external databases in this ambiguity check and fail-close for those carriers.

Tests
  • ⚠️ 04836_client_dump_schema.sh still does not pin any of the three regressions above: there is no constrained-profile replay case, no Replicated-database POPULATE replay case, and no omitted external-database ambiguity case. A focused regression for each would keep these fixes from dropping out again.
Final Verdict

Not ready. The current head still breaks replay for some supported schemas and can silently rebind subset dumps that depend on omitted external databases.

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

clickhouse-gh Bot commented Aug 16, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9e9dbae16 with master b08a8526f (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 ⚠️

7 object files changed (+549.15 KiB total), 1 added.

Object file Master PR Δ
src/CMakeFiles/dbms.dir/Client/SchemaDumper.cpp.o new 522.82 KiB +522.82 KiB

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

26 translation units recompiled, 172 s compile time in total, 25 of them have a recent master baseline.

Translation units without a recent master baseline:

  • src/Client/SchemaDumper.cpp: 7.0 s

Job report

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
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
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
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
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
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
@groeneai

Copy link
Copy Markdown
Collaborator

Checked the three claims at head 682631524c97, committed 10:07:50Z. That sha is also the tip of dump-database-schema on your fork read straight from the git ref, so the PR object is not lagging behind a push, and it predates your 13:04:04Z comment by just under three hours.

The code-comment claim holds. The older-target sentence is still at SchemaDumper.cpp:1391-1394, unchanged: the prelude is a function of the source, replay works whenever the target knows every name the source did, and the older-target case is not decidable there.

The two docs claims are not in the tree yet. The row at docs/concepts/features/interfaces/client.mdx:875 still ends produces a script meant to be replayed into a server of the same version or newer than the one it was taken from, which is the wording you quoted as the old one, and --ignore-error appears zero times anywhere in the PR, docs and code alike. The zero is not a broken grep: the same fetch carries that docs row and that exact sentence, and I read the file at the head ref rather than out of the diff.

So it reads as an unpushed working tree rather than a disagreement. I will read the clause when it lands, since it is the only place a user learns the failure is total rather than proportional to the version gap.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

You are right, and my earlier comment was wrong to describe it in the present tense. The clause exists as a local commit, 2ea201f30e8, and is deliberately unpushed: roughly 150 jobs were mid-flight on 682631524c9, and pushing a docs-only commit would have cancelled that run and re-queued all of it. That run is nearly done — 123 green, 27 still going, no failures — so the clause lands shortly after it finishes.

Nothing about the content has changed; the wording and the --ignore-error clause are as I quoted them. I should have written "committed, not yet pushed" instead of phrasing it as something you could go and read. That cost you a verification round, which is exactly the kind of round your checking is too useful to spend on.

Worth saying that your check was right on all three counts, including the one that agreed with me: the code comment at SchemaDumper.cpp:1391-1394 is unchanged, and it should stay that way — the older-target case genuinely is not decidable at that point, so the docs line is the only place it can be said.

@valerypetrov

Copy link
Copy Markdown
Contributor Author

Landed. Head is now 2ea201f30e8, a fast-forward over 682631524c9, and the two things you grepped for are there: --ignore-error goes from zero occurrences to one, and the row at docs/concepts/features/interfaces/client.mdx:875 now carries the older-target clause. Checked at the head ref rather than out of my working tree, since that is the distinction that tripped this up.

The run on the parent finished clean before I pushed, which is why the push waited: 152 jobs green, nothing failed, and 04836_client_dump_schema came back OK in 37 separate runs across asan/ubsan, msan, debug, binary, distributed-plan and s3-storage shards, including the 5-repetition flaky checks, 24 to 164 seconds. No FAIL or ERROR on any test on that sha. So the window-view removal is validated well beyond the one shard I would have settled for.

Your --ignore-error count-as-audit framing is what made that clause worth writing rather than a bare warning, so thanks for it.

Comment thread src/Client/ClientBase.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 Outdated
/// `allExperimentalSettingNames()` is the list it maintains for exactly that. Emitting that list
/// keeps the dump complete as gates are added, instead of a private copy that has to be audited.
///
/// Emitted unconditionally rather than matched against the statement. Several of these are

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.

This makes every replay script start with SET statements for all create-time gates the source knows, even when the dumped schema uses none of them. Replaying that SQL goes through InterpreterSetQuery::execute(), which checks settings constraints before any CREATE runs, so a plain schema can now fail immediately under a profile that allows DDL but keeps an unrelated setting such as database_replicated_allow_explicit_uuid readonly / CONST.

That breaks the "replayable same-version dump" contract for ordinary schemas. I think the prelude needs to be narrowed to settings the dump actually needs, or otherwise emitted in a form that does not abort on unrelated constrained settings.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The failure mode is real and I had not accounted for it: the values are inert when a
statement does not need them, which is what the comment there claims, but the SET
statements are not — InterpreterSetQuery::execute() runs the constraint check before any
CREATE, so a profile that pins one unrelated gate readonly / CONST aborts the replay of
a plain MergeTree schema. That is the wrong way round: the schemas most likely to be replayed
under a restricted profile are exactly the ones that need none of these.

I have not changed it yet, because narrowing is only partly decidable and the split decides
what the feature promises:

  • Decidable from the dumped text: the engine and type gates — allow_experimental_time_series_table
    ↔ ENGINE = TimeSeries, enable_nullable_tuple_type ↔ a Nullable(Tuple(...)), the
    database-engine ones ↔ their ENGINE. These can be emitted only when the dump actually
    contains the construct, and that alone removes the whole prelude for an ordinary schema,
    which is the case you are worried about.
  • Not decidable: the analyzer-side and validator ones, which gate re-analysis of a view's
    AS SELECT rather than anything recorded in the stored CREATE
    (allow_materialized_view_with_bad_select, database_replicated_allow_explicit_uuid, the
    suspicious-type validators). Dropping these when unused is not something the dump can
    determine; keeping them unconditionally reintroduces your failure for any profile that
    constrains one of them.

So the choice is between "emit only what the text implies, plus a small undecidable core" and
"stop promising replay under constrained profiles and say so in the docs". I lean to the
first, with the undecidable core kept as small as the list above. Which would you rather
have? I would rather not narrow this by guesswork given recoverLostReplica maintains the
shared list for the same reason.

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.

I would keep the first contract: emit only the settings the dumped text proves are needed, plus the smallest unavoidable undecidable core.

That preserves the advertised same-version replay path for ordinary schemas, which is the default case this feature needs to get right. If there is still a small residual core that cannot be inferred from the stored CREATE, I would keep that list explicit and document that narrower limitation, rather than leave the whole prelude unconditional.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Taking that contract. First step in e9aaf8c, and I want to be clear about how far it goes.

The structural half is done: replaySettingsPrelude now receives the statements it precedes, and
a gate can be marker-gated. That needed no buffering — both call sites already have
create_database_query_by_db and tables[i].create_query materialized before the prelude is
written, and the per-database file case scopes the decision to that database's own statements.

Two gates are narrowed so far, chosen because their marker is unmistakable rather than inferred:
database_replicated_allow_explicit_uuid on UUID ' (only a dump taken with
show_table_uuid_in_table_create_query_if_not_nil carries one), and
database_replicated_allow_replicated_engine_arguments on MergeTree('. The first is the setting
from your original example, so the concrete failure you described no longer happens for a plain
schema. 04836 pins it, with an ungated gate checked alongside so a prelude that vanished
entirely could not pass.

Everything else stays unconditional on purpose. allExperimentalSettingNames() is 61 entries and
none of them carries marker metadata, so narrowing them means a hand-written table — and a marker
derived from a setting's name is exactly the kind of inference that fails silently. Take
allow_experimental_geo_types: nothing in the name tells you the marker is Point / Ring /
Polygon, and getting it wrong turns "the dump replays" into "the dump replays unless you used
geo types", discovered only by the user. I would rather add those in batches I can justify one by
one than land 61 guesses at once.

Two decidable axes look worth doing next, and I would value your read before I build them: the
type/engine/index/codec gates via an explicit marker table, and the function-level gates
(funnel, nlp, hyperscan, simdjson, the window ones) gated on whether the dump contains a
CREATE ... VIEW at all, since a table-only dump can need none of them. That second one covers a
whole family with a single unmistakable condition.

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.

I would do both, with one constraint on the first axis: the marker table has to key off syntax the stored CREATE can only produce for that gate, not a raw substring anywhere in the SQL text.

The two current markers are not at that bar. An ordinary literal/comment can contain UUID ' or MergeTree(', which would emit database_replicated_allow_explicit_uuid = 3 / database_replicated_allow_replicated_engine_arguments = 3 for a schema that never uses either feature and reintroduce this thread's constrained-profile failure through a different path. If you keep the marker table, I would derive those markers from structured metadata or a token-aware parse of the stored CREATE, not dumped_sql.contains(...).

The coarse CREATE ... VIEW / CREATE MATERIALIZED VIEW gate for the analyzer-side and suspicious-type settings looks reasonable to me as the undecidable core. A table-only dump cannot need that family, and keeping the residual list explicit makes the remaining limitation inspectable instead of silently growing.

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.

I agree with that split.

View-gating the genuinely query-level / analyzer-side settings looks like the right boundary, and keeping the column-list validators unconditional until each has a structured signal is the safer side. The one extra constraint I would keep is that an empty dump should suppress the prelude entirely regardless of the residual unconditional set, because there is no statement stream there that needs replay-time gates at all.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Empty-dump constraint implemented in 2ba316bed97, and I agree with it — with no statement stream
there is nothing for a gate to guard. Reachable when every database is predefined, or a
--dump-schema-exclude removes the rest; the new test arm covers both, plus an ungated gate read
from the same dump so a prelude that vanished entirely cannot pass the check.

allow_materialized_view_with_bad_select is view-gated in the same commit: all three of its checks
sit inside InterpreterCreateQuery's materialized-view branch (:1167, :1245, :1267), so a
dump without one cannot need it.

I stopped short of the rest of the split, because the marker does not hold. I went to read each
enforcement site before writing the table, and three findings contradict the axis — including in
the part I proposed, so this is me correcting my own suggestion:

  • The function families are not query-level. Those gates live in the functions' own create()
    (Functions/fuzzQuery.cpp:41, Functions/synonyms.cpp:40, Functions/lemmatize.cpp:71), and
    InterpreterCreateQuery.cpp:688 analyses column DEFAULT/MATERIALIZED expressions through
    validateColumnsDefaultsAndGetSampleBlock at CREATE time. A plain CREATE TABLE with a
    MATERIALIZED column calling one needs the gate with no view anywhere.
  • A view is not the only carrier of analyzable text. A projection's SELECT is fully resolved at
    description time — ProjectionsDescription.cpp:404-410 runs buildQueryTree and
    runOnlyResolve — so CREATE TABLE t (..., PROJECTION p (SELECT x, count() GROUP BY x)) reaches
    validateGroupByKeyType with no view present. That covers
    allow_suspicious_types_in_group_by, allow_suspicious_types_in_order_by and
    allow_experimental_correlated_subqueries alike.
  • Two of the names cannot gate anything. allow_experimental_window_functions is
    MAKE_OBSOLETE (Settings.cpp:9185) and allow_experimental_hash_functions has no reader in
    src/ outside its own declaration. allow_simdjson never rejects either — DataTypeObject.cpp:159
    and FunctionsJSON.cpp:696 use it to pick a parser, not to throw.

The axis I would propose instead is "the dumped statements contain analyzable query text" — a
view's AS SELECT or a projection — for the three genuinely analyzer-side settings, and no
narrowing at all for the function families, since every CREATE TABLE can carry an expression that
trips them. That is decidable from the parsed statement, the same way the gates already shipped are.

I have not built it yet on purpose. It is a second narrowing, and a wrong marker fails in the
direction nobody sees until a user's dump will not replay — so I would rather have your read on the
projection path first than ship a table I inferred.

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.

The projection path is real. ProjectionDescription::fillProjectionDescriptionByQuery builds a query tree and runs runOnlyResolve on the projection SELECT (src/Storages/ProjectionsDescription.cpp:404-410), so a plain CREATE TABLE ... PROJECTION ... can still reach allow_suspicious_types_in_group_by, allow_suspicious_types_in_order_by, or allow_experimental_correlated_subqueries with no view present.

So if you keep narrowing this list, I would key that analyzer-side family off "the dump contains analyzable query text" (AS SELECT on a view/MV, or a projection), not off the presence of a view specifically. Separately, I would drop names that cannot gate replay at all from the residual unconditional set: allow_experimental_window_functions is obsolete, allow_experimental_hash_functions has no reader outside its declaration, and allow_simdjson only selects the JSON parser implementation rather than rejecting a CREATE.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Built in f46fd10c055, on the marker as you corrected it.

collectReplayGateNeeds now sets analyzable_query_text when a parsed statement carries an
AS SELECT (create->select) or a non-empty projection list, and the three analyzer-side gates —
allow_suspicious_types_in_group_by, allow_suspicious_types_in_order_by,
allow_experimental_correlated_subqueries — are emitted only then. A statement that fails to parse
still keeps everything, same as the other gates.

The three dead names are dropped outright. Re-verified each before dropping, headers included this
time: allow_experimental_window_functions and allow_experimental_hash_functions have zero
readers anywhere under src/, and every allow_simdjson reader is an implementation pick —
DataTypeObject.cpp:159, FunctionSQLJSON.h:518, FunctionsJSON.cpp:614 are all if/else between
SimdJSON and RapidJSON, never a throw. Since the drop only matters within the feature's stated
support envelope (replay target >= source), and any target >= source treats the obsolete gate as
accepted-and-ignored, nothing can start failing that passed before.

The function families stay unconditional per the earlier part of this thread — their gates fire
from a plain column expression, so no statement shape rules them out.

Three new arms pin the edges: analyzer gate off for a plain no-view/no-projection schema, back on
for a projection-only schema (PROJECTION p (SELECT x, count() GROUP BY x) — the exact path you
confirmed), and the dead trio absent even from the main dump, which is full of views — proving it
is an unconditional drop rather than a narrowing that happens to miss them.

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.

The constrained-profile failure from this thread is present again on the current head. replaySettingsPrelude() is back to emitting every name from allExperimentalSettingNames() unconditionally at src/Client/SchemaDumper.cpp:1485-1487, so a plain dump still hits InterpreterSetQuery::execute() for unrelated gates before the first CREATE.

That means the advertised same-version replay path still aborts under a profile that marks an unrelated setting like database_replicated_allow_explicit_uuid readonly / CONST, even when the dumped schema never uses that feature.

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
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
@valerypetrov

Copy link
Copy Markdown
Contributor Author

Verification update for today's push (3a2a69b..fed6f4d):

I ran the whole 04836 test locally end to end, with a local keeper for the replicated fixture, and reproduced the three red CI assertions. All three were stale expectations, not code gaps:

  • "session context inside wrapped merge() refused": the server folds constant session context (currentDatabase()) into merge() arguments at CREATE (unlike cluster() arguments, which stay as stored expressions), so the stored view carries its create-time binding, the dump is faithful, and refusing is neither possible nor needed. The arm now pins that: the dump succeeds, the folded literal is present, and the wrapped source is ordered before its reader.
  • "replicated engine arguments gate at 3: 1" / "explicit uuid gate at 3: 1": the reference still carried the unconditional-prelude-era counts while the earlier arm on the same dump already expected 0. Both are now 0 for the plain dump, and the value-3 pins were moved onto dumps that actually carry the markers: an explicit-UUID dump (taken with show_table_uuid_in_table_create_query_if_not_nil=1) and a dump of a real replicated engine that kept its arguments (the test is now zookeeper-tagged, with the path under $CLICKHOUSE_TEST_ZOOKEEPER_PREFIX per the style check).

One real hole surfaced while verifying (3a2a69b): merge('', '^t$'). An empty database literal is the database-less form — it resolves against the session database at CREATE and against USE <own database> at replay. The walker previously emitted an empty-named edge that matched nothing and ordered no source before its reader, so a replayed view could CREATE-fail on an empty merge. The walker now folds the owning object's database in, with the same guess semantics as the database-less dictionary() references; a regression arm was added ("empty-database merge() resolves against the owning database").

Full 04836 is green locally on darwin except the four fixtures that cannot exist there (the case-colliding database names and the 127.0.0.2-bound remote/cluster/nested-macro fixtures) — unchanged by these commits, covered by CI, and the reason for the existing no-darwin tag.

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
Comment thread src/Client/ClientBase.cpp Resolved
Comment thread src/Client/SchemaDumper.cpp Resolved
/// current database into the view context, so a database-less reference resolves
/// against whoever reads it, in the original object as much as in the replayed one.
String other_databases;
for (const auto & [db, names] : table_names_by_db)

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.

This still only looks for collisions inside table_names_by_db, i.e. the databases we decided to dump. That misses the same silent-rebinding bug when the owning database contains the unqualified name and an omitted database did too at CREATE time.

Concrete shape: USE b; CREATE VIEW a.v AS SELECT * FROM loop(zzz_src); with both a.zzz_src and b.zzz_src present, then --dump-schema=a. InterpreterCreateQuery resolves the source against b while the view is created, but this branch sees only a, records the dependency on a.zzz_src, and the replayed USE a; CREATE VIEW ... loop(zzz_src) now infers its header from the wrong table. The same gap exists for database-less dictionary() / joinGet() references. We need an omitted-database existence check here, or a fail-close refusal for subset dumps whenever an omitted database could also satisfy the name.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👷🏻 Fixed in 5735344: the dumper now fetches the omitted databases' table names (predefined ones excluded — they cannot hold such references) and refuses the fold whenever an omitted database could also have satisfied the database-less name at CREATE time. 04836 arm covers exactly your USE b / dump a joinGet shape.

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.

Current head still misses one omitted-database class here. undumped_table_names_by_db is filled from system.tables at src/Client/SchemaDumper.cpp:1325-1331, but unlike fetchRawRows it never probes or enables show_data_lake_catalogs_in_system_tables. system.databases does list DataLakeCatalog databases unconditionally, so a subset dump can still leave an omitted catalog database out of this map even though a database-less dictionary / joinGet / loop reference bound there at CREATE time. The sibling merge('', ...) refusal reads the same map, so it stays incomplete for the same reason. In that shape the dump goes back to the same silent-rebinding / missed-refusal bug this thread is about.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👷🏻 The map is gone entirely, so the gap goes with it. The omitted-database refusal it fed was unusable — it fired whenever any other database on the server held a same-named table, and CI proved it: the flaky check runs 04836 concurrently and a sibling run's database tripped the pre-existing empty-database merge() arm. Since replay does USE <owning database> and that database does contain the name, an omitted database cannot be bound by the replay at all. The provable refusals stay: no match in the owning database, and a name two dumped databases can satisfy.

/// when the owning database cannot (the binding then lies outside the fold).
if (!database_is_regexp && database_pattern->empty())
{
for (const auto & [db, tables] : table_names_by_db)

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.

This still hard-binds merge('', ...) to the owning database whenever that database has a match, but TableFunctionMerge::parseArguments() resolves the empty first argument through the CREATE session's current database, not the object's database.

If both a.t and omitted b.t match, USE b; CREATE VIEW a.v AS SELECT * FROM merge('', '^t$') dumped as --dump-schema=a records a.t here and replays under USE a, so the recreated view can silently read and infer its structure from the wrong table. The ambiguity scan at :725-745 only looks at dumped databases, so this omitted-database half never trips. This path needs the same omitted-database probe or fail-close behavior as the other database-less reference carriers.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👷🏻 Fixed in 5735344: the merge('', ...) ambiguity scan now covers the omitted databases too, so owning-match plus omitted-match refuses instead of hard-binding to the owning database. 04836 arm covers the both-match subset shape; fixture creates under USE and was verified locally.

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.

Current head still has the omitted-database half of this bug. collectMergeAndLoopReferences() only scans table_names_by_db at src/Client/SchemaDumper.cpp:723-745; the only use of undumped_databases in this function is the regexp-database branch at :700-706, and there is no omitted-database table-name scan anymore. So USE b; CREATE VIEW a.v AS SELECT * FROM merge('', '^t$'), dumped as --dump-schema=a with both a.t and omitted b.t, still binds silently to a.t on replay instead of refusing the ambiguous CREATE-time binding.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

👷🏻 That scan was removed on purpose in 6c05180, and I don't think it should come back in this form.

It cannot distinguish the hazard from the ordinary case: it fires whenever any database on the server holds a same-named table. CI demonstrated that — the flaky check runs 04836 concurrently, a sibling run's test database held the same source name, and the refusal broke the pre-existing empty-database merge() resolves against the owning database arm. On any server with repeated table names across databases the dumper would stop working.

On the replay semantics: the script emits USE a before the CREATE, and a.t is in the dump, so the reference resolves to an object the script itself creates. Database b is not dumped and cannot be bound by the replay at all. What is genuinely lost is that b.t's structure may have been what the view was inferred from at CREATE time — real, but not provable from the dump, and not worth refusing every dump on a server with a repeated table name. A warning has the same false-positive rate, so it would be noise rather than signal.

The refusals that are provable are still there: no matching table in the owning database (the binding was outside the dump set and replay would fail), and a name two dumped databases can satisfy (the script itself creates both). If you would rather have strictness at that cost, the clean way is an opt-in flag rather than the default, and I'll add it on request.

Comment thread src/Client/ClientBase.cpp Resolved
undumped_list += ", ";
undumped_list += quoteString(db);
}
executeQuery(connection, timeouts, client_info,

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.

undumped_table_names_by_db is populated from plain system.tables, but unlike fetchRawRows() this query never enables either show_data_lake_catalogs_in_system_tables or show_remote_databases_in_system_tables. system.databases lists both external database kinds unconditionally, so subset dumps can still miss an omitted DataLakeCatalog / MySQL / PostgreSQL table that satisfied an unqualified dictionary() / joinGet() / loop() / merge('', ...) reference at CREATE time.

In that shape the ambiguity checks at src/Client/SchemaDumper.cpp:648-656 and :1053-1067 fall through and the replayed script silently rebinds the object to the owning database instead of refusing the unsound dump. This map needs the same external-database visibility handling as the main system.tables scan, or the omitted-database check needs to stop relying on external databases being visible here.

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

3 participants