chkit generate
Compares your current schema definitions against the previous snapshot, computes a migration plan, and writes migration SQL and an updated snapshot.
Synopsis
Section titled “Synopsis”chkit generate [flags]| Flag | Type | Default | Description |
|---|---|---|---|
-n, --name <name> | string | — | Migration name (used in the filename) |
--migration-id <id> | string | — | Escape hatch: override the default timestamp migration prefix |
--rename-table <mapping> | string | — | Explicit table rename: old_db.old_table=new_db.new_table |
--rename-column <mapping> | string | — | Explicit column rename: db.table.old_column=new_column |
--rename-dictionary <mapping> | string | — | Explicit dictionary rename: old_db.old_dict=new_db.new_dict |
-t, --table <selector> | string | — | Scope operations to matching tables |
--dryrun | boolean | false | Print the plan without writing any files |
--empty | boolean | false | Scaffold a blank manual migration without diffing the schema |
--cutover <mapping> | string | — | Cut a structural change of a table over without downtime instead of dropping and recreating it: db.table=key_column[,key_column]. Repeatable |
--cutover-copy <mode> | string | migration | Where a cutover copies the existing rows: migration (inside the migration) or backfill (with the backfill plugin) |
--cutover-old <mode> | string | keep | What happens to the pre-cutover table: keep (as <table>_previous) or drop |
--drop-retained <table> | string | — | Drop a table that a keep cutover retained, e.g. analytics.events_previous. Repeatable |
Global flags documented on CLI Overview.
Behavior
Section titled “Behavior”Schema diff and plan
Section titled “Schema diff and plan”- Loads your config and schema definitions
- Reads the previous snapshot from
metaDir/snapshot.json - Computes a diff between old and new definitions using
planDiff()from@chkit/core - Produces an ordered list of SQL operations (see Operation order)
Definitions are compared in canonical form. SQL fragments such as a view’s as lose their comments and have each run of whitespace collapsed to one space, so editing a comment or re-indenting a query does not produce a migration. See SQL fragments.
If there are no differences, no migration file is created.
Operation order
Section titled “Operation order”Operations run in groups. Without a rename, the order is drops, then ALTER statements, then CREATE DATABASE, then creates. When a rename is applied (a --rename-* flag or renamedFrom), the order is drops, then CREATE DATABASE, then table and dictionary renames, then the other ALTER statements (column renames included), then creates. Creates run tables first, then views, then dictionaries and materialized views; drops run one object type at a time. Dropping a skip index, constraint or projection runs before the other ALTER statements, so it never blocks dropping or changing a column it reads. Each group is sorted by name, except that the column statements of a table (ADD, MODIFY, DROP and RENAME COLUMN) and its TTL change (MODIFY TTL or REMOVE TTL) are ordered by the columns they read and remove:
- an
ADD COLUMNorMODIFY COLUMNwhose newDEFAULT,MATERIALIZEDorALIASexpression reads a column, or aMODIFY TTLthat reads it, runs after theADD COLUMNof that column, or theRENAME COLUMNto its name; - a
DROP COLUMNruns after theMODIFY COLUMNorDROP COLUMNof every column whose old expression reads it, and after the TTL change when the old TTL reads it, since ClickHouse refuses to drop a column something still reads. ARENAME COLUMNneeds no such wait: ClickHouse rewrites the expressions and the TTL that read the old name; - a
MODIFY COLUMNwhose new expression would close a cycle with the old expressions of other columns runs after theMODIFY COLUMNthat removes the old read, since ClickHouse rejects a cycle (Cyclic alias detected). For example, whenz DEFAULT adrops its default andachanges toDEFAULT z,zis changed first. When more than oneMODIFY COLUMNcould break the cycle, the first one in name order runs first: fromb DEFAULT candc DEFAULT a, changing toa DEFAULT b,b DEFAULT idandc DEFAULT idrunsb, thena, thenc. That breaker can be a column’sREMOVE DEFAULT, which then runs before theMODIFY COLUMNthat closes the cycle while the column’s ownMODIFY COLUMNruns later. A plan that closes no cycle in name order keeps that order. So does a table whose cycle no change can break. ARENAME COLUMNkeeps its column on the cycle under the new name, since ClickHouse rewrites the expressions that read the old name; a table with a rename from or to a keyword or literal name (such astrueornot, in any case) or a dotted name keeps the name order, since ClickHouse rewrites a read of a column renamed totrueas the literal and one renamed tonotas the operator. This reordering also only covers tables whose column expressions use nothing but the table’s columns, function calls, number and string literals (includingNULL,TRUEandFALSE), operators (includingAND,ORandNOT), parentheses, andCAST(x AS T)orx::T. Any other syntax, such asINTERVAL,CASE, a lambda, an alias,.access, a call that can take a date unit (dateDiff,date_add,extractand the like, in any form), a column named like an expression keyword (such ascase,dateorinterval) written without backquotes, or a column namednot,true,false,inf,nanorinfinityeven in backquotes (the cycle check ofALTERreads those as an operator or a literal), may be read wrong, so that table keeps the name order. A table whose cycles take too long to check also keeps the name order.
A name followed by ( is a function call, not a column. Neither is a lambda parameter inside its lambda (c in arrayMap(c -> c + 1, arr)), nor a type in CAST(x AS T) or x::T. These rules apply to column expressions and to the table TTL alike. Columns that read each other in a cycle keep the name order. Statements for the same column keep their planned order: removing a column’s expression (REMOVE DEFAULT or REMOVE MATERIALIZED) or codec (REMOVE CODEC) runs before the column’s MODIFY COLUMN. The ordered statements take the places the table’s column and TTL statements had, so a DROP COLUMN that waits for the TTL change can run after the table’s other ALTER statements, such as a setting change.
A keyword reads no column of the same name: NULL, TRUE, FALSE, inf, nan, infinity and NOT never do, and the words of CASE … WHEN … THEN … ELSE … END, IS, IN, LIKE, BETWEEN, AND, OR, FROM, FOR, DIV, MOD and AS don’t after an operand (x IS NULL, substring(s FROM 1)). Neither does the alias name in x AS alias. As in ClickHouse, the same word where an operand belongs reads its column (end + 1, THEN end), and so does a quoted name. Where chkit can’t tell which one it is, it keeps the read.
A MODIFY COLUMN that changes a column’s type runs after the ADD, MODIFY or DROP COLUMN of every column, and the TTL change, whose old expression reads the column and whose new one no longer does, and before the statements whose new expression or TTL starts reading it, since ClickHouse checks every expression of the table against the new type (code 43). For example, when a changes from String to UInt64 and b DEFAULT length(a) becomes b DEFAULT 0, b is changed first. generate can’t tell which types an expression accepts, so other orders stay: a statement whose old and new expression both read the column stays on its side of the type change, and type changes keep their order among themselves. When the old and the new expression both need their own type, as from b DEFAULT length(a) to b DEFAULT a + 1, no order works: split the change into two migrations, removing b’s default first. A move that would conflict with another ordering rule is left out. The plan keeps its order when the moves would make column expressions read each other in a cycle at some step (counting lambda parameters, as the cycle check of ALTER does), would move a statement past another ALTER (such as ADD INDEX), or would change the order of the ADD COLUMN and DROP COLUMN statements among themselves or of the type changes, and for a table with a column rename in the same migration. Since the cycle check replays the whole plan, a plan whose name order closes a temporary cycle anywhere, which the repair above then breaks, keeps the order without these moves in every table.
generate then reorders creates and drops by the dependencies between the objects in the migration: an object is created after every object it reads and dropped before them. A view that reads another view, a materialized view, or a dictionary is created after it, even when its name sorts first. Dependencies come from:
database.namereferences in a view or materialized view query, including subqueries, joins, andINclauses- unqualified names directly after
FROMorJOIN, resolved against the view’s own database (CTE names are skipped) - the name argument of
dictGetand its variants,dictHas,dictIsIn,joinGet, and thedictionary()table function, as a string ('analytics.users_dict') or a name (analytics.users_dict,users_dict); either form without a database resolves against the object’s own database - a materialized view’s
totable andrefresh.dependsOnviews - the column expressions (
DEFAULT,MATERIALIZED,ALIAS, andEPHEMERAL) of a table that is created or dropped, such as a default that callsdictGet - a dictionary’s
CLICKHOUSEsource, asTABLE/DBorQUERY
Apart from those name arguments and source parameters, names inside string literals and comments are ignored. A quoted name or string is read as ClickHouse reads it: `events\x5fraw` is events_raw, while `raw\q` keeps its backslash. Objects with no dependency inside the migration keep the kind-then-name order, and objects that reference each other in a cycle keep that order among themselves. Only dependencies inside the migration count: a refreshable materialized view whose DEPENDS ON target already exists is ordered like any other object.
ALTER statements are not reordered. A migration that adds or modifies a column whose expression calls dictGet on a dictionary created in the same migration fails, because the ALTER runs before the dictionary exists. A migration that drops a dictionary and also drops or changes the column expression that calls it fails too, because the dictionary drop runs first. Split such a change into two migrations: create the dictionary first, or change the column first.
Qualify names in view SQL (analytics.events, not events). ClickHouse resolves an unqualified name against the session’s current database, which generate can’t see, so generate assumes the view’s own database.
Risk levels
Section titled “Risk levels”Every operation in the plan is assigned a risk level:
| Risk | Meaning | Example operations |
|---|---|---|
safe | Non-destructive, no data loss | CREATE TABLE, ADD COLUMN |
caution | Potentially impactful, review recommended | ALTER TABLE settings changes |
danger | Destructive, may cause data loss | DROP TABLE, DROP COLUMN |
Table scoping
Section titled “Table scoping”The --table flag limits operations to tables matching a selector:
database.table— exact matchdatabase.prefix*— prefix wildcard in a specific databasetable— matches across all databases
An empty match set emits a warning and produces no output.
Rename workflow
Section titled “Rename workflow”chkit detects potential renames through two mechanisms:
- Schema metadata — set
renamedFromon your schema definition - CLI flags —
--rename-table old_db.old_table=new_db.new_table,--rename-column db.table.old_col=new_col, and--rename-dictionary old_db.old_dict=new_db.new_dict
CLI flags take priority when both sources specify a mapping for the same object. Rename flags accept comma-separated values for multiple mappings.
A dictionary rename emits a single RENAME DICTIONARY IF EXISTS ... TO ... statement instead of a drop_dictionary + create_dictionary pair — see Dictionary rename.
Validation errors are raised for conflicting, chained, or cyclic rename mappings.
Zero-downtime cutover
Section titled “Zero-downtime cutover”A change to a table’s engine, orderBy, primaryKey, partitionBy or a read-only setting such as index_granularity cannot be made with ALTER, so generate plans a DROP TABLE and a CREATE TABLE, which loses every row and needs --allow-destructive. With --cutover db.table=key, generate plans a zero-downtime cutover for that table instead: writers keep inserting into the table while chkit mirrors new inserts into a shadow table with the new definition, copies the existing rows, verifies the copy, and swaps the two tables with EXCHANGE TABLES.
chkit generate --name events_by_user --cutover analytics.events=id- The value after
=names the columns that identify a row (a unique key). NoINSERTmay reuse an existing key until the migration completes; the copy tells copied rows from mirrored rows by it. - The migration keeps the old table as
<table>_previous(--cutover-old keep), recorded in the snapshot as retained:drift,checkand the nextgeneratetreat it as managed, without it appearing in your schema files. Drop it later with--drop-retained analytics.events_previous, a normal destructive change. With--cutover-old dropthe migration drops it (adangeroperation). - With
--cutover-copy backfillthe migration stops at the copy check;chkit plugin backfill plan --cutover analytics.eventscopies the rows, thenchkit migrate --applyverifies and swaps. - The swap is an
exchange_tablesoperation with riskcaution; it does not need--allow-destructive. - A cutover is refused when only the engine arguments change: it tells the old table from the new one by engine name, sorting key, primary key, partition key and read-only settings.
- The cutover’s first statement checks that every replica runs ClickHouse 24.9 or later. It also checks, on every replica, that the table uses the engine the schema declares, stores the read-only settings the migration expects and no column that the schema does not declare, that it has every column the copy writes with the type the schema declares, that it computes the columns the schema declares
ALIASorEPHEMERALand stores the others, and, when the snapshot is createdASthe table, that its replication path (the engine’s first argument) has{uuid}and that it has no TTL, before anything is created or copied. A table that does not declareindex_granularitystores the server’s default, which chkit takes fromclickhouse.indexGranularity(8192 by default). If they differ, the migration stops there: setclickhouse.indexGranularityto the server’s value and generate the cutover again. - The cutover mirrors and copies a
Nestedcolumn as flattened columns such asn.xand creates its tables withflatten_nested = 1, which needs ClickHouse 25.1 or newer. The first statement refuses the cutover if the live table stores aNestedcolumn as one column (flatten_nested = 0) or the server is older than 25.1.generaterefuses aNestedcolumn with aDEFAULT,MATERIALIZED,ALIASorEPHEMERALexpression, aNestedkey column, a table that setsflatten_nesteditself, and a column declared asNestedin one definition and as its flattenedArraycolumns in the other. - A cutover is refused, with a
cutover_unsupportedvalidation issue, for engines other thanMergeTree,ReplicatedMergeTreeandSharedMergeTree, aReplicatedtable withoutclickhouse.cluster, a Nullable key, a TTL, a column whose type changes or that is renamed in the same migration, a renamed table, a newCHECKconstraint, and writers chkit cannot follow (a Kafka-style consumer, directly or through intermediate tables, a refreshable materialized view or aBuffertable writing into the table). A view that reads from or writes into the table and is recreated in the same migration is refused too. migratestops a cutover, at its first step and before the swap, while asynchronous inserts withwait_for_async_insert = 0reach the table: ClickHouse drops their buffered rows when the table is swapped.
When a cutover does not fit
Section titled “When a cutover does not fit”A table without a unique key, a change that transforms rows, or an engine that merges rows needs a reviewed hand-written migration instead of --cutover. chkit does not mirror the writes of such a migration or verify its copy: pause the writers from the copy until the swap, run its DDL on every replica (ON CLUSTER with clickhouse.cluster), and run chkit drift after it is applied.
The cutover’s first statement also refuses a Replicated table created without PRIMARY KEY whose replication path in the schema has no {uuid}, while a replica runs ClickHouse older than 26.7: the cutover’s snapshot then takes PRIMARY KEY from the schema, and the table’s parts do not attach to it. The statement creates and copies nothing, so either:
- upgrade every replica to ClickHouse 26.7 or later and run the same
chkit migratecommand again, or - replace the cutover as Abandoning a failed migration describes: delete the migration file, restore
chkit/meta/snapshot.jsonfrom git to its state before the cutover was generated, runchkit generatewithout--cutover, and replace the generatedDROP TABLEandCREATE TABLEwith the hand-written migration before you apply it. Statements of the migration that ran before the cutover’s first statement stay applied; that page covers them.
Dictionary password warnings
Section titled “Dictionary password warnings”A dictionary’s SOURCE(...) clause is a raw string (see Credentials in source), so any credentials it embeds are written verbatim into the generated migration SQL — ClickHouse has no DDL-level secret substitution. A password change is a real diff like any other field change and produces a CREATE OR REPLACE DICTIONARY migration.
generate warns when a dictionary being created or replaced this run has a literal password '...' in its SOURCE(...) — it will land in the committed migration file as plain text. This prints to the console and is included as a warnings array in --json output.
The one exception: a dictionary whose source still carries ClickHouse’s [HIDDEN] introspection placeholder (written by chkit pull when it can’t recover the real password) never produces a migration on its own — chkit doesn’t know the real value, so it can’t safely diff or render it. Replace [HIDDEN] with a real credential in the schema file first.
Experimental codec warnings
Section titled “Experimental codec warnings”generate warns about every operation that sets the experimental ALP codec, which ClickHouse rejects unless allow_experimental_codecs is 1. Apply such a migration with chkit migrate --apply --setting allow_experimental_codecs=1. The warning prints to the console and is included in the warnings array of --json output.
Quoted string defaults
Section titled “Quoted string defaults”generate warns when a plain string default, on a column or a dictionary attribute, is itself a quoted SQL string literal such as default: "'standard'". It renders DEFAULT '''standard''', so the stored value keeps the quotes. The warning names the table and column (or dictionary and attribute) and the fixes: default: 'standard' for the value, or default: { expression: "'standard'" } for SQL. The migration is still generated, because a value may contain quotes. The warning prints to the console and is included in the warnings array of --json output.
Dryrun mode
Section titled “Dryrun mode”With --dryrun, the command prints the migration plan (operations with risk levels and SQL) without writing any files. Useful for previewing changes before committing.
Plans for objects in a database include a create_database operation (CREATE DATABASE IF NOT EXISTS, risk safe), so a single new table reports operationCount: 2 — the create_database plus the create_table. The CREATE DATABASE is idempotent and a no-op if the database already exists.
Empty mode
Section titled “Empty mode”With --empty, the command skips the schema diff entirely and writes a blank, timestamped migration stub for you to hand-edit. Use it for DDL that chkit does not model — raw INSERT/backfill statements, OPTIMIZE, manual dictionary reloads, or one-off data fixes.
The stub carries the standard migration header (with operation-count: 0) plus a placeholder comment. The snapshot is left untouched, so an empty migration never absorbs pending schema drift. The --name and --migration-id flags apply; without --name, the file defaults to manual. Schema-diff flags (--table, --rename-table, --rename-column, --rename-dictionary, --dryrun) are not used in empty mode.
chkit migrate picks the file up like any other migration and applies it in filename order. Until the stub contains at least one SQL statement, chkit migrate --apply refuses to run and lists it (see empty migrations), so an unfinished stub is never recorded as applied. Editing a migration after it has run triggers a checksum mismatch.
Codegen integration
Section titled “Codegen integration”If the codegen plugin is configured with runOnGenerate: true (the default), chkit generate automatically runs codegen after writing migration artifacts. A codegen failure causes generate to fail.
Validation errors
Section titled “Validation errors”Schema validation issues (such as invalid definitions) produce a validation_failed error with structured issue codes and messages. The process exits with code 1 and writes no migration or snapshot. For example, a function call written as the plain string DEFAULT of a column that cannot hold a string (default: 'now64(3)' on a DateTime64 column) fails with column_default_looks_like_expression instead of producing a migration that ClickHouse rejects. See Validation rules for every code.
Migration data-copy warnings
Section titled “Migration data-copy warnings”generate warns about standalone INSERT and data-reading/exporting SELECT statements in saved migration files and newly planned SQL in schema-diff modes (including dry runs), excluding ordinary DDL definitions, assert_backfill SELECTs, SELECT throwIf(...) guards and SELECT barriers; this warning never changes the exit status. Text prints Warning: copy.sql, statement 1: Data copies should usually run as resumable backfill jobs; small copies in migrations are acceptable.; JSON includes the same message without the Warning: prefix in its warnings string array, for example {"warnings": ["copy.sql, statement 1: Data copies …"]}.
Examples
Section titled “Examples”Generate a named migration:
chkit generate --name add_users_tablePreview changes without writing files:
chkit generate --dryrunScaffold a blank manual migration:
chkit generate --empty --name backfill_signupsScope to a specific table:
chkit generate --table analytics.eventsExplicit table rename:
chkit generate --rename-table old_db.users=new_db.accountsExplicit column rename:
chkit generate --rename-column analytics.events.old_name=new_nameChange a populated table’s sort key without downtime:
chkit generate --name events_by_user --cutover analytics.events=idCopy with the backfill plugin and drop the old table afterwards:
chkit generate --name events_by_user --cutover analytics.events=id --cutover-copy backfill --cutover-old dropDrop the table a cutover kept:
chkit generate --name drop_events_previous --drop-retained analytics.events_previousExplicit dictionary rename:
chkit generate --rename-dictionary old_db.old_dict=new_db.new_dictExit codes
Section titled “Exit codes”| Code | Meaning |
|---|---|
| 0 | Success |
| 1 | Validation error |
JSON output
Section titled “JSON output”Plan mode (--dryrun)
Section titled “Plan mode (--dryrun)”{ "command": "generate", "schemaVersion": 1, "scope": { "enabled": false }, "mode": "plan", "operationCount": 2, "riskSummary": { "safe": 2, "caution": 0, "danger": 0 }, "operations": [ { "type": "create_database", "key": "database:default", "risk": "safe", "sql": "CREATE DATABASE IF NOT EXISTS default;" }, { "type": "create_table", "key": "default.users", "risk": "safe", "sql": "CREATE TABLE ..." } ], "renameSuggestions": [], "warnings": []}Apply mode (default)
Section titled “Apply mode (default)”{ "command": "generate", "schemaVersion": 1, "scope": { "enabled": false }, "migrationFile": "./chkit/migrations/20260604104251_add_users_table.sql", "snapshotFile": "./chkit/meta/snapshot.json", "definitionCount": 3, "operationCount": 2, "riskSummary": { "safe": 2, "caution": 0, "danger": 0 }, "warnings": []}Cutover
Section titled “Cutover”A plan or apply with --cutover adds a cutovers array:
{ "cutovers": [ { "table": "analytics.events", "key": ["id"], "copy": "migration", "oldTable": "keep", "shadow": "analytics.events__cutover_20260604104251", "mirror": "analytics.events__cutover_20260604104251_mirror", "snapshot": "analytics.events__cutover_20260604104251_snapshot", "columns": ["id", "user_id", "event_type", "occurred_at"], "retainedAs": "analytics.events_previous", "nextSteps": ["chkit migrate --apply"] } ]}Empty mode (--empty)
Section titled “Empty mode (--empty)”{ "command": "generate", "schemaVersion": 1, "mode": "empty", "migrationFile": "./chkit/migrations/20260604104251_backfill_signups.sql"}Validation error
Section titled “Validation error”{ "command": "generate", "schemaVersion": 1, "error": "validation_failed", "issues": [ { "code": "column_default_looks_like_expression", "kind": "table", "database": "analytics", "name": "events", "message": "Table analytics.events column \"updated_at\" has default \"now64(3)\", a plain string that looks like a SQL function call. Plain strings render as quoted literals (DEFAULT 'now64(3)'), which ClickHouse rejects for type DateTime64(3, 'UTC'). Use default: { expression: \"now64(3)\" } to render DEFAULT now64(3). If chkit misjudged the type and the column should store this text, use default: { expression: \"'now64(3)'\" }." } ]}Related commands
Section titled “Related commands”- The migration workflow — why generate is offline, and what to commit alongside the SQL
chkit init— scaffold a project before your first generatechkit migrate— apply generated migrations to ClickHousechkit codegen— manually trigger type generationchkit snapshot— rebuildsnapshot.jsonafter two branches conflict on it