alata.
Database

Migrations

Version your database schema with migration files, a fluent schema builder, and safe batch-based rollbacks.

Migrations are version control for your database schema. Each migration is a small Python file that knows how to apply a change (up) and how to revert it (down). Alata tracks which migrations have run, applies pending ones in order, and can roll back the last batch on PostgreSQL, MySQL, and SQLite.

Generating Migrations

Generate a new migration with the project CLI:

./alata make:migration create_posts_table

This writes a timestamped file to database/migrations/:

database/migrations/2026_07_28_143000_create_posts_table.py

The timestamp prefix (YYYY_MM_DD_HHMMSS_) keeps migrations sorted in creation order — that filename order is exactly the order they run in. The migration name is converted to a PascalCase class name, and when the name follows the create_<table>_table pattern, the stub pre-fills the table name:

database/migrations/2026_07_28_143000_create_posts_table.py
from alata.db.migrator import Migration


class CreatePostsTable(Migration):
    def up(self):
        """
        Run the migrations.
        """
        with self.schema.create("posts") as blueprint:
            blueprint.increments("id")
            blueprint.timestamps()

    def down(self):
        """
        Revert the migrations.
        """
        self.schema.drop("posts")

Migration Anatomy

Every migration subclasses Migration and implements two methods:

  • up() — apply the change.
  • down() — revert it. Write down() as the exact mirror of up(); rollbacks and migrate:fresh depend on it.

Inside both methods, self.schema is a fluent Schema builder bound to the current database engine. Shared schema operations compile through SQLAlchemy DDL for PostgreSQL, MySQL, and SQLite. Some operations are database-specific; see altering tables.

One migration per file: the runner picks the Migration subclass defined in the file, so importing a shared helper base alongside it is safe. A file defining two of its own raises AmbiguousMigrationError naming both.

from alata.db.migrator import Migration


class CreateUsersTable(Migration):
    def up(self):
        with self.schema.create("users") as table:
            table.increments("id")
            table.string("email").unique()
            table.string("name")
            table.text("bio").nullable()
            table.boolean("active").default(True)
            table.timestamps()
            table.soft_deletes()

    def down(self):
        self.schema.drop("users")

Running Migrations

./alata migrate

Runs every pending migration, in filename order, as a new batch. The other commands in the family:

CommandWhat it does
./alata migrateRun all pending migrations
./alata migrate:rollbackRevert the last batch (calls each migration's down() in reverse order)
./alata migrate:statusShow every migration with its ran/pending state and batch number
./alata migrate:freshRevert applied migrations, drop the tracking table, and run all migrations again
./alata migrate:syncRecord discovered migrations as applied without executing their up() methods
./alata migrate:publishCopy framework infrastructure migrations into the application
./alata make:migration <name>Generate a new migration file

migrate:fresh destroys all migrated tables and their data. It is for development and test databases only.

What migrate:fresh guarantees

On PostgreSQL, teardown and re-run hold the migration lock. Run migration commands one at a time on MySQL and SQLite, where Alata does not acquire this advisory lock.

Only migrations the tracking table records as applied are reverted. A pending migration never ran, so there is nothing for its down() to undo — and an ALTER-style down() against a table that does not exist would abort the whole teardown.

The order is deliberate: those down() methods run first, in reverse, and the tracking table is dropped last. Each successfully reverted migration has its tracking row deleted. If down() fails, the command stops and retains the remaining tracking records. On databases without transactional DDL, inspect any partial schema changes before retrying.

If a down() fails, fix it (or drop the objects by hand) and run migrate:fresh again.

migrate:sync is the adoption path: if your tables already exist (created by hand or by a previous tool), run it once so the tracking table matches reality and migrate reports nothing to do.

Publishing framework migrations

New projects already include the framework tables. When enabling database caching or queues in an existing application, publish the missing migrations first:

./alata migrate:publish --dry-run
./alata migrate:publish --only=cache
./alata migrate:publish --only=jobs
./alata migrate

Omit --only to publish all infrastructure migrations. Existing files or migrations creating the same tables are skipped; review before using --force to override that protection.

The tracking table

Alata records completed migrations in a namespaced table — alata_migrations by default — storing the migration name, its batch number, and when it ran. The namespaced default avoids colliding with any other tracking table already in the database. Override it in config/database.py:

config/database.py
DB_CONFIG = {
    "strict_mode": settings.EFFECTIVE_DB_STRICT_MODE,
    "default": "postgres",
    "migration_table": "my_migrations",   # optional — defaults to "alata_migrations"
}

Database-specific behavior

Migration commands coordinate automatically on all three databases. Failure recovery follows each database's transaction support:

  • PostgreSQL — the migrator holds an advisory lock so migration commands against the same database wait for one another. Each regular migration's DDL, data changes, and tracking-table update share a transaction and roll back together on failure. Concurrent index builds run after that transaction commits.
  • MySQL — a database-scoped lock serializes migration commands. DDL implicitly commits, so a whole migration cannot be rolled back atomically. On failure, Alata attempts the failing migration's down() and reports any cleanup failure.
  • SQLite — migration commands against the same database file are serialized across processes. Each migration's schema changes, data changes, and tracking record share a transaction and roll back together on failure.

PostgreSQL migration locking works as follows:

pg_advisory_lock pg_advisory_lock (blocks) BEGIN — DDL + tracking INSERT — COMMIT pg_advisory_unlock lock acquired — nothing pending pg_advisory_unlock Deploy A Deploy B PostgreSQL

Schema snapshots

Save the current schema and applied migration history:

./alata schema:dump
./alata schema:dump --connection=reporting
./alata migrate --connection=reporting

Snapshots are written under database/schema/, separately for each connection and database driver. Commit them with your application. When ./alata migrate encounters an empty database, it loads the matching snapshot and then runs migrations created after it.

To remove applied migration files after saving the snapshot:

./alata schema:dump --prune

Pending migration files remain. Existing databases keep their migration history and continue normally. migrate:status labels pruned history as Squashed. New migrations can be rolled back normally; changes already incorporated into a pruned snapshot require a new migration. migrate:fresh rebuilds the snapshot and applies subsequent migrations.

Snapshots contain schema and migration history, not application rows. Use seeders for reference data that a fresh database needs. Each database driver needs its own snapshot.

PostgreSQL requires pg_dump and psql on the command's PATH. Use clients from the same major release as your server: newer dump output may not restore to an older server. MySQL requires compatible MySQL mysqldump and mysql clients. SQLite needs no external client.

PostgreSQL and SQLite restore transactionally; a failed MySQL restore can leave partial schema because MySQL DDL commits implicitly.

Creating Tables

schema.create(name) is a context manager that yields a Blueprint. Declare columns and constraints inside the block; the CREATE TABLE (plus any indexes) executes when the block exits:

with self.schema.create("posts") as table:
    table.increments("id")
    table.integer("user_id")
    table.string("title", 200)
    table.text("body").nullable()
    table.string("status", 20).default("draft")
    table.index("status")
    table.foreign("user_id").references("id").on("users").on_delete("CASCADE")
    table.timestamps()

Column types

MethodProduces
increments(name)Auto-incrementing INTEGER primary key
big_increments(name)Auto-incrementing BIGINT primary key
string(name, length=255)VARCHAR(length)
text(name)TEXT
boolean(name)BOOLEAN
integer(name)INTEGER
big_integer(name)BIGINT
tiny_integer(name)SMALLINT
float(name)FLOAT
decimal(name, precision=8, scale=2)NUMERIC(precision, scale)
enum(name, values)Dialect-portable enum (named enum_<table>_<column>)
json(name)JSON (JSONB on PostgreSQL)
date(name)DATE
timestamp(name, tz=False)TIMESTAMP, with time zone when tz=True
timestamps()created_at + updated_at (both TIMESTAMPTZ, nullable)
soft_deletes()deleted_at (TIMESTAMPTZ, nullable)

json() maps to the dialect's parsed JSON type — JSONB on PostgreSQL, native JSON on MySQL — so the stored value is decoded and queryable the same way everywhere: text searches see real characters (not \uXXXX escapes), and PostgreSQL gains GIN indexing and containment (@>) queries. The trade-off is jsonb semantics: object key order is not preserved and duplicate keys collapse. If you need PostgreSQL's raw text-preserving json type, create the column with self.execute() in a migration.

Column modifiers

Each column method returns a definition you can keep chaining:

table.string("slug").unique()
table.text("notes").nullable()
table.integer("points").default(0).unsigned()
table.string("code", 10).primary()
ModifierEffect
.nullable()Allow NULL (columns are NOT NULL by default)
.default(value)Column default — see below
.primary()Mark as primary key
.unique()Single-column unique constraint
.unsigned()Adds a CHECK (col >= 0) constraint
.case_sensitive()Compare this text column exactly — see below
.after(column)Ordering hint (no-op on most backends)
.change()In ALTER mode: modify this existing column instead of adding it. Constraints chained alongside it (.unique(), .unsigned()) are emitted, not dropped

Exact text comparison

MySQL's default collation (utf8mb4_0900_ai_ci) compares text case- and accent-insensitively, so User:ABC, user:abc and user:abç are the same value. For a display name that is usually what you want; for a key it is a bug — one principal reads another's cached entry, separate rate-limit buckets merge into one, and a lookup matches a row it was never meant to.

.case_sensitive() asks for exact comparison and lets each backend decide what that requires:

with schema.create("api_tokens") as table:
    table.string("token").primary().case_sensitive()

MySQL gets CHARACTER SET utf8mb4 COLLATE utf8mb4_bin. PostgreSQL and SQLite already compare byte-for-byte, so nothing is emitted for them — the modifier states the requirement rather than a collation name, so the same migration is correct on every backend. It applies on both the create and ALTER paths, and raises on a non-text column rather than passing silently on the two backends that would have ignored it.

Database-level defaults

.default(value) writes a real DEFAULT clause into the DDL — not just an application-side default. Raw SQL inserts, other services, and manual psql sessions all get the default too. For server-side expressions, wrap the SQL in Expression so it is emitted verbatim instead of quoted:

from alata.db.grammars import Expression

table.boolean("active").default(True)                              # DEFAULT true
table.string("status", 20).default("draft")                        # DEFAULT 'draft'
table.timestamp("created_at", tz=True).default(Expression("CURRENT_TIMESTAMP"))

Timestamps and soft deletes

timestamps() creates nullable created_at and updated_at columns matching the timestamps every model manages automatically. soft_deletes() creates the deleted_at column that the SoftDeletes mixin expects. These helpers and timestamp() preserve microsecond precision.

Existing MySQL tables created with an earlier version may store only whole seconds. Upgrade those columns in a new migration:

with self.schema.table("orders") as table:
    table.timestamp("created_at", tz=True).nullable().change()
    table.timestamp("updated_at", tz=True).nullable().change()

Apply the same change to deleted_at and other timestamp columns where needed, keeping their existing nullability and defaults. This preserves future microseconds; precision already lost cannot be recovered.

Indexes and unique constraints

table.index("status")                      # idx_posts_status
table.index(["user_id", "status"])         # idx_posts_user_id_status (composite)
table.unique("slug")                       # uq_posts_slug
table.unique(["user_id", "title"])         # composite unique constraint

Index names follow idx_<table>_<columns> and unique constraints uq_<table>_<columns> — you'll need these names to drop them later. A column-level .unique() produces the same uq_<table>_<column> name, so it is droppable by name too; declaring the same unique both ways emits one constraint, not two.

Generated names (indexes, constraints, foreign keys, enum types) are capped at 63 characters — the smallest limit among the supported dialects — and anything longer is truncated with a deterministic hash suffix. The suffix is stable across runs and identical on every dialect, so a later drop_unique() still names the object that was created.

Full-text indexes

MySQL and PostgreSQL support full-text indexes in both create() and table() blocks:

with self.schema.table("posts") as table:
    table.full_text(["title", "body"])  # ft_posts_title_body

Use the same columns in where_full_text(). PostgreSQL also accepts language="english"; use the same language for the index and the query. Remove the index with table.drop_full_text("ft_posts_title_body").

Foreign keys

table.foreign("user_id").references("id").on("users")
table.foreign("team_id").references("id").on("teams").on_delete("CASCADE")
table.foreign("plan_id").references("id").on("plans").on_delete("SET NULL").on_update("CASCADE")

Valid actions for on_delete / on_update are CASCADE, RESTRICT, SET NULL, SET DEFAULT, and NO ACTION; the default for both is RESTRICT. Constraints are named fk_<table>_<column>.

Altering Tables

schema.table(name) opens an existing table for modification. The same Blueprint fluent API applies, plus ALTER-only operations:

def up(self):
    with self.schema.table("posts") as table:
        table.string("subtitle").nullable()              # ADD COLUMN
        table.string("status", 40).change()              # ALTER COLUMN type
        table.rename_column("body", "content")           # RENAME COLUMN
        table.drop_column("legacy_flag")                 # DROP COLUMN
        table.index("subtitle")                          # ADD INDEX
        table.foreign("editor_id").references("id").on("users")  # ADD FK

The full ALTER toolkit:

table.drop_index("idx_posts_status")
table.drop_foreign("fk_posts_user_id")
table.drop_unique("uq_posts_slug")
table.rename_index("idx_old", "idx_new")
table.drop_primary()                        # defaults to <table>_pkey
table.add_primary(["id", "tenant_id"])
table.comment("status", "Editorial workflow state")   # pass None to drop the comment

Operations run in a safe order automatically: index/constraint drops first, then column adds/changes/renames/drops, then new indexes and foreign keys. You don't have to sequence them by hand.

Database-specific limitations:

  • SQLite rebuilds tables automatically for column changes and primary, foreign, and table-level unique constraint changes. Existing data and schema objects are preserved; invalid changes roll back. SQLite 3.35 or newer is required.
  • drop_primary() on MySQL costs the column its AUTO_INCREMENT. MySQL refuses to drop the key an auto-increment column depends on, so the framework gives up AUTO_INCREMENT first (the column keeps its type, nullability and comment) and then drops the key. If the replacement key should keep generating values, re-declare the column. PostgreSQL is unaffected.
  • Column comments are silently unavailable on SQLite. SQLite has no column-comment syntax and stores nothing for one, so table.comment(...) and schema.comment(...) run without error and keep nothing. MySQL and PostgreSQL both persist them: MySQL has no standalone COMMENT ON, so the framework reads the column's current definition and restates it — type, nullability, default, character set and collation, AUTO_INCREMENT, generation expression and spatial SRID all survive.

Concurrent indexes

Building an index on a large PostgreSQL table takes a write lock that blocks every writer for the duration. index_concurrently() builds it without that lock:

with self.schema.table("events") as table:
    table.index_concurrently("occurred_at")

It works in create() blocks too — the index is built once the table exists.

How it runs. CREATE INDEX CONCURRENTLY cannot run inside a transaction, and the lock it needs is one that the migration's own transaction already holds. So the migrator defers it: the migration's DDL and its tracking row commit first, and the index is built immediately afterwards on a separate autocommit connection. Two consequences worth knowing:

  • The index appears a moment after the migration reports success, not atomically with it.
  • If the build fails, the schema change stays committed — only the index is missing, and PostgreSQL may leave an unusable index behind. The migrator says so, names the index, and exits non-zero. Drop the leftover (DROP INDEX IF EXISTS <name>) and rebuild it, or add a follow-up migration.

The build waits at most 30 seconds to acquire its lock. Blocked behind a long-running transaction, it fails with a database error rather than waiting forever.

Calling index_concurrently() on a Schema bound to a connection with an open transaction — outside the migrator — raises ConcurrentIndexInTransactionError rather than deadlocking against itself. Declare concurrent indexes in a migration, or run them through an engine with no transaction open.

On dialects without concurrent index support (MySQL, SQLite) it compiles to a regular index and runs inline, so the index exists when the migration finishes.

Other Schema Operations

self.schema.drop("posts")                        # drop if exists
self.schema.drop_if_exists("posts")              # alias
self.schema.rename_table("posts", "articles")
self.schema.truncate("audit_logs")
self.schema.has_table("posts")                   # -> bool
self.schema.has_column("posts", "subtitle")      # -> bool
self.schema.comment("posts", "status", "Workflow state")
self.schema.table_comment("posts", "User-authored content")

has_table / has_column are handy for defensive migrations that must run against databases in mixed states:

def up(self):
    if not self.schema.has_column("users", "timezone"):
        with self.schema.table("users") as table:
            table.string("timezone", 64).default("UTC")

Data Migrations

Migrations can move data, not just schema — backfilling a new column, seeding reference rows, deleting orphans. Three tiers, from structured to raw:

  • self.schema — DDL, through the Blueprint API above.
  • self.table(name) — a small, model-free gateway for simple DML.
  • self.execute(sql, params) — raw SQL for everything else.
database/migrations/2026_07_30_090000_seed_default_roles.py
from alata.db.migrator import Migration


class SeedDefaultRoles(Migration):
    ROLES = [
        {"slug": "admin", "name": "Administrator"},
        {"slug": "editor", "name": "Editor"},
        {"slug": "viewer", "name": "Viewer"},
    ]

    def up(self):
        self.table("roles").insert_or_ignore(self.ROLES, unique_by=["slug"])

    def down(self):
        raise RuntimeError("Reference roles must be removed in a separate migration.")

This example requires a unique index on roles.slug and preserves existing roles. It is intentionally irreversible: those roles may predate the migration or already be assigned to users. Its down() stops rollback and migrate:fresh; remove roles through a separate migration that handles their assignments. For reversible data migrations, undo only changes the migration owns.

On PostgreSQL and SQLite, these data changes join the migration's transaction, so they roll back with its DDL and tracking record if the migration fails. MySQL DDL implicitly commits; see database-specific behavior.

The table gateway

self.table(name) returns a fresh, unfiltered gateway each time you call it:

MethodWhat it does
insert(rows)Insert one row (dict) or many (list of dicts); returns the row count
insert_or_ignore(rows, unique_by)Insert, silently skipping rows that already exist per the unique_by constraint; returns the number actually inserted on PostgreSQL/SQLite (re-run → 0) — on MySQL the count is advisory, so guard idempotency with the data, not the return
upsert(rows, unique_by, update_cols)Insert, updating only update_cols on conflict; other columns keep their existing values. Every update_cols entry must appear in the supplied rows, and update_cols=[] raises — use insert_or_ignore for that
where(col, value) / where_in(col, values)Chainable equality/membership filters for update and delete. where_in rejects a bare string with TypeError rather than iterating it into one character per element
update(values) / delete()Apply to the filtered rows; returns the affected count. update may run unfiltered (whole-table backfills are legitimate); delete requires at least one condition — a deliberate full-table delete goes through execute()
exists(**equalities)True when at least one row matches every column=value given — an idempotency guard for backfills. Requires at least one condition

On MySQL, insert_or_ignore and upsert compile to ON DUPLICATE KEY UPDATE, which fires on a violation of any unique index — MySQL cannot target the unique_by constraint specifically — and the returned counts differ for conflicting rows (the driver counts skipped duplicates too, which is why the return is advisory there).

Raw SQL

execute runs a statement with bound parameters and returns the affected-row count (-1 when the driver does not report one). A collection expands into one placeholder per element only where the statement uses it in an IN position, so IN clauses take collections directly:

def up(self):
    self.execute(
        "UPDATE users SET plan = :plan WHERE id IN :ids",
        {"plan": "legacy", "ids": [17, 23, 42]},
    )

Anywhere else a collection binds as a single value, which is what it means there — VALUES (:tags) against a PostgreSQL text[] column binds one array. Parameters the statement never mentions are ignored whatever their type.

Because :name marks a bind parameter, a literal colon inside a SQL string literal must be escaped as \::

self.execute(r"UPDATE sites SET url = 'https\://example.com' WHERE id = :id", {"id": 1})

fetch_all returns every row as a plain dict, and fetch_one returns the first row or None — same binding rules, meant for guard checks before an expensive backfill:

def up(self):
    if self.fetch_one("SELECT 1 FROM settings WHERE key = 'currency'") is None:
        self.execute("INSERT INTO settings (key, value) VALUES ('currency', 'USD')")

Never import application models in a migration. A migration replays against the historical schema — on a fresh database, years after it was written — while models always describe today's. A model-based data migration silently breaks the moment the model drifts. This is why the gateway is model-free and its surface deliberately tiny (no hydration, no joins, no ordering): every statement names exactly the columns the migration states. Anything beyond it belongs in self.execute().

Data migrations are for one-time corrections tied to a point in schema history. Recurring reference data and development fixtures belong in seeders, which run in full application context and are meant to use your models.

Programmatic Access

The migrator is registered in the service container as "migrator", so scripts and tooling can drive it directly:

from alata.container import container

migrator = container.make("migrator")
migrator.run()        # ./alata migrate
migrator.rollback()   # ./alata migrate:rollback
migrator.status()     # ./alata migrate:status

On this page