Migration Runtime
db.migrate() applies pending migrations from your schema in order.
What db.migrate() does
- Ensures
__tsql_migrationsexists. - Reads already-applied migration names.
- Compiles schema SQL from
schema.migrations. - Runs each pending migration inside its own transaction.
- Records migration name and timestamp after success.
If a migration fails, that migration transaction is rolled back and execution stops.
Operational usage
- Preferred: run in CI/deploy bootstrap step.
- Monolith: run once during startup before serving traffic.
- Safe to call repeatedly; applied migrations are skipped.
Example bootstrap script
import { db } from "../src/db";
await db.migrate();
DML in migrations
Use migration queries directly in the migration callback:
export const schema = defineDatabase((db) =>
db
.migration("001_create_users", (schemaBuilder) =>
schemaBuilder.createTable("users", (t) => ({
id: t.text().primaryKey(),
email: t.text().notNull(),
})),
)
.migration("002_uppercase_user_ids", (migration) =>
migration
.update("users")
.set(({ users }) => ({
id: users.id.upper(),
}))
.execute(),
),
);
The same callback can mix schema and data steps in sequence.
Each migration runs in a transaction, so failures roll back cleanly; rerunning db.migrate() resumes from the first migration that has not been recorded yet.