ClickHouse Migrations

0.9.1 · active · verified Thu Apr 16

clickhouse-migrations is a Python library designed for managing file-based database migrations in ClickHouse. It supports multi-statement SQL files, cluster deployments, and ensures migration state consistency across nodes. The project is actively maintained, with the current version being 0.9.1, and receives regular updates.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to programmatically connect to a ClickHouse instance and apply migrations from a specified directory. It creates a dummy migration file for illustration. Ensure `CH_DB_HOST`, `CH_DB_USER`, `CH_DB_PASSWORD`, `CH_DB_NAME`, and `CH_MIGRATIONS_HOME` environment variables are set or default values are appropriate for your ClickHouse instance.

import os
from clickhouse_migrations.clickhouse_cluster import ClickhouseCluster

db_host = os.environ.get('CH_DB_HOST', 'localhost')
db_user = os.environ.get('CH_DB_USER', 'default')
db_password = os.environ.get('CH_DB_PASSWORD', '')
db_name = os.environ.get('CH_DB_NAME', 'test_db')
migrations_home = os.environ.get('CH_MIGRATIONS_HOME', './migrations')

# Ensure migrations directory exists for the example
os.makedirs(migrations_home, exist_ok=True)

# Create a dummy migration file for the example
with open(f"{migrations_home}/1_create_test_table.sql", "w") as f:
    f.write("CREATE TABLE IF NOT EXISTS my_table (id UInt64, name String) ENGINE = MergeTree() ORDER BY id;")

cluster = ClickhouseCluster(
    db_host=db_host,
    db_user=db_user,
    db_password=db_password
)

try:
    print(f"Applying migrations to {db_host}/{db_name} from {migrations_home}...")
    cluster.migrate(
        db_name=db_name,
        migrations_home=migrations_home,
        create_db_if_no_exists=True,
        multi_statement=True
    )
    print("Migrations applied successfully.")
except Exception as e:
    print(f"An error occurred during migration: {e}")

view raw JSON →