# Model

`Model` is the base class every Ferro model inherits from. The lifecycle is: define a subclass with annotated fields (which registers its table schema), [`connect()`](<https://ferro-orm.x54.sh/api/connection/index.md>) to a database, then perform CRUD through classmethods (`create`, `get`, `where`, ...) and instance methods (`save`, `delete`, `refresh`). Because `Model` is a Pydantic model, instances validate on construction and serialize like any other Pydantic object.

## Model

```python
Model(**data: Any)
```

Bases: `BaseModel`

The base class of every Ferro model: a Pydantic model backed by a table.

A subclass declares its columns as annotated fields, and its table is created on `connect` with `auto_migrate=True`. Every database call runs inside a session, opened with `async with engines.session():`, and the examples on this page run in one. See [Models and fields](<https://ferro-orm.x54.sh/guide/models-and-fields/index.md>) to declare a model and [Connections](<https://ferro-orm.x54.sh/guide/connections/#sessions>) for sessions.

A model declares table-wide constraints in class attributes: `__ferro_composite_uniques__` and `__ferro_composite_indexes__` (see [Composite uniques](<https://ferro-orm.x54.sh/guide/models-and-fields/#composite-uniques>) and [Composite indexes](<https://ferro-orm.x54.sh/guide/models-and-fields/#composite-indexes>)), `__ferro_checks__` (see [Table checks](<https://ferro-orm.x54.sh/guide/models-and-fields/#table-checks>)) and `__ferro_rls__` (see [Using with Postgres RLS](<https://ferro-orm.x54.sh/guide/row-level-security/index.md>)).

Examples:

```python
mary = await Author.create(name="Mary Somerville", email="mary@example.com")
fetched = await Author.get(mary.id)
assert fetched is mary
```

Within a session, fetching a row you already hold returns the same object.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `**data` | `Any` | The field values. A forward relation is set through its foreign-key column, `team_id=team.id`, never by its own name. | `{}` |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | A keyword names a retired field, a generated one or a forward relation. |
| `ValidationError` | A keyword names no field, or a value does not validate. |

Methods:

| Name | Description |
| --- | --- |
| `model_dump` | Dump the instance's fields to a dict, as Pydantic's `model_dump` does. |
| `model_dump_json` | Dump the instance's fields to JSON, as Pydantic's `model_dump_json` does. |
| `model_copy` | Copy the instance, as Pydantic's `model_copy` does. |
| `save` | Write the instance to its row: insert it when new, update it otherwise. |
| `delete` | Delete the instance's row. |
| `all` | Fetch every row of the model's table. |
| `get` | Fetch one record by primary key. |
| `get_or_none` | Fetch one record by primary key, or `None` when no row has it. |
| `refresh` | Reload the instance's fields from its row, in place. |
| `load` | Fill an unloaded instance from its row, in place, and return it. |
| `where` | Start a query filtered by a lambda predicate. |
| `select` | Start a query, of whole records or of some columns. |
| `using` | Run this model's operations on a named connection. |
| `create` | Insert a new record and return it. |
| `upsert` | Insert a record, or update the row that has its primary key. |
| `bulk_create` | Insert many new records in one call. |
| `get_or_create` | Fetch the first record whose fields match, or create it. |
| `update_or_create` | Update the first record whose fields match, or create it. |

### model\_dump

```python
model_dump(*args: Any, **kwargs: Any) -> dict[str, Any]
```

Dump the instance's fields to a dict, as Pydantic's `model_dump` does.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*args` | `Any` | Pydantic's positional `model_dump` options. | `()` |
| `**kwargs` | `Any` | Pydantic's keyword `model_dump` options, such as `mode="json"` or `exclude`. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `dict[str, Any]` | The field values by name. |

Raises:

| Type | Description |
| --- | --- |
| `InstanceNotLoaded` | The instance is unloaded; load it with `.load()` first. |

### model\_dump\_json

```python
model_dump_json(*args: Any, **kwargs: Any) -> str
```

Dump the instance's fields to JSON, as Pydantic's `model_dump_json` does.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*args` | `Any` | Pydantic's positional `model_dump_json` options. | `()` |
| `**kwargs` | `Any` | Pydantic's keyword `model_dump_json` options, such as `indent` or `exclude`. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `str` | The JSON text. |

Raises:

| Type | Description |
| --- | --- |
| `InstanceNotLoaded` | The instance is unloaded; load it with `.load()` first. |

### model\_copy

```python
model_copy(*, update: Mapping[str, Any] | None = None, deep: bool = False) -> Self
```

Copy the instance, as Pydantic's `model_copy` does.

A cached relation the copy's foreign-key column no longer points at is dropped, so the copy reads the relation its own key names.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `update` | `Mapping[str, Any] \| None` | Field values to change in the copy. Defaults to `None`. | `None` |
| `deep` | `bool` | Copy the field values too. Defaults to `False`. | `False` |

Returns:

| Type | Description |
| --- | --- |
| `Self` | The copy. |

Raises:

| Type | Description |
| --- | --- |
| `InstanceNotLoaded` | `update` names a column of an unloaded instance; load it with `.load()` first. |
| `TypeError` | `update` names a relation; set its foreign-key column instead, as the constructor says. |

### save

```python
save(*, using: str | None = None, session: Session | None = None, on_conflict: Literal['update'] | None = None, only: set[str] | frozenset[str] | list[str] | tuple[str, ...] | None = None, exclude: set[str] | frozenset[str] | list[str] | tuple[str, ...] | None = None) -> None
```

Write the instance to its row: insert it when new, update it otherwise.

An instance you built and never saved is inserted. One fetched from the database, or saved before, updates its row by primary key, and `only=` or `exclude=` limit that update to some columns. For an update across many rows, use `Query.update`. See [Saving: INSERT or UPDATE](<https://ferro-orm.x54.sh/guide/mutations/#saving-insert-or-update>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `using` | `str \| None` | The named connection to write on. Defaults to `None`, the session's connection, or the one the instance was loaded from. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `on_conflict` | `Literal['update'] \| None` | `"update"` inserts the row or, when its primary key already exists, updates it, whether or not the instance was saved before. Defaults to `None`, a plain insert or update. | `None` |
| `only` | `set[str] \| frozenset[str] \| list[str] \| tuple[str, ...] \| None` | On an update, the columns to write, as a set, list or tuple of field names. Defaults to `None`, every column. | `None` |
| `exclude` | `set[str] \| frozenset[str] \| list[str] \| tuple[str, ...] \| None` | On an update, the columns not to write. Defaults to `None`; `exclude=set()` writes every column. | `None` |

Raises:

| Type | Description |
| --- | --- |
| `InstanceNotLoaded` | The instance is unloaded; load it with `.load()` first. |
| `UniqueViolationError` | An insert repeats a primary key or unique value. |
| `ModelDoesNotExist` | The row behind a saved instance no longer exists, or its primary key was changed in memory. |
| `TypeError` | `only` or `exclude` is a bare string. |
| `ValueError` | `on_conflict` is neither `None` nor `"update"`; `only` or `exclude` is given on an insert or with `on_conflict`, both are given, or one names an unknown field or a relation; or a saved instance has no primary key value. |

> [!NOTE]
>
> The instance is not reloaded after a partial update, so a field left out of `only` keeps its value in memory even if the row differs. A copy made with `model_copy()` updates the same row as the original. An instance inserted in a transaction that rolled back still counts as saved, so its next `save()` raises `ModelDoesNotExist`.

Examples:

Saving a new instance inserts it:

```python
mary = Author(name="Mary Somerville", email="mary@example.com")
await mary.save()
assert mary.id == 3
```

Saving a fetched instance with `only=` updates just those columns:

```python
post = await Post.get(2)
post.views = 1000
post.title = "Not written to the row"
await post.save(only={"views"})

rows = await Post.select("title", "views").where(lambda post: post.id == 2).all()
assert rows[0].title == "The Education of a Computer"
assert rows[0].views == 1000
```

### delete

```python
delete(*, using: str | None = None, session: Session | None = None) -> None
```

Delete the instance's row.

The instance stays in memory and counts as new again: saving it inserts a new row. An instance without a primary key value has no row, and the call does nothing.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `using` | `str \| None` | The named connection to delete on. Defaults to `None`, the session's connection, or the one the instance was loaded from. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Raises:

| Type | Description |
| --- | --- |
| `ValueError` | `using` names a different connection from the one the instance was loaded from. |

Examples:

```python
post = await Post.get(2)
await post.delete()
assert await Post.get_or_none(2) is None
```

### all

```python
all(*, using: str | None = None, session: Session | None = None) -> list[Self]
```

Fetch every row of the model's table.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `using` | `str \| None` | The named connection to read from. Defaults to `None`, the session's connection. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `list[Self]` | One instance per row, in the order the database returns them. |

Examples:

```python
authors = await Author.all()
assert sorted(author.name for author in authors) == ["Ada Lovelace", "Grace Hopper"]
```

### get

```python
get(pk: Any, *, session: Session | None = None) -> Self
```

Fetch one record by primary key.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `pk` | `Any` | The primary key value to look up. | *required* |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `Self` | The record whose primary key is `pk`. |

Raises:

| Type | Description |
| --- | --- |
| `ModelDoesNotExist` | No row has that key. Use `get_or_none` to get `None` instead. |
| `RuntimeError` | The model declares no primary key. |

Examples:

```python
author = await Author.get(1)
assert author.name == "Ada Lovelace"
```

### get\_or\_none

```python
get_or_none(pk: Any, *, session: Session | None = None) -> Self | None
```

Fetch one record by primary key, or `None` when no row has it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `pk` | `Any` | The primary key value to look up. | *required* |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `Self \| None` | The record whose primary key is `pk`, or `None`. |

Raises:

| Type | Description |
| --- | --- |
| `RuntimeError` | The model declares no primary key. |

Examples:

```python
assert await Author.get_or_none(99) is None
```

### refresh

```python
refresh(*, using: str | None = None, session: Session | None = None) -> None
```

Reload the instance's fields from its row, in place.

A change made in memory and not saved is lost. See [`refresh()`](<https://ferro-orm.x54.sh/guide/mutations/#refresh>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `using` | `str \| None` | The named connection to read from. Defaults to `None`, the session's connection, or the one the instance was loaded from. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Raises:

| Type | Description |
| --- | --- |
| `ModelDoesNotExist` | The row no longer exists. |
| `RuntimeError` | The instance has no primary key value. |

Examples:

```python
post = await Post.get(1)
post.views = 0
await post.refresh()
assert post.views == 1843
```

### load

```python
load() -> Self
```

Fill an unloaded instance from its row, in place, and return it.

A forward relation nothing loaded reads as an unloaded instance that holds only its primary key. `load()` reads the row through the connection the instance came from and fills the same object, so every reference to it sees the row. On a complete instance it sends no statement. See [Loaded relations](<https://ferro-orm.x54.sh/guide/queries/#loading-relations-with-include>).

Returns:

| Type | Description |
| --- | --- |
| `Self` | The instance itself, now complete. |

Raises:

| Type | Description |
| --- | --- |
| `ModelDoesNotExist` | The row no longer exists. |

Examples:

```python
async with engines.session():  # a session that holds no author yet
    post = await Post.get(1)
    author = await post.author.load()
    assert author is post.author
    assert author.name == "Ada Lovelace"
```

### where

```python
where(predicate: Predicate[Self], *, session: Session | None = None) -> Query[Self]
```

Start a query filtered by a lambda predicate.

The lambda receives a stand-in for one row; comparing its fields builds the SQL condition. Name the parameter after the model, in lowercase. A field name the model does not declare raises when the query is built. See [Queries](<https://ferro-orm.x54.sh/guide/queries/#filtering-with-where>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `predicate` | `Predicate[Self]` | A lambda that takes the row stand-in and returns a condition, such as `lambda post: post.views > 1000`. | *required* |
| `session` | `Session \| None` | The session the query runs in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `Query[Self]` | A query over the matching rows; nothing runs until you await one of its methods, such as `all`. |

Examples:

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

### select

```python
select(*, session: Session | None = None) -> Query[Self]
```

```python
select(selector: RowSelector[Self], *, session: Session | None = None) -> ProjectedQuery[Self]
```

```python
select(*columns: str, session: Session | None = None) -> ProjectedQuery[Self]
```

```python
select(*selectors: RowSelector[Self] | str, session: Session | None = None) -> Query[Self] | ProjectedQuery[Self]
```

Start a query, of whole records or of some columns.

With no argument, the query returns model instances. With a lambda that picks fields, or with column names, it returns `Row` records holding only those columns. See [Selecting a column subset](<https://ferro-orm.x54.sh/guide/queries/#selecting-a-column-subset>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*selectors` | `RowSelector[Self] \| str` | Nothing; one lambda returning a field, a tuple of fields or a dict naming them; or column names as strings. | `()` |
| `session` | `Session \| None` | The session the query runs in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `Query[Self] \| ProjectedQuery[Self]` | A `Query` with no selector, otherwise a `ProjectedQuery`. |

Raises:

| Type | Description |
| --- | --- |
| `AttributeError` | A selector names a column the model does not have. |
| `TypeError` | The selectors mix a lambda with column names, or are not a lambda or strings. |
| `ValueError` | The selection is empty, two fields share an output name, or a string names a related column. |

Examples:

```python
rows = await Post.select(lambda post: (post.title, post.views)).order_by(lambda post: post.id).all()
assert rows[0].title == "Notes on the Analytical Engine"
assert rows[0].views == 1843
```

### using

```python
using(name: str) -> ModelConnection[Self]
```

Run this model's operations on a named connection.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `name` | `str` | The connection's name, as given to `connect(..., name=...)`. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `ModelConnection[Self]` | An object with this model's `create`, `get`, `where` and other class methods, each running on `name`. |

Examples:

```python
from ferro import connect, engines

await connect("sqlite::memory:", name="archive", auto_migrate=True)
async with engines.session("archive"):
    await Author.using("archive").create(name="Mary Somerville", email="mary@example.com")
    archived = await Author.using("archive").all()

assert [author.name for author in archived] == ["Mary Somerville"]
```

### create

```python
create(*, session: Session | None = None, **fields: Any) -> Self
```

Insert a new record and return it.

`create` always inserts; use `upsert` to update a row whose primary key exists.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `**fields` | `Any` | The field values. A forward relation is set through its foreign-key column, `team_id=team.id`, never by its own name. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `Self` | The saved instance, with a generated primary key filled in. |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | A keyword names a forward relation, or a retired or generated field. |
| `ValidationError` | A keyword names no field, or a value does not validate. |
| `UniqueViolationError` | A row with the same primary key or unique value exists. |

Examples:

```python
mary = await Author.create(name="Mary Somerville", email="mary@example.com")
assert mary.id == 3
```

### upsert

```python
upsert(*, session: Session | None = None, **fields: Any) -> Self
```

Insert a record, or update the row that has its primary key.

Without a primary key value, an auto-increment key has nothing to conflict on and the record is inserted.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `**fields` | `Any` | The field values, including the primary key. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `Self` | The saved instance. |

Examples:

```python
await Author.upsert(id=1, name="Ada King", email="ada@example.com")
assert (await Author.get(1)).name == "Ada King"
```

### bulk\_create

```python
bulk_create(instances: list[Self], *, using: str | None = None, session: Session | None = None) -> int
```

Insert many new records in one call.

Every record is inserted or none is. Ferro splits a batch too large for one statement into several, inside the same all-or-nothing boundary. See [Creating rows](<https://ferro-orm.x54.sh/guide/mutations/#creating-rows>).

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `instances` | `list[Self]` | The instances to insert. | *required* |
| `using` | `str \| None` | The named connection to write on. Defaults to `None`, the session's connection. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |

Returns:

| Type | Description |
| --- | --- |
| `int` | The number of rows inserted. |

Examples:

```python
inserted = await Author.bulk_create(
    [
        Author(name="Mary Somerville", email="mary@example.com"),
        Author(name="Hedy Lamarr", email="hedy@example.com"),
    ]
)
assert inserted == 2
```

### get\_or\_create

```python
get_or_create(defaults: dict[str, Any] | None = None, *, session: Session | None = None, **fields: Any) -> tuple[Self, bool]
```

Fetch the first record whose fields match, or create it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `defaults` | `dict[str, Any] \| None` | Extra field values used only when creating. Defaults to `None`. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `**fields` | `Any` | The values to match exactly, also used when creating. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `tuple[Self, bool]` | The record, and `True` when it was created or `False` when it was found. |

Examples:

```python
author, created = await Author.get_or_create(
    email="mary@example.com", defaults={"name": "Mary Somerville"}
)
assert created is True

again, created = await Author.get_or_create(email="mary@example.com")
assert created is False
assert again is author
```

### update\_or\_create

```python
update_or_create(defaults: dict[str, Any] | None = None, *, session: Session | None = None, **fields: Any) -> tuple[Self, bool]
```

Update the first record whose fields match, or create it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `defaults` | `dict[str, Any] \| None` | The field values to write, on the found record or the new one. Defaults to `None`. | `None` |
| `session` | `Session \| None` | The session to run in. Defaults to `None`, the session opened by the enclosing `async with engines.session():`. | `None` |
| `**fields` | `Any` | The values to match exactly, also used when creating. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `tuple[Self, bool]` | The record, and `True` when it was created or `False` when it was updated. |

Examples:

```python
author, created = await Author.update_or_create(
    email="ada@example.com", defaults={"name": "Ada King"}
)
assert created is False
assert author.name == "Ada King"
```

## Routing one call

`Model.using(name)` binds the model's class methods to one named connection and returns a `ModelConnection`.

## ModelConnection

```python
ModelConnection(model_cls: type[M], connection_name: str)
```

A model's class methods bound to one named connection.

`Model.using` returns one. Each method behaves like the model's class method of the same name and runs on the bound connection.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `model_cls` | `type[M]` | The model class. | *required* |
| `connection_name` | `str` | The name of the connection to run on. | *required* |

Methods:

| Name | Description |
| --- | --- |
| `create` | Insert a new record on the connection and return it. |
| `upsert` | Insert a record on the connection, or update the row with its primary key. |
| `all` | Fetch every row of the model's table on the connection. |
| `select` | Start a query of whole records on the connection. |
| `where` | Start a query on the connection, filtered by a lambda predicate. |
| `get` | Fetch one record by primary key on the connection. |
| `get_or_none` | Fetch one record by primary key on the connection, or `None`. |
| `bulk_create` | Insert many new records on the connection in one call. |
| `get_or_create` | Fetch the first matching record on the connection, or create it. |
| `update_or_create` | Update the first matching record on the connection, or create it. |

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `model_cls` | `type[M]` | The bound model class. |

### model\_cls

```python
model_cls: type[M] = model_cls
```

The bound model class.

### create

```python
create(**fields: Any) -> M
```

Insert a new record on the connection and return it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `**fields` | `Any` | The field values. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `M` | The saved instance. |

Raises:

| Type | Description |
| --- | --- |
| `UniqueViolationError` | A row with the same primary key or unique value exists. |

### upsert

```python
upsert(**fields: Any) -> M
```

Insert a record on the connection, or update the row with its primary key.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `**fields` | `Any` | The field values, including the primary key. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `M` | The saved instance. |

### all

```python
all() -> list[M]
```

Fetch every row of the model's table on the connection.

Returns:

| Type | Description |
| --- | --- |
| `list[M]` | One instance per row. |

### select

```python
select() -> Query[M]
```

Start a query of whole records on the connection.

Returns:

| Type | Description |
| --- | --- |
| `Query[M]` | A query over every row. |

### where

```python
where(predicate: Predicate[M]) -> Query[M]
```

Start a query on the connection, filtered by a lambda predicate.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `predicate` | `Predicate[M]` | A lambda that takes the row stand-in and returns a condition. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `Query[M]` | A query over the matching rows. |

### get

```python
get(pk: Any) -> M
```

Fetch one record by primary key on the connection.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `pk` | `Any` | The primary key value to look up. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `M` | The record whose primary key is `pk`. |

Raises:

| Type | Description |
| --- | --- |
| `ModelDoesNotExist` | No row has that key. |

### get\_or\_none

```python
get_or_none(pk: Any) -> M | None
```

Fetch one record by primary key on the connection, or `None`.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `pk` | `Any` | The primary key value to look up. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `M \| None` | The record whose primary key is `pk`, or `None`. |

Raises:

| Type | Description |
| --- | --- |
| `RuntimeError` | The model declares no primary key. |

### bulk\_create

```python
bulk_create(instances: list[M]) -> int
```

Insert many new records on the connection in one call.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `instances` | `list[M]` | The instances to insert. | *required* |

Returns:

| Type | Description |
| --- | --- |
| `int` | The number of rows inserted. |

### get\_or\_create

```python
get_or_create(defaults: dict[str, Any] | None = None, **fields: Any) -> tuple[M, bool]
```

Fetch the first matching record on the connection, or create it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `defaults` | `dict[str, Any] \| None` | Extra field values used only when creating. Defaults to `None`. | `None` |
| `**fields` | `Any` | The values to match exactly, also used when creating. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `tuple[M, bool]` | The record, and whether it was created. |

### update\_or\_create

```python
update_or_create(defaults: dict[str, Any] | None = None, **fields: Any) -> tuple[M, bool]
```

Update the first matching record on the connection, or create it.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `defaults` | `dict[str, Any] \| None` | The field values to write, on the found record or the new one. Defaults to `None`. | `None` |
| `**fields` | `Any` | The values to match exactly, also used when creating. | `{}` |

Returns:

| Type | Description |
| --- | --- |
| `tuple[M, bool]` | The record, and whether it was created. |

## Table-level declarations

A model declares its table checks in `__ferro_checks__` and its row security in `__ferro_rls__`; see [Table checks](<https://ferro-orm.x54.sh/guide/models-and-fields/#table-checks>) and [Using with Postgres RLS](<https://ferro-orm.x54.sh/guide/row-level-security/index.md>).

## Check

```python
Check(suffix: str, predicate: Predicate[Any])
```

A `CHECK` constraint across the columns of one row, declared in `__ferro_checks__`.

Ferro names the constraint `ck_<table>_<suffix>` and writes it inside `CREATE TABLE`, on SQLite and Postgres alike. The predicate is a lambda written like a `where` filter. See [Table checks](<https://ferro-orm.x54.sh/guide/models-and-fields/#table-checks>) for the predicates it accepts.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `suffix` | `str` | The end of the constraint's name: a lowercase identifier (`[a-z][a-z0-9_]*`), unique within the model, without the `ck_<table>_` prefix Ferro adds. | *required* |
| `predicate` | `Predicate[Any]` | A lambda over the model's own columns, its parameter named after the model. | *required* |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | `suffix` is not a lowercase identifier or starts with `ck_`, or `predicate` is not callable. |

Examples:

```python
from typing import ClassVar

from ferro import Check, CheckViolationError, Field, Model, create_tables


class Payment(Model):
    __ferro_checks__: ClassVar[tuple[Check, ...]] = (
        Check("positive_amount", lambda payment: payment.amount > 0),
    )

    id: int | None = Field(default=None, primary_key=True)
    amount: int


await create_tables()
try:
    await Payment.create(amount=0)
except CheckViolationError as error:
    assert "ck_payment_positive_amount" in str(error)
else:
    raise AssertionError("expected CheckViolationError")
```

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `suffix` | `str` | The constraint name's suffix, after `ck_<table>_`. |
| `predicate` | `Predicate[Any]` | The lambda the constraint's body is rendered from. |

### suffix

```python
suffix: str
```

The constraint name's suffix, after `ck_<table>_`.

### predicate

```python
predicate: Predicate[Any]
```

The lambda the constraint's body is rendered from.

## RowSecurity

```python
RowSecurity(*policies: RowPolicy, force: bool = True)
```

A model's row security: its policies and the table's flags.

Assign it to the model's `__ferro_rls__`. On Postgres the table gets `ENABLE ROW LEVEL SECURITY` and one `CREATE POLICY` per policy; on SQLite, which has no row security, Ferro warns and creates the table without them. See [Scope rows by tenant](<https://ferro-orm.x54.sh/guide/row-level-security/index.md>) for the setup.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `*policies` | `RowPolicy` | The table's policies. | `()` |
| `force` | `bool` | Also emit `FORCE ROW LEVEL SECURITY`, so the policies apply to the table's owner too. Defaults to `True`; without it, an application that connects as the owner is never filtered. See [`FORCE` and `BYPASSRLS`](<https://ferro-orm.x54.sh/concepts/row-level-security/#force-and-bypassrls>). | `True` |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | A policy is not a `RowPolicy`, or `force` is not a `bool`. |

Examples:

```python
from typing import ClassVar
from uuid import UUID

from ferro import Field, Model, RowPolicy, RowSecurity


class Invoice(Model):
    id: int | None = Field(default=None, primary_key=True)
    tenant_id: UUID
    total: int

    __ferro_rls__: ClassVar = RowSecurity(
        RowPolicy(column="tenant_id", setting="app.tenant_id")
    )
```

On Postgres, `Invoice`'s table is created with:

```sql
ALTER TABLE "invoice" ENABLE ROW LEVEL SECURITY
ALTER TABLE "invoice" FORCE ROW LEVEL SECURITY
CREATE POLICY "rls_invoice_tenant_id" ON "invoice" FOR ALL
  USING ("tenant_id" = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
  WITH CHECK ("tenant_id" = NULLIF(current_setting('app.tenant_id', true), '')::uuid)
```

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `policies` | `tuple[RowPolicy, ...]` | The table's policies, in declaration order. |
| `force` | `bool` | Whether the table also gets `FORCE ROW LEVEL SECURITY`. |

### policies

```python
policies: tuple[RowPolicy, ...]
```

The table's policies, in declaration order.

### force

```python
force: bool = True
```

Whether the table also gets `FORCE ROW LEVEL SECURITY`.

## RowPolicy

```python
RowPolicy(name: str | None = None, command: str = 'all', restrictive: bool = False, column: str | None = None, setting: str | None = None, using: str | None = None, with_check: str | None = None)
```

One Postgres row policy: which rows a command may read or write.

It comes in two forms. The shorthand, `RowPolicy(column=..., setting=...)`, compares a column with a session setting and renders, for both `USING` and `WITH CHECK`:

```sql
"tenant_id" = NULLIF(current_setting('app.tenant_id', true), '')::uuid
```

The cast follows the column's type: `uuid`, `text`, `varchar` and the integer types are supported, and any other type is refused when the class is defined. The `NULLIF` makes an unset or reset setting match no rows instead of raising a cast error; see [Policy expressions](<https://ferro-orm.x54.sh/concepts/row-level-security/#policy-expressions>). The raw form, `RowPolicy(name=..., using=...)`, takes the SQL expressions as written and needs a name.

Parameters:

| Name | Type | Description | Default |
| --- | --- | --- | --- |
| `name` | `str \| None` | The end of the policy's name, `rls_<table>_<name>`: a lowercase identifier. Defaults to `None`, the column's name in the shorthand; required in the raw form. | `None` |
| `command` | `str` | The command the policy covers: `"all"` (the default), `"select"`, `"insert"`, `"update"` or `"delete"`. | `'all'` |
| `restrictive` | `bool` | Make the policy `AS RESTRICTIVE`, so it must hold alongside every other policy instead of being one alternative. Defaults to `False`. | `False` |
| `column` | `str \| None` | Shorthand: the model column holding the scope value. | `None` |
| `setting` | `str \| None` | Shorthand: the dotted Postgres setting to compare it with, such as `"app.tenant_id"`. | `None` |
| `using` | `str \| None` | Raw: the `USING` expression, which decides the rows a command can see. | `None` |
| `with_check` | `str \| None` | Raw: the `WITH CHECK` expression, which decides the rows a write may leave behind. | `None` |

Raises:

| Type | Description |
| --- | --- |
| `TypeError` | The two forms are mixed or neither is given, a clause is one the command does not accept, or a name, command or flag has the wrong shape. |
| `ValueError` | `setting` is not a dotted custom setting name. |

Examples:

```python
from ferro import RowPolicy

tenant = RowPolicy(column="tenant_id", setting="app.tenant_id")
invitee = RowPolicy(
    name="invitee_read",
    command="select",
    using="id IN (SELECT document_id FROM membership)",
)
assert (tenant.resolved_name, invitee.resolved_name) == ("tenant_id", "invitee_read")
```

Attributes:

| Name | Type | Description |
| --- | --- | --- |
| `name` | `str \| None` | The policy name's suffix, or `None` for the shorthand's column name. |
| `command` | `str` | The command the policy covers. |
| `restrictive` | `bool` | Whether the policy is `AS RESTRICTIVE`. |
| `column` | `str \| None` | Shorthand: the column holding the scope value. |
| `setting` | `str \| None` | Shorthand: the Postgres setting the column is compared with. |
| `using` | `str \| None` | Raw: the `USING` expression. |
| `with_check` | `str \| None` | Raw: the `WITH CHECK` expression. |
| `resolved_name` | `str` | The policy name's suffix: `name`, or the column in the shorthand. |

### name

```python
name: str | None = None
```

The policy name's suffix, or `None` for the shorthand's column name.

### command

```python
command: str = 'all'
```

The command the policy covers.

### restrictive

```python
restrictive: bool = False
```

Whether the policy is `AS RESTRICTIVE`.

### column

```python
column: str | None = None
```

Shorthand: the column holding the scope value.

### setting

```python
setting: str | None = None
```

Shorthand: the Postgres setting the column is compared with.

### using

```python
using: str | None = None
```

Raw: the `USING` expression.

### with\_check

```python
with_check: str | None = None
```

Raw: the `WITH CHECK` expression.

### resolved\_name

```python
resolved_name: str
```

The policy name's suffix: `name`, or the column in the shorthand.
