You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Support Replicated MergeTree engines and ON CLUSTER DDL (#71) - #73
On a self-managed cluster, the provider creates only plain MergeTree family tables, and only on the server of the connection. Rows written to one replica do not get to the other replicas. The migrations history table has the same problem: each replica has its own history, so a migration that ran through one replica looks unapplied on another. That is the divergence that #71 reports.
A Replicated engine alone does not fix this. ClickHouse does not replicate CREATE TABLE and DROP TABLE. It does replicate ALTER TABLE on a Replicated table, so running the migrations once on each host fails at the second host. The DDL must run once, on all hosts.
What
Replicated engines. Each MergeTree family engine builder has two new methods:
b.ToTable("events", t =>t.HasReplacingMergeTreeEngine("Version").WithOrderBy("Id").WithReplication());// ReplicatedReplacingMergeTree(`Version`)// .WithReplication("/clickhouse/tables/{shard}/{database}/{table}", "{replica}")// // ReplicatedReplacingMergeTree('/clickhouse/...', '{replica}', `Version`)
Without arguments, ClickHouse uses the server settings default_replica_path and default_replica_name. The model keeps the engine annotation as it is (for example ReplacingMergeTree) and adds ClickHouse:Replicated, ClickHouse:Replicated:ZooKeeperPath and ClickHouse:Replicated:ReplicaName. Model validation rejects replication on Log and Memory engines, and a path without a replica name. Because the annotations have the ClickHouse: prefix, the existing AlterTable check rejects a migration that turns replication on or off.
UseCluster(name). A context option that adds ON CLUSTER '<name>' to the DDL that migrations, EnsureCreated() and EnsureDeleted() generate:
CREATE DATABASE and DROP DATABASE (the migration operations and the database creator)
CREATE TABLE, DROP TABLE, RENAME TABLE
every ALTER TABLE: ADD/DROP/MODIFY/RENAME COLUMN, the REMOVE CODEC/TTL/COMMENT statements, ADD/DROP INDEX, ADD/DROP CONSTRAINT
The name is a string literal, so macros such as {cluster} work. DROP TABLE and the two check constraint operations now have their own overrides, because the base implementations have no place for the clause. The check constraint overrides keep the statement terminator of the base implementations. The CREATE TABLE override writes the statement itself for the same reason.
Replicated migrations history table.
With UseCluster, __EFMigrationsHistory is ReplicatedMergeTree('/clickhouse/tables/{uuid}', '{shard}-{replica}'). The server default path contains {shard}, which gives each shard its own history. Then a host on a second shard sees no applied migrations and fails on CREATE TABLE ... ON CLUSTER (TABLE_ALREADY_EXISTS). I checked both paths on a two-shard cluster. {shard}-{replica} keeps the replica names unique when shards reuse the same replica names.
A database with the Replicated engine refuses ON CLUSTER and an explicit path. So UseReplicatedMigrationsHistoryTable() gives ReplicatedMergeTree() without ON CLUSTER. There, each shard has its own history: a Replicated database refuses a replicated table that the shards share, also with database_replicated_allow_replicated_engine_arguments set to 1 or 3 (checked on a two-shard cluster). The README and XML docs say to run the migrations through one shard.
A replicated history table has replicated_deduplication_window = 0 and replicated_deduplication_window_for_async_inserts = 0. Without them, ClickHouse drops the second history row of a migration that is reverted and applied again (the row is equal to the first one). Then the next Migrate() fails with TABLE_ALREADY_EXISTS.
An existing history table is not converted. The README has the SQL to convert a MergeTree history table, and I tested it on the cluster.
Statement terminators in migration scripts (also fixed here). EF Core puts only a line break between the commands of a migration script. The provider's ALTER TABLE, RENAME TABLE, CREATE DATABASE and DROP DATABASE statements had no ;, so clickhouse-client read two statements as one and failed with a syntax error. This bug is also on main. Migrations that run from code were not affected, because the provider sends each statement separately. All statement ends in the SQL generator now go through one helper, TerminateStatement, that appends the terminator.
How
ClickHouseEngineBuilder has two protected helpers that set the annotations. The seven MergeTree family builders expose them as WithReplication overloads. Log and Memory builders do not get the method.
ClickHouseMigrationsSqlGenerator puts the path and replica name before the engine arguments, and prefixes the engine name with Replicated. The engine-argument code now returns a list, so that the two kinds of arguments join with one separator.
UseCluster and UseReplicatedMigrationsHistoryTable are properties of ClickHouseOptionsExtension. The generator, the database creator and the history repository read them from IDbContextOptions. These services are scoped, so two contexts with different settings that share one internal service provider still generate different DDL.
The MergeTree family check moves to one internal helper (ClickHouseEngines), which the convention, the validator and the generator share.
Design notes
Replication is part of the model, so it is in the migrations. The cluster name is an option, so the same migrations can run with or without ON CLUSTER. A development server without ClickHouse Keeper cannot create a Replicated table.
Public API change: the constructors of ClickHouseMigrationsSqlGenerator and ClickHouseDatabaseCreator take IDbContextOptions (the creator also takes IRelationalTypeMappingSource). A subclass must pass them on.
WithReplication() without arguments uses the server default path, which contains {uuid}. ClickHouse accepts {uuid} only with ON CLUSTER or in a Replicated database. The README and XML docs say this.
A Replicated table ignores an insert with the same rows as a recent insert, so two equal SaveChanges calls store the rows once. The README says this and names the table setting that keeps both. (On 26.10 the session setting insert_deduplicate=0 has no effect, because deduplicate_insert overrides it.)
The provider has no migration lock (this is not new). Two migrators on different replicas can still race, and a host sees a migration as applied only after its history row has replicated. The README says to run the migrations from one place.
Not in this PR: Distributed tables, DROP ... SYNC, and a Replicated database engine for EnsureCreated(). The README tells users to keep {uuid} in an explicit path, because a drop and a create with the same fixed path fails for about 8 minutes (REPLICA_ALREADY_EXISTS). To use other history table settings, a user can derive from ClickHouseHistoryRepository. A test shows how.
Tests
MigrationScriptIntegrationTests (1 test, single server): generates the script of three migrations that use each overridden statement, as dotnet ef migrations script does, splits it at the terminators and runs each statement. It then checks the schema and the history rows. I also ran the same script through clickhouse-client --multiquery by hand: exit code 0, with the expected schema and 3 history rows. Every_DDL_statement_ends_with_the_statement_terminator checks all 14 DDL statement kinds, with and without UseCluster. Without the terminator, all three tests fail.
ReplicationSqlGenerationTests (35 tests, no server): the default and the explicit path for each of the 7 engines, escaping, validation, the AlterTable rejection, ON CLUSTER on each DDL statement, and the three history table configurations.
ReplicationIntegrationTests (5 tests): a new ClickHouseClusterFixture starts three clickhouse-server:latest containers, with ClickHouse Keeper embedded in the first. It defines two clusters: test_cluster, one shard with the replicas ch1 and ch2, and two_shards, which adds ch3 as a second shard. ch3 reuses the replica name r1 of ch1. Each test writes through one host and reads through another:
EnsureCreated with all 6 engines that need no server config (GraphiteMergeTree needs a rollup config). Each table has 2 replicas in system.replicas, rows written through replica 1 can be read through replica 2, and EnsureDeleted removes the database on both.
Migrations: migration 1 applied through replica 1, then replica 2 lists only migration 2 as pending and applies it. Replica 1 then lists both as applied, reverts migration 2 and applies it again, and replica 2 then has no pending migrations.
Two shards that reuse a replica name: migration 1 applied through shard 01, then ch3 (shard 02) lists only migration 2 as pending and applies it. A history path with {shard} makes this test fail on the pending migrations. A replica name without {shard} makes it fail with REPLICA_ALREADY_EXISTS.
An explicit path and UseCluster("{cluster}").
A Replicated database with UseReplicatedMigrationsHistoryTable().
I made each part of the fix fail on purpose and ran the cluster tests. With a history table that is not replicated, the 2 migration tests fail. Without ON CLUSTER, the 3 tests that use it fail. With insert deduplication left on in the history table, the migration test fails at the revert-and-apply step.
Not in CI, checked by hand: the history table conversion SQL, and the migration code and model snapshot that dotnet ef migrations add scaffolds for a replicated table. The annotations come out as .Annotation("ClickHouse:Replicated", true) and so on.
A separate review agent read the first commit and tested it on the cluster. The second commit fixes what it found: the history row deduplication, the shard path, ON CLUSTER for check constraints, and the missing docs.
Full suite: EFCore.ClickHouse.Tests 704 passed (661 before), EFCore.ClickHouse.FunctionalTests 323 passed, 4 skipped (the same as before). The cluster fixture adds about 45 s.
Build: 0 errors. The provider project has the same 45 warnings as main. The test projects have 13 more EF1001 warnings, because the new unit tests use ClickHouseAnnotationNames the same way as the existing tests.
Medium Risk
Changes migration DDL generation and shared migration history on clusters; incorrect cluster/replication config can fail migrations or diverge history across hosts. Constructor signature changes affect custom subclasses of the SQL generator and database creator.
Overview
Adds cluster-ready table engines and DDL so self-managed ClickHouse deployments can use Replicated MergeTree tables and run migrations consistently across hosts.
Replicated engines: Every MergeTree-family fluent builder gains .WithReplication() and .WithReplication(zooKeeperPath, replicaName), which emit Replicated* engines with Keeper path/replica arguments ahead of engine-specific args. Replication is stored on the model (ClickHouse:Replicated, path, replica name); validation blocks replication on Log/Memory engines and mismatched path/replica pairs; migrations that toggle replication are rejected like other engine changes.
Cluster DDL:UseCluster(clusterName) on UseClickHouse adds ON CLUSTER to generated DDL from migrations, EnsureCreated/EnsureDeleted, and the database creator—covering create/drop database, create/drop/rename table, and all migration ALTER TABLE paths (including check constraints). UseReplicatedMigrationsHistoryTable() targets Replicated-engine databases (no ON CLUSTER). The history repository now builds a shared ReplicatedMergeTree history table when those options are set, with deduplication settings disabled so revert/re-apply keeps history rows.
Other fixes in this PR: Migration scripts now terminate every statement with ; (fixes clickhouse-client multi-statement runs). SummingMergeTree with multiple sum columns emits a tuple argument. ClickHouseMigrationsSqlGenerator and ClickHouseDatabaseCreator constructors take extra dependencies (IDbContextOptions, and type mapping on the creator)—subclasses must forward them.
Docs (README, changelog) and integration/SQL-generation tests for replication and clusters are included.
Reviewed by Cursor Bugbot for commit 4bae37a. Bugbot is set up for automated code reviews on this repo. Configure here.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Shard-specific migration histories can cause already-applied migrations to rerun across shards, while missing check-constraint statement terminators produce invalid migration scripts.
Adds replicated MergeTree engines and cluster-wide DDL to the ClickHouse EF Core provider, addressing the table and migration-history divergence reported in #71.
Changes:
Adds replication configuration and validation for all seven MergeTree-family engines.
Adds UseCluster for cluster-wide DDL and replicated migration-history options.
Adds SQL-generation tests, two-replica integration coverage, and deployment documentation.
The reason will be displayed to describe this comment to others. Learn more.
🔵 Needs a closer look
The shared history configuration lacks an automated two-shard integration test with reused replica names to catch history isolation or replica-name collisions and verify migration continuity across shards.
Please add an automated two-shard integration test for this shared history configuration, with replica names reused across shards. The current fixture assigns both hosts to shard 01, so it cannot catch regressions that isolate history by shard or cause cross-shard replica-name collisions. Extend the fixture and verify that, after synchronizing history, a host on shard 2 sees migrations applied through shard 1 and can apply the next migration without replaying the first.
Add WithReplication() and WithReplication(zooKeeperPath, replicaName) to
every MergeTree family engine builder. The migrations SQL generator then
emits the Replicated variant of the engine, with the path and replica
name before the engine arguments.
Add the UseCluster(clusterName) option. It adds ON CLUSTER to the DDL
that migrations, EnsureCreated() and EnsureDeleted() generate, so that
each statement runs on all hosts.
With UseCluster, or with the new UseReplicatedMigrationsHistoryTable()
option for databases with the Replicated engine, the migrations history
table uses ReplicatedMergeTree. All replicas then see the same applied
migrations.
Tests run the DDL and migrations on a cluster with two replicas and
write through one replica and read through the other.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Under UseCluster, create the history table with the path
/clickhouse/tables/{uuid} and the replica name {shard}-{replica}. The
default path contains {shard}, so each shard had its own history.
Turn off insert deduplication for a replicated history table. Otherwise
ClickHouse drops the history row of a migration that is reverted and
then applied again.
Add ON CLUSTER to ADD CONSTRAINT and DROP CONSTRAINT.
Document that WithReplication() without arguments needs ON CLUSTER or a
Replicated database, that Replicated tables drop duplicate inserts, and
how to convert an existing history table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
End ADD CONSTRAINT and DROP CONSTRAINT with the statement terminator,
as the EF Core base implementations do. A migration script joins the
commands with only a line break.
Document that UseReplicatedMigrationsHistoryTable() gives each shard
its own history: a Replicated database refuses a replicated table that
the shards share, also with database_replicated_allow_replicated_engine_arguments.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
EF Core puts only a line break between the commands of a migration
script. The ALTER TABLE, RENAME TABLE, CREATE DATABASE and DROP DATABASE
statements had no terminator, so clickhouse-client read two statements
as one and failed with a syntax error. All statement ends now go through
one helper that appends the terminator.
A new integration test generates the script of migrations that use each
overridden statement and runs it statement by statement.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Add a third host, ch3, as shard 02 of a new cluster two_shards. Its
replica name r1 is also the replica name of ch1 in shard 01. The new
test applies the first migration through shard 01, then checks that
ch3 sees it as applied and applies only the second migration.
A history path with {shard} makes the test fail on the pending
migrations. A replica name without {shard} makes it fail with
REPLICA_ALREADY_EXISTS.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
4bae37af2c6f is approved by security-ai-gate-reviewer[bot], an automated identity, not a human. The approval stands on the required AI review: Cursor Bugbot concluded green on this commit and the AI review gate is SUCCESS (its own comment has the verdict), and the change touches no path that requires a human reviewer. It is bound to this commit: a new push dismisses it and the approver re-evaluates.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Closes #71.
Why
On a self-managed cluster, the provider creates only plain MergeTree family tables, and only on the server of the connection. Rows written to one replica do not get to the other replicas. The migrations history table has the same problem: each replica has its own history, so a migration that ran through one replica looks unapplied on another. That is the divergence that #71 reports.
A Replicated engine alone does not fix this. ClickHouse does not replicate
CREATE TABLEandDROP TABLE. It does replicateALTER TABLEon a Replicated table, so running the migrations once on each host fails at the second host. The DDL must run once, on all hosts.What
Replicated engines. Each MergeTree family engine builder has two new methods:
Without arguments, ClickHouse uses the server settings
default_replica_pathanddefault_replica_name. The model keeps the engine annotation as it is (for exampleReplacingMergeTree) and addsClickHouse:Replicated,ClickHouse:Replicated:ZooKeeperPathandClickHouse:Replicated:ReplicaName. Model validation rejects replication on Log and Memory engines, and a path without a replica name. Because the annotations have theClickHouse:prefix, the existing AlterTable check rejects a migration that turns replication on or off.UseCluster(name). A context option that addsON CLUSTER '<name>'to the DDL that migrations,EnsureCreated()andEnsureDeleted()generate:CREATE DATABASEandDROP DATABASE(the migration operations and the database creator)CREATE TABLE,DROP TABLE,RENAME TABLEALTER TABLE:ADD/DROP/MODIFY/RENAME COLUMN, theREMOVE CODEC/TTL/COMMENTstatements,ADD/DROP INDEX,ADD/DROP CONSTRAINTThe name is a string literal, so macros such as
{cluster}work.DROP TABLEand the two check constraint operations now have their own overrides, because the base implementations have no place for the clause. The check constraint overrides keep the statement terminator of the base implementations. TheCREATE TABLEoverride writes the statement itself for the same reason.Replicated migrations history table.
UseCluster,__EFMigrationsHistoryisReplicatedMergeTree('/clickhouse/tables/{uuid}', '{shard}-{replica}'). The server default path contains{shard}, which gives each shard its own history. Then a host on a second shard sees no applied migrations and fails onCREATE TABLE ... ON CLUSTER(TABLE_ALREADY_EXISTS). I checked both paths on a two-shard cluster.{shard}-{replica}keeps the replica names unique when shards reuse the same replica names.Replicatedengine refusesON CLUSTERand an explicit path. SoUseReplicatedMigrationsHistoryTable()givesReplicatedMergeTree()withoutON CLUSTER. There, each shard has its own history: aReplicateddatabase refuses a replicated table that the shards share, also withdatabase_replicated_allow_replicated_engine_argumentsset to 1 or 3 (checked on a two-shard cluster). The README and XML docs say to run the migrations through one shard.replicated_deduplication_window = 0andreplicated_deduplication_window_for_async_inserts = 0. Without them, ClickHouse drops the second history row of a migration that is reverted and applied again (the row is equal to the first one). Then the nextMigrate()fails withTABLE_ALREADY_EXISTS.MergeTreehistory table, and I tested it on the cluster.Statement terminators in migration scripts (also fixed here). EF Core puts only a line break between the commands of a migration script. The provider's
ALTER TABLE,RENAME TABLE,CREATE DATABASEandDROP DATABASEstatements had no;, soclickhouse-clientread two statements as one and failed with a syntax error. This bug is also onmain. Migrations that run from code were not affected, because the provider sends each statement separately. All statement ends in the SQL generator now go through one helper,TerminateStatement, that appends the terminator.How
ClickHouseEngineBuilderhas two protected helpers that set the annotations. The seven MergeTree family builders expose them asWithReplicationoverloads. Log and Memory builders do not get the method.ClickHouseMigrationsSqlGeneratorputs the path and replica name before the engine arguments, and prefixes the engine name withReplicated. The engine-argument code now returns a list, so that the two kinds of arguments join with one separator.UseClusterandUseReplicatedMigrationsHistoryTableare properties ofClickHouseOptionsExtension. The generator, the database creator and the history repository read them fromIDbContextOptions. These services are scoped, so two contexts with different settings that share one internal service provider still generate different DDL.ClickHouseEngines), which the convention, the validator and the generator share.Design notes
ON CLUSTER. A development server without ClickHouse Keeper cannot create a Replicated table.ClickHouseMigrationsSqlGeneratorandClickHouseDatabaseCreatortakeIDbContextOptions(the creator also takesIRelationalTypeMappingSource). A subclass must pass them on.WithReplication()without arguments uses the server default path, which contains{uuid}. ClickHouse accepts{uuid}only withON CLUSTERor in aReplicateddatabase. The README and XML docs say this.SaveChangescalls store the rows once. The README says this and names the table setting that keeps both. (On 26.10 the session settinginsert_deduplicate=0has no effect, becausededuplicate_insertoverrides it.)Distributedtables,DROP ... SYNC, and aReplicateddatabase engine forEnsureCreated(). The README tells users to keep{uuid}in an explicit path, because a drop and a create with the same fixed path fails for about 8 minutes (REPLICA_ALREADY_EXISTS). To use other history table settings, a user can derive fromClickHouseHistoryRepository. A test shows how.Tests
MigrationScriptIntegrationTests(1 test, single server): generates the script of three migrations that use each overridden statement, asdotnet ef migrations scriptdoes, splits it at the terminators and runs each statement. It then checks the schema and the history rows. I also ran the same script throughclickhouse-client --multiqueryby hand: exit code 0, with the expected schema and 3 history rows.Every_DDL_statement_ends_with_the_statement_terminatorchecks all 14 DDL statement kinds, with and withoutUseCluster. Without the terminator, all three tests fail.ReplicationSqlGenerationTests(35 tests, no server): the default and the explicit path for each of the 7 engines, escaping, validation, the AlterTable rejection,ON CLUSTERon each DDL statement, and the three history table configurations.ReplicationIntegrationTests(5 tests): a newClickHouseClusterFixturestarts threeclickhouse-server:latestcontainers, with ClickHouse Keeper embedded in the first. It defines two clusters:test_cluster, one shard with the replicasch1andch2, andtwo_shards, which addsch3as a second shard.ch3reuses the replica namer1ofch1. Each test writes through one host and reads through another:EnsureCreatedwith all 6 engines that need no server config (GraphiteMergeTree needs a rollup config). Each table has 2 replicas insystem.replicas, rows written through replica 1 can be read through replica 2, andEnsureDeletedremoves the database on both.ch3(shard 02) lists only migration 2 as pending and applies it. A history path with{shard}makes this test fail on the pending migrations. A replica name without{shard}makes it fail withREPLICA_ALREADY_EXISTS.UseCluster("{cluster}").Replicateddatabase withUseReplicatedMigrationsHistoryTable().ON CLUSTER, the 3 tests that use it fail. With insert deduplication left on in the history table, the migration test fails at the revert-and-apply step.dotnet ef migrations addscaffolds for a replicated table. The annotations come out as.Annotation("ClickHouse:Replicated", true)and so on.ON CLUSTERfor check constraints, and the missing docs.EFCore.ClickHouse.Tests704 passed (661 before),EFCore.ClickHouse.FunctionalTests323 passed, 4 skipped (the same as before). The cluster fixture adds about 45 s.main. The test projects have 13 more EF1001 warnings, because the new unit tests useClickHouseAnnotationNamesthe same way as the existing tests.🤖 Generated with Claude Code
Note
Medium Risk
Changes migration DDL generation and shared migration history on clusters; incorrect cluster/replication config can fail migrations or diverge history across hosts. Constructor signature changes affect custom subclasses of the SQL generator and database creator.
Overview
Adds cluster-ready table engines and DDL so self-managed ClickHouse deployments can use Replicated MergeTree tables and run migrations consistently across hosts.
Replicated engines: Every MergeTree-family fluent builder gains
.WithReplication()and.WithReplication(zooKeeperPath, replicaName), which emitReplicated*engines with Keeper path/replica arguments ahead of engine-specific args. Replication is stored on the model (ClickHouse:Replicated, path, replica name); validation blocks replication on Log/Memory engines and mismatched path/replica pairs; migrations that toggle replication are rejected like other engine changes.Cluster DDL:
UseCluster(clusterName)onUseClickHouseaddsON CLUSTERto generated DDL from migrations,EnsureCreated/EnsureDeleted, and the database creator—covering create/drop database, create/drop/rename table, and all migrationALTER TABLEpaths (including check constraints).UseReplicatedMigrationsHistoryTable()targetsReplicated-engine databases (noON CLUSTER). The history repository now builds a sharedReplicatedMergeTreehistory table when those options are set, with deduplication settings disabled so revert/re-apply keeps history rows.Other fixes in this PR: Migration scripts now terminate every statement with
;(fixesclickhouse-clientmulti-statement runs).SummingMergeTreewith multiple sum columns emits a tuple argument.ClickHouseMigrationsSqlGeneratorandClickHouseDatabaseCreatorconstructors take extra dependencies (IDbContextOptions, and type mapping on the creator)—subclasses must forward them.Docs (
README, changelog) and integration/SQL-generation tests for replication and clusters are included.Reviewed by Cursor Bugbot for commit 4bae37a. Bugbot is set up for automated code reviews on this repo. Configure here.