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 |
required |
auto_migrate
|
bool
|
Create the missing tables of every registered model.
Existing tables are left as they are. Defaults to |
False
|
name
|
str | None
|
The connection's name, made of ASCII letters, digits and
underscores. Defaults to |
None
|
default
|
bool
|
Make this named connection the default, the one
|
False
|
pool
|
PoolConfig | None
|
The pool's size and how sessions send their settings. Defaults
to |
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
|
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 |
False
|
migrate_destructive
|
bool
|
Also drop columns the models no longer declare,
never whole tables. Implies |
False
|
Raises:
| Type | Description |
|---|---|
ValueError
|
A connection with this name is already registered (or a
default one, when |
MigrationRefused
|
A migrate flag was given for a
database that migrations govern (run |
OperationalError
|
On Postgres, a statement of the pass waited longer
than |
SettingsError
|
The configured databases set different |
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
|
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"
-
Reference
Python API
connect, Session and the registry
PoolConfigvalidate
-
Reference
Python API
connect, Session and the registry
connect
Methods:
| Name | Description |
|---|---|
validate |
Check that |
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 |
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
|
|
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
No connection is registered under |
RuntimeError
|
The engine's state could not be locked. |
Examples:
reset_engine
¶
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)
- How-to How to test a Ferro app with pytest
- Reference Python API connect, Session and the registry
version
¶
version() -> str
Return the version of the installed Ferro.
Returns:
| Type | Description |
|---|---|
str
|
The version string, such as |
Examples:
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.
-
Reference
Python API
connect, Session and the registry
engines
Methods:
| Name | Description |
|---|---|
session |
Open a session on a connection, for use with |
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
|
settings
|
Mapping[str, str] | None
|
Postgres settings for every operation, as dotted
custom names mapped to |
None
|
Returns:
| Type | Description |
|---|---|
Session
|
A |
Raises:
| Type | Description |
|---|---|
TypeError
|
A settings key or value is not a |
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:
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"
-
Reference
Python API
connect, Session and the registry
EngineManagersession
-
Reference
Python API
connect, Session and the registry
EngineManagersession
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 |
session_id |
str | None
|
The open session's id, or |
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
¶
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 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 |
set_config
async
¶
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
|
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
|
|
ValueError
|
|
Examples:
current_session
¶
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 |
Examples:
from ferro import current_session, engines
async with engines.session() as session:
assert current_session() is session
-
Reference
Python API
connect, Session and the registry
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
|
Returns:
| Type | Description |
|---|---|
PassReport
|
Every statement the pass ran and every warning it raised, as a
|
Raises:
| Type | Description |
|---|---|
MigrationRefused
|
Migrations govern the database,
or the run lock stayed held longer than |
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 )'
]
- Reference Python API connect, Session and the registry
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
|
updates
|
bool
|
Change existing tables as well as creating missing ones.
Defaults to |
True
|
destructive
|
bool
|
Also drop columns the models no longer declare. Implies
|
False
|
Returns:
| Type | Description |
|---|---|
PassReport
|
Every statement the pass sent, in order, and every warning it raised,
as a |
Raises:
| Type | Description |
|---|---|
MigrationRefused
|
Migrations govern the database,
or the run lock stayed held longer than |
OperationalError
|
A statement failed partway through the pass. Its
|
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'
]
-
Reference
Python API
connect, Session and the registry
create_tables
clear_registry
¶
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)
-
Reference
Python API
connect, Session and the registry
reset_engine
ensure_resolved_modelset
¶
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 |
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
|
session
|
Session | None
|
The session whose map to evict from. Defaults to |
None
|
Raises:
| Type | Description |
|---|---|
RuntimeError
|
No session, |
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
- Concepts Identity map See also
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)
# ()
- Reference Python API connect, Session and the registry
- Reference Python API connect, Session and the registry
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. |
ExecutedStatement
dataclass
¶
One statement the pass sent to the database.
-
Reference
Python API
connect, Session and the registry
PassReportstatements
-
Reference
Python API
connect, Session and the registry
PassReport
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: |
Report
dataclass
¶
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.
-
Reference
Python API
connect, Session and the registry
Subject
-
Reference
Python API
connect, Session and the registry
PassReportwarnings
-
Reference
Python API
connect, Session and the registry
PassReport
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
str
|
The warning's kind, such as |
subject |
Subject
|
What the warning is about. |
text |
str
|
The sentence the pass printed and raised as a |
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.
-
Reference
Python API
connect, Session and the registry
Reportsubject
-
Reference
Python API
connect, Session and the registry
Report
Attributes:
| Name | Type | Description |
|---|---|---|
scope |
Literal['modelset', 'table', 'column', 'enum_type']
|
Which of the four it is: |
table |
str | None
|
The table, for the |
column |
str | None
|
The column, for the |
type_name |
str | None
|
The Postgres enum type, for the |
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.
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
¶
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" ```
-
Reference
Python API
connect, Session and the registry
DatabaseSettings
- Reference Python API ferro.migrations
Methods:
| Name | Description |
|---|---|
settings_customise_sources |
Read the located config file and nothing else. |
database |
Return the database called |
database_for |
Return the database that owns |
Attributes:
| Name | Type | Description |
|---|---|---|
config_path |
Path | None
|
The config file read, or |
config_table |
tuple[str, ...]
|
Where the keys sit in it: |
searched |
list[Path]
|
Every directory the walk-up examined without finding a config. |
python_path |
list[Path]
|
Directories put on |
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
¶
Where the keys sit in it: ("tool", "ferro"), or () for the top level.
searched
class-attribute
instance-attribute
¶
Every directory the walk-up examined without finding a config.
python_path
class-attribute
instance-attribute
¶
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 |
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
|
Returns:
| Type | Description |
|---|---|
DatabaseSettings
|
That database's settings. |
Raises:
| Type | Description |
|---|---|
SettingsError
|
No config file was found, no database has that
name, or |
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
|
|
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.
-
Reference
Python API
connect, Session and the registry
FerroSettings
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: |
import_models |
Import this database's |
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
The database's name: |
models |
list[str]
|
The dotted modules that define the database's models. |
dialects |
list[Dialect]
|
The dialects its migrations are rendered for: |
url_env |
str
|
The environment variable holding the database URL. Defaults to |
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 |
ddl_lock_timeout |
str
|
How long a DDL statement on Postgres waits for its table lock. Defaults to |
lock_timeout |
str
|
How long a run waits for the run lock. Defaults to |
ddl_lock_timeout_seconds |
float
|
|
lock_timeout_seconds |
float
|
|
name
class-attribute
instance-attribute
¶
The database's name: "default" for a single database.
models
class-attribute
instance-attribute
¶
The dotted modules that define the database's models.
dialects
class-attribute
instance-attribute
¶
The dialects its migrations are rendered for: "postgres", "sqlite" or both.
url_env
class-attribute
instance-attribute
¶
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
¶
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
¶
Return how many seconds a run on this database waits for the run lock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
override
|
str | float | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
float
|
The wait in seconds. |
Raises:
| Type | Description |
|---|---|
SettingsError
|
|
url_for
¶
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The URL. |
Raises:
| Type | Description |
|---|---|
SettingsError
|
No |
import_models
¶
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. |