Skip to content

Migrate from SQLAlchemy

This page maps each SQLAlchemy 2.0 idiom to its Ferro equivalent, using one User and Post pair throughout. Ferro keeps a session, but it only routes calls to a connection and holds an identity map: there is no add(), flush() or commit(). Open one with async with engines.session(): and write the call on the model:

async with session_factory() as session:
    user = User(username="ada", email="ada@example.com", age=36)
    session.add(user)
    await session.commit()
async with engines.session():
    ada = await User.create(username="ada", email="ada@example.com", age=36)
    assert ada.id is not None  # inserted now; the key is set

The SQLAlchemy block inserts the row on commit(). The Ferro block inserts it inside create() and returns the instance with its primary key set. The Ferro blocks below run inside a session like this one; see Connections › Sessions.

Comparison

Concept SQLAlchemy 2.0 Ferro
Model definition DeclarativeBase + Mapped / mapped_column Pydantic Model + type annotations
Validation Separate (for example Pydantic on top) The model is a Pydantic model
Querying select(User).where(...) executed on a session User.where(...) awaited inside a session
Get by primary key session.get(User, pk) returns None if missing User.get(pk) raises; User.get_or_none(pk) returns None
Sessions async_sessionmaker, session.add, commit async with engines.session(): once per request; no add or commit
Transactions async with session.begin(): async with transaction():
Relationships mapped_column() with a ForeignKey + relationship() Field(foreign_key=...) + Forward / Reverse / ManyToMany
Async Native Native (async-only)
Migrations Alembic ferro migrate, or Alembic through get_metadata() and ferro_options()

Models

The SQLAlchemy models are:

from sqlalchemy import ForeignKey
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship


class Base(DeclarativeBase):
    pass


class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    username: Mapped[str] = mapped_column(unique=True)
    email: Mapped[str]
    age: Mapped[int]
    posts: Mapped[list["Post"]] = relationship(back_populates="author")


class Post(Base):
    __tablename__ = "posts"

    id: Mapped[int] = mapped_column(primary_key=True)
    title: Mapped[str]
    author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    author: Mapped["User"] = relationship(back_populates="posts")

The Ferro models, in either declaration style, are:

from ferro import Field, Forward, Model, Relation, Reverse


class User(Model):
    id: int | None = Field(default=None, primary_key=True)
    username: str = Field(unique=True)
    email: str
    age: int

    posts: Relation[list["Post"]] = Reverse("author_id")


class Post(Model):
    id: int | None = Field(default=None, primary_key=True)
    title: str
    author_id: int = Field(foreign_key=User)

    author: Relation[User] = Forward("author_id")
from ferro import Field, Forward, Model, Relation, Reverse


class User(Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    username: Annotated[str, Field(unique=True)]
    email: str
    age: int

    posts: Relation[list["Post"]] = Reverse("author_id")


class Post(Model):
    id: Annotated[int | None, Field(primary_key=True)] = None
    title: str
    author_id: Annotated[int, Field(foreign_key=User)]

    author: Relation[User] = Forward("author_id")

The two declare the same tables; the later sections reuse these models. What changes:

  • There is no __tablename__: the table name comes from the class name (user).
  • The auto-increment primary key is int | None with default=None: it is None until the row is inserted.
  • Validation and serialization come from Pydantic, so the model doubles as your API schema.
  • author_id is declared with Field(foreign_key=User), where SQLAlchemy passes mapped_column() a ForeignKey, and Forward("author_id") names it where relationship() would. User.posts is Reverse("author_id"), naming the same column.
  • Declare fields on each concrete model. A Model base class does not pass its fields on; shared behavior goes in plain mixins, as in the Timestamps how-to.

See the Models and fields guide for every field option.

Queries

Fetch every row:

from sqlalchemy import select

async with session_factory() as session:
    result = await session.execute(select(User))
    users = result.scalars().all()
users = await User.all()
assert [user.username for user in users] == ["ada", "grace", "linus", "alan"]

Both return a list of User instances; the assert shows the Ferro list in insertion order. Filter, order and limit:

stmt = select(User).where(User.age >= 18).order_by(User.age).limit(2)
result = await session.execute(stmt)
adults = result.scalars().all()
adults = (
    await User.where(lambda user: user.age >= 18)
    .order_by(lambda user: user.age)
    .limit(2)
    .all()
)
assert [user.username for user in adults] == ["ada", "alan"]

Both return the two youngest adults as a list. Ferro takes lambda predicates named after the model; see the Queries guide for the other styles.

Get by primary key. session.get(User, pk) returns None when the row is missing. Ferro's User.get(pk) raises ModelDoesNotExist, and get_or_none is the optional variant:

user = await session.get(User, 1)
grace = await User.get(2)
assert grace.username == "grace"

try:
    await User.get(99)
except ModelDoesNotExist:
    missing = None
else:
    raise AssertionError("User.get(99) should raise ModelDoesNotExist")
assert missing is None

assert await User.get_or_none(99) is None

A hit returns the User. A miss raises, or returns None from get_or_none, which matches session.get.

See the Queries guide for the full predicate and builder API.

Creating records

create() inserts at once and returns the instance, so there is nothing to flush. Ferro also covers the common session idioms directly:

  • bulk_create([...]) inserts a batch.
  • get_or_create(...) and update_or_create(...) cover upsert-style flows.
  • upsert(...) is an insert-or-update on the primary key, like PostgreSQL ON CONFLICT DO UPDATE.
  • instance.refresh() re-reads the row, like session.refresh.

Look up a user, or create one:

user, created = await User.get_or_create(
    username="ada", defaults={"email": "other@example.com", "age": 1}
)
assert (created, user.id) == (False, ada.id)

The user ada exists, so created is False and the stored row is unchanged. See the Mutations guide for each call.

Relationships

A forward relation reads as the related instance, and a reverse relation (Reverse) is a chainable query. Nothing loads on attribute access: .load() fetches a forward relation's row, and include() loads it with the query:

post = await Post.create(title="Notes on the engine", author_id=ada.id)
await Post.create(title="Poetical science", author_id=ada.id)

author = await post.author.load()
assert author.username == "ada"

recent = await ada.posts.order_by(lambda post: post.id, "desc").limit(5).all()
assert [row.title for row in recent] == [
    "Poetical science",
    "Notes on the engine",
]

await post.author.load() returns the User, and ada.posts returns her posts, newest first. Many-to-many uses ManyToMany(through="<join table>") on one side and Reverse("<attribute>") on the other; see the Relationships guide.

Transactions

SQLAlchemy commits when session.begin() exits. Ferro's transaction() runs everything inside it on one connection and commits or rolls back together:

async with session.begin():
    session.add(User(username="margaret", email="m@example.com", age=30))
    raise RuntimeError("abort")  # rolls back
try:
    async with transaction():
        await User.create(username="margaret", email="m@example.com", age=30)
        raise RuntimeError("abort")
except RuntimeError:
    ...  # the block raised, so the insert rolled back

assert await User.where(lambda user: user.username == "margaret").count() == 0

In both, the raised error rolls the insert back, and no margaret row exists afterwards. See the Transactions guide.

Migrations

Your Alembic chain keeps working through the switch. Ferro ships a bridge that builds a SQLAlchemy MetaData from your Ferro models, and its options keep Alembic's own comparator off Ferro's tables, so alembic revision --autogenerate writes the same changes Ferro's planner decides. Pass both in env.py:

from alembic import context

from ferro.migrations import ferro_options, get_metadata

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

The block hands Alembic Ferro's metadata. Install the extra with pip install "ferro-orm[alembic]". The bridge fits while the project is in transition, or while Alembic still manages SQLAlchemy tables beside your Ferro models; see Alembic.

Once the models are all Ferro, move to Ferro's own migrations (pip install "ferro-orm[cli]"), which also write backfills and SQLite table rebuilds. Bring each database to alembic upgrade head and baseline it; no DDL runs. For development and tests, connect(url, auto_migrate=True) creates tables without migration files. See Schema management and the Migrations API.

Features without a Ferro equivalent

Some SQLAlchemy features map differently, or have no Ferro counterpart today:

  • Eager and lazy loading (joinedload / selectinload, and a lazy relationship()): forward relations load with include() in one statement, or one at a time with await post.author.load(). Reverse and ManyToMany collections are queries you run, such as await ada.posts.all().
  • Partial column selects (select(User.id, User.name)): select(lambda user: (user.id, user.username)) returns projected records; traversal and output aliases use the dict form.
  • func.sum / avg / min / max and group_by(): aggregate methods on columns (order.amount.sum()), with grouping derived from the projection. There is deliberately no group_by() chainer. having() is not built yet; filter groups in Python or use raw SQL.
  • Atomic update expressions: written as a recipe, not SQLAlchemy's update().values(...): update(lambda counter: {"n": counter.n + 1, "updated_at": now}). Keyword update() accepts literals only. update() recipes support Postgres .merge(); .concat() is planned.

Where you hit a gap, execute() and fetch_all() run full SQL with bound parameters. For what is planned, see the Roadmap.

See also