Migrations¶
Use this when you need to change a database schema to match your models, one reviewed SQL file at a time.
The idea¶
The schema is the shape of the database: its tables, columns, keys and indexes. When you change a model, for example by adding a field, the real database must change too. A migration is a SQL file that makes one such change, like 0002_add_note.sql. Files are numbered, so they run in order.
Why files, and not "sync the database to the models" on start-up? Because a schema change can destroy data. A file is something you can read before it runs, review in a pull request, and keep in git next to the code that needs it. Every database (your laptop, staging, production) then gets the same changes in the same order.
Once a file has been applied somewhere, never edit it. Other databases already ran the old text, and they would no longer match. To change the schema again, write a new file.
The workflow¶
Four steps: make, review, apply, status.
makecompares your models with the same-named tables of thepublicschema and writes the SQL that closes the gap, as the next numbered file. Other tables inpublicare left alone. (publicis Postgres. A SQLite database is one file with no schemas, somakecompares with that file. See SQLite.)- You read the file. Dangerous statements carry a
-- korbase:reviewmarker. applyruns the pending files in order and records each one.statuslists every file asapplied,pending,changedormissing.
Here are two rounds. models.py holds one model:
from typing import Annotated, Optional
import msgspec
from korbase import PK, table
@table("items")
class Item(msgspec.Struct):
id: Annotated[int, PK()]
name: str
note: Optional[str] = None
export KORBASE_DSN="postgresql://user:password@localhost:5432/app"
python -m korbase.migrate make --models models --dir migrations -m "create items"
python -m korbase.migrate apply --dir migrations
python -m korbase.migrate status --dir migrations
The output is migrations/0001_create_items.sql, then applied 0001_create_items.sql twice (once from apply, once from status). Now rename the field name to title and run make again. The new file stops apply:
-- Generated by korbase on 2026-11-20.
SET standard_conforming_strings = on;
-- korbase:review NOT NULL column without default fails on a non-empty table
-- possible rename: rewrite as ALTER TABLE "items" RENAME COLUMN "name" TO "title"
ALTER TABLE "items" ADD COLUMN "title" text NOT NULL;
-- korbase:review drops column items.name, its data is lost
-- possible rename: rewrite as ALTER TABLE "items" RENAME COLUMN "name" TO "title"
ALTER TABLE "items" DROP COLUMN "name";
apply prints error: migration 0002_rename_name_to_title.sql still has a -- korbase:review marker and runs nothing. korbase cannot know that this was a rename. You do, so you edit the file to keep the data:
-- Generated by korbase on 2026-11-20.
SET standard_conforming_strings = on;
ALTER TABLE "items" RENAME COLUMN "name" TO "title";
Now apply runs it, and a new make prints no changes.
Local work with dev¶
On your own machine, make then apply for every small change is slow. dev does both in one step:
python -m korbase.migrate dev --models models --dir migrations -m "add note"
It writes the next file, then applies it, and prints applied migrations/0003_add_note.sql (or no changes). If the new file holds a -- korbase:review line, dev applies nothing, prints the file name and the flagged lines, and exits with 1. Review the file as above, then run apply.
Use dev only on a development database. It skips the step where a person reads the file before it runs, and it also applies any pending file that came before. For staging and production, run make on a development database, review and commit the file, then run apply.
Command line¶
make,dev,applyandstatusare the four commands.--modelsis the dotted path of a module that holds your@tableclasses. It must be importable from the current directory.makeanddevneed it.--diris the migrations folder. It defaults tomigrations.-mnames the new file. It defaults tomigration.--all-tablesis formake: compare the wholepublicschema, not only the tables of your models. See Tables korbase does not manage.makeprints the new file's path, orno changes.devprintsapplied PATH, orno changes.applyprints oneapplied NAMEline per file.statusprintsSTATE NAMEper file.- The exit code is 0 on success and 1 on error.
Python API¶
import asyncio
import os
from korbase import Database
from korbase.migrate import apply, collect_models, dev, make, status
async def migrate(dsn: str) -> None:
async with await Database.connect(dsn) as db:
path = await make(db, collect_models("models"), "migrations", "create items")
print(path) # the new file's path, or None when nothing differs
print(await status(db, "migrations")) # [("0001_create_items.sql", "pending")]
print(await apply(db, "migrations")) # ["0001_create_items.sql"]
async def local(dsn: str) -> None:
async with await Database.connect(dsn) as db:
print(await dev(db, collect_models("models"), "migrations", "add note")) # path, or None
asyncio.run(migrate(os.environ["KORBASE_DSN"]))
collect_models(module_path)returns the@tableclasses of a module. It raisesKorbaseErrorif there are none.make(db, models, directory, message, all_tables=False)returns the new file's path, orNone. Passall_tables=Trueto compare the wholepublicschema.dev(db, models, directory, message="dev")makes then applies, and returns the new file's path orNone. It raisesKorbaseError, naming the file and the flagged lines, when the file needs review. Local use only.apply(db, directory)returns the names of the files it ran.status(db, directory)returns a list of(name, state)pairs.
Reviewing a file¶
A statement that can lose data or fail on existing rows gets a -- korbase:review line above it. apply refuses to run while any pending file still contains one. It applies nothing, not even the files before it. To go on:
- Read the statement and check it against your data.
- Change the SQL if it is wrong.
- Delete the
-- korbase:reviewlines.
On SQLite, make also writes table rebuilds for changes SQLite cannot ALTER. A rebuild carries a review line only when the copy can lose data: a type change (copied with CAST), a column that becomes NOT NULL, a dropped column, or a new NOT NULL column without a default. Before you delete the line, check the data with a SELECT: CAST turns text that is not a clean number into 0 or another number and does not fail. See Table rebuilds.
Then run apply again. If a file fails half way, its changes are rolled back and the error names the file. Files before it stay applied. Fix the file or the database, then run apply again.
Tests¶
create_all(db, models) creates the tables of your models straight from the models, in one transaction. It records no versions and runs no files. Use it to set up an empty test database. Use make and apply for every database that holds data you keep.
from korbase import Database
from korbase.migrate import collect_models, create_all
async def setup(db: Database) -> None:
await create_all(db, collect_models("models"))
The tests of this workflow are in tests/test_migrate.py and tests/test_apply.py.
Going further¶
How make works. It does not change your data. In one transaction it creates a scratch schema, builds your models in it, reads that schema and public, writes the difference, and always rolls back. So it needs the CREATE privilege on the database. Run it against a development database, not production. It compares with public (on SQLite, with the database file; the scratch database is built in memory, so nothing is created in your file and no CREATE privilege is needed): use the database whose schema should be brought up to date. Only the tables your models name are compared, unless you pass --all-tables.
What the differ detects. Tables created or dropped. Columns added or dropped, and changes of type, NOT NULL, default and identity. Primary keys, unique constraints, foreign keys (with ON DELETE) and indexes. Renames are not detected.
Ordering. Statements are sorted so they can run. First: create tables, add columns, alter columns, change keys, add foreign keys, add indexes. Then the drops: foreign keys, indexes and constraints, columns, and tables last. A foreign key held up by a primary key change is dropped first and added back. Identical statements appear once.
Tables korbase does not manage. By default make looks only at the tables your models define. A table in public that no model names is ignored, so a shared database does not fill your files with drops of other tools' tables. Inside a table your models do define, an index that is not in your models is still dropped, flagged for review.
The cost is that deleting a model no longer drops its table. To drop it, run make --all-tables (or make(..., all_tables=True)). That compares the whole public schema, so the file then holds a flagged DROP TABLE for the removed model and for every other table the models do not know. Keep the lines you want and delete the rest before you apply. dev has no such option: it never drops a removed model's table. The korbase_migrations table is always left out. Only ordinary and partitioned tables are read: views and other objects are not.
Review markers, and why each exists.
| Marker reason | Why |
|---|---|
| drops table, drops column | the data is lost |
| type changes | the USING cast can fail, or change values |
becomes NOT NULL |
fails if a NULL exists |
new NOT NULL column without default |
fails on a table that has rows |
| identity changes | the values that the database hands out change |
| primary key changes | other tables may depend on it |
| index not managed or removed | it may serve queries that korbase cannot see |
Rename hints. When a column is dropped and another added in the same table, make adds -- possible rename: rewrite as ALTER TABLE ... RENAME COLUMN .... Dropped and added columns are paired in order, so with several at once, check each pair. Replace the ADD COLUMN and DROP COLUMN with the RENAME COLUMN. If the column was indexed, the DROP INDEX and CREATE INDEX lines can stay, but their review lines go.
Checksums and the version table. apply creates the version table korbase_migrations: the name, the checksum (SHA-256 of the file bytes) and the time of each applied file. status compares files with rows:
pending: not applied yet.applied: applied, and the file is unchanged.changed: applied, but the checksum differs now.missing: applied, but the file is gone.
apply refuses, and runs nothing, if any file is changed or missing. If you edited an applied file by mistake, put the original text back. File names must look like 0001_create_items.sql: four or more digits, an underscore, then lower-case letters, digits and underscores. A pending file numbered lower than the last applied one is refused, because it would run out of order.
Advisory lock. apply takes a Postgres advisory lock on one connection for the whole run, before it reads the version table. Two runs at the same time therefore apply each file once: the second waits, then finds nothing to do. The lock is released even when a file fails.
-- korbase:no-transaction and CREATE INDEX CONCURRENTLY. Each file normally runs in its own transaction, with its version row. Postgres refuses CREATE INDEX CONCURRENTLY inside a transaction. Make the first line of the file -- korbase:no-transaction to run it without one:
-- korbase:no-transaction
CREATE INDEX CONCURRENTLY "items_title_idx" ON "items" ("title");
The marker must be the very first line, so move it above the header that make writes, or delete the header. Put one statement in such a file. A file is sent as one multi-statement text, and Postgres treats that as one transaction, so a second statement next to CONCURRENTLY fails with cannot run inside a transaction block. Without a transaction, a failed file is not rolled back, so check the database by hand.
On SQLite the marker has a second use. A table rebuild must run with PRAGMA foreign_keys=OFF, which has no effect inside a transaction, so make writes -- korbase:no-transaction as line 1 of such a file and opens its own BEGIN IMMEDIATE. You do not add it yourself. If the file fails, apply rolls it back and records nothing. See Table rebuilds.
standard_conforming_strings is forced on. apply sets it to on for its own session, whatever the role's default, then restores it. A backslash in a string literal is therefore read the same way in every file. make writes SET standard_conforming_strings = on; at the top of its files for the same reason.
KORBASE_DSN and --dsn. Set KORBASE_DSN in the environment. --dsn wins when both are given, but a command-line argument shows in ps and in shell history, so other users on the machine can read it. Errors never print the DSN: a connection failure reads could not connect to the database.
Next: Korvex integration