Skip to content

Implement CREATE OR REPLACE for MATERIALIZED VIEWs - #100539

Merged
alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
il9ue:create-or-replace-materialized-view
May 19, 2026
Merged

alexey-milovidov merged 11 commits into
ClickHouse:masterfrom
il9ue:create-or-replace-materialized-view

Conversation

@il9ue

@il9ue il9ue commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Implement CREATE OR REPLACE for MATERIALIZED VIEWs

CREATE OR REPLACE TABLE and CREATE OR REPLACE VIEW already work, but CREATE OR REPLACE MATERIALIZED VIEW was silently misparsed as an ordinary view. This PR fixes that.

What changed

Parser fix (ParserCreateQuery.cpp): Removed the !replace_view && guard that prevented MATERIALIZED from being consumed when OR REPLACE was set. Now both replace_view and is_materialized_view can be true simultaneously. All MV-specific clauses (TO, ENGINE, POPULATE, REFRESH) are gated on is_materialized_view and parse correctly.

Access check fix (InterpreterCreateQuery.cpp): The replace-view access check unconditionally required CREATE_VIEW. Now it requires CREATE_MATERIALIZED_VIEW when 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, or ASTCreateQuery.h — the downstream interpreter (doCreateOrReplaceTable) already handles the atomic swap correctly for MVs:

  1. Temp MV created (auto-creates inner table when no TO clause)
  2. Atomic RENAME EXCHANGE swaps temp ↔ target
  3. Old MV dropped (dropInnerTableIfAny cleans up its inner table)

Test coverage (04054_create_or_replace_materialized_view)

Case Description
1 First create (MV doesn't exist yet)
2 Replace with schema change, verify pipeline works
3 Inner table recreation (exactly one .inner_id.* after replace)
4 TO-table case
5 Switch inner-table → TO-table
6 Switch TO-table → inner-table
7 REPLACE MATERIALIZED VIEW (without CREATE) → clientError SYNTAX_ERROR
8 POPULATE with OR REPLACE — existing rows populated, second replace repopulates
9 Idempotency — identical replace twice; documents data-loss semantics
10 REFRESH EVERY N HOUR clause parses and replaces correctly
11 OR REPLACE + IF NOT EXISTS → clientError SYNTAX_ERROR
12 Complex AS SELECT with INNER JOIN

Closes #94898
Ref #5709

Changelog category (leave one):

  • New Feature

Changelog entry

Support CREATE OR REPLACE MATERIALIZED VIEW with the same atomic swap semantics as CREATE OR REPLACE TABLE. Works with inner tables, TO tables, POPULATE, REFRESH, and ON CLUSTER.

Documentation entry for user-facing changes

  • Documentation is written (mandatory for new features)

CREATE OR REPLACE MATERIALIZED VIEW is now supported on Atomic and Replicated databases. Semantics:

  • Atomically replaces the view definition and its inner storage table (if any).
  • When no TO clause is used, the old inner table is dropped and a new one is created. Existing data in the inner table is lost unless POPULATE is specified.
  • When a TO clause is used, only the view definition is replaced; the target table is unaffected.
  • Compatible with REFRESH, POPULATE, ON CLUSTER, and all engine options.
-- Basic usage
CREATE OR REPLACE MATERIALIZED VIEW mv
    ENGINE = MergeTree ORDER BY x
    AS SELECT x, sum(y) AS total FROM src GROUP BY x;

-- With explicit target table
CREATE OR REPLACE MATERIALIZED VIEW mv TO target_table
    AS SELECT x FROM src;

-- With POPULATE (backfill existing data)
CREATE OR REPLACE MATERIALIZED VIEW mv
    ENGINE = MergeTree ORDER BY x
    POPULATE
    AS SELECT x FROM src;

Version info

  • Merged into: 26.5.1.792

@alexey-milovidov alexey-milovidov added the can be tested Allows running workflows for external contributors label Mar 24, 2026
@alexey-milovidov alexey-milovidov self-assigned this Mar 24, 2026
@clickhouse-gh

clickhouse-gh Bot commented Mar 24, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [ca588ac]

Summary: ✅


AI Review

Summary

This PR correctly fixes parsing and documentation around CREATE OR REPLACE MATERIALIZED VIEW, but one core behavior mismatch remains: on Ordinary databases the query is still accepted and executed as non-atomic drop+create. I requested changes because this contradicts the stated unsupported semantics and can cause silent non-atomic replacement.

Findings

❌ Blockers

  • [src/Interpreters/InterpreterCreateQuery.cpp:1792,1923] CREATE OR REPLACE MATERIALIZED VIEW is still not rejected on Ordinary databases. The code only routes replace_view into doCreateOrReplaceTable for Atomic/Replicated; for Ordinary it falls back to doCreateTable, which drops and recreates when create.replace_view is set. This is a semantic mismatch vs the documented “not supported on Ordinary” behavior and should be rejected explicitly.
    Suggested fix: route replace_view through the same rejection path for non-UUID databases, or add an explicit guard before doCreateTable to throw INCORRECT_QUERY for replace_view on Ordinary.

⚠️ Majors

  • [src/Databases/DatabaseReplicated.cpp:2315] The new DatabaseReplicated-specific inner-table metadata path still has no dedicated regression test in a replicated/ZooKeeper environment. The current stateless tests do not validate this code path, so regressions in .inner_id.* metadata handling can reappear unnoticed.
    Suggested fix: add a replicated integration/stateless-zookeeper test that does CREATE OR REPLACE MATERIALIZED VIEW (auto inner table) followed by explicit DROP, and asserts clean metadata lifecycle with no No node exception.
Tests
  • ⚠️ Add a negative Ordinary-database test for CREATE OR REPLACE MATERIALIZED VIEW to lock expected behavior (INCORRECT_QUERY if unsupported).
  • ⚠️ Add a replicated/ZooKeeper regression test for the .inner_id.* metadata path changed in DatabaseReplicated::commitCreateTable.
ClickHouse Rules
Item Status Notes
Deletion logging ➖
Serialization versioning ➖
Core-area scrutiny ✅
No test removal ✅
Experimental gate ➖
No magic constants ✅
Backward compatibility ⚠️ Ordinary path still performs non-atomic replace semantics instead of rejecting unsupported syntax
SettingsChangesHistory.cpp ➖
PR metadata quality ✅
Safe rollout ⚠️ Replicated metadata fix is not covered by a dedicated replicated test
Compilation time ✅
No large/binary files ✅
Final Verdict
  • Status: ⚠️ Request changes
  • Minimum required actions:
    1. Reject CREATE OR REPLACE MATERIALIZED VIEW on Ordinary databases in code (or intentionally support it and update docs/tests accordingly, but behavior and docs must match).
    2. Add replicated-path regression coverage for the inner-table metadata fix in DatabaseReplicated.

@clickhouse-gh clickhouse-gh Bot added the pr-feature Pull request with new product feature label Mar 24, 2026
Comment thread src/Databases/DatabaseReplicated.cpp Resolved
il9ue added 3 commits April 3, 2026 16:15
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.
@il9ue
il9ue force-pushed the create-or-replace-materialized-view branch from 2367b96 to c4b0e31 Compare April 3, 2026 14:15
- 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`.
@alexey-milovidov

Copy link
Copy Markdown
Member

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.

@il9ue
il9ue force-pushed the create-or-replace-materialized-view branch from 0dd1f4e to 0a05d0c Compare April 7, 2026 12:54
@alexey-milovidov

Copy link
Copy Markdown
Member

The test 02859_replicated_db_name_zookeeper is fixed in #101952

Comment thread src/Databases/DatabaseReplicated.cpp Resolved
@alexey-milovidov

Copy link
Copy Markdown
Member

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

@alexey-milovidov

Copy link
Copy Markdown
Member

The Hung check failure is fixed by #102008 and #102010, let's update the branch

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
@alexey-milovidov

Copy link
Copy Markdown
Member

@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 02932_refreshable_materialized_views_2 timeout is a known flaky test (27 failures in 14 days across 24 unique PRs in Fast test alone, per CIDB). It is unrelated to this PR (which doesn't touch refreshable MV code). Please provide a fix in a separate PR. If a fix is already in progress, link it here.

@groeneai

Copy link
Copy Markdown
Collaborator

@alexey-milovidov tracking and fix PR: #105156 — marks the test long so Fast test (--no-long) stops running it; every other stateless test job still covers it. CIDB confirms the test is chronic in Fast test only (30 fails/30d/27 PRs, 0 master failures with head_ref = 'master'), and the 99th-percentile wall time on Fast test is already up against the 60s budget. cc @al13n321 (refreshable-MV component owner) for review on #105156.

pull Bot pushed a commit to admariner/ClickHouse that referenced this pull request May 17, 2026
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]>
@clickhouse-gh

clickhouse-gh Bot commented May 18, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 84.10% 84.10% +0.00%
Functions 91.10% 91.10% +0.00%
Branches 76.50% 76.50% +0.00%

Changed lines: 64.71% (11/17) · Uncovered code

Full report · Diff report

@alexey-milovidov
alexey-milovidov added this pull request to the merge queue May 19, 2026
Merged via the queue into ClickHouse:master with commit 235dafa May 19, 2026
325 of 326 checks passed
@robot-clickhouse-ci-2 robot-clickhouse-ci-2 added the pr-synced-to-cloud The PR is synced to the cloud repo label May 19, 2026
alexey-milovidov added a commit to vvo/ClickHouse that referenced this pull request May 19, 2026
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
alexey-milovidov added a commit to vvo/ClickHouse that referenced this pull request May 19, 2026
…erialized-view

Implement CREATE OR REPLACE for MATERIALIZED VIEWs
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 pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement CREATE OR REPLACE for MATERIALIZED VIEWs

4 participants