Skip to content

ferro.migrations

ferro.migrations is what an application, a data step, a test and an Alembic env.py import. The guides show each in use: Deploying migrations for up and require_applied, Data steps and backfills for the declarations, Testing migrations for the harness, Alembic for the bridge. The commands are in the CLI reference.

import ferro
import ferro.migrations

await ferro.connect(url)
await ferro.migrations.up()                # an app with no deploy step
await ferro.migrations.require_applied()   # a server that migrates in its deploy step

Running migrations

Each call takes these parameters to say which project, database and connection it works on:

Parameter Meaning Taken by
settings= None is FerroSettings(), the project's config file every call
database= None is the one database configured every call
using= the open connection of that name; None is the default connection, unless url= is given up, require_applied, status, drift, baseline, remove_baseline
url= a private connection opened for the call and closed after it the same six

Passing both using= and url= raises MigrationRefused. check reads only the models and the migrations directory and takes no connection. A refusal is raised, never returned: a refused up raises MigrationRefused whose .report is the run's report, saying what it applied before it stopped.

up async

up(settings: FerroSettings | None = None, database: str | None = None, *, using: str | None = None, url: str | None = None, lock_timeout: str | float | None = None, allow_ahead: AllowAhead = False, progress: Callable[[str], Any] | None = None, on_event: Callable[[RunEvent], Any] | None = None) -> RunReport

Apply every pending migration, in order, under the run lock.

This is ferro migrate up. A second run waits for the lock, saying so on stderr at once. See Deploying migrations.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None
lock_timeout str | float | None

How long to wait for another run's lock: "30s", "500ms", "1m" or a number of seconds; 0 refuses at once. Defaults to the database's lock_timeout.

None
allow_ahead AllowAhead

Run beside a database that has applied migrations the directory lacks: "expand-only" when every step they hold is expand (the previous release of a rolling deploy), True whatever they hold. Defaults to False, which refuses.

False
progress Callable[[str], Any] | None

Receives each line as the run goes: one per squash it inherits (before any step), one per applied step, and one per attempt a step makes while it waits for a table lock.

None
on_event Callable[[RunEvent], Any] | None

Receives the same lines as data, each just before progress receives its line(): an InheritedEvent per squash inherited, a StepEvent per applied step, a RunNote for any other. A failed step is a StepEvent too, with no line for progress.

None

Returns:

Type Description
RunReport

What the run did: the squashes it inherited, in order, then the steps it applied.

Raises:

Type Description
DatabaseAheadError

The database has applied migrations the directory lacks, and nothing else is in the way.

MigrationRefused

The run refused or a step failed; the message says why and how to resume, and .report is the run's report. Also raised when the configuration names no single database, or for a connection the run cannot work on.

TypeError

allow_ahead is not False, True or "expand-only".

Examples:

await ferro.connect(url)
report = await ferro.migrations.up(progress=print)
# 0002_add_teams  01_schema  applied (9 ms)
print([step.migration for step in report.applied])
# ['0002_add_teams']

require_applied async

require_applied(settings: FerroSettings | None = None, database: str | None = None, *, using: str | None = None, url: str | None = None, allow_ahead: AllowAhead = False) -> None

Return when the database stands at the head of its migrations; raise otherwise.

Takes no lock and changes nothing. The answer is the run planner's: the plan up would make, read with no lock, after the squash inheritance it would make first. A database that applied a squash's originals is pending that squash, never ahead by them, whatever allow_ahead says. A step's class is read from its step record; a record an older Ferro wrote holds none and reads as contract until the first run of this Ferro on the database classifies it.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None
allow_ahead AllowAhead

Let a database that has applied migrations this checkout lacks through: "expand-only" when every step they hold is expand (the previous release of a rolling deploy), True whatever they hold. Defaults to False, which refuses.

False

Raises:

Type Description
PendingMigrationsError

A migration is pending, or the tracking table refuses a run (an interrupted run, an edited applied file).

DatabaseAheadError

The database has applied migrations this checkout lacks.

TypeError

allow_ahead is not False, True or "expand-only".

Examples:

try:
    await ferro.migrations.require_applied(allow_ahead="expand-only")
except ferro.migrations.DatabaseAheadError as ahead:
    print(ahead.contract_steps)  # ['0008_drop_bio:01']
else:
    print("the database is at the head")

status async

status(settings: FerroSettings | None = None, database: str | None = None, *, using: str | None = None, url: str | None = None) -> StatusReport

Report where the database stands against its migrations directory.

This is ferro migrate status. It takes no lock and creates nothing: a database without the tracking table reports every migration pending. The refusal up would meet (an edited file, a broken chain) is part of the report.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None

Returns:

Type Description
StatusReport

The status report: each migration's state, and whether anything is pending or needs attention.

Raises:

Type Description
MigrationRefused

The configuration names no single database, or there is no connection to work on.

Examples:

report = await ferro.migrations.status()
print(report.head_applied.name, report.pending)
# 0006_add_teams True

check async

check(settings: FerroSettings | None = None, database: str | None = None) -> CheckReport

Check, offline, that every model change has a migration and the directory is intact.

This is ferro migrate check. It reads files only and takes no connection. It reports an ungenerated model change (naming the models), a broken snapshot chain (naming both files), a duplicate or missing number, a DDL step without the rendering a target dialect needs, and a data step still holding todo(...). It raises nothing for a problem.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None

Returns:

Type Description
CheckReport

The report; its raise_for_problems() raises on any problem.

Raises:

Type Description
MigrationRefused

The configuration names no single database.

Examples:

In CI, fail the build on an ungenerated change:

(await ferro.migrations.check()).raise_for_problems()

Reports

up() returns a RunReport, status() a StatusReport and check() a CheckReport. You read them, you never build one. The types of their fields, and of the event up(on_event=...) passes its callback, are documented below them.

RunReport dataclass

RunReport(inherited: list[InheritedMigration] = list(), applied: list[AppliedStep] = list(), reverted: list[AppliedStep] = list(), declined: bool = False, refusal: str | None = None, refused: RunRefused | None = None, notes: list[str] = list(), ahead: list[str] = list(), failed: StepFailure | None = None, direction: Literal['up', 'down'] = 'up')

What a migration run did: what up returns.

A refused run raises MigrationRefused with this report as .report, saying what the run applied before it stopped.

Examples:

report = await ferro.migrations.up()
for step in report.applied:
    print(step.migration, step.step, step.ms)
# 0002_add_teams 01_schema 9

Attributes:

Name Type Description
inherited list[InheritedMigration]

The squashes the run inherited before anything else, in order.

applied list[AppliedStep]

The steps applied, in order.

reverted list[AppliedStep]

The steps a down run reverted, newest first.

declined bool

Whether a down run's confirm said no, so nothing was reverted.

refusal str | None

Why the run stopped: a refusal before anything ran, a lost lock, or a failed step; None when it finished.

refused RunRefused | None

The refusal itself when the run was refused; None when it finished or a step failed.

notes list[str]

What the run accepted on the way (an edited unfinished step).

ahead list[str]

Applied migrations the directory lacks: let through by allow_ahead, or the ones that refused the run.

failed StepFailure | None

The step the run stopped at when one failed (refusal is its message); None otherwise.

direction Literal['up', 'down']

Which way the run went: "up" or "down".

inherited class-attribute instance-attribute

inherited: list[InheritedMigration] = field(default_factory=list)

The squashes the run inherited before anything else, in order.

applied class-attribute instance-attribute

applied: list[AppliedStep] = field(default_factory=list)

The steps applied, in order.

reverted class-attribute instance-attribute

reverted: list[AppliedStep] = field(default_factory=list)

The steps a down run reverted, newest first.

declined class-attribute instance-attribute

declined: bool = False

Whether a down run's confirm said no, so nothing was reverted.

refusal class-attribute instance-attribute

refusal: str | None = None

Why the run stopped: a refusal before anything ran, a lost lock, or a failed step; None when it finished.

For a failed step it holds the error and how to resume.

refused class-attribute instance-attribute

refused: RunRefused | None = None

The refusal itself when the run was refused; None when it finished or a step failed.

refusal is its text; its kind, migration, step and reason say what it is about.

notes class-attribute instance-attribute

notes: list[str] = field(default_factory=list)

What the run accepted on the way (an edited unfinished step).

ahead class-attribute instance-attribute

ahead: list[str] = field(default_factory=list)

Applied migrations the directory lacks: let through by allow_ahead, or the ones that refused the run.

failed class-attribute instance-attribute

failed: StepFailure | None = None

The step the run stopped at when one failed (refusal is its message); None otherwise.

direction class-attribute instance-attribute

direction: Literal['up', 'down'] = 'up'

Which way the run went: "up" or "down".

InheritedMigration dataclass

InheritedMigration(squash: str, replaced: list[str])

A squash a run inherited before it planned.

The database had applied every migration the squash replaced, so the run swapped their step records for the squash's and ran nothing.

Attributes:

Name Type Description
squash str

The squash, NNNN_<name>.

replaced list[str]

Each migration whose records it replaced (NNNN_<name>), in chain order: what the database had applied.

line str

The line a run prints: inherited <squash>: this database had applied <first> … <last>; nothing was run.

squash instance-attribute

squash: str

The squash, NNNN_<name>.

replaced instance-attribute

replaced: list[str]

Each migration whose records it replaced (NNNN_<name>), in chain order: what the database had applied.

line property

line: str

The line a run prints: inherited <squash>: this database had applied <first> … <last>; nothing was run.

AppliedStep

Bases: NamedTuple

One step a run applied or reverted.

Attributes:

Name Type Description
migration str

The migration, NNNN_<name>.

step str

The step, NN_<name>.

ms int

How long the step ran, in milliseconds.

migration instance-attribute

migration: str

The migration, NNNN_<name>.

step instance-attribute

step: str

The step, NN_<name>.

ms instance-attribute

ms: int

How long the step ran, in milliseconds.

StepFailure dataclass

StepFailure(migration: str, file: str, duration_ms: int, error: str, hint: str, rows_done: int | None = None)

The step a run stopped at: its error, what the failure left applied, and how to resume.

The run report's refusal is its message.

Attributes:

Name Type Description
migration str

The migration, NNNN_<name>.

file str

The step's file (02_backfill_account.py).

duration_ms int

How long the step ran before it failed, in milliseconds.

error str

What failed (NotNullViolationError: null value in column ...).

hint str

What stayed applied and how to resume (its last sentence is Nothing after it ran.).

rows_done int | None

The rows a chunked step's committed batches did before it failed; None for any other step.

stem str

The step's name, its file without the suffix (01_expand).

message str

The failure as the run prints it: ferro migrate: <migration>/<file> failed: <error>, then the hint.

migration instance-attribute

migration: str

The migration, NNNN_<name>.

file instance-attribute

file: str

The step's file (02_backfill_account.py).

duration_ms instance-attribute

duration_ms: int

How long the step ran before it failed, in milliseconds.

error instance-attribute

error: str

What failed (NotNullViolationError: null value in column ...).

hint instance-attribute

hint: str

What stayed applied and how to resume (its last sentence is Nothing after it ran.).

rows_done class-attribute instance-attribute

rows_done: int | None = None

The rows a chunked step's committed batches did before it failed; None for any other step.

stem property

stem: str

The step's name, its file without the suffix (01_expand).

message property

message: str

The failure as the run prints it: ferro migrate: <migration>/<file> failed: <error>, then the hint.

RunEvent module-attribute

What a run says: one event per line progress receives.

StepEvent dataclass

StepEvent(migration: str, file: str, outcome: Literal['applied', 'reverted', 'nothing to reverse', 'failed'], duration_ms: int | None, reason: str | None, name_width: int = 0, stem_width: int = 0)

One step a run finished: applied, reverted, reverted with nothing to reverse, or failed.

line() is the line progress receives for it (0002_add_team 01_expand applied (412 ms)); a failed step's is None, as progress hears nothing of it (its message is the run's refusal, in the report's failed).

Methods:

Name Description
line

Render the progress line <migration> <step> <said>.

Attributes:

Name Type Description
migration str

The migration, NNNN_<name>.

file str

The step's file (01_expand.up.postgres.sql).

outcome Literal['applied', 'reverted', 'nothing to reverse', 'failed']

What happened: "applied", "reverted", "nothing to reverse" or "failed".

duration_ms int | None

How long the step ran; None when it had nothing to reverse.

reason str | None

Why its down runs no statement, when outcome is "nothing to reverse".

name_width int

The run's migration column width: its longest migration name.

stem_width int

The run's step column width: its longest step name.

stem str

The step's name, its file without the suffix (01_expand).

said str

What happened, as the line ends it: applied (412 ms), reverted (8 ms) or nothing to reverse: <reason>.

migration instance-attribute

migration: str

The migration, NNNN_<name>.

file instance-attribute

file: str

The step's file (01_expand.up.postgres.sql).

outcome instance-attribute

outcome: Literal['applied', 'reverted', 'nothing to reverse', 'failed']

What happened: "applied", "reverted", "nothing to reverse" or "failed".

duration_ms instance-attribute

duration_ms: int | None

How long the step ran; None when it had nothing to reverse.

reason instance-attribute

reason: str | None

Why its down runs no statement, when outcome is "nothing to reverse".

name_width class-attribute instance-attribute

name_width: int = 0

The run's migration column width: its longest migration name.

stem_width class-attribute instance-attribute

stem_width: int = 0

The run's step column width: its longest step name.

stem property

stem: str

The step's name, its file without the suffix (01_expand).

said property

said: str

What happened, as the line ends it: applied (412 ms), reverted (8 ms) or nothing to reverse: <reason>.

line

line(name_width: int | None = None, stem_width: int | None = None) -> str | None

Render the progress line <migration> <step> <said>.

Parameters:

Name Type Description Default
name_width int | None

The migration column's width. Defaults to the run's.

None
stem_width int | None

The step column's width. Defaults to the run's.

None

Returns:

Type Description
str | None

The line, or None for a failed step.

RunNote dataclass

RunNote(text: str)

Any other line a run says, such as a step waiting for a table lock.

For example 0003_add_slug 01_add_slug waiting for a lock on "author" ..., or an edited unfinished step re-recorded before it runs.

Methods:

Name Description
line

Return the line progress receives: the text itself.

Attributes:

Name Type Description
text str

The line.

text instance-attribute

text: str

The line.

line

line() -> str

Return the line progress receives: the text itself.

Returns:

Type Description
str

The text.

InheritedEvent dataclass

InheritedEvent(squash: str, replaced: list[str])

A squash the run inherited, said before any step.

Its line reads inherited 0005_teams_epic: this database had applied 0005_add_teams … 0009_fix_rows; nothing was run.

Methods:

Name Description
line

Return the line progress receives.

Attributes:

Name Type Description
squash str

The squash, NNNN_<name>.

replaced list[str]

Each migration whose records it replaced, NNNN_<name>.

squash instance-attribute

squash: str

The squash, NNNN_<name>.

replaced instance-attribute

replaced: list[str]

Each migration whose records it replaced, NNNN_<name>.

line

line() -> str

Return the line progress receives.

Returns:

Type Description
str

The same line the run report's InheritedMigration.line holds.

StatusReport dataclass

StatusReport(database: str, url: str, dialect: str, table: str, migrations: list[MigrationStatus], ahead: list[str] = list(), inheritable: list[str] = list(), refusal: str | None = None, refusal_needs_attention: bool = False)

Where a database stands against its migrations: what status() returns.

ferro migrate status prints it. It also says where the database stands for every caller that has to know (drift, the test harness). For a database with 0006_add_teams applied and 0007_nickname part-way:

assert report.head_applied.name == "0006_add_teams"
assert report.unfinished.name == "0007_nickname"
assert report.pending

Methods:

Name Description
from_core

Build the report from the tracked database's status document.

render

Render the text ferro migrate status prints.

to_json

Render the report as the JSON document status --json prints.

Attributes:

Name Type Description
database str

The configured database's name.

url str

The database's URL, its secrets masked by ***.

dialect str

The database's dialect, postgres or sqlite.

table str

The tracking table, <schema>._ferro_migrations.

migrations list[MigrationStatus]

Every migration in the directory, in order.

ahead list[str]

Migrations this database has applied that the directory lacks.

inheritable list[str]

Each squash the next run inherits (NNNN_<name>), running nothing, whatever allow_ahead says.

refusal str | None

What up would refuse with, when it would.

refusal_needs_attention bool

Whether refusal is one a person has to look at (exit 4) rather than a pending state.

head_applied MigrationStatus | None

The last fully applied migration, or None when no migration is.

unfinished MigrationStatus | None

The first migration a run left part-way (or is in), or None.

pending bool

Whether anything is still to apply.

needs_attention bool

Whether a person has to look before anything runs.

exit_code int

The exit code status exits with: 4 when anything needs attention, 3 when anything is pending, else 0.

database instance-attribute

database: str

The configured database's name.

url instance-attribute

url: str

The database's URL, its secrets masked by ***.

dialect instance-attribute

dialect: str

The database's dialect, postgres or sqlite.

table instance-attribute

table: str

The tracking table, <schema>._ferro_migrations.

migrations instance-attribute

migrations: list[MigrationStatus]

Every migration in the directory, in order.

ahead class-attribute instance-attribute

ahead: list[str] = field(default_factory=list)

Migrations this database has applied that the directory lacks.

Never the originals of a squash the database is pending the inheritance of.

inheritable class-attribute instance-attribute

inheritable: list[str] = field(default_factory=list)

Each squash the next run inherits (NNNN_<name>), running nothing, whatever allow_ahead says.

refusal class-attribute instance-attribute

refusal: str | None = None

What up would refuse with, when it would.

refusal_needs_attention class-attribute instance-attribute

refusal_needs_attention: bool = False

Whether refusal is one a person has to look at (exit 4) rather than a pending state.

head_applied property

head_applied: MigrationStatus | None

The last fully applied migration, or None when no migration is.

Its schema snapshot is the one the database is measured against.

unfinished property

unfinished: MigrationStatus | None

The first migration a run left part-way (or is in), or None.

The database stands at neither its parent's snapshot nor its own.

pending property

pending: bool

Whether anything is still to apply.

needs_attention property

needs_attention: bool

Whether a person has to look before anything runs.

exit_code property

exit_code: int

The exit code status exits with: 4 when anything needs attention, 3 when anything is pending, else 0.

from_core classmethod

from_core(raw: dict[str, Any], *, database: str, url: str, dialect: str, table: str, refusal: str | None = None, rows_done: dict[tuple[int, int], int] | None = None, finished_at: dict[tuple[int, int], str | None] | None = None) -> StatusReport

Build the report from the tracked database's status document.

Parameters:

Name Type Description Default
raw dict[str, Any]

The status document the core returns.

required
database str

The configured database's name.

required
url str

The database's URL, its secrets masked.

required
dialect str

The database's dialect.

required
table str

The tracking table, <schema>._ferro_migrations.

required
refusal str | None

A refusal that replaces the document's own, when given.

None
rows_done dict[tuple[int, int], int] | None

Each chunked step's committed rows, by (migration, step).

None
finished_at dict[tuple[int, int], str | None] | None

Each step record's stored finish time, by (migration, step).

None

Returns:

Type Description
StatusReport

The report.

render

render(steps: bool = False) -> str

Render the text ferro migrate status prints.

Parameters:

Name Type Description Default
steps bool

Print every migration's steps, each with its class after its flags, as --steps does. Defaults to only the migrations that need attention.

False

Returns:

Type Description
str

The report as plain text, one line per migration or step.

to_json

to_json() -> str

Render the report as the JSON document status --json prints.

Returns:

Type Description
str

The report as indented JSON.

MigrationStatus dataclass

MigrationStatus(number: int, name: str, steps: list[StepStatus], inherits: list[str] = list())

One migration and its steps.

Attributes:

Name Type Description
number int

The migration's number.

name str

The migration's directory name, NNNN_<name>.

steps list[StepStatus]

Its steps, in order.

inherits list[str]

For a squash pending its inheritance, each migration the database applied in its place.

hint str | None

What status says to do about this migration on its row, or None.

applied_at str | None

When the migration was applied: the last finished step's finished_at, or None.

applied bool

Whether every step is applied.

pending bool

Whether a step is still to apply.

unfinished_step StepStatus | None

The first step a run left part-way (or is in), if any.

unfinished bool

Whether a run left this migration part-way.

running bool

Whether a run holding the run lock is in this migration.

state str

The migration's state as status prints it on its row.

expands bool

Whether status prints this migration's steps without --steps.

number instance-attribute

number: int

The migration's number.

name instance-attribute

name: str

The migration's directory name, NNNN_<name>.

steps instance-attribute

steps: list[StepStatus]

Its steps, in order.

inherits class-attribute instance-attribute

inherits: list[str] = field(default_factory=list)

For a squash pending its inheritance, each migration the database applied in its place.

Each is NNNN_<name>, in chain order. Empty otherwise.

hint property

hint: str | None

What status says to do about this migration on its row, or None.

For a squash pending inheritance: run `ferro migrate up`; this database applied <first> … <last> and nothing will be run.

applied_at property

applied_at: str | None

When the migration was applied: the last finished step's finished_at, or None.

A partial migration reports when it stopped.

applied property

applied: bool

Whether every step is applied.

pending property

pending: bool

Whether a step is still to apply.

unfinished_step property

unfinished_step: StepStatus | None

The first step a run left part-way (or is in), if any.

unfinished property

unfinished: bool

Whether a run left this migration part-way.

True when a step is unfinished, or only some of its steps are applied. A wholly pending migration is not.

running property

running: bool

Whether a run holding the run lock is in this migration.

state property

state: str

The migration's state as status prints it on its row.

The steps' one state when every step agrees (applied, applied (baseline), applied (inherited), pending or pending (inheritable)); running while a run is in it; applied (different checksum) when every step is applied and one changed; else partial, X of N steps.

expands property

expands: bool

Whether status prints this migration's steps without --steps.

CheckReport dataclass

CheckReport(ok: bool, head: str | None = None, problems: list[Problem] = list())

What check found: whether the migrations are complete, and each problem.

Examples:

report = await ferro.migrations.check()
for problem in report.problems:
    print(problem.kind, problem.message)
report.raise_for_problems()

Methods:

Name Description
raise_for_problems

Raise when the report has any problem; do nothing otherwise.

Attributes:

Name Type Description
ok bool

Whether check found no problem.

head str | None

The newest migration's directory name, when there is one.

problems list[Problem]

Every problem found, in the order found.

ok instance-attribute

ok: bool

Whether check found no problem.

head class-attribute instance-attribute

head: str | None = None

The newest migration's directory name, when there is one.

problems class-attribute instance-attribute

problems: list[Problem] = field(default_factory=list)

Every problem found, in the order found.

raise_for_problems

raise_for_problems() -> None

Raise when the report has any problem; do nothing otherwise.

Raises:

Type Description
MigrationsCheckError

The report has a problem; the message lists each, and its report is this report.

Problem dataclass

Problem(kind: str, message: str, changes: tuple[Change, ...] = (), headline: str | None = None, notes: tuple[str, ...] = ())

One thing check found wrong.

Attributes:

Name Type Description
kind str

A stable identifier, such as ungenerated, broken_chain, duplicate_number or unwritten_step.

message str

What is wrong and how to fix it.

changes tuple[Change, ...]

An ungenerated problem's change summary, as data; empty for every other kind.

headline str | None

An ungenerated problem's message without the summary and notes it quotes; None otherwise.

notes tuple[str, ...]

The notes an ungenerated problem's message quotes after its summary; empty otherwise.

kind instance-attribute

kind: str

A stable identifier, such as ungenerated, broken_chain, duplicate_number or unwritten_step.

message instance-attribute

message: str

What is wrong and how to fix it.

changes class-attribute instance-attribute

changes: tuple[Change, ...] = ()

An ungenerated problem's change summary, as data; empty for every other kind.

It says what the migration ferro migrate new would write changes.

headline class-attribute instance-attribute

headline: str | None = None

An ungenerated problem's message without the summary and notes it quotes; None otherwise.

For example the models changed since 0001_initial and no migration records it; run ...: what a terminal prints above the summary it lays out from changes.

notes class-attribute instance-attribute

notes: tuple[str, ...] = ()

The notes an ungenerated problem's message quotes after its summary; empty otherwise.

Baseline and drift

baseline async

baseline(settings: FerroSettings | None = None, database: str | None = None, *, target: str | None = None, using: str | None = None, url: str | None = None, lock_timeout: str | float | None = None) -> BaselineReport

Record migrations as applied on a database that already has their schema.

This is ferro migrate baseline. Under the run lock, the database is checked against the target's schema snapshot first, as drift checks it; when that finds anything, nothing is recorded and the report's drift lists it. There is no override. See Adopting migrations.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
target str | None

The last migration to record, "0006" or "0006_add_teams". Defaults to the newest migration.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None
lock_timeout str | float | None

How long to wait for another run's lock: "30s", "500ms", "1m" or a number of seconds; 0 refuses at once. Defaults to the database's lock_timeout.

None

Returns:

Type Description
BaselineReport

What was recorded, or the drift that stopped it; its raise_for_problems() raises with every drift line.

Raises:

Type Description
AlreadyTrackedError

The database is already tracked (its tracking table holds step records). Another pre-deploy may have adopted it first; carry on to up().

MigrationRefused

The target is not in the migrations directory, the directory holds no migration, the lock wait outlasts lock_timeout, or the configuration names no single database.

Examples:

report = await ferro.migrations.baseline(target="0006")
report.raise_for_problems()
print(report.recorded[-1])  # 0006_add_teams

remove_baseline async

remove_baseline(settings: FerroSettings | None = None, database: str | None = None, *, using: str | None = None, url: str | None = None, lock_timeout: str | float | None = None) -> list[str]

Delete every record a baseline wrote, under the run lock.

This is ferro migrate baseline --remove. The migrations are pending afterwards.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None
lock_timeout str | float | None

How long to wait for another run's lock: "30s", "500ms", "1m" or a number of seconds; 0 refuses at once. Defaults to the database's lock_timeout.

None

Returns:

Type Description
list[str]

The migrations whose baseline was removed (NNNN_<name>); empty when there was none.

Raises:

Type Description
AppliedAboveBaselineError

A run applied a migration above the baseline; revert it with ferro migrate down first, as the message says.

MigrationRefused

The lock wait outlasts lock_timeout, or the configuration names no single database.

BaselineReport dataclass

BaselineReport(recorded: list[str], data_steps_listed: list[str], drift: DriftReport | None, steps: int = 0, reports: list[dict[str, Any]] = list())

What baseline did: what it recorded, or the drift that stopped it.

Methods:

Name Description
render

Render the text ferro migrate baseline prints on stdout.

raise_for_problems

Raise unless the baseline was recorded.

Attributes:

Name Type Description
recorded list[str]

Every migration it recorded (NNNN_<name>); empty when the drift check found something.

data_steps_listed list[str]

Every data step it recorded without running (NNNN_<name>/<file>).

drift DriftReport | None

The drift check's report when it found something; None when the database matched the target's snapshot.

steps int

How many step records were written.

reports list[dict[str, Any]]

What the drift check reported without counting it as drift, as drift reports it.

warnings list[str]

Each report's sentence, in order.

recorded instance-attribute

recorded: list[str]

Every migration it recorded (NNNN_<name>); empty when the drift check found something.

data_steps_listed instance-attribute

data_steps_listed: list[str]

Every data step it recorded without running (NNNN_<name>/<file>).

drift instance-attribute

drift: DriftReport | None

The drift check's report when it found something; None when the database matched the target's snapshot.

steps class-attribute instance-attribute

steps: int = 0

How many step records were written.

reports class-attribute instance-attribute

reports: list[dict[str, Any]] = field(default_factory=list)

What the drift check reported without counting it as drift, as drift reports it.

A foreign or unverifiable row policy, for example.

warnings property

warnings: list[str]

Each report's sentence, in order.

render

render() -> str

Render the text ferro migrate baseline prints on stdout.

Returns:

Type Description
str

The drift lines and nothing was recorded, or what was recorded.

raise_for_problems

raise_for_problems() -> None

Raise unless the baseline was recorded.

Raises:

Type Description
MigrationRefused

The drift check found something; the message names every drift line.

drift async

drift(settings: FerroSettings | None = None, database: str | None = None, *, using: str | None = None, url: str | None = None) -> DriftReport

Compare the live database with the schema snapshot of the last migration applied to it.

This is ferro migrate drift. It takes no lock and changes nothing, and raises nothing for drift or for a database it cannot compare (mid-migration, no records): the report says so.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

An open connection to work on. Defaults to the default connection.

None
url str | None

A URL to open a private connection to, closed after the call. Refused together with using.

None

Returns:

Type Description
DriftReport

The drift report; its raise_for_problems() raises with every line.

Raises:

Type Description
MigrationRefused

The configuration names no single database, there is no connection to work on, or the migrations directory is unreadable.

Examples:

A test fixture that aborts on drift, in one line:

(await ferro.migrations.drift()).raise_for_problems()

DriftReport dataclass

DriftReport(against: str | None, lines: list[str] = list(), operations: list[dict[str, Any]] = list(), refusal: str | None = None, reports: list[dict[str, Any]] = list())

What drift found: one line per difference, or why it could not compare.

Methods:

Name Description
render

Render the text ferro migrate drift prints on stdout.

raise_for_problems

Raise unless the report is clean.

Attributes:

Name Type Description
against str | None

The applied migration the database was compared with (NNNN_<name>), or None when drift refused.

lines list[str]

One plain-language line per difference, such as author.slug column is missing.

operations list[dict[str, Any]]

The planner's ops behind the lines, each {"kind": ..., <fields>}.

refusal str | None

Why there was nothing to compare: a run is unfinished, or the database has no migration records.

reports list[dict[str, Any]]

What the planner reports without planning an op for it, in planning order.

warnings list[str]

Each report's sentence, in order.

clean bool

Whether the database matches the snapshot it was compared with; false after a refusal.

against instance-attribute

against: str | None

The applied migration the database was compared with (NNNN_<name>), or None when drift refused.

lines class-attribute instance-attribute

lines: list[str] = field(default_factory=list)

One plain-language line per difference, such as author.slug column is missing.

operations class-attribute instance-attribute

operations: list[dict[str, Any]] = field(default_factory=list)

The planner's ops behind the lines, each {"kind": ..., <fields>}.

refusal class-attribute instance-attribute

refusal: str | None = None

Why there was nothing to compare: a run is unfinished, or the database has no migration records.

reports class-attribute instance-attribute

reports: list[dict[str, Any]] = field(default_factory=list)

What the planner reports without planning an op for it, in planning order.

A foreign or unverifiable row policy, for example; each is {"kind", "subject", "text", "recurs", "blocks"}. A report never makes the drift report unclean.

warnings property

warnings: list[str]

Each report's sentence, in order.

clean property

clean: bool

Whether the database matches the snapshot it was compared with; false after a refusal.

render

render() -> str

Render the text ferro migrate drift prints on stdout.

Returns:

Type Description
str

The drift lines under drift against <migration>:, no drift against <migration>, or an empty string for a refusal.

raise_for_problems

raise_for_problems() -> None

Raise unless the report is clean.

Raises:

Type Description
MigrationRefused

The report has drift lines (the message names every one) or a refusal (the message is the refusal).

render_op

render_op(op: dict[str, Any]) -> str

Render one planner op as one plain-language line.

An op kind this function does not know still renders, as <kind> on <table>. AlterColumnType reads live_type / snapshot_type and AlterColumnNullability reads live_nullable when the op carries them; without them the line says only that the two differ.

Parameters:

Name Type Description Default
op dict[str, Any]

The op, as DriftReport.operations holds it: {"kind": ..., <fields>}.

required

Returns:

Type Description
str

The line, such as author.slug column is missing.

Raises:

Type Description
ValueError

A known kind is missing one of its fields; the message names both.

Examples:

from ferro.migrations import render_op

print(render_op({"kind": "AddColumn", "table": "author", "column": "slug"}))
# author.slug column is missing
print(render_op({"kind": "DropTable", "table": "post"}))
# post table is extra

Errors

A database ahead of the checkout raises DatabaseAheadError: .ahead names the migrations it has applied that the directory lacks, and .contract_steps each of their steps whose class is not expand (["0003_drop_bio:01"]), the steps allow_ahead="expand-only" refuses on. The rolling-deploy recipe shows it in use.

try:
    await ferro.migrations.require_applied(allow_ahead="expand-only")
except ferro.migrations.DatabaseAheadError as ahead:
    print(ahead.contract_steps)   # ['0003_drop_bio:01']

MigrationRefused

MigrationRefused(message: str, *, report: RunReport | CheckReport | StatusReport | None = None)

Bases: FerroError

A migration call's refusal, naming the fix.

The base of every refusal: a run's, ferro migrate check's problems, a configuration that names no single database, and the subclasses an application branches on.

Attributes:

Name Type Description
report

The report of the call that refused, or None when it has none.

report instance-attribute

report = report

The report of the call that refused, or None when it has none.

The RunReport of a refused up (what it did before it stopped, and the refusal itself as report.refused), the CheckReport whose problems raise_for_problems() raised, or the StatusReport of the database a baseline refusal is about.

PendingMigrationsError

PendingMigrationsError(pending: Sequence[str], refusals: Sequence[str] = ())

Bases: MigrationRefused

The refusal require_applied() raises for a database behind its migrations.

Attributes:

Name Type Description
pending

Each migration with a step still to apply, as NNNN_<name>.

refusals

The tracking table's own refusals, each the text ferro migrate up would print.

pending instance-attribute

pending = list(pending)

Each migration with a step still to apply, as NNNN_<name>.

refusals instance-attribute

refusals = list(refusals)

The tracking table's own refusals, each the text ferro migrate up would print.

An interrupted run or an edited applied file, for example.

DatabaseAheadError

DatabaseAheadError(ahead: Sequence[str], message: str, *, report: RunReport | None = None, contract_steps: Sequence[str] = ())

Bases: MigrationRefused

The refusal up() and require_applied() raise for a database ahead of the checkout.

The database has applied migrations this checkout does not have. allow_ahead="expand-only" lets the database through when contract_steps is empty, and its message names the first of them; pass allow_ahead=True to run beside any of them, as a rolling deploy with a fixed old version does. See Deploying migrations. Its report is the RunReport of the refused up, or None for require_applied().

Attributes:

Name Type Description
ahead

The migrations the database has applied that the checkout lacks, as NNNN_<name>.

contract_steps

Each of their steps whose class is not expand, as NNNN_<name>:NN.

ahead instance-attribute

ahead = list(ahead)

The migrations the database has applied that the checkout lacks, as NNNN_<name>.

contract_steps instance-attribute

contract_steps = list(contract_steps)

Each of their steps whose class is not expand, as NNNN_<name>:NN.

Each is a step the previous release's writes may fail beside.

RunRefused

RunRefused(message: str, *, kind: str | None = None, migration: int | None = None, step: int | None = None, reason: str | None = None, ahead_only: bool = False, contract_steps: Sequence[str] | None = None, names: Sequence[str] | None = None, head: str | None = None)

Bases: MigrationRefused

A migration run's refusal before it ran anything, naming the fix.

Raised for every refusal the run planner, the run lock and the tracking tables make, and by connect(auto_migrate=True) on a database that migrations manage; its message is the operator's text. It is a MigrationRefused, so except MigrationRefused catches it too. Some refusals also carry what they are about in kind, so a caller matches on it rather than on the text; on the others kind is None. A kind with a class of its own (AlreadyTrackedError, AppliedAboveBaselineError) arrives as that class.

Examples:

try:
    await ferro.migrations.up()
except ferro.migrations.RunRefused as refused:
    if refused.kind == "edited_applied":
        print(refused)   # names the applied migration that was edited
    raise

Methods:

Name Description
from_core

Build the refusal for kind, as the subclass a caller branches on when there is one.

Attributes:

Name Type Description
kind

The refusal's kind ("irreversible", "edited_applied", ...), or None.

migration

The migration number the refusal names, or None.

step

The step number the refusal names, or None.

reason

An irreversible step's declared reason, or None.

ahead_only

Whether allow_ahead alone would have let the run through.

contract_steps

With ahead_only, each step of those migrations whose class is not expand.

names

The migrations (NNNN_<name>) a refusal about a set of them names.

head

The newest of a tracked database's records, for an already-tracked refusal; None otherwise.

kind instance-attribute

kind = kind

The refusal's kind ("irreversible", "edited_applied", ...), or None.

Only some refusals carry a kind. connect(auto_migrate=True) on a database that migrations manage, a lost run lock and a data step that does not load are among those whose kind is None; match those on the message, or catch the MigrationRefused base.

migration instance-attribute

migration = migration

The migration number the refusal names, or None.

step instance-attribute

step = step

The step number the refusal names, or None.

reason instance-attribute

reason = reason

An irreversible step's declared reason, or None.

ahead_only instance-attribute

ahead_only = ahead_only

Whether allow_ahead alone would have let the run through.

True when the database holds migrations the directory lacks and nothing else stood in the way.

contract_steps instance-attribute

contract_steps = list(contract_steps or ())

With ahead_only, each step of those migrations whose class is not expand.

Each is NNNN_<name>:NN: what allow_ahead="expand-only" refuses on. Empty otherwise.

names instance-attribute

names = list(names or ())

The migrations (NNNN_<name>) a refusal about a set of them names.

A tracked database's records, or the run-applied migrations above a baseline. Empty otherwise.

head instance-attribute

head = head

The newest of a tracked database's records, for an already-tracked refusal; None otherwise.

from_core classmethod

from_core(message: str, *, kind: str | None = None, **payload: Any) -> RunRefused

Build the refusal for kind, as the subclass a caller branches on when there is one.

The class is chosen by kind alone, never by message.

Parameters:

Name Type Description Default
message str

The refusal's text, naming the fix.

required
kind str | None

The planner's refusal kind, or None for a refusal that is not the planner's.

None
**payload Any

The other keyword data RunRefused takes.

{}

Returns:

Type Description
RunRefused

An AlreadyTrackedError or AppliedAboveBaselineError when the kind has one, a plain RunRefused otherwise.

AlreadyTrackedError

AlreadyTrackedError(message: str, **payload: Any)

Bases: RunRefused

The refusal baseline() raises for a database that is already tracked.

A baseline records only on a database whose tracking table holds no step records; nothing was recorded. Two pre-deploys that adopt one database at once both find no records and both call baseline(); the run lock lets one record, and the other raises this, so the caller carries on to up(). The target is the migration the previous release's models generated, so an unattended baseline records no step it did not run. Its head is the newest of the records, and its report the database's StatusReport, what status() reports.

Examples:

try:
    await ferro.migrations.baseline(target="0001")
except ferro.migrations.AlreadyTrackedError:
    pass
await ferro.migrations.up()

Attributes:

Name Type Description
applied

Every migration the records name, as NNNN_<name>, in order.

applied instance-attribute

applied = list(self.names)

Every migration the records name, as NNNN_<name>, in order.

AppliedAboveBaselineError

AppliedAboveBaselineError(message: str, **payload: Any)

Bases: RunRefused

The refusal remove_baseline() raises when a run applied migrations above the baseline.

Removing the baseline under them would leave applied migrations above pending ones. The message names the ferro migrate down --to that reverts them; nothing was removed. Its report is the database's StatusReport.

Attributes:

Name Type Description
above

The run-applied migrations above the baseline, as NNNN_<name>.

above instance-attribute

above = list(self.names)

The run-applied migrations above the baseline, as NNNN_<name>.

Data step declarations

atomic

atomic(fn: F) -> F

Declare a step function atomic: one transaction, with the step's record committed inside it.

The function is async def up(ctx) (or down); ctx is the step's context.

Parameters:

Name Type Description Default
fn F

The step function.

required

Returns:

Type Description
F

The function, unchanged apart from its declaration.

Raises:

Type Description
TypeError

fn is not callable.

Examples:

from ferro.migrations import atomic


@atomic
async def up(ctx):
    for author in await ctx.models.Author.where(lambda author: author.slug == None).all():
        author.slug = author.name.lower().replace(" ", "-")
        await author.save()

chunked

chunked(query: Callable[[HistoricalModels], Query[Any]], *, batch_size: int) -> Callable[[F], F]

Declare a step function chunked: the runner pages a query in batches, one transaction each.

The runner calls async def up(ctx, batch) once per batch and commits the batch's cursor with it, so a failed or interrupted run resumes after the last committed batch. See Data steps and backfills.

Parameters:

Name Type Description Default
query Callable[[HistoricalModels], Query[Any]]

A function of ctx.models that returns the query to page. It orders by keys that include the model's primary key, and selects only the rows that still need the step, so a resumed run re-pages from its cursor.

required
batch_size int

The rows each transaction takes; a positive int.

required

Returns:

Type Description
Callable[[F], F]

A decorator that declares the step function chunked.

Raises:

Type Description
TypeError

query is not callable.

ValueError

batch_size is not a positive int.

StepRefused

At run time, before anything runs: the query does not build, pages a table without a single primary key, is not ordered by keys that include the primary key, orders by a related model's column, or sets its own limit, offset, after or before.

Examples:

from ferro.migrations import chunked


@chunked(
    lambda models: models.Author.where(lambda author: author.slug == None)
    .order_by(lambda author: author.id),
    batch_size=1000,
)
async def up(ctx, batch):
    for author in batch:
        author.slug = author.name.lower().replace(" ", "-")
        await author.save()

irreversible

irreversible(reason: str) -> Callable[[F], F]

Declare a down irreversible, saying why.

A run that would revert the step refuses before reverting anything, and prints the reason.

Parameters:

Name Type Description Default
reason str

Why the step cannot be reversed; a non-empty string.

required

Returns:

Type Description
Callable[[F], F]

A decorator that declares the down irreversible.

Raises:

Type Description
TypeError

reason is not a non-empty string.

Examples:

from ferro.migrations import irreversible


@irreversible("the old nicknames were dropped with the column")
def down(ctx): ...

nothing_to_reverse

nothing_to_reverse(reason: str) -> Callable[[F], F]

Declare that a down has nothing to reverse, saying why.

Reverting the step removes its record and runs nothing.

Parameters:

Name Type Description Default
reason str

Why there is nothing to reverse; a non-empty string.

required

Returns:

Type Description
Callable[[F], F]

A decorator that declares the down as having nothing to reverse.

Raises:

Type Description
TypeError

reason is not a non-empty string.

Examples:

from ferro.migrations import nothing_to_reverse


@nothing_to_reverse("slugs are derived; nothing to put back")
def down(ctx): ...

todo

todo(message: str) -> Any

Mark a value in a data step that only a person can supply.

The loader reads every call from the file's syntax tree, and up refuses the migration before running anything, naming the file, the line and the message.

Parameters:

Name Type Description Default
message str

What is missing, as a string literal: the refusal prints it.

required

Raises:

Type Description
NotWrittenError

Always, when a run reaches the call anyway.

Examples:

from ferro.migrations import atomic, todo


@atomic
async def up(ctx):
    for author in await ctx.models.Author.where(lambda author: author.slug == None).all():
        author.slug = todo("the slug for an existing author")
        await author.save()

The test harness

ferro.migrations.testing is imported by a project's tests, never by its application code.

harness

harness(*, settings: FerroSettings | None = None, database: str | None = None, using: str | None = None) -> Harness

Return a Harness over one configured database.

The test connects the database and makes it fresh itself.

Parameters:

Name Type Description Default
settings FerroSettings | None

The project's configuration. Defaults to FerroSettings().

None
database str | None

The configured database. Defaults to the only one configured.

None
using str | None

The open connection to work on. Defaults to the default connection.

None

Returns:

Type Description
Harness

The harness.

Raises:

Type Description
MigrationRefused

No configuration is found, or database names none of its databases.

Examples:

Migration 0012_add_slug adds author.slug and backfills it in a data step. The test seeds a row the way the table stood at 0011, applies exactly 0012, and reads the row back the way 0012 left it:

from ferro.migrations.testing import harness


async def test_slug_backfill(db_url, migrations_settings):
    await ferro.connect(db_url)
    h = harness(settings=migrations_settings, database="default")
    await h.apply_through("0011")
    async with h.models_at("0011") as models:
        await models.Author(name="Ada").save()  # the schema as it stood
    await h.apply("0012")  # refused unless the database stands at 0011
    async with h.models_at("0012") as models:
        ada = await models.Author.where(lambda author: author.name == "Ada").first()
        assert ada.slug == "ada"
    await h.revert_to("0011")
    await h.round_trip()

Harness

Harness(target: Target)

A migration chain driven by name, for a test.

Build it with harness. Each method takes a migration as "0007" or "0007_split_name".

Methods:

Name Description
apply_through

Apply every pending migration up to and including one, under the run lock.

apply

Apply exactly one migration, under the run lock.

revert_to

Revert every migration above one, newest first, with no prompt, leaving it applied.

revert_all

Revert every applied migration, newest first, with no prompt.

models_at

Install the historical models of one migration's snapshot for the block.

round_trip

Apply every migration, revert every one, and apply them all again, checking drift at each stop.

apply_through async

apply_through(migration: str) -> RunReport

Apply every pending migration up to and including one, under the run lock.

A database already standing at migration is left alone.

Parameters:

Name Type Description Default
migration str

The last migration to apply, "0007" or "0007_split_name".

required

Returns:

Type Description
RunReport

The run's report; empty when nothing was pending.

Raises:

Type Description
MigrationRefused

The database stands past migration (naming both), or there is no such migration.

apply async

apply(migration: str) -> RunReport

Apply exactly one migration, under the run lock.

A test that seeded at 0006 and applies 0007 knows only 0007 ran.

Parameters:

Name Type Description Default
migration str

The migration to apply, "0007" or "0007_split_name".

required

Returns:

Type Description
RunReport

The run's report.

Raises:

Type Description
MigrationRefused

The database does not stand at the migration's parent (for the first migration: at nothing); the message names where it stands and where it would have to.

revert_to async

revert_to(migration: str) -> RunReport

Revert every migration above one, newest first, with no prompt, leaving it applied.

The runner's rules hold: an irreversible step in the way refuses before anything is reverted.

Parameters:

Name Type Description Default
migration str

The migration to leave applied, "0007" or "0007_split_name".

required

Returns:

Type Description
RunReport

The run's report.

Raises:

Type Description
MigrationRefused

The database stands below migration (naming both), or an irreversible step is in the way.

revert_all async

revert_all() -> RunReport

Revert every applied migration, newest first, with no prompt.

On a database with nothing applied it does nothing and creates nothing.

Returns:

Type Description
RunReport

The run's report.

Raises:

Type Description
MigrationRefused

An irreversible step is in the way; nothing was reverted.

models_at async

models_at(migration: str) -> AsyncIterator[HistoricalModels]

Install the historical models of one migration's snapshot for the block.

They are the same models object a data step's context carries, with every table as that one snapshot declares it (a column a later migration adds is absent, not nullable). The block is a session on the harness's connection, so the models need no using=. While it is open today's classes are unreachable (Author raises naming models.Author); they are restored on exit, error and cancellation. Reads no database state.

Parameters:

Name Type Description Default
migration str

The migration whose snapshot to install, "0007" or "0007_split_name".

required

Yields:

Type Description
AsyncIterator[HistoricalModels]

The historical models.

Examples:

async with h.models_at("0011") as models:
    await models.Author(name="Ada").save()
    links = await models.table("author_tags").all()

round_trip async

round_trip() -> RoundTripResult

Apply every migration, revert every one, and apply them all again, checking drift at each stop.

The walk moves one migration per stop. A step whose down is declared irreversible ends the downward walk at its migration: the result reports it and the walk back up completes; it is not a failure. With every migration reverted there is no snapshot to compare with, so that one stop instead checks that none of the first migration's tables remain.

Returns:

Type Description
RoundTripResult

What the walk applied, where it stopped going down, and the irreversible step that stopped it.

Raises:

Type Description
MigrationRefused

At the first stop where the database is not what that migration's snapshot declares, with the drift lines.

Examples:

async def test_the_chain_round_trips(db_url):
    await ferro.connect(db_url)
    result = await harness().round_trip()
    assert result.irreversible is None

RoundTripResult dataclass

RoundTripResult(applied: list[str] = list(), reverted_to: str | None = None, irreversible: tuple[str, str, str] | None = None)

What Harness.round_trip walked.

For a chain whose every down reaches its parent:

RoundTripResult(applied=["0001_create_author", "0002_add_slug"],
                reverted_to=None, irreversible=None)

and for one whose 0002 declares a step irreversible:

RoundTripResult(applied=["0001_create_author", "0002_add_slug"],
                reverted_to="0002_add_slug",
                irreversible=("0002_add_slug", "01_schema", "the index is shared"))

Attributes:

Name Type Description
applied list[str]

Every migration of the chain, in order (NNNN_<name>).

reverted_to str | None

Where the downward walk stopped: the migration holding the irreversible step, still applied.

irreversible tuple[str, str, str] | None

The (migration, step, reason) of the irreversible step that ended the downward walk, or None.

applied class-attribute instance-attribute

applied: list[str] = field(default_factory=list)

Every migration of the chain, in order (NNNN_<name>).

Each stood applied with no drift on the way up, and again on the way back up.

reverted_to class-attribute instance-attribute

reverted_to: str | None = None

Where the downward walk stopped: the migration holding the irreversible step, still applied.

None when the walk reverted everything.

irreversible class-attribute instance-attribute

irreversible: tuple[str, str, str] | None = None

The (migration, step, reason) of the irreversible step that ended the downward walk, or None.

The Alembic bridge

Requires the ferro-orm[alembic] extra. These three functions load on first use, so the calls above never import Alembic.

get_metadata

get_metadata(database: str | None = None) -> MetaData

Build SQLAlchemy MetaData for the project's Ferro models, for Alembic's env.py.

Pass it as target_metadata together with ferro_options. With a Ferro configuration (ferro.toml or [tool.ferro]) it imports the configured database's models modules and returns only that database's tables; a registered model no configured database claims is refused by name. With no configuration it renders every registered model.

Enum columns map to named sqlalchemy.Enum types, named after the enum class in lowercase (or after the column when the annotation is not an enum.Enum), so Postgres autogenerate and DDL compilation succeed.

A generated column's expression and a table check's body are written for the engine the metadata compiles against: least(...) on Postgres and min(...) on SQLite, so metadata.create_all(engine) builds a table either database runs. On SQLite a generated column also gets the range check Ferro writes there, so a value too large for the Postgres column fails on both. Compiling them for any other database raises sqlalchemy.exc.CompileError.

A column's nullable follows the nullable of its FerroField when that is a boolean. The default, nullable="infer", uses whether the annotation allows None, a foreign-key column's included. Primary key columns are never nullable.

Parameters:

Name Type Description Default
database str | None

The configured database whose tables to return. Defaults to the only one configured; name it when several are.

None

Returns:

Type Description
MetaData

The metadata, one table per model.

Examples:

from ferro.migrations import ferro_options, get_metadata

context.configure(
    connection=connection,
    target_metadata=get_metadata(),
    **ferro_options(),
)

ferro_options

ferro_options(*, include_object: _IncludeObject | None = None, render_item: _RenderItem | None = None) -> dict[str, Any]

Return the options env.py passes to context.configure beside get_metadata().

The returned include_object keeps Alembic's own comparator off Ferro's tables and both tracking tables, so every op on a Ferro table is the planner's; the returned render_item writes a native enum type the revision must not create. Autogenerate over get_metadata() without these options is refused, naming this line.

Parameters:

Name Type Description Default
include_object _IncludeObject | None

The project's own include_object hook. Ferro's filter asks it about every object Ferro does not hide.

None
render_item _RenderItem | None

The project's own render_item hook. Ferro's renderer falls through to it whenever Ferro's returns False.

None

Returns:

Type Description
dict[str, Any]

The include_object and render_item keyword arguments for context.configure.

Examples:

from ferro.migrations import ferro_options, get_metadata

context.configure(
    connection=connection,
    target_metadata=get_metadata(),
    **ferro_options(),
)

render_item

render_item(type_: str, obj: Any, autogen_context: AutogenContext) -> str | Literal[False]

Render a native Postgres enum type the revision must not create, for Alembic.

The planner creates every enum type a revision needs, so a column of one is written postgresql.ENUM(..., create_type=False). Everything else returns False, so Alembic's own renderers keep their say. You do not call this directly: ferro_options passes it to Alembic.

Parameters:

Name Type Description Default
type_ str

The kind of item Alembic is rendering, such as "type".

required
obj Any

The item.

required
autogen_context AutogenContext

Alembic's autogenerate context, which collects the revision's imports.

required

Returns:

Type Description
str | Literal[False]

The rendered type, or False for anything this hook does not render.