Migrations and schema evolution
Migrations are asynchronous classes describing ordered physical changes. up applies a change and down describes its reversal. Every applied file is recorded in the migrations table on the same connection. Seeders have separate history and run after the schema is ready.
Prepare framework storage tables
Section titled “Prepare framework storage tables”Since 1.3.0, auth:migrate, cache:migrate, schedule:migrate, and session:migrate prepare internal SQL storage alongside the existing queue:migrate. They create missing tables from definitions shipped in Orionis, independently of application migrations. They neither discover files under database/ nor add entries to the migrations history.
| Command | Configured tables | SQL connection |
|---|---|---|
auth:migrate | AUTH_TOKEN_TABLE (personal_access_tokens), AUTH_PASSWORD_RESET_TABLE (password_reset_tokens), and the five authorization tables. | Application default connection. |
cache:migrate | DB_CACHE_TABLE (cache) and DB_CACHE_LOCK_TABLE (cache_locks) | DB_CACHE_CONNECTION. |
queue:migrate | Every configured SQL queue table, including QUEUE_TABLE (jobs), plus QUEUE_FAILED_TABLE (failed_jobs) | Each queue’s SQL connection, including QUEUE_DB_CONNECTION, and QUEUE_FAILED_DB_CONNECTION for failures. |
schedule:migrate | DB_TASK_TABLE (scheduler_tasks) | DB_TASK_CONNECTION. |
session:migrate | SESSION_DB_TABLE (sessions) | SESSION_DB_CONNECTION. |
Connection values are names declared in config/database.py; omitted optional connections use the default. Run the relevant command from the application root, for example:
python -B reactor auth:migrateThese commands accept only -h/--help, not --database. Configure their destination before executing them. They can prepare SQL storage even when the corresponding active driver uses memory, files, Redis, or sync; cache and scheduler still require their stores.database configuration. They do not start workers, execute scheduled tasks, or switch the active driver.
All authentication, cache, queue, and session table names respect their SQL connection’s prefix. Scheduler storage uses the native APScheduler schema and indexes, taking DB_TASK_TABLE directly without applying that prefix. The connection needs the required DDL permissions and backend guarantees, including enforced unique constraints.
Rerunning a command preserves existing rows and tables. It does not run DROP or ALTER, repair incompatible schemas, or relocate existing data after a configuration change. Use an explicit application migration for a deliberate schema change. Successful preparation returns 0; a reported storage or configuration failure returns 1.
Authorization and recovery since 1.5.0
Section titled “Authorization and recovery since 1.5.0”auth:migrate prepares permissions, roles, model_has_permissions, model_has_roles, and role_has_permissions, plus the configured personal access token and password recovery tables. The two configurable table names must differ from each other and from the five authorization tables, ignoring case. Configure them before running the command: a collision is rejected before storage is created.
The core provides the technical schema. Identity (users, its model, and its migration), the domain, business capability names, their assignments, and policies belong to the application. For a new database, use this sequence so seeders have all their required tables:
python -B reactor migratepython -B reactor auth:migratepython -B reactor seedauth:migrate does not create users or insert roles, permissions, or administrator accounts. It does not execute seeders either. migrate --seed does not prepare internal auth storage by itself; use the sequence above when a seeder depends on it.
The reference application removes m0000000006_create_permissions_table.py, m0000000007_create_roles_table.py, m0000000008_create_model_has_permissions_table.py, m0000000009_create_model_has_roles_table.py, m0000000010_create_role_has_permissions_table.py, and m0000000012_create_password_reset_tokens_table.py, together with their _v1.py schemas. The users migration and business seeders remain in the application.
In an existing project, auth:migrate reuses existing tables and preserves their records and history. Keep already-applied migration files and the schemas they import so their recorded batches can be rolled back. Do not clear history, renumber files, or run a reset to adopt 1.5.0. Updating the package does not automatically remove files from your application or skeleton. Use an explicit migration to change an existing schema: the command only creates missing tables.
Existing projects and the 1.3.0 cleanup
Section titled “Existing projects and the 1.3.0 cleanup”The framework’s reference application removed five duplicate migration files: m0000000001_create_scheduler_tasks_table.py, m0000000002_create_cache_table.py, m0000000003_create_cache_locks_table.py, m0000000004_create_sessions_table.py, and m0000000011_create_personal_access_tokens_table.py, together with their five corresponding _v1.py schemas. In 1.3.0 it retained migrations for users, permissions, roles, their associations, and recovery with their original numbers. The 1.5.0 section describes the subsequent move of authorization and recovery into the core. Queue preparation remains provided by queue:migrate.
That source cleanup does not alter existing databases or migration history. An existing project or skeleton may still contain those files: retain already-applied migrations and their schemas so rollback can resolve their identities. Do not renumber the remaining files or clear history to adopt these commands. New storage can be prepared with the commands above; business tables continue to use migrate.
Generating a migration
Section titled “Generating a migration”Database command reference: syntax, arguments and options for application migrations, internal storage, inspection and wiping.
orionis make:database-migration create_flagspython -B reactor make:database-migration create_flagsThese commands are alternatives. The real command is make:database-migration with a required name: str and only -h/—help for help; there is no —create, —table, or —force. The generator uses database_migrations, normally database/migrations. It creates m<YYYYmmddHHMMSS>_create_flags.py using the application timezone and a CreateFlags class with empty async up/down methods. The m prefix makes the file importable as a Python module.
Choose snake_case for predictable names. Subdirectories using / or \ are accepted, such as catalog/create_flags. Components are normalized to lowercase and must form Python modules (letters, digits, and underscores, beginning with a letter). One filename extension is stripped; absolute paths, empty components, . and .. are rejected. Required directories are created. Existing files produce an error and are never overwritten; identical names generated within the same second can collide.
Complete the generated contents:
from orionis.database import Migrationfrom orionis.support.facades import Schema
class CreateFlags(Migration): async def up(self) -> None: async with Schema.create("flags") as table: table.id() table.string("name", 80) table.unique("name", name="uq_flags_name")
async def down(self) -> None: await Schema.drop("flags")Discovery and ordering
Section titled “Discovery and ordering”The runner recursively discovers modules under the configured path and imports local Migration subclasses. Package initializers are not required. Reexports and initializer modules are ignored. Each file must define one unambiguous local subclass: multiple classes for the same identity raise ValueError. Identity is the filename stem rather than class name or directory: matching stems in different subdirectories also collide. Files run in lexical order; timestamp prefixes preserve creation order.
Discovery is cached on each Migrator instance. A new process sees new files. Do not rename, delete, or change an applied migration: history uses its identity and down might no longer resolve. Add another file for future changes and preserve versioned schemas.
Every command and option
Section titled “Every command and option”Run the application migration commands below from the project root using orionis
| Command | Specific options | Result |
|---|---|---|
| migrate | —seed, bool False by default | Applies pending migrations; —seed runs pending seeders after success, including when no new migrations were pending. |
| migrate:status | None | Shows discovered migration state and batch; may create an empty tracking table. |
| migrate:rollback | —step N / -s N, optional int, effective default 1 | Reverts the last N batches. |
| migrate:reset | None | Calls down for every applied migration in reverse order. |
| migrate:refresh | —step N / -s N, optional int, None means all | Reverts selected batches and reapplies pending migrations. |
| migrate:fresh | None | Resets, removes migrations/seeders history, and applies again as batch 1. |
| seed / db:seed | None | Runs pending seeders; see the guide. |
orionis migrate:statuspython -B reactor migrate:status
orionis migrate --seedpython -B reactor migrate --seed
orionis migrate --database reportingpython -B reactor migrate --database reporting
orionis migrate:rollback --step 1python -B reactor migrate:rollback --step 1
orionis migrate:refresh --step 2python -B reactor migrate:refresh --step 2step counts batches rather than files and must be a positive integer. One migrate invocation assigns the same batch to its pending files, but every file has its own transaction. rollback reverts the most recently applied records within selected batches. refresh accepts no —seed; run seed afterward to populate again. fresh also accepts no —seed and does not arbitrarily drop every table: it relies on down to remove recorded structures and leaves unrelated tables intact.
Transactions and history
Section titled “Transactions and history”sequenceDiagram
participant CLI as Reactor
participant M as Migrator
participant DB as Selected connection
participant U as Migration
CLI->>M: migrate(connection)
M->>DB: Read migration history
loop Pending files in lexical order
M->>DB: Begin transaction
M->>U: Build through container and await up()
U->>DB: Schema / DB operations
M->>DB: Insert migration, batch, migrated_at
alt Success
M->>DB: Commit
else Failure
M->>DB: Rollback and propagate error
end
endThe migrations table contains a generated id, unique migration identity, batch, and migrated_at as epoch seconds. Each operation sets a contextual connection: unqualified DB, Schema, and ORM resolution use it. Explicitly selecting another connection can escape that transaction; keep a migration file on its target connection. Migration instances are constructed through app.build, supporting constructor injection; up/down are called without arguments and receive no method injection.
from orionis.database import Migrationfrom orionis.database.contracts.schema import ISchema
class CreateAuditEntries(Migration): def __init__(self, schema: ISchema) -> None: self._schema = schema
async def up(self) -> None: async with self._schema.create("audit_entries") as table: table.id() table.string("message", 255)
async def down(self) -> None: await self._schema.drop("audit_entries")A failure aborts the current file, rolls back its transaction, and prevents recording success. Earlier files from that batch may already be committed; rerunning applies remaining files. DDL reversibility depends on the backend: engines with implicit commits cannot guarantee restoring a table merely through rollback. down is explicit code and must be tested. The runner provides no global deployment lock between migration processes; coordinate one executor per connection.
Partial reversal preserves seeders history. Reverting the last applied migration removes that history with the final step, allowing seed to run again after reconstruction. reset leaves empty migrations history; fresh removes and recreates history as the first batch.
Programmatic Migrator API
Section titled “Programmatic Migrator API”Migrator(app: IApplication, conn_manager: IConnectionManager) can be injected into custom commands. Every operation is asynchronous; connection=None selects the default and events=None reports no progress. There is no individual file selection or force argument.
migrate
Section titled “migrate”async migrate(*, connection: str | None=None, events: MigrationEvents | None=None) -> list[str]Returns list[str] of applied identities in order, or [] when nothing is pending. This API does not run seeders: —seed belongs to the CLI command.
from orionis.database import Migrator
async def migrate_example(migrator: Migrator) -> list[str]: return await migrator.migrate(connection=None, events=None)rollback
Section titled “rollback”async rollback(steps: int=1, *, connection: str | None=None, events: MigrationEvents | None=None) -> list[str]Returns list[str] of reversed identities in reverse order. steps defaults to 1; nonintegers, bool, or values <1 raise ValueError. Applied identities with missing files raise MigrationNotFoundException before reversions begin.
from orionis.database import Migrator
async def rollback_example(migrator: Migrator) -> list[str]: return await migrator.rollback(steps=1, connection=None, events=None)async reset(*, connection: str | None=None, events: MigrationEvents | None=None) -> list[str]Reverts all and returns identities in reverse order; [] if none were applied. Propagates down failures and missing files.
from orionis.database import Migrator
async def reset_example(migrator: Migrator) -> list[str]: return await migrator.reset(connection=None, events=None)refresh
Section titled “refresh”async refresh(steps: int | None=None, *, connection: str | None=None, events: MigrationEvents | None=None) -> list[str]steps=None means reset followed by migrate; steps=N means rollback(N) followed by migrate. Returns newly applied rather than reverted identities.
from orionis.database import Migrator
async def refresh_example(migrator: Migrator) -> list[str]: return await migrator.refresh(steps=None, connection=None, events=None)async fresh(*, connection: str | None=None, events: MigrationEvents | None=None) -> list[str]Resets, removes migrations history and residual seeders history, then migrates. Returns reapplied identities. This neither repairs an incorrect down nor drops untracked tables.
from orionis.database import Migrator
async def fresh_example(migrator: Migrator) -> list[str]: return await migrator.fresh(connection=None, events=None)status
Section titled “status”async status(*, connection: str | None=None) -> list[dict[str, Any]]Returns list[dict] in discovery order with migration: str, ran: bool, batch: int | None. Enumerates discovered files rather than an independent list of every historical record.
from orionis.database import Migrator
async def status_example(migrator: Migrator) -> list[dict[str, object]]: return await migrator.status(connection=None)from orionis.console.base.command import BaseCommandfrom orionis.database import Migrator
class InspectMigrations(BaseCommand): signature = "database:inspect-migrations" description = "Show migration history for the default connection."
async def handle(self, migrator: Migrator) -> None: rows = await migrator.status() self.table( ["Migration", "Ran", "Batch"], [[row["migration"], row["ran"], row["batch"]] for row in rows], )[ {"migration": "m20261022090000_create_flags", "ran": True, "batch": 1}, {"migration": "m20261022090100_create_audit_entries", "ran": False, "batch": None},]The second block illustrates returned data rather than a migration file. IMigrator exposes the same operation signatures.
Progress and errors
Section titled “Progress and errors”from orionis.console.base.command import BaseCommandfrom orionis.database import Migratorfrom orionis.database.migrations.events import MigrationEvents
class ApplyMigrations(BaseCommand): signature = "database:apply-migrations" description = "Apply pending migrations and show progress."
async def handle(self, migrator: Migrator) -> None: events = MigrationEvents( on_start=lambda name: self.info(f"Starting {name}"), on_success=lambda name, elapsed: self.info(f"Done {name}: {elapsed:.2f}s"), on_error=lambda name, elapsed: self.error(f"Failed {name}: {elapsed:.2f}s"), ) applied = await migrator.migrate(connection=None, events=events) self.info(f"Applied: {len(applied)}")MigrationEvents(*, on_start: Callable[[str], None] | None = None, on_success: Callable[[str, float], None] | None = None, on_error: Callable[[str, float], None] | None = None) is frozen/slotted and accepts synchronous callbacks. started(name) calls on_start; succeeded(name, elapsed) calls on_success; failed(name, elapsed) calls on_error. All three methods return None; elapsed is measured in seconds. NO_EVENTS is the callback free instance.
Do not raise exceptions from callbacks: started runs before the transaction, succeeded after commit, and failed during failure propagation; callback exceptions propagate too. SeederEvents is an alias of the same type.
Unknown connection names raise ConnectionNotFoundException. A type lacking a builder or invalid DDL raises QueryException. Python errors fail during module import. Ambiguous migrations raise ValueError. There are no pretend, file skipping, production confirmation, or automatic cross-backend DDL compatibility options. See verified alterations to evolve existing tables.
Connection context for integrations
Section titled “Connection context for integrations”current_migration_connection() -> IConnection | Nonemigration_connection_scope(connection: IConnection) -> Generator[None]These functions are in orionis.database.migrations.context. The first reads the contextual connection without creating it; the second is a synchronous contextmanager setting and restoring its ContextVar in finally. Migrations and seeders manage this automatically; the context alone opens no transaction and commits or rolls back nothing. A custom runner must retain the same async task and combine this context with a real connection transaction.
MigrationEvents.started(name: str) -> NoneMigrationEvents.succeeded(name: str, elapsed: float) -> NoneMigrationEvents.failed(name: str, elapsed: float) -> None