Python migrations
Write a Python migration script as a versioned .py file with a migrate(context) function. This page describes the MigrationContext API, file naming and execution contract. Relational engines accept Python alongside .sql files; MongoDB and Azure Cosmos DB use Python files only.
For a complete SQL and Python walkthrough, start with the Python database migrations tutorial. For collections, indexes and document backfills, follow MongoDB migrations in Python. Connection setup is covered in the database quickstart.
The same naming rules apply as for SQL: V1_0_0__create_users.py, optional U1_0_0__drop_users.py, R__seed.py. On MongoDB and Cosmos DB there is no SQL DDL surface to run, so a .sql file fails with DBLIFT-NOSQL-001 before anything executes. See the MongoDB and Cosmos DB engine pages for connection settings.
pip install "dblift[cosmosdb]"pip install "dblift[mongodb]"
The contract
Each file defines a top-level migrate function. Undo is a separate U<version>__*.py file with its own migrate.
from dblift.api import MigrationContext
def migrate(context: MigrationContext) -> None:
if context.dry_run:
return
...| Attribute | What it is |
|---|---|
context.db | Cosmos: azure.cosmos.DatabaseProxy. MongoDB: pymongo.database.Database. Relational: the SQLAlchemy connection/engine handle. |
context.raw_client | Cosmos: CosmosClient. MongoDB: MongoClient. |
context.log | .debug(), .info(), .warning(), .error(). |
context.dry_run | Simulation flag for callers that execute the function in dry-run mode. Guard mutations — DBLift cannot intercept SDK calls. |
context.execute(sql) | Cosmos: native SELECT only; writes raise NoSqlWriteNotSupportedError. MongoDB: always raises DBLIFT-NOSQL-002. |
context.schema | From config. Document stores are schemaless. |
context.placeholders | Effective placeholder map. No automatic substitution — read them yourself. |
In DBLift 4.9.0, the CLI's migrate --dry-run lists pending Python files without executing their bodies. It cannot preview the rows or documents changed by arbitrary Python code. Keep the guard for callers that execute your function in simulation mode. validate-sql does not lint Python files.
See Error codes for DBLIFT-NOSQL-001 and DBLIFT-NOSQL-002, and the MongoDB and Cosmos DB engine pages.
Read next
- MongoDB migrations in Python with DBLift: a collection, an index, a backfill, an undo, and a failure, all Python files, with real output.
- Python database migrations: a SQL and Python tutorial: apply, validate and undo on SQLite.
- DBLift vs Alembic: how versioned files compare with model-generated revisions.