Repository navigation
Add --dump-schema option to clickhouse-client and clickhouse-local - #114098
valerypetrov wants to merge 1 commit into
Conversation
|
@groeneai, please check this one. If you won't have any major findings, please tag someone from the ClickHouse team to review this PR. |
|
Reviewed. One blocker, then some smaller notes. Blocker: views and materialized views are not dependency-ordered, so the dump does not replay
Reproduced on master (26.8.1.1), realistic names, no cycle involved:
Same failure for a plain Two things fall out of this:
Smaller notes
Given the blocker I have not tagged a reviewer yet. Ping me once the ordering is fixed and I will route it. |
|
@groeneai Fixed, thanks for the very thorough repro — I reproduced your exact case locally ( Root cause was exactly what you found: Also fixed the Test ( 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 |
|
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 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). |
|
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 Two distinct false-positive classes, both reproduced on master (26.8.1.1) by running the predicate at 1. Substring, not identifier, matching. 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;
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. So subqueries and CTEs (the residual you flagged) resolve correctly, and both false-positive classes disappear. Better still, Smaller notes:
Thanks for the ordering and |
|
@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: Your CTE-alias caveat turned out to be free: I confirmed empirically that a CTE alias reference stays unqualified in server-formatted SQL ( Went with the local AST-walk fallback you flagged, not Verified against both your exact repros ( Test now covers both false-positive classes, a genuine view-on-view/view-on-table chain (round-tripped through actual replay), and the |
|
The AST walk is the right call, and I verified all three things you claimed. The empty-database-part filter ( 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 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;
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 Two precisions so you do not over-fix, both measured:
Fix direction: the scan you already wrote is the right tool, just gated too narrowly. Dropping the The test cannot catch this: 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. |
|
@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 Verified against your exact JOIN repro ( |
|
Round-4 blocker is discharged. I verified the widened gate at One more blocker in the same place, though.
Negative control for both: emit the missed object first and replay is RC=0 with data flowing ( Two precisions, since they scope it:
The test cannot catch either. Fix direction, verified only to this depth: the server's own extractor already handles exactly these argument positions in Holding the reviewer routing one more round, for the same reason as before. Ping me once this is in and I will route it. |
|
@groeneai Fixed. Went further than the two cases you'd verified — audited Deliberately excluded 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 Your exact |
|
Verified at The arm discriminates, which is the part the previous rounds' suites failed. Restoring the old I also checked the widening for a round-2 style false cycle, since arg 0 of One correction, not a blocker. 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 cc @azat @yakov-olkhovskiy, could you review this? It adds a client-side |
|
Workflow [PR], commit [675b6bd] AI ReviewSummaryThis PR adds Findings❌ Blockers
Tests
Final VerdictNot ready. The current head still breaks replay for some supported schemas and can silently rebind subset dumps that depend on omitted external databases. |
Build profile diff (arm_release)Comparing Binary sizes
The official master build is compiled with Object file sizes
|
| 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
|
Checked the three claims at head The code-comment claim holds. The older-target sentence is still at The two docs claims are not in the tree yet. The row at 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. |
|
You are right, and my earlier comment was wrong to describe it in the present tense. The clause exists as a local commit, Nothing about the content has changed; the wording and the Worth saying that your check was right on all three counts, including the one that agreed with me: the code comment at |
|
Landed. Head is now The run on the parent finished clean before I pushed, which is why the push waited: 152 jobs green, nothing failed, and Your |
| /// `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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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↔ aNullable(Tuple(...)), the
database-engine ones ↔ theirENGINE. 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 SELECTrather than anything recorded in the storedCREATE
(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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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:688analyses columnDEFAULT/MATERIALIZEDexpressions through
validateColumnsDefaultsAndGetSampleBlockat CREATE time. A plainCREATE TABLEwith 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-410runsbuildQueryTreeand
runOnlyResolve— soCREATE TABLE t (..., PROJECTION p (SELECT x, count() GROUP BY x))reaches
validateGroupByKeyTypewith no view present. That covers
allow_suspicious_types_in_group_by,allow_suspicious_types_in_order_byand
allow_experimental_correlated_subqueriesalike. - Two of the names cannot gate anything.
allow_experimental_window_functionsis
MAKE_OBSOLETE(Settings.cpp:9185) andallow_experimental_hash_functionshas no reader in
src/outside its own declaration.allow_simdjsonnever rejects either —DataTypeObject.cpp:159
andFunctionsJSON.cpp:696use 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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.
|
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:
One real hole surfaced while verifying (3a2a69b): 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. |
| /// 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
👷🏻 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
👷🏻 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) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
👷🏻 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.
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
👷🏻 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.
a3e5f41 to
854fc1b
Compare
82a2604 to
675b6bd
Compare
| undumped_list += ", "; | ||
| undumped_list += quoteString(db); | ||
| } | ||
| executeQuery(connection, timeouts, client_info, |
There was a problem hiding this comment.
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>
675b6bd to
a79c21a
Compare
Closes: #60681
Adds a
--dump-schema[=<db1,db2,...>]option that dumpsCREATE DATABASE/CREATE TABLE/CREATE DICTIONARY/CREATE MATERIALIZED VIEW/CREATE VIEWstatements for one or more databases, or all non-system user databases if no value is given, to stdout, then exits — similar topg_dump --schema-only.Tables are ordered (via
TablesDependencyGraph, the same classDatabaseCataloguses 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 signalsystem.tablesexposes, combined:loading_dependencies_*(dictionaries), inverteddependencies_*(a materialized view's source — recorded only on the source row, not the view),target_database/target_table(a materialized view'sTOtarget, explicit or implicit), and — since the server tracks none of this for plain views at all (DROP TABLEon a view's source succeeds even with the view still referencing it) — a best-effort scan of each view's stored, server-formattedSELECTtext 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_queryandSHOW CREATE DATABASEalready 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 asSuggest.cpp) and prints the results in dependency order.--dump-schemaalso accepts a comma-separated database list (--dump-schema=db1,db2), and two modifiers:--dump-schema-exclude=db1,db2dumps 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>.sqlfile 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 withescapeForFileNamebefore 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:
CREATE MATERIALIZED VIEWstatement) — 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-schemaforces 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. Forclickhouse-local, it's also rejected combined with--file/--structure.--dump-schema-exclude/--dump-schema-dirare rejected if--dump-schemaitself isn't given — all validated inprocessConfig(), beforeconnect(), so a plain argument mistake fails fast instead of after a connection attempt (which could otherwise block on an interactive password prompt).clickhouse-localinstance: a source table with a materialized view (implicit storage), a dictionary, a plain view, a view-on-view chain, and an explicitTOtarget, named so that alphabetical order alone would produce an unreplayable dump without the fix; single/list/exclude/all-databases selection;--dump-schema-diroutput 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 thatFoo/foocoexist 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):
Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):
Added a
--dump-schema[=<db1,db2,...>]option toclickhouse-clientandclickhouse-localthat dumpsCREATE DATABASE/CREATE TABLE/CREATE DICTIONARY/CREATE MATERIALIZED VIEW/CREATE VIEWstatements for the given database(s), or all user databases if no value is given, to stdout in dependency order, then exits — similar topg_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>.sqlfile per dumped database into that directory instead of stdout.Workflow [PR]
Sync PR [sync-upstream/pr/114098]