SQLAlchemy 2.1.0 went final on September 24, 2026, and the announcement says a plain pip install sqlalchemy now gives you 2.1. The latest patch on PyPI is 2.1.9, from November 16. If your dependency line reads sqlalchemy>=2.0, the next fresh Docker build pulls the new minor whether you planned the upgrade or not.

Most of 2.1 is additive. A few changes are not, and four of them can break an async service in ways that do not show up until runtime: the greenlet dependency moved behind an extra, bare postgresql:// URLs now pick psycopg 3, autoflush now runs before raw text() statements, and filter_by() stopped guessing which table you meant. All four are in the official What's New in SQLAlchemy 2.1 guide.

Each one gets a small adapter test below. Write them while you are still on 2.0, make them green, then bump the pin and run them again.

One precondition comes before any test. The migration guide says 2.1 starts at Python 3.11, with 3.10 dropped ahead of its October 2026 end of life. PyPI lists Requires: Python >=3.11 for the current release.

That floor fails quietly. With a loose >=2.0 pin on a 3.10 image, pip compares Requires-Python against the runtime and installs the last release that still supports it. You stay on 2.0.x, your laptop on 3.12 gets 2.1, and the two environments drift apart without an error. Fix the base image first, and set requires-python = ">=3.11" in pyproject.toml, so installing the project on 3.10 fails loudly instead of resolving to 2.0.x. If your image installs from a requirements file, pin sqlalchemy>=2.1 there too.

Where the upgrade lands in a hexagonal codebase

In a ports-and-adapters layout, the domain and the use cases talk to a repository port. Only one package imports SQLAlchemy. That turns "upgrade the ORM" into "upgrade one folder", and you can check the claim with one command before you start:

grep -rl "sqlalchemy" src/ | grep -v "adapters/sqlalchemy" 

If that prints nothing, every change below lands in src/orders/adapters/sqlalchemy/ plus pyproject.toml. If it prints files, those files are where the upgrade will surprise you, and they are worth moving behind the port first.

A hexagon-shaped core with one outer segment lifted out and swapped by a crane, the rest of the hexagon untouched
The ORM sits in one adapter segment, so the upgrade swaps one piece.

The adapter used in the tests is small. Two tables, one repository:

# src/orders/adapters/sqlalchemy/models.py from sqlalchemy import ForeignKey from sqlalchemy.orm import ( DeclarativeBase, Mapped, mapped_column, relationship, ) class Base(DeclarativeBase): pass class CustomerRow(Base): __tablename__ = "customers" id: Mapped[int] = mapped_column(primary_key=True) name: Mapped[str] class OrderRow(Base): __tablename__ = "orders" id: Mapped[int] = mapped_column(primary_key=True) customer_id: Mapped[int] = mapped_column( ForeignKey("customers.id") ) status: Mapped[str] customer: Mapped[CustomerRow] = relationship() 

The test fixtures use pytest, pytest-asyncio and aiosqlite so the file runs anywhere. In CI, point the same fixture at the Postgres you run in production.

# tests/adapters/sqlalchemy/conftest.py import pytest_asyncio from sqlalchemy.ext.asyncio import create_async_engine from orders.adapters.sqlalchemy.engine import make_sessions from orders.adapters.sqlalchemy.models import Base @pytest_asyncio.fixture async def engine(tmp_path): url = f"sqlite+aiosqlite:///{tmp_path / 'test.db'}" eng = create_async_engine(url) async with eng.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield eng await eng.dispose() @pytest_asyncio.fixture async def session(engine): async with make_sessions(engine)() as s: yield s 

Change 1: greenlet only comes with the [asyncio] extra

The release notes say greenlet no longer installs by default and is still required for every asyncio feature. The asyncio extension docs give the install line: pip install sqlalchemy[asyncio].

The trap is that an existing virtualenv keeps the greenlet it already has, so the upgrade looks fine on your machine. The fresh build in CI or Docker is the one without it. The test checks for the package and then makes the engine do real async I/O:

# tests/adapters/sqlalchemy/test_upgrade_21.py from importlib.util import find_spec import pytest from sqlalchemy import text @pytest.mark.asyncio async def test_async_engine_round_trip(engine): assert find_spec("greenlet") is not None async with engine.connect() as conn: assert await conn.scalar(text("select 1")) == 1 

The fix lives in one line of pyproject.toml: "sqlalchemy[asyncio]>=2.1,<2.2". Run this test in a brand-new environment, never only in the one you upgraded in place.

Change 2: postgresql:// now means psycopg 3

The migration guide says the default PostgreSQL DBAPI changed from psycopg2 to psycopg (version 3). A URL with no +driver part now tries to load psycopg. psycopg2 is still fully supported, but only when you name it: postgresql+psycopg2://.

Your async app URL probably already says postgresql+asyncpg://, since asyncpg has to be named to be used. The bare URL tends to hide in the sync side: Alembic's alembic.ini, a seed script, a one-off admin command. Make the adapter own both URLs and name both drivers:

# src/orders/adapters/sqlalchemy/engine.py from sqlalchemy.engine import URL, make_url from sqlalchemy.ext.asyncio import ( AsyncEngine, async_sessionmaker, create_async_engine, ) APP_DRIVER = "postgresql+asyncpg" MIGRATION_DRIVER = "postgresql+psycopg" # or +psycopg2 def app_url(raw: str) -> URL: return make_url(raw).set(drivername=APP_DRIVER) def migration_url(raw: str) -> URL: return make_url(raw).set(drivername=MIGRATION_DRIVER) def make_engine(raw: str) -> AsyncEngine: return create_async_engine(app_url(raw)) def make_sessions(engine: AsyncEngine): return async_sessionmaker(engine, expire_on_commit=False) 

Point Alembic's env.py and any scripts at migration_url(), so this module is the only place that knows a driver name. The test pins the decision and checks that the DBAPI you named is installed:

# same test file, continued from orders.adapters.sqlalchemy.engine import ( app_url, migration_url, ) RAW = "postgresql:///orders" def test_urls_name_their_driver(): assert app_url(RAW).get_driver_name() == "asyncpg" assert migration_url(RAW).get_driver_name() == "psycopg" def test_named_drivers_are_installed(): assert find_spec("asyncpg") is not None assert find_spec("psycopg") is not None 

URL.get_driver_name() returns the part after the + when it is there, and falls back to the dialect's default driver when it is not. That fallback is exactly what changed in 2.1, which is why the adapter never hands SQLAlchemy a bare URL. If you stay on psycopg2, change MIGRATION_DRIVER and the expected string, and the test still guards the choice.

Change 3: autoflush now runs before text()

In 2.0, session.execute(select(OrderRow)) autoflushed and session.execute(text("select * from orders")) did not. In 2.1 both do: the guide calls the new rule unconditional, a flush on every execution, Core or ORM.

That changes results without changing code. A repository method that counts rows with raw SQL used to miss objects you had added but not flushed. After the bump it sees them. It also moves errors: an IntegrityError from a pending object can now surface on a line that only reads, because that read is where the flush happens.

Pending parcels pushed through a gate onto a shelf just before a magnifying lens inspects the shelf
In 2.1, pending objects reach the database before any statement runs, raw SQL included.

Stop depending on the implicit rule. Flush explicitly where the adapter needs pending rows to be visible, so 2.0 and 2.1 return the same answer:

# src/orders/adapters/sqlalchemy/repository.py from sqlalchemy import select, text from sqlalchemy.ext.asyncio import AsyncSession from .models import OrderRow class SqlOrderRepository: def __init__(self, session: AsyncSession) -> None: self._session = session def add(self, order: OrderRow) -> None: self._session.add(order) async def count_pending(self) -> int: await self._session.flush() result = await self._session.execute( text( "select count(*) from orders" " where status = 'pending'" ) ) return result.scalar_one() async def get_with_customer( self, order_id: int ) -> OrderRow | None: stmt = ( select(OrderRow) .join(OrderRow.customer) .where(OrderRow.id == order_id) ) return await self._session.scalar(stmt) 

The real repository maps rows to domain objects before returning them; that mapping is trimmed here. The test:

# same test file, continued from orders.adapters.sqlalchemy.models import ( CustomerRow, OrderRow, ) from orders.adapters.sqlalchemy.repository import ( SqlOrderRepository, ) @pytest.mark.asyncio async def test_raw_count_sees_unflushed_add(session): session.add(CustomerRow(id=7, name="Acme Ltd")) repo = SqlOrderRepository(session) repo.add(OrderRow(id=1, customer_id=7, status="pending")) assert await repo.count_pending() == 1 

Delete the flush() line and this test fails on 2.0, then passes on 2.1. With the line in, it passes on both, and the behavior no longer depends on which minor version is installed.

Change 4: filter_by() stops guessing

In 2.0, Select.filter_by() looked only at the last joined entity or the first FROM entity. In 2.1 it searches every entity in the FROM clause, and a name that exists in more than one now raises AmbiguousColumnError. The legacy Query.filter_by() is unchanged.

Look at what that means for an easy line to write:

stmt = ( select(OrderRow) .join(OrderRow.customer) .filter_by(id=order_id) ) 

On 2.0 the last joined entity is CustomerRow, so this filters on the customer's id and quietly returns the wrong order, or none. On 2.1 it raises, because both tables have an id. The repository above already uses .where(OrderRow.id == order_id), which means the same thing on both versions. The test uses data where the two ids differ, so the old bug cannot hide:

@pytest.mark.asyncio async def test_get_with_customer_uses_order_id(session): session.add(CustomerRow(id=7, name="Acme Ltd")) session.add(OrderRow(id=1, customer_id=7, status="pending")) await session.flush() repo = SqlOrderRepository(session) found = await repo.get_with_customer(1) assert found is not None assert found.id == 1 

With filter_by(id=...) this test fails on 2.0 and errors on 2.1. With the explicit where(), it passes on both. The test deliberately does not import AmbiguousColumnError: that class only exists from 2.1, and the file has to load on 2.0 too.

The bump, in order

  1. Stay on the 2.0 pin. Add the four tests and make them green by fixing the adapter: explicit driver names, an explicit flush(), explicit where() clauses.
  2. Move the base image to Python 3.11 or newer and set requires-python.
  3. Change one dependency line to "sqlalchemy[asyncio]>=2.1,<2.2" and add psycopg[binary] if you chose psycopg 3.
  4. Build a fresh environment and run pytest tests/adapters/sqlalchemy first. Then the full suite.

Steps 1 and 4 run the same tests. If they pass on 2.0 and on 2.1, the version number stopped mattering to the rest of your code, which is the reason the ORM sits behind a port in the first place.

The migration guide lists other changes these four tests do not cover, including new rules for dataclass defaults and how loader options apply across paths. Read it once with your adapter folder open next to it.

If this was useful

The upgrade stayed inside one folder because the domain never imported SQLAlchemy. That boundary is what Hexagonal Architecture in Python is about: it builds one async FastAPI and SQLAlchemy 2 service five ways (Hexagonal, Clean, Onion, layered, vertical slice), then measures the trade-offs, so you can see what keeping the database behind a port buys you and what it costs. Every listing runs from the free companion repo, so you can try the adapter tests against a real layout.

Hexagonal Architecture in Python by Gabriel Anhaia