Skip to content

connect, Session and the registry

connect() registers a connection pool, optionally under a name, and engines.session() opens a session on one; every model call runs inside a session. reset_engine() closes every connection. See the Connections and databases guide.

Connecting

connect async

connect(url: str, auto_migrate: bool = False, name: str | None = None, default: bool = False, pool: PoolConfig | None = None, *, identity_map: bool = True, migrate_updates: bool = False, migrate_destructive: bool = False) -> None

Open a connection pool and register it under a name.

Call it once at startup. ORM calls then run inside a session opened on the connection; see Sessions.

The three migrate flags make the database match the registered models as the connection opens, each one going further than the last. They run under the run lock ferro migrate up takes and read the project's lock_timeout and ddl_lock_timeout settings. Auto-migrate lists what each flag changes on each backend and how the lock waits. A change the pass refuses, such as a primary-key change, is a migration's job: see Changing a primary key.

Parameters:

Name Type Description Default
url str

The database URL, such as "sqlite:app.db?mode=rwc", "sqlite::memory:" or "postgresql://user:password@localhost/app".

required
auto_migrate bool

Create the missing tables of every registered model. Existing tables are left as they are. Defaults to False.

False
name str | None

The connection's name, made of ASCII letters, digits and underscores. Defaults to None, which registers it as "default".

None
default bool

Make this named connection the default, the one engines.session() opens when given no name. Defaults to False.

False
pool PoolConfig | None

The pool's size and how sessions send their settings. Defaults to None, which means PoolConfig().

None
identity_map bool

Keep an identity map in each session on this connection, so one primary key loads as one instance within the session. Defaults to True.

True
migrate_updates bool

Also change existing tables to match the models: add columns and indexes, and on Postgres change types, nullability and foreign keys. Implies auto_migrate. Defaults to False.

False
migrate_destructive bool

Also drop columns the models no longer declare, never whole tables. Implies migrate_updates. Defaults to False.

False

Raises:

Type Description
ValueError

A connection with this name is already registered (or a default one, when name is omitted), or name holds a character other than an ASCII letter, digit or underscore. Pass another name, or call reset_engine first.

MigrationRefused

A migrate flag was given for a database that migrations govern (run ferro migrate up instead), the run lock stayed held longer than lock_timeout, or the Postgres URL goes through a transaction-mode pooler.

OperationalError

On Postgres, a statement of the pass waited longer than ddl_lock_timeout for its table lock on ten attempts. Its .report lists what committed before the failure.

SettingsError

The configured databases set different lock_timeout or ddl_lock_timeout values.

Examples:

from ferro import connect, engines

await connect("sqlite::memory:", auto_migrate=True)
async with engines.session():
    await Author.create(name="Ada Lovelace", email="ada@example.com")
    assert len(await Author.all()) == 1

PoolConfig

Bases: BaseModel

Pool size and settings delivery for one connection.

Pass it to connect as pool=. settings_delivery chooses how a session sends its session settings to Postgres; read Connection delivery for what "connection" saves and what it costs before you opt in.

Raises:

Type Description
ValidationError

A size is out of range, or min_connections exceeds max_connections.

Examples:

from ferro import PoolConfig, connect

pool = PoolConfig(max_connections=10, min_connections=1)
await connect("sqlite::memory:", name="pooled", pool=pool)
assert pool.settings_delivery == "transaction"

Methods:

Name Description
validate

Check that min_connections does not exceed max_connections.

Attributes:

Name Type Description
max_connections int

The most connections the pool opens at once. Defaults to 5; at least 1.

min_connections int

The connections the pool keeps open while idle. Defaults to 0.

settings_delivery Literal['transaction', 'connection']

How sessions send their settings to Postgres. Defaults to "transaction".

max_connections class-attribute instance-attribute

max_connections: int = PydanticField(default=5, ge=1)

The most connections the pool opens at once. Defaults to 5; at least 1.

min_connections class-attribute instance-attribute

min_connections: int = PydanticField(default=0, ge=0)

The connections the pool keeps open while idle. Defaults to 0.

settings_delivery class-attribute instance-attribute

settings_delivery: Literal['transaction', 'connection'] = 'transaction'

How sessions send their settings to Postgres. Defaults to "transaction".

"transaction" sets them inside each transaction, which is safe behind a transaction-mode pooler. "connection" sets them once on a connection the session holds until it closes; use it only when the pool reaches Postgres directly.

validate

validate() -> PoolConfig

Check that min_connections does not exceed max_connections.

Pydantic runs it on construction, so a PoolConfig you hold has already passed it.

Returns:

Type Description
PoolConfig

This configuration, unchanged.

Raises:

Type Description
ValueError

min_connections exceeds max_connections.

set_default_connection

set_default_connection(name: str) -> None

Set the connection engines.session() opens when called without a name.

See The default connection for the other two ways to set it.

Parameters:

Name Type Description Default
name str

A connection registered with connect(url, name=...).

required

Raises:

Type Description
ValueError

No connection is registered under name, or name holds a character other than an ASCII letter, digit or underscore.

RuntimeError

The engine's state could not be locked.

Examples:

from ferro import connect, engines, set_default_connection

await connect("sqlite::memory:", name="app", default=True)
await connect("sqlite::memory:", name="archive")
set_default_connection("archive")
async with engines.session() as session:
    assert session.connection_name == "archive"

reset_engine

reset_engine() -> None

Close every connection and drop every open session and transaction.

Call it between tests to start each one from a clean engine. The next connect without a name registers as the default again. Declared models stay registered; see clear_registry to drop their schema as well.

Raises:

Type Description
RuntimeError

The engine's state could not be locked.

Examples:

from ferro import connect, reset_engine

await connect("sqlite::memory:", auto_migrate=True)
reset_engine()
await connect("sqlite::memory:", auto_migrate=True)

version

version() -> str

Return the version of the installed Ferro.

Returns:

Type Description
str

The version string, such as "0.25.0".

Examples:

from importlib.metadata import version as installed

from ferro import version

assert version() == installed("ferro-orm")

Sessions

engines module-attribute

engines = EngineManager()

The connections connect registered: engines.session(name) opens a session on one.

EngineManager

The registry of connections that sessions open on; use the engines instance.

Methods:

Name Description
session

Open a session on a connection, for use with async with.

session

session(name: str | None = None, *, settings: Mapping[str, str] | None = None) -> Session

Open a session on a connection, for use with async with.

With settings, every operation in the session sends those Postgres settings first, so row-level security policies see them. Inside a transaction() block they follow its BEGIN once; outside one, each operation wraps itself in a transaction to carry them, which costs three extra round trips. A session without settings sends nothing extra. See Round trips per operation.

Parameters:

Name Type Description Default
name str | None

The connection to open on. Defaults to None, the default connection.

None
settings Mapping[str, str] | None

Postgres settings for every operation, as dotted custom names mapped to str values. Defaults to None, no settings beyond the ones an enclosing session passes on.

None

Returns:

Type Description
Session

A Session, not yet open: enter it with async with.

Raises:

Type Description
TypeError

A settings key or value is not a str.

ValueError

A settings key is not a dotted custom setting name.

RuntimeError

On entering, a session that declares settings is on a connection that is not Postgres.

Examples:

from ferro import engines

async with engines.session():
    post = await Post.where(lambda post: post.views > 1000).first()
assert post.title == "Notes on the Analytical Engine"

With settings, on Postgres:

async with engines.session(settings={"myapp.tenant_id": "acme"}):
    invoices = await Invoice.where(lambda invoice: invoice.total > 100).all()

Session dataclass

Session(connection_name: str | None = None, session_id: str | None = None, settings: Mapping[str, str] | None = None, _token: Any = None, _enter_context: Context | None = None, _enter_task: Task[Any] | None = None, _close_lock: Lock | None = None)

A unit of work on one connection, with its own identity map and settings.

Open one with async with engines.session():. Every ORM call and raw query inside the block runs in it, and code called from the block finds it with current_session. Leaving the block closes the session. See Sessions.

settings are Postgres settings that every operation in the session sends, which is what row-level security policies read; see Session settings. A session opened inside another starts from the outer one's settings.

Examples:

from ferro import engines

async with engines.session() as session:
    authors = await Author.where(lambda author: author.id <= 2).all()
assert [author.name for author in authors] == ["Ada Lovelace", "Grace Hopper"]
assert session.connection_name == "default"

Methods:

Name Description
close

Close the session and release what it holds.

set_config

Set one session setting while the session is open.

query

Start a query of a model's records in this session.

Attributes:

Name Type Description
connection_name str | None

The connection the session runs on, or None for the default until it opens.

session_id str | None

The open session's id, or None before it opens and after it closes.

settings Mapping[str, str] | None

The settings this session declares, as given.

effective_settings dict[str, str]

The settings the session runs with: its own over the ones it inherits.

connection_name class-attribute instance-attribute

connection_name: str | None = None

The connection the session runs on, or None for the default until it opens.

session_id class-attribute instance-attribute

session_id: str | None = None

The open session's id, or None before it opens and after it closes.

settings class-attribute instance-attribute

settings: Mapping[str, str] | None = None

The settings this session declares, as given.

effective_settings class-attribute instance-attribute

effective_settings: dict[str, str] = field(default_factory=dict, init=False, repr=False, compare=False)

The settings the session runs with: its own over the ones it inherits.

close async

close() -> None

Close the session and release what it holds.

Leaving the async with block calls it; call it yourself for a session you entered by hand. Under settings_delivery="connection", the session first resets exactly the setting keys it set on its connection, then returns the connection to the pool. A second call does nothing.

Raises:

Type Description
RuntimeError

A transaction() block of the session is still open, another session became current in this task without closing first, or resetting the held connection failed. In the last case the session is closed anyway and the connection is discarded.

set_config async

set_config(key: str, value: str) -> None

Set one session setting while the session is open.

Use it when the value is known only partway through the session, such as a tenant resolved from an auth token. An operation or transaction() block that starts after it returns sees the new value, and so does a transaction() block of this session already open in any task. It also empties the session's identity map. Setting a key to the value it holds sends nothing. See Visibility of a new value.

Parameters:

Name Type Description Default
key str

A dotted custom Postgres setting name, such as "myapp.tenant_id".

required
value str

The setting's new value.

required

Raises:

Type Description
RuntimeError

The session is not open, its connection is not Postgres, or delivering the value to an open transaction failed. The new value is recorded even then.

TypeError

key or value is not a str.

ValueError

key is not a dotted custom setting name.

Examples:

async with engines.session() as session:
    tenant = await resolve_tenant(request)
    await session.set_config("myapp.tenant_id", tenant)
    invoices = await Invoice.where(lambda invoice: invoice.total > 100).all()

query

query(model_cls: type[M]) -> Query[M]

Start a query of a model's records in this session.

Parameters:

Name Type Description Default
model_cls type[M]

The model to query.

required

Returns:

Type Description
Query[M]

A Query over every row of the model's table, run in this session.

Examples:

from ferro import current_session

posts = await current_session().query(Post).where(lambda post: post.views > 1000).all()
assert [post.title for post in posts] == ["Notes on the Analytical Engine"]

current_session

current_session() -> 'Session | None'

Return the session open in the current task, or None.

Code called from inside async with engines.session(): reaches the session through it instead of taking it as an argument. Inside nested sessions it returns the innermost one.

Returns:

Type Description
'Session | None'

The current session, or None outside every session.

Examples:

from ferro import current_session, engines

async with engines.session() as session:
    assert current_session() is session

Registry

create_tables async

create_tables(using: str | None = None) -> PassReport

Create the missing tables of every registered model.

A table that already exists is left as it is; changing one is migrate's job. A model defined after connect is created too. Like connect's migrate flags, it runs under the run lock and refuses a database that migrations govern.

Parameters:

Name Type Description Default
using str | None

The connection to create the tables on. Defaults to None, the default connection.

None

Returns:

Type Description
PassReport

Every statement the pass ran and every warning it raised, as a PassReport.

Raises:

Type Description
MigrationRefused

Migrations govern the database, or the run lock stayed held longer than lock_timeout.

Examples:

from ferro import Field, Model, create_tables


class Note(Model):
    id: int | None = Field(default=None, primary_key=True)
    body: str


report = await create_tables()
assert [statement.sql for statement in report.statements] == [
    'CREATE TABLE IF NOT EXISTS "note" ( "body" varchar NOT NULL, '
    '"id" integer NOT NULL PRIMARY KEY AUTOINCREMENT )'
]

migrate async

migrate(using: str | None = None, updates: bool = True, destructive: bool = False) -> PassReport

Run the auto-migrate pass on an open connection.

It runs the same pass as connect(migrate_updates=True): it creates the missing tables, then changes existing ones to match the models. See On-demand migrate() for what it changes on each backend. Like connect's migrate flags, it runs under the run lock and refuses a database that migrations govern.

Parameters:

Name Type Description Default
using str | None

The connection to migrate. Defaults to None, the default connection.

None
updates bool

Change existing tables as well as creating missing ones. Defaults to True; False runs only the create pass, as create_tables does.

True
destructive bool

Also drop columns the models no longer declare. Implies updates. Defaults to False.

False

Returns:

Type Description
PassReport

Every statement the pass sent, in order, and every warning it raised, as a PassReport. Each warning is also raised as a UserWarning.

Raises:

Type Description
MigrationRefused

Migrations govern the database, or the run lock stayed held longer than lock_timeout.

OperationalError

A statement failed partway through the pass. Its .report lists what committed before the failure.

Examples:

from ferro import Field, Model, execute, migrate

await execute('CREATE TABLE "tag" ("id" integer PRIMARY KEY, "label" varchar NOT NULL)')


class Tag(Model):
    id: int | None = Field(default=None, primary_key=True)
    label: str
    color: str | None = None


report = await migrate()
assert [statement.sql for statement in report.statements] == [
    'ALTER TABLE "tag" ADD COLUMN "color" varchar'
]

clear_registry

clear_registry() -> None

Drop the schema the engine holds for the registered models.

Call it in a test fixture, after reset_engine, when the next test declares its own models: the next connect then builds the schema only from what is registered at that point, and leaves out the many-to-many join tables of earlier tests. Model classes you have declared stay declared and keep working after the next connect.

Examples:

from ferro import clear_registry, connect, reset_engine

await connect("sqlite::memory:", auto_migrate=True)
reset_engine()
clear_registry()
await connect("sqlite::memory:", auto_migrate=True)

ensure_resolved_modelset

ensure_resolved_modelset() -> dict[str, Any]

Return the schema of every registered model, relationships resolved.

It is the schema connect, create_tables and ferro migrate new read, as a JSON-ready dict. Relationships between models are resolved first, so a model declared since the last call is included. Declaring models in another thread while it runs is unsupported and can raise.

Returns:

Type Description
dict[str, Any]

The schema as a dict, ready for json.dumps.

evict_instance

evict_instance(model: type[Model] | str, pk: str, *, using: str | None = None, session: Session | None = None) -> None

Remove one instance from the session's identity map.

Within a session, fetching a row you already hold returns the same object. After an eviction, the next fetch of that row builds a new instance and leaves the one you hold detached. A re-fetch already refreshes a held instance in place, so evict only when you want a second, separate object. See Eviction.

Parameters:

Name Type Description Default
model type[Model] | str

The model class, or its name when the name is unambiguous.

required
pk str

The instance's primary key, as a string.

required
using str | None

The named connection whose map to evict from. Defaults to None, the session's connection.

None
session Session | None

The session whose map to evict from. Defaults to None, the session opened by the enclosing async with engines.session():.

None

Raises:

Type Description
RuntimeError

No session, using= or transaction gives the call a database route.

Examples:

from ferro import evict_instance

ada = await Author.get(1)
evict_instance(Author, "1")
fresh = await Author.get(1)
assert fresh is not ada

Auto-migrate reports

ferro.migrate() and ferro.create_tables() return a PassReport, built from the statements the database actually ran. A pass that fails partway raises its usual error with .report set to what committed before the failure:

report = await ferro.migrate(updates=True)
[(s.subject, s.sql) for s in report.statements if s.role == "schema"]
# [('author', 'ALTER TABLE "author" ADD COLUMN "slug" TEXT')]
[(w.kind, str(w)) for w in report.warnings]
# []

Each ExecutedStatement names its table (subject) and its role; each warning is a typed Report.

PassReport dataclass

PassReport(statements: tuple[ExecutedStatement, ...] = (), warnings: tuple[Report, ...] = ())

What one auto-migrate pass sent to the database and the warnings it raised.

Every warning is also raised as a Python UserWarning.

Examples:

import ferro

await ferro.raw.execute('DROP TABLE "post"')
report = await ferro.create_tables()
print([(statement.subject, statement.role) for statement in report.statements])
# [('post', 'schema')]
print(report.warnings)
# ()

Attributes:

Name Type Description
statements tuple[ExecutedStatement, ...]

Every statement the pass sent, in execution order.

warnings tuple[Report, ...]

Every warning the pass raised, in the order raised.

statements class-attribute instance-attribute

statements: tuple[ExecutedStatement, ...] = ()

Every statement the pass sent, in execution order.

warnings class-attribute instance-attribute

warnings: tuple[Report, ...] = ()

Every warning the pass raised, in the order raised.

ExecutedStatement dataclass

ExecutedStatement(subject: str, sql: str, role: Role)

One statement the pass sent to the database.

Attributes:

Name Type Description
subject str

The table or enum type the statement belongs to.

sql str

The statement, exactly as it ran.

role Role

What it was for: "schema" (DDL), "lock_timeout" or "probe" (a read that changes nothing).

subject instance-attribute

subject: str

The table or enum type the statement belongs to.

sql instance-attribute

sql: str

The statement, exactly as it ran.

role instance-attribute

role: Role

What it was for: "schema" (DDL), "lock_timeout" or "probe" (a read that changes nothing).

Report dataclass

Report(kind: str, subject: Subject, text: str, recurs: bool)

One warning a pass raised, with a kind code can match on.

str(report) is the sentence the pass printed. The Auto-migrate guide lists every kind.

Attributes:

Name Type Description
kind str

The warning's kind, such as "LeftoverChecks", "RefusedConversion" or "RunLockWait".

subject Subject

What the warning is about.

text str

The sentence the pass printed and raised as a UserWarning.

recurs bool

Whether every pass raises it again until someone acts.

kind instance-attribute

kind: str

The warning's kind, such as "LeftoverChecks", "RefusedConversion" or "RunLockWait".

subject instance-attribute

subject: Subject

What the warning is about.

text instance-attribute

text: str

The sentence the pass printed and raised as a UserWarning.

recurs instance-attribute

recurs: bool

Whether every pass raises it again until someone acts.

Subject dataclass

Subject(scope: Literal['modelset', 'table', 'column', 'enum_type'], table: str | None = None, column: str | None = None, type_name: str | None = None)

What a Report is about.

The modelset as a whole, one table, one column, or one enum type. Only the fields its scope names are set.

Attributes:

Name Type Description
scope Literal['modelset', 'table', 'column', 'enum_type']

Which of the four it is: "modelset", "table", "column" or "enum_type".

table str | None

The table, for the "table" and "column" scopes; None otherwise.

column str | None

The column, for the "column" scope; None otherwise.

type_name str | None

The Postgres enum type, for the "enum_type" scope; None otherwise.

scope instance-attribute

scope: Literal['modelset', 'table', 'column', 'enum_type']

Which of the four it is: "modelset", "table", "column" or "enum_type".

table class-attribute instance-attribute

table: str | None = None

The table, for the "table" and "column" scopes; None otherwise.

column class-attribute instance-attribute

column: str | None = None

The column, for the "column" scope; None otherwise.

type_name class-attribute instance-attribute

type_name: str | None = None

The Postgres enum type, for the "enum_type" scope; None otherwise.

Project settings

FerroSettings() reads the project's one config file (ferro.toml, or [tool.ferro] in pyproject.toml); every ferro.migrations call takes settings=None to mean exactly that. No file is not an error until a database is asked for; a malformed or contradictory configuration, or a database asked of none, raises SettingsError, whose message names the fix.

FerroSettings

FerroSettings(config: Path | str | None = None)

Bases: BaseSettings

A project's Ferro configuration, read from its one config file.

`FerroSettings()` looks for the file in this order: the `FERRO_CONFIG`
environment variable, then the nearest directory, walking up from the
working directory, that holds a `ferro.toml` or a `pyproject.toml` with
a `[tool.ferro]` table. The file found is used alone: no environment
variable overrides a key. With no file found the object is empty
(`databases == {}`, and `searched` lists every directory examined); it
refuses only when a database is asked for. Each `FerroSettings()` reads
the file again. See [Configuration](../reference/configuration.md).

Args:
    config: The config file to read, skipping the lookup. Defaults to
        `None`.

Raises:
    SettingsError: The file is malformed or contradicts itself, a key is
        unknown or misplaced, or one directory holds both a `ferro.toml`
        and a `[tool.ferro]` table.

Examples:
    ```python {test=run prelude=reference}
    import tempfile
    from pathlib import Path

    from ferro import FerroSettings

    config = Path(tempfile.mkdtemp()) / "ferro.toml"
    config.write_text('models = ["blog.models"]

dialects = ["postgres", "sqlite"] ') database = FerroSettings(config=config).database() assert database.name == "default" assert database.directory == config.resolve().parent / "migrations" ```

Methods:

Name Description
settings_customise_sources

Read the located config file and nothing else.

database

Return the database called name.

database_for

Return the database that owns model, decided by its defining module.

Attributes:

Name Type Description
config_path Path | None

The config file read, or None when none was found.

config_table tuple[str, ...]

Where the keys sit in it: ("tool", "ferro"), or () for the top level.

searched list[Path]

Every directory the walk-up examined without finding a config.

python_path list[Path]

Directories put on sys.path before importing models, resolved against the config file.

databases dict[str, DatabaseSettings]

The configured databases, by name; empty when no file was found.

config_path class-attribute instance-attribute

config_path: Path | None = None

The config file read, or None when none was found.

config_table class-attribute instance-attribute

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

Where the keys sit in it: ("tool", "ferro"), or () for the top level.

searched class-attribute instance-attribute

searched: list[Path] = Field(default_factory=list)

Every directory the walk-up examined without finding a config.

python_path class-attribute instance-attribute

python_path: list[Path] = Field(default_factory=list)

Directories put on sys.path before importing models, resolved against the config file.

databases class-attribute instance-attribute

databases: dict[str, DatabaseSettings] = Field(default_factory=dict)

The configured databases, by name; empty when no file was found.

settings_customise_sources classmethod

settings_customise_sources(settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource, env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource, file_secret_settings: PydanticBaseSettingsSource) -> tuple[PydanticBaseSettingsSource, ...]

Read the located config file and nothing else.

Pydantic-settings calls it while building the object. No environment variable, .env file or secrets directory sets a field, since these keys decide what a migration contains.

Parameters:

Name Type Description Default
settings_cls type[BaseSettings]

The settings class being built.

required
init_settings PydanticBaseSettingsSource

What the constructor located: the path, its table header and the directories searched.

required
env_settings PydanticBaseSettingsSource

Unused: no environment variable sets a key.

required
dotenv_settings PydanticBaseSettingsSource

Unused: no .env file is read.

required
file_secret_settings PydanticBaseSettingsSource

Unused: no secrets directory is read.

required

Returns:

Type Description
tuple[PydanticBaseSettingsSource, ...]

The constructor's source, and the config file's when one was found.

Raises:

Type Description
SettingsError

The file is not valid TOML, or a key the constructor sets appears in it.

database

database(name: str | None = None) -> DatabaseSettings

Return the database called name.

Parameters:

Name Type Description Default
name str | None

The database's name. Defaults to None, which is allowed when exactly one database is configured.

None

Returns:

Type Description
DatabaseSettings

That database's settings.

Raises:

Type Description
SettingsError

No config file was found, no database has that name, or name is None and several databases are configured.

database_for

database_for(model: type) -> DatabaseSettings

Return the database that owns model, decided by its defining module.

A model belongs to each database whose models list holds its module or a parent of it.

Parameters:

Name Type Description Default
model type

A model class.

required

Returns:

Type Description
DatabaseSettings

The settings of the one database that claims the model.

Raises:

Type Description
SettingsError

model is not a model class, no config file was found, no database or several claim the model, or one of its foreign keys points at a model its database does not claim.

DatabaseSettings

Bases: BaseModel

One configured database: a named set of models with one line of migrations.

FerroSettings builds it from [tool.ferro] (one database, named "default") or from [tool.ferro.databases.<name>] (several). Paths are already resolved against the config file's directory. See Keys for each key.

Methods:

Name Description
lock_wait

Return how many seconds a run on this database waits for the run lock.

url_for

Return the database URL: override, else the url_env variable.

import_models

Import this database's models modules and return its models.

Attributes:

Name Type Description
name str

The database's name: "default" for a single database.

models list[str]

The dotted modules that define the database's models.

dialects list[Dialect]

The dialects its migrations are rendered for: "postgres", "sqlite" or both.

url_env str

The environment variable holding the database URL. Defaults to "DATABASE_URL".

directory Path

The migrations directory, resolved against the config file's directory.

tracking_schema str | None

Postgres only: the schema of the tracking tables. Defaults to None, the current schema.

ddl_lock_timeout str

How long a DDL statement on Postgres waits for its table lock. Defaults to "5s".

lock_timeout str

How long a run waits for the run lock. Defaults to "30s"; "0" waits without a limit.

ddl_lock_timeout_seconds float

ddl_lock_timeout in seconds; 0.0 when it is off.

lock_timeout_seconds float

lock_timeout in seconds; one year, no limit, for "0".

name class-attribute instance-attribute

name: str = Field(min_length=1)

The database's name: "default" for a single database.

models class-attribute instance-attribute

models: list[str] = Field(min_length=1)

The dotted modules that define the database's models.

dialects class-attribute instance-attribute

dialects: list[Dialect] = Field(min_length=1)

The dialects its migrations are rendered for: "postgres", "sqlite" or both.

url_env class-attribute instance-attribute

url_env: str = Field(default='DATABASE_URL', min_length=1)

The environment variable holding the database URL. Defaults to "DATABASE_URL".

directory instance-attribute

directory: Path

The migrations directory, resolved against the config file's directory.

tracking_schema class-attribute instance-attribute

tracking_schema: str | None = Field(default=None, min_length=1)

Postgres only: the schema of the tracking tables. Defaults to None, the current schema.

ddl_lock_timeout class-attribute instance-attribute

ddl_lock_timeout: str = '5s'

How long a DDL statement on Postgres waits for its table lock. Defaults to "5s".

lock_timeout class-attribute instance-attribute

lock_timeout: str = '30s'

How long a run waits for the run lock. Defaults to "30s"; "0" waits without a limit.

ddl_lock_timeout_seconds property

ddl_lock_timeout_seconds: float

ddl_lock_timeout in seconds; 0.0 when it is off.

lock_timeout_seconds property

lock_timeout_seconds: float

lock_timeout in seconds; one year, no limit, for "0".

It is how long a run (ferro migrate up, down, baseline, rerecord) or an auto-migrate pass waits for the run lock another one holds.

lock_wait

lock_wait(override: str | float | None = None) -> float

Return how many seconds a run on this database waits for the run lock.

Parameters:

Name Type Description Default
override str | float | None

--lock-timeout, or a call's lock_timeout=. Defaults to None, the configured lock_timeout.

None

Returns:

Type Description
float

The wait in seconds.

Raises:

Type Description
SettingsError

override is not a lock timeout.

url_for

url_for(override: str | None = None) -> str

Return the database URL: override, else the url_env variable.

The config file never holds a URL.

Parameters:

Name Type Description Default
override str | None

A URL given on the command line (--url). Defaults to None, which reads the variable url_env names.

None

Returns:

Type Description
str

The URL.

Raises:

Type Description
SettingsError

No override was given and the variable is unset or empty.

import_models

import_models() -> list[type]

Import this database's models modules and return its models.

The config file's directory goes first on sys.path, then each python_path entry, and the entries stay for the rest of the process, since an imported module may import its siblings later. A foreign key naming its target by string is resolved against every configured database's modules, importing them if needed.

Returns:

Type Description
list[type]

Every registered model this database claims, in registration order.

Raises:

Type Description
SettingsError

The modules registered no model (no models is never read as "drop every table"), a registered model belongs to no database, one of this database's models has a foreign key into another database, or the settings were built by hand rather than read from a config file.