Skip to content

Python CLI for ClickHouse

Plain SQL.Auditable migrations.

Version schema changes in Git, validate them before execution, and run them from the CLI or CI.

PyClickHouseMigrator mascot carrying ClickHouse columns
pip install py-clickhouse-migrator

Every query stays explicit.

Each -- @stmt block is sent to ClickHouse as one query. The same file carries the up and down SQL.

Format guide
-- migrator:up
-- @stmt
CREATE TABLE IF NOT EXISTS events
(
    id UInt64,
    created_at DateTime DEFAULT now()
)
ENGINE = MergeTree
ORDER BY id

-- migrator:down
-- @stmt
DROP TABLE IF EXISTS events

A focused migration workflow

No ORM, schema diff, or framework. You write the SQL. The migrator handles ordering, checks, state, and advisory locking.

Plain SQL

Keep migrations in versioned files. Every statement boundary is explicit and reviewable in Git.

20260801120000_create_events.sql

Integrity checks

Detect edited or missing migrations that the tool previously applied.

Rollback you control

Write the down SQL yourself. The stored version is used for rollback.

Preflight validation

EXPLAIN AST runs before up and rollback by default.

Deployment locking

Reduce common CI races with a TTL-based advisory lock.

Cluster-aware state

Replicate service tables while leaving migration SQL unchanged.

Compare migration approaches

Inside migrator up

By default, an apply run follows this path from connection to recorded state. Select a step to inspect it.

Compare stored checksums

Compare stored SHA-256 values with the current up and down blocks. A mismatch or missing file stops the run by default.

$ migrator up
Error: Checksum mismatch for applied migrations:
001_create_events.sql:
stored=dd495f29709d... actual=6a406ca4f1d7...
Run 'migrator repair' to update checksums.

Guardrails before execution.

The default path checks applied history, preflights pending SQL, and coordinates migration runners.

Checksum integrity

Compares current blocks with the checksum stored at apply time.

$ migrator show
Applied:
[X] 001_create_events.sql (HEAD, modified)
WARNING: 1 integrity issue found
001_create_events.sql: checksum mismatch

A mismatch or missing checksummed file stops migrator up before pending SQL by default.

Preflight validation

Runs EXPLAIN AST before up or rollback execution.

$ migrator up --dry-run
-- 002_add_user_id.sql (up)
ALTER TABLE users
ADD COLUMN IF NOT EXISTS user_id UInt64

Dry-run uses the same validation path. This is a best-effort check, not a safety guarantee.

Advisory locking

Uses a TTL-based lock to reduce concurrent migration races.

$ migrator lock-info
Locked by: runner-01:1234:abc123ef
Locked at: 2026-08-01 14:30:00
Expires at: 2026-08-01 14:40:00

Up, rollback, and baseline use it by default. Keep one migration runner per deployment.

Choose your path

Pick the guide that matches your database and delivery process.