Migrations¶
SQLSpec includes a built-in schema migration runner supporting sequential .sql and .py revisions across every sync and async adapter—without requiring SQLAlchemy or Alembic when your project is pure SQL.
flowchart LR
Author["SQL / Python Revisions"] --> Upgrade["upgrade / downgrade"]
Upgrade --> Tracker[("ddl_migrations Table")]
Tracker --> Verify["verify --strict"]
Verify --> Squash["squash & dump-schema"]
Configure Migration Settings and pyproject.toml¶
Enable migrations on any adapter configuration by supplying migration_config:
from sqlspec.adapters.sqlite import SqliteConfig
database_config = SqliteConfig(
bind_key="app",
connection_config={"database": "app.db"},
migration_config={
"script_location": "migrations",
"version_table_name": "schema_versions",
"auto_dump_schema": True,
"schema_dump_path": "migrations/schema.sql",
},
)
Point [tool.sqlspec] in pyproject.toml at your module attribute or factory callable so the sqlspec CLI discovers configurations automatically:
Common MigrationConfig keys:
script_location: Directory containing migration files ("migrations"by default).version_table_name: Tracking table name ("ddl_migrations"by default).default_schema: Default target schema for unqualified DDL objects.version_table_schema: Dedicated admin schema holding the version-tracking table.include_extensions: Optional list of extension schemas to bundle (such as["litestar", "adk", "events"]).schema_dump_path: Default output path written bydump_schema()whenoutput_pathis omitted (auto_dump_schema=Truefalls back to<script_location>/schema.sqlwhenschema_dump_pathis unset).auto_dump_schema: Set toTrue(or a file path) to refreshschema.sqlautomatically after everyupgradethat applies revisions.
default_schema, version_table_schema, and -- schema: directives require an adapter with migration schema support: PostgreSQL drivers, CockroachDB, DuckDB, Oracle, IBM Db2, SQL Server, Snowflake, and PostgreSQL-backed ADBC. Other adapters raise MigrationError. To keep the tracking table in a specific schema on those adapters, set version_table_name to "<schema>.ddl_migrations".
SQLSpec restores the session schema after each migration, whether it succeeds or fails. A failed transactional migration rolls back first, and the original error is reported.
Authoring SQL and Python Revisions¶
Revisions execute in lexical prefix order (0001_..., 0002_... or timestamp prefixes normalized via sqlspec fix). You can mix .sql and .py files in the same migrations/ directory:
Multi-Schema Migration Tracking¶
Enterprise deployments frequently store application tables in app_schema while isolating migration tracking metadata in admin_schema. Configure default_schema and version_table_schema together—or invoke SyncMigrationCommands / AsyncMigrationCommands programmatically:
from sqlspec.adapters.duckdb import DuckDBConfig
from sqlspec.migrations.commands import SyncMigrationCommands
MIGRATION_SCRIPT = '''"""Create users."""
def up() -> list[str]:
"""Create an unqualified table in app_schema."""
return [
"""
CREATE TABLE users (id INTEGER PRIMARY KEY, name VARCHAR NOT NULL)
"""
]
def down() -> list[str]:
"""Drop the unqualified table from app_schema."""
return ["DROP TABLE IF EXISTS users"]
'''
def run_multi_schema_migration(base_dir: Path) -> DuckDBConfig:
"""Apply a migration across app_schema and admin_schema in DuckDB."""
migration_dir = base_dir / "migrations"
db_path = base_dir / "app.duckdb"
config = DuckDBConfig(
connection_config={"database": str(db_path)},
migration_config={
"script_location": str(migration_dir),
"version_table_name": "schema_versions",
"default_schema": "app_schema",
"version_table_schema": "admin_schema",
},
)
with config.provide_session() as session:
session.execute("CREATE SCHEMA app_schema")
session.execute("CREATE SCHEMA admin_schema")
commands = SyncMigrationCommands(config)
commands.init(str(migration_dir), package=True)
revision_file = migration_dir / "0001_create_users.py"
revision_file.write_text(MIGRATION_SCRIPT, encoding="utf-8")
commands.upgrade()
return config
When PostgreSQL adapters (AsyncpgConfig, PsycopgSyncConfig, PsycopgAsyncConfig, PsqlpyConfig) run behind transaction-mode PgBouncer (pooler_mode="transaction") and define direct_dsn, MigrationCommands automatically routes DDL execution through config.derive_direct_config() so session-level locks and DDL statements bypass the transaction pooler.
On PostgreSQL (not CockroachDB), the tracking table is always resolved by schema and name, never through search_path. When version_table_schema is not configured, SQLSpec pins the table to the session's current_schema() and uses the qualified name for every tracking statement, so a migration that changes search_path or creates a temporary table of the same name cannot redirect tracking writes. The migrating role must own the tracking table, belong to the role that does, or be a superuser; the check runs again right after the migration lock is taken. The advisory lock key derives from the configured table name, so it does not change when the schema is pinned, and the pin is re-resolved on every locked command.
Lifecycle, Squash, and Schema Commands¶
| Action | CLI Command | Behavior |
|---|---|---|
| Apply pending revisions | uv run sqlspec upgrade |
Runs unapplied migrations in lexical order and records each version in version_table_name. |
| Target a specific revision | uv run sqlspec upgrade 0003 |
Applies pending revisions up to and including 0003. |
| Roll back revisions | uv run sqlspec downgrade -1 |
Executes the down section of the most recently applied revision (downgrade base reverts all). |
| Verify checksums & drift | uv run sqlspec verify --strict |
Audits applied checksums, orphaned tracker rows, pending files, and partial squashes. Writes only to upgrade legacy checksum rows (see below). |
| Export live schema DDL | uv run sqlspec dump-schema -o migrations/schema.sql |
Writes topologically ordered schema DDL to --output or directly to stdout. |
| Bootstrap from live schema | uv run sqlspec create-migration -m "baseline" --from-schema |
Populates a new .sql or .py revision with CREATE DDL in up and reverse DROP DDL in down. |
| Bootstrap from data | uv run sqlspec create-migration -m "events" --from-data events.jsonl |
Infers a typed CREATE TABLE revision from a JSON/JSONL/Parquet/Arrow file or staging table. |
| Baseline an existing DB | uv run sqlspec stamp head |
Records the target revision in version_table_name without executing DDL statements. |
| Consolidate history | uv run sqlspec squash 1:10 -m "baseline" --strategy ddl --yes |
Collapses a revision range (or all revisions when omitted) into one file with -- Squashed from: metadata. |
Checksum Verification¶
upgrade and downgrade (including --dry-run) compare every applied migration file with the checksum recorded when it was applied, before running any migration. A changed file raises MigrationError naming the versions, so an edited up or down section cannot run unreviewed. Set migration_config["verify_checksums"] = False to skip the check after you have reviewed a deliberate edit. verify --strict always fails on the drift.
The digest ignores the version number in each single-line -- name: migrate-<version>-up|down header and in single-line Version: lines, so fix renames keep checksums stable. Each header is replaced by a version-free marker (-- name:up or -- name:down), so moving a down header changes the digest. Python assignments such as version: str = "x" are part of the digest.
Rows recorded by earlier releases verify through the previous form, which dropped header lines entirely. When such a row matches, verify, upgrade, and downgrade re-record it as the current digest in the same transaction (a dry run only prints Would re-record legacy checksums for [...]). A header value that is not a single token, such as -- Version: 1.0 beta, does not verify against a legacy row.
Squashing Strategies and Reconciliation¶
sqlspec squash (and commands.squash(...)) consolidates sequential or timestamp revisions into one baseline file while recording superseded versions in -- Squashed from: (SQL) or __replaces__ / Squashed from: (Python) file headers:
from sqlspec.adapters.sqlite import SqliteConfig
from sqlspec.migrations.commands import SyncMigrationCommands
FIRST_MIGRATION = """-- name: migrate-0001-up
CREATE TABLE users (
id INTEGER PRIMARY KEY,
email TEXT NOT NULL UNIQUE
);
-- name: migrate-0001-down
DROP TABLE users;
"""
SECOND_MIGRATION = """-- name: migrate-0002-up
ALTER TABLE users ADD COLUMN display_name TEXT;
-- name: migrate-0002-down
ALTER TABLE users DROP COLUMN display_name;
"""
def run_squash_and_dump(base_dir: Path) -> tuple[str, bool, str, str]:
"""Apply, verify, squash into canonical DDL, and dump the live schema."""
migration_dir = base_dir / "migrations"
db_path = base_dir / "app.sqlite"
conn_cfg = {"database": str(db_path)}
mig_cfg = {"script_location": str(migration_dir), "echo": False}
config = SqliteConfig(connection_config=conn_cfg, migration_config=mig_cfg)
commands = SyncMigrationCommands(config)
commands.init(str(migration_dir), package=False)
rev1 = migration_dir / "0001_create_users.sql"
rev2 = migration_dir / "0002_add_display_name.sql"
rev1.write_text(FIRST_MIGRATION, encoding="utf-8")
rev2.write_text(SECOND_MIGRATION, encoding="utf-8")
try:
commands.upgrade(echo=False)
report = commands.verify(strict=True, echo=False)
commands.squash("0001", "0002", "baseline", strategy="ddl", yes=True)
squashed_file = next(migration_dir.glob("0001_*.sql"))
squashed_sql = squashed_file.read_text(encoding="utf-8")
schema_path = migration_dir / "schema.sql"
schema_sql = commands.dump_schema(schema_path, echo=False)
return squashed_file.name, bool(report["valid"]), squashed_sql, schema_sql
finally:
config.close_pool()
Choose the squash strategy that matches your migration history:
concat(default): Preserves everyupstatement verbatim in chronological order and reversesdownstatements. Safe for histories containing seedINSERT/UPDATEDML, views, triggers, functions, or procedural blocks.ddl: Parses chronological DDL with SQLGlot and foldsCREATE/ALTER/DROP/RENAMEoperations into netCREATE TABLE,CREATE SEQUENCE, andCREATE INDEXstatements. Fails closed withSquashValidationErrorwhenever a statement (such as data DML, views/triggers, dynamic PL/SQL, or destructive column rewrites) cannot be folded faithfully.schema: Emits topological DDL reflected directly from the live database catalog viadriver.data_dictionary.get_schema_ddl(...).
Schema extraction (schema squash, create-migration --from-schema, and dump-schema) emits tables, columns, indexes, and constraints. It refuses to run when an included table is protected by row-level security: PostgreSQL RLS or policies, Oracle VPD policies, or SQL Server security policies, because rebuilding the database from the dump would silently drop that protection. On PostgreSQL it also logs one migration.schema_extraction.omitted warning naming the grants, materialized views, functions, triggers, and domains it does not emit; carry those over with --strategy ddl or hand-written migrations. The tracking table and its _lock table are ignored by these checks.
When upgrade() runs against downstream environments after a squash has been committed:
- All replaced versions applied: SQLSpec replaces the superseded tracker rows with the squashed revision (
replacesmetadata recorded) without re-executing DDL. Under--dry-run, reconciliation is reported without mutatingversion_table_name. - No replaced versions applied: Fresh databases execute the squashed migration once.
- Partial overlap: If only a subset of replaced versions was applied,
upgrade()andverify --strictraise an error rather than guessing which statements remain unapplied.
Unversioned Extension Schema Reconciliation¶
Built-in extensions (adk, litestar, and events) and external packages default to idempotent unversioned schema reconciliation (migration_mode="reconcile") instead of recording synthetic ext_<name>_* rows in ddl_migrations (automatically falling back to "versioned" when an unconfigured external extension directory provides only numbered 0001_* revisions and no reconcile.py):
with tempfile.TemporaryDirectory() as root_dir:
root = Path(root_dir)
migrations = root / "migrations"
migrations.mkdir()
(migrations / "0001_items.sql").write_text(
"-- name: migrate-0001-up\n"
"CREATE TABLE items (id INTEGER PRIMARY KEY);\n"
"-- name: migrate-0001-down\n"
"DROP TABLE items;\n",
encoding="utf-8",
)
ext_dir = root / "audit_ext"
ext_dir.mkdir()
(ext_dir / "reconcile.py").write_text(
"from sqlspec.migrations.context import MigrationContext\n"
"from sqlspec.migrations.schema import (\n"
" SchemaTarget,\n"
" ensure_schema_sync,\n"
")\n\n"
"def reconcile(context: MigrationContext) -> None:\n"
" if context.driver is None:\n"
" return\n"
" target = SchemaTarget.from_ddl(\n"
" 'audit_runs',\n"
" 'CREATE TABLE audit_runs '\n"
" '(id INTEGER PRIMARY KEY, note TEXT)',\n"
" dialect='sqlite',\n"
" )\n"
" ensure_schema_sync(\n"
" context.driver,\n"
" [target],\n"
" manage_schema=True,\n"
" commit=False,\n"
" strict=True,\n"
" )\n"
" context.driver.execute(\n"
" 'INSERT INTO audit_runs (note) VALUES (:note)',\n"
" note='head',\n"
" )\n",
encoding="utf-8",
)
config = SqliteConfig(
connection_config={"database": str(root / "app.db")},
migration_config={"script_location": str(migrations), "echo": False},
)
audit_extension_migration_settings = {"manage_schema": True}
config.add_extension_migrations(
"audit_ext",
migrations_path=ext_dir,
settings=audit_extension_migration_settings,
migration_mode="reconcile",
)
try:
commands = create_migration_commands(config)
commands.upgrade(echo=False)
commands.upgrade(echo=False)
with config.provide_session() as session:
runs = session.select_value("SELECT COUNT(*) FROM audit_runs")
rows = session.select("SELECT version_num FROM ddl_migrations")
ledger = sorted(row["version_num"] for row in rows)
print(f"callback runs: {runs}, app ledger: {ledger}")
assert runs == 2
assert ledger == ["0001"]
finally:
config.close_pool()
Configuring Built-In and External Extensions¶
"reconcile" (from sqlspec.config import ExtensionMigrationMode) is the default mode for extensions:
- Built-in extensions:
adk,litestar(whensession_tableis enabled), andeventsreconcile automatically; pass"migration_mode": "versioned"insideextension_config[name]only if you need numberedext_<name>_*revision rows. - External extensions: Call
config.add_extension_migrations(name, migrations_path, settings=None, *, migration_mode="reconcile")(which mutatesconfigin place and returnsNone), or passsettings={"migration_mode": "versioned"}when targeting numbered files.
Authoring an Extension Reconciler Callback¶
Place a reconcile.py module inside <migrations_path> exporting a synchronous or asynchronous reconcile(context: MigrationContext) -> None and an optional downgrade(context: MigrationContext) -> None (or down) callback (from sqlspec.migrations.context import MigrationContext). Run DDL on context.driver within the migration runner's transaction and schema lifecycle, and pass manage_schema=True, commit=False, strict=True to ensure_schema_sync or ensure_schema_async (manage_schema defaults to False, commit=False leaves transaction commit and rollback to the runner, and strict=True refuses lossy or ambiguous schema changes).
Scheduling, Base-Only Downgrade, and Ledger Retention¶
- Upgrade execution order: Reconcilers execute in
include_extensionsorder before pending numbered revisions on everyupgrade(revision)(bothupgrade("head")and targeted revisions), including when zero numbered migrations are pending. Co-located numbered migration files for that extension are skipped, and zeroext_<name>_*rows are inserted intoddl_migrations. - Drop-at-base downgrade: Partial downgrades (such as rolling back
0002 -> 0001) preserve reconciled extension tables. Whendowngradereachesbase(downgrade("base")ordowngrade("-1")leaving zero applied revisions inddl_migrations), SQLSpec executes each reconciler'sdowngrade(context)callback in reverseinclude_extensionsorder to drop the extension schema and removes any retainedext_<name>_*ledger rows.downgrade --dry-runat base previews reconciler downgrades without executing DDL. - Retained ledger & versioned extension ordering: Any previously applied
ext_<name>_*rows already present inddl_migrationspasssqlspec verify --strictwithout orphan warnings. When an extension usesmigration_mode="versioned", itsext_<name>_*migrations sort before core migrations ininclude_extensionsorder and are excluded from out-of-order and auto-sync checksum warnings. - Serialized upgrades: mutating commands (
upgrade,downgrade,stamp, and the ledger phases ofsquashandfix) hold a migration lock, so concurrent migrators wait for each other and raiseMigrationErrorafter the lock timeout. The lock depends on the backend:
| Backend | Lock |
|---|---|
| PostgreSQL family | Session advisory lock |
| MySQL and MariaDB | GET_LOCK |
| SQL Server | sp_getapplock |
| SQLite (native adapters) | BEGIN IMMEDIATE transaction lock |
| CockroachDB, Oracle, DuckDB, Spanner, Db2, Sybase, SQL Anywhere, Teradata, and SQLite or DuckDB through ADBC or Arrow ODBC | Lease row in <version_table_name>_lock |
| BigQuery and Snowflake | None. SQLSpec logs migration.lock.unsupported once and continues; run one migrator at a time. |
The lease lasts migration_config["lock_lease_seconds"] (default 900) and is renewed before each migration, so set it longer than your longest single migration. An abandoned lease blocks other migrators until it expires. Lease times use the client clock, so migrator hosts should have roughly synchronized clocks.
Strict Schema Safety and Built-In Adapter Coverage¶
When strict=True, ensure_schema_sync and ensure_schema_async raise MigrationError before executing DDL if a target requires missing constraint_columns (PRIMARY KEY, UNIQUE, FOREIGN KEY, or CHECK), unsafe_add_columns (generated, identity, or collated columns), defaultless NOT NULL columns, missing tables when create_schema=False, or existing-column nullability narrowing or cross-family type drift. Existing-row backfills and versioned data conversions remain separate work.
Built-in reconcilers (litestar, events, and adk) run across:
- 22 unconditional adapters:
sqlite,aiosqlite,asyncpg,psycopg,psqlpy,cockroach_asyncpg,cockroach_psycopg,aiomysql,asyncmy,pymysql,mysqlconnector,duckdb,mssql_python,pymssql,oracledb,spanner,snowflake,bigquery,db2,sqlanywhere,sybase, andteradata. - Arrow ODBC (
arrow_odbc): Supported whenstatement_config.dialectis"mssql","tsql", or"db2". - Apache Arrow ADBC (
adbc): Supported on every backend with a resolved dialect (postgresql,sqlite,duckdb,bigquery,snowflake,mssql,oracle,db2,teradata, andmysql).
Remaining built-in refusals and their remedies:
- ADBC over FlightSQL without a dialect: Configure an explicit
statement_configdialect orgizmosql_backend("duckdb"or"sqlite"), or setmigration_mode="versioned". - Arrow ODBC outside SQL Server or Db2, or unresolvable/external adapters: Register a custom
reconcile.pyviaadd_extension_migrations(..., migration_mode="reconcile")(custom callbacks control their own dialect checks) or keepmigration_mode="versioned". - Constrained or unsafe column additions, or BigQuery
NOT NULL/defaulted columns on existing tables: Author an explicit numbered.sqlor.pyrevision for non-additive or backfilled schema transitions.
Schema Snapshots, Verification, and Data Bootstrap¶
- Read-Only
verify: Checks applied tracker rows against migration files on disk without creatingversion_table_nameon empty databases. Combine--strictwith--fail-on-pendingas a pre-deploy CI gate. - Extraction limits:
dump-schemaand--from-schemarefuse tables protected by PostgreSQL RLS, Oracle VPD, or SQL Server security policies, and warn about PostgreSQL grants, materialized views, functions, triggers, and domains they do not emit (see Squashing Strategies above). - Deterministic
dump-schema: Exports live schema DDL excludingversion_table_nameby default (--include-migrations-tableincludes it;--target-dialecttranspiles across SQLGlot dialects). Omitting--outputwrites pure SQL to stdout sosqlspec dump-schema > schema.sqlproduces a clean SQL script.
How Data Bootstrap Classifies Sources¶
create-migration --from-data <source> classifies <source> deterministically from its spelling rather than checking local filesystem state first:
- Values containing a path separator (
seeds/users.json) or ending in a data suffix (.json,.json.gz,.jsonl,.jsonl.gz,.ndjson,.ndjson.gz,.parquet,.arrow,.ipc,.feather) are treated as files. Missing files, directories, or unsupported suffixes (such as.csv) fail immediately without writing a migration file. - All other values are treated as table names (
raw_staging_usersorstaging.raw_users) and profiled viadriver.data_dictionary.infer_table_ddl_from_data(...). Pass--schema public --from-data jsonwhen profiling a table whose name matches a file suffix.
Recap¶
- Declare
migration_configon your adapter config andconfig = "module:attr"under[tool.sqlspec]inpyproject.toml. - Keep
--strategy concatwhen squashing histories that mix DDL and data migrations, and use--strategy ddlor--strategy schemato produce compactCREATE-only baselines. - Pair
sqlspec verify --strict --fail-on-pendingandauto_dump_schema: Trueto catch drift early and keepschema.sqlreviewable in pull requests.