Repository navigation
Implement CREATE OR REPLACE for MATERIALIZED VIEWs - #100539
alexey-milovidov merged 11 commits into
Conversation
|
Workflow [PR], commit [ca588ac] Summary: ✅ AI ReviewSummaryThis PR correctly fixes parsing and documentation around Findings❌ Blockers
Tests
ClickHouse Rules
Final Verdict
|
The parser previously prevented `OR REPLACE` from combining with
`MATERIALIZED VIEW` due to a guard on the `replace_view` flag
(`!replace_view && s_materialized.ignore(...)`). Removing this guard
allows both `replace_view` and `is_materialized_view` to be set
simultaneously. The downstream interpreter (`doCreateOrReplaceTable`)
already handles the atomic swap correctly for materialized views via
the existing temp-table + RENAME EXCHANGE mechanism:
1. A temporary MV (with a hash-based random name) is created, which
also auto-creates the inner table when no `TO` clause is given.
2. The temporary MV is atomically exchanged with the target MV.
3. The old MV is dropped, which auto-drops its inner table via
`dropInnerTableIfAny`.
Also add extended test coverage for CREATE OR REPLACE MATERIALIZED VIEW :
Cases 7-12 added to `04054_create_or_replace_materialized_view`:
7. `REPLACE MATERIALIZED VIEW` (without CREATE) is a client-side
syntax error — the parser only handles `REPLACE TABLE`, not
`REPLACE MATERIALIZED VIEW`; uses `clientError SYNTAX_ERROR`.
8. `POPULATE` with `OR REPLACE`: verifies that existing `src` rows
are read into the new inner table via `fillTableIfNeeded`, and
that a second replace populates from the full current `src`.
9. Idempotency: two identical `CREATE OR REPLACE` in sequence;
documents data-loss semantics (the inner table is replaced, so
rows inserted before the second replace are gone).
10. `REFRESH` clause: `OR REPLACE` parses and executes correctly
when combined with `REFRESH EVERY N HOUR`.
11. `OR REPLACE` combined with `IF NOT EXISTS` is a client-side
syntax error (the parser skips `IF NOT EXISTS` when
`replace_view=true`, leaving `IF` as an unexpected table-name
token); uses `clientError SYNTAX_ERROR`.
12. Non-trivial `AS SELECT` with `INNER JOIN`: verifies that a
complex SELECT in the body parses and the MV is created.
Also fix the `clientError` annotation for cases 7 and 11: both errors
are caught by the ClickHouse client-side parser before the query
reaches the server, so `serverError` was incorrect.
Closes ClickHouse#94898
Ref ClickHouse#5709
…eplicated databases When `CREATE OR REPLACE MATERIALIZED VIEW` runs against a `DatabaseReplicated`, the atomic swap (RENAME EXCHANGE) commits the ZooKeeper metadata transaction. The subsequent cleanup drops (old MV under its temp name and its old inner table) happen outside that already-committed transaction. Because both the metadata-node removal and the per-replica digest update in `dropTable` are gated on `!isCreateOrReplaceQuery()`, neither ran for those cleanup drops. The old inner table's ZK metadata node (`/metadata/.inner_id.<UUID>`) was never removed, and the ZK digest diverged from the local `tables_metadata_digest`. This caused `lost_according_to_digest = true` in `DatabaseReplicatedWorker`, which triggered `recoverLostReplica`, which then failed with `KEEPER_EXCEPTION` trying to operate on the stale node. Fix: in `DatabaseReplicated::dropTable`, add an `else if` branch for the case `isCreateOrReplaceQuery() && isExecuted()`. In that branch, perform direct ZK operations (outside any transaction) to: 1. `tryRemove` the metadata node (no-op for tables that were never written to ZK). 2. `trySet` the per-replica digest to keep local and ZK state in sync.
In `DatabaseReplicated::dropTable`, the `CREATE OR REPLACE` cleanup branch uses direct ZK operations (outside the already-committed transaction) to remove the old metadata node and update the per-replica digest. The previous code used bare `try*` calls and discarded the return code, so transient errors (`ZCONNECTIONLOSS`, `ZSESSIONEXPIRED`, `ZOPERATIONTIMEOUT`) would silently leave ZK state inconsistent with local state, causing subsequent digest mismatches and unintended recovery. Fix: check the return code of both calls and throw `zkutil::KeeperException::fromPath` on non-expected errors. - `tryRemove`: `ZNONODE` is expected (temp tables never written to ZK); anything else is a genuine failure and is re-thrown. - `trySet` on the digest path: `ZNONODE` would mean the replica's `/digest` node is missing, which is itself an inconsistency; every non-`ZOK` code is re-thrown.
2367b96 to
c4b0e31
Compare
- Replace bare `DROP TABLE test_mv` in case 4 of `04054_create_or_replace_materialized_view.sql` with a direct `CREATE OR REPLACE`, avoiding a double-remove of the ZK metadata node that caused `Transaction failed (No node)` on `DatabaseReplicated`. - Add `SYNC` to all `DROP TABLE IF EXISTS test_mv` calls in the test so drops complete before subsequent creates in a replicated database. - Add `DROP TABLE IF EXISTS src2 SYNC` to the cleanup section. - Add documentation for `CREATE OR REPLACE MATERIALIZED VIEW` to `docs/en/sql-reference/statements/create/view.md` to satisfy the `feature_docs.py` CI gate.
…d databases Root cause: `DatabaseReplicated::commitCreateTable` skips writing the ZK metadata node when `isCreateOrReplaceQuery()` is true, which is correct for the outer temporary MV table (the RENAME EXCHANGE transaction creates the metadata under the final name). However, the inner table (`.inner_id.<uuid>`) is NOT renamed during the exchange — it keeps its UUID-based name throughout — so its ZK metadata was never written anywhere. A subsequent explicit `DROP TABLE` on the MV would try to remove `/metadata/.inner_id.<uuid>` and fail with `KEEPER_EXCEPTION: Transaction failed (No node)`. Fix: in `commitCreateTable`, write the ZK metadata node for inner tables even when `isCreateOrReplaceQuery()` is true. The op is appended to the transaction without committing it; it is committed atomically together with the RENAME EXCHANGE ops when `renameTable` fires `txn->commit()`. Also restructure test case 8 to remove `POPULATE` from `CREATE OR REPLACE MATERIALIZED VIEW`, as `CREATE ... POPULATE` is not supported on Replicated databases (throws `SUPPORT_IS_DISABLED`). The restructured case verifies the same property — the inner table is fresh after a replace — without `POPULATE`.
|
The Stress test (arm_msan) failure is fixed by #101239, which should be merged first. After it is merged, please update the branch to include the fix. |
0dd1f4e to
0a05d0c
Compare
|
The test |
|
The MSan stress test failure (MemorySanitizer: use-of-uninitialized-value, STID 4179-5154 or 4148-3044) is a known pre-existing issue unrelated to this PR. Fix: #102158 |
…create-or-replace-materialized-view
CI failure in DatabaseReplicated config: case 10 of `04054_create_or_replace_materialized_view` failed because refreshable MVs with non-replicated inner tables are refused on a `Replicated` database with `BAD_ARGUMENTS`: "This combination doesn't work: refreshable materialized view, no APPEND, replicated database, non-replicated table. The refresh would be done on one replica, but the table would be replaced on other replicas too (with empty tables). Refusing to create." Moved the `REFRESH` case into its own test `04227_create_or_replace_refresh_mv.sql` tagged `no-ordinary-database, no-replicated-database`; the original test keeps its `no-ordinary-database` tag so it still exercises the `DatabaseReplicated` path that this PR also fixes. Doc updates (review feedback): - Split the `CREATE [OR REPLACE] MATERIALIZED VIEW` syntax line into two forms and note that `OR REPLACE` and `IF NOT EXISTS` are mutually exclusive. - Corrected the privileges bullet to `CREATE VIEW` and `DROP VIEW` (the interpreter check uses these, not `CREATE_MATERIALIZED_VIEW`). - Clarified that `POPULATE` is supported only on `Atomic` databases, not on `Replicated` ones. CI report: ClickHouse#100539
|
@groeneai, investigate the failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100539&sha=ca588ac6d6dad5bfd61156a014a09e928cea8ed4&name_0=PR&name_1=Fast%20test — the Fast test |
|
@alexey-milovidov tracking and fix PR: #105156 — marks the test |
This stateless test is fundamentally too heavy for the `Fast test` job's 60-second per-test budget. It exercises ~10 `SYSTEM WAIT VIEW` calls, multiple `REFRESH EVERY 1 SECOND` materialized views with `sleepEachRow(1)` source data, and ~11 polling loops, each of which spawns a fresh `clickhouse-client` process. CIDB shows the test passes 99% of `Fast test` runs (median 13s, p99 18s, max passing 48s) but the remaining ~1% spike past the 60s timeout under CI load and are killed at process-group level. The killed call site is typically the first `system wait view e;` after creating a `REFRESH EVERY 1 SECOND` view, where CI load delays scheduler progress past the budget. Recent timeline (chronic, not a regression): 30 days, `Fast test` job alone: 30 failures across 27 distinct PRs. 0 master failures with `head_ref = 'master'` (the 3 nominal master failures were `gh-readonly-queue/master/pr-*` merge-queue runs that also exercised `Fast test`). The `long` tag keeps this test out of `Fast test` (which is invoked with `--no-long` in `ci/jobs/fast_test.py`) while preserving coverage on all other stateless test configurations — including `amd_debug, parallel`, `amd_tsan, parallel`, `amd_msan, WasmEdge`, `amd_asan_ubsan, distributed plan`, `arm_binary`, `arm_asan_ubsan, azure`, `amd_llvm_coverage` and the various flaky-check variants. Each of these saw 500+ passing runs in 30 days with zero failures, so coverage on the actual test is not affected. A representative failure: https://s3.amazonaws.com/clickhouse-test-reports/json.html?PR=100539&sha=ca588ac6d6dad5bfd61156a014a09e928cea8ed4&name_0=PR&name_1=Fast%20test (failure raised on ClickHouse#100539 by @alexey-milovidov) Co-Authored-By: Claude Opus 4.7 <[email protected]>
LLVM Coverage Report
Changed lines: 64.71% (11/17) · Uncovered code |
235dafa
CI failure in DatabaseReplicated config: case 10 of `04054_create_or_replace_materialized_view` failed because refreshable MVs with non-replicated inner tables are refused on a `Replicated` database with `BAD_ARGUMENTS`: "This combination doesn't work: refreshable materialized view, no APPEND, replicated database, non-replicated table. The refresh would be done on one replica, but the table would be replaced on other replicas too (with empty tables). Refusing to create." Moved the `REFRESH` case into its own test `04227_create_or_replace_refresh_mv.sql` tagged `no-ordinary-database, no-replicated-database`; the original test keeps its `no-ordinary-database` tag so it still exercises the `DatabaseReplicated` path that this PR also fixes. Doc updates (review feedback): - Split the `CREATE [OR REPLACE] MATERIALIZED VIEW` syntax line into two forms and note that `OR REPLACE` and `IF NOT EXISTS` are mutually exclusive. - Corrected the privileges bullet to `CREATE VIEW` and `DROP VIEW` (the interpreter check uses these, not `CREATE_MATERIALIZED_VIEW`). - Clarified that `POPULATE` is supported only on `Atomic` databases, not on `Replicated` ones. CI report: ClickHouse#100539
…erialized-view Implement CREATE OR REPLACE for MATERIALIZED VIEWs
Implement CREATE OR REPLACE for MATERIALIZED VIEWs
CREATE OR REPLACE TABLEandCREATE OR REPLACE VIEWalready work, butCREATE OR REPLACE MATERIALIZED VIEWwas silently misparsed as an ordinary view. This PR fixes that.What changed
Parser fix (
ParserCreateQuery.cpp): Removed the!replace_view &&guard that preventedMATERIALIZEDfrom being consumed whenOR REPLACEwas set. Now bothreplace_viewandis_materialized_viewcan be true simultaneously. All MV-specific clauses (TO,ENGINE,POPULATE,REFRESH) are gated onis_materialized_viewand parse correctly.Access check fix (
InterpreterCreateQuery.cpp): The replace-view access check unconditionally requiredCREATE_VIEW. Now it requiresCREATE_MATERIALIZED_VIEWwhen the target is a materialized view, preventing privilege escalation.Error message (
InterpreterCreateQuery.cpp): The non-Atomic database error now says "CREATE OR REPLACE MATERIALIZED VIEW" instead of the generic "CREATE OR REPLACE TABLE".No changes to
StorageMaterializedView,DatabaseAtomic, orASTCreateQuery.h— the downstream interpreter (doCreateOrReplaceTable) already handles the atomic swap correctly for MVs:TOclause)dropInnerTableIfAnycleans up its inner table)Test coverage (
04054_create_or_replace_materialized_view).inner_id.*after replace)TO-table caseTO-tableTO-table → inner-tableREPLACE MATERIALIZED VIEW(withoutCREATE) →clientError SYNTAX_ERRORPOPULATEwithOR REPLACE— existing rows populated, second replace repopulatesREFRESH EVERY N HOURclause parses and replaces correctlyOR REPLACE+IF NOT EXISTS→clientError SYNTAX_ERRORAS SELECTwithINNER JOINCloses #94898
Ref #5709
Changelog category (leave one):
Changelog entry
Support
CREATE OR REPLACE MATERIALIZED VIEWwith the same atomic swap semantics asCREATE OR REPLACE TABLE. Works with inner tables,TOtables,POPULATE,REFRESH, andON CLUSTER.Documentation entry for user-facing changes
CREATE OR REPLACE MATERIALIZED VIEWis now supported on Atomic and Replicated databases. Semantics:TOclause is used, the old inner table is dropped and a new one is created. Existing data in the inner table is lost unlessPOPULATEis specified.TOclause is used, only the view definition is replaced; the target table is unaffected.REFRESH,POPULATE,ON CLUSTER, and all engine options.Version info
26.5.1.792