SQLAlchemy released 2.1.10 and 2.0.59 on 4 December 2026. These are patch releases, so there are no big new APIs. But a few of the fixes change behaviour you may rely on today. One closes a SQL injection path through identifiers and inline literals. Another changes what objects in your session look like after a bulk UPDATE. A third maps asyncpg errors to more specific exception classes, which can change which except block catches them.

This post explains the changes that matter most, with code I ran against SQLAlchemy 2.1.10 on Python 3.14. The source is the official 2.1.10 release notes. Most fixes are also backported to 2.0.59.

How to upgrade

# 2.1 series
pip install -U "sqlalchemy==2.1.10"

# still on 2.0? the backports land in 2.0.59
pip install -U "sqlalchemy==2.0.59"

# using asyncio? install the extra so greenlet is present
pip install -U "sqlalchemy[asyncio]==2.1.10"

SQLAlchemy 2.1 requires Python 3.11 or newer, according to PyPI.

1. Placeholder tokens can no longer smuggle SQL

Internally, SQLAlchemy uses placeholder tokens such as __[POSTCOMPILE_name] and __[SCHEMA_name] in compiled SQL and swaps them for real values at execution time. Before this release, a label, column name, table name or inline literal that contained one of those tokens had that text replaced too. That broke its quoting. If the name or value came from user input, someone could inject SQL.

From 2.1.10 and 2.0.59, identifiers and inline literal values that contain __[ followed by an uppercase word and an underscore are refused with a CompileError:

import sqlalchemy as sa
from sqlalchemy import select, String
from sqlalchemy.exc import CompileError

engine = sa.create_engine("sqlite://")

try:
    stmt = select(sa.literal("__[POSTCOMPILE_x]", String))
    stmt.compile(engine, compile_kwargs={"literal_binds": True})
except CompileError as e:
    print(e)
# Literal value '__[POSTCOMPILE_x]' contains '__[POSTCOMPILE_',
# which is reserved for SQLAlchemy placeholder tokens

try:
    t = sa.table("t", sa.column("__[SCHEMA_x]"))
    select(t).compile(engine)
except CompileError as e:
    print(e)
# Identifier '__[SCHEMA_x]' contains '__[SCHEMA_', ...

Bound parameters, the default, are not affected. This still works and returns the string unchanged:

with engine.connect() as conn:
    value = conn.execute(select(sa.bindparam("v", "__[POSTCOMPILE_x]"))).scalar()
    print(value)  # __[POSTCOMPILE_x]

What to check in your code

Search for places where user input becomes an identifier or an inline literal:

  • dynamic column or table names built from request data (sort keys, report builders, multi-tenant schema names)
  • literal_binds=True used to render SQL for logs or exports
  • label() names taken from user input

Even with this fix, the safe pattern doesn’t change. Pass values as bound parameters, and map user choices to a fixed allow-list of column objects:

SORTABLE = {"name": User.name, "created": User.created_at}
column = SORTABLE.get(request_sort, User.id)
stmt = select(User).order_by(column)

Note that raw text you pass yourself through literal_column() or text() is still your responsibility. SQLAlchemy can’t tell your SQL fragments apart from an attacker’s.

2. Bulk UPDATE with synchronize_session now matches SQL semantics

When you run an ORM-enabled update() with synchronize_session="evaluate", SQLAlchemy evaluates the SET and WHERE expressions in Python and patches the objects already loaded in your Session. Several bugs meant those in-memory objects could disagree with the database. The release notes list the fixes:

  • SET expressions that read other columns being SET now see the values from before the UPDATE, as SQL does.
  • A SET expression that reads an expired attribute now expires the target attribute, instead of storing an internal placeholder.
  • Objects whose WHERE-criteria attributes are expired are now expired as a whole.
  • Python evaluation follows SQL’s NULL rules for AND, IN and NOT IN, including empty IN lists.
  • Integer modulus takes the sign of the dividend, as in SQL.

Here’s the first fix in action:

from sqlalchemy import create_engine, select, update
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, Session

class Base(DeclarativeBase):
    pass

class Account(Base):
    __tablename__ = "account"
    id: Mapped[int] = mapped_column(primary_key=True)
    balance: Mapped[int]
    bonus: Mapped[int]

engine = create_engine("sqlite://")
Base.metadata.create_all(engine)

with Session(engine) as s:
    s.add(Account(id=1, balance=100, bonus=0))
    s.commit()
    acct = s.get(Account, 1)

    s.execute(
        update(Account)
        .where(Account.id == 1)
        .values(balance=Account.balance + 50, bonus=Account.balance)
        .execution_options(synchronize_session="evaluate")
    )
    print(acct.balance, acct.bonus)  # 150 100  (bonus = old balance)
    s.commit()
    print(s.scalars(select(Account.bonus)).one())  # 100

On 2.1.10 the in-session object and the database agree: bonus is the old balance, 100. If you have tests that assert on objects after bulk updates, run them after upgrading. A test that passed by accident may now fail, or the reverse.

3. Loader criteria no longer leak into deeper levels

PropComparator.and_() inside selectinload(), lazyload() or subqueryload() used to filter the next level of a self-referential relationship as well. For example, filtering a category’s children to “active” also filtered the grandchildren. Now the criteria apply only to the relationship the option names, which matches how joinedload() already worked.

from sqlalchemy.orm import selectinload

stmt = select(Category).options(
    selectinload(Category.children.and_(Category.active.is_(True)))
)

After upgrading, deeper levels may load more rows than before. To keep the old behaviour, add and_() for each level, or use selectinload(..., recursion_depth=N), where the criteria apply at every level the recursion loads.

4. asyncpg errors get proper exception classes

Before this fix, the asyncpg dialect raised a plain DBAPIError for most PostgreSQL errors. Now each SQLSTATE class maps to the same PEP 249 exception psycopg uses. For example, a data exception raises DataError, and a deadlock or serialization failure raises OperationalError.

Code that catches DBAPIError is unaffected, because all of these are subclasses. But if your asyncpg app catches OperationalError or DatabaseError for a specific purpose, such as reconnect logic, it may now also receive deadlocks, serialization failures and statement timeouts there. Review those handlers:

from sqlalchemy.exc import OperationalError

try:
    await session.commit()
except OperationalError as e:
    sqlstate = getattr(e.orig, "sqlstate", None)
    if sqlstate in {"40001", "40P01"}:  # serialization failure, deadlock
        ...  # retry the transaction
    else:
        raise

5. New: two-phase transactions in asyncio

2.1.10 adds two-phase commit support to the asyncio extension. AsyncConnection.begin_twophase() returns an AsyncTransaction with prepare(), is_two_phase and xid. There are also recover_twophase(), commit_prepared() and rollback_prepared() proxies.

async with engine.connect() as conn:
    tx = await conn.begin_twophase()
    await conn.execute(text("UPDATE ledger SET amount = amount - 10 WHERE id = 1"))
    await tx.prepare()
    await tx.commit()

Two-phase commit needs database support. PostgreSQL, for example, requires max_prepared_transactions above zero.

Smaller fixes worth a look

  • MySQL: “Packet sequence number wrong” from PyMySQL, aiomysql and asyncmy now counts as a disconnect, so pool_pre_ping replaces the connection instead of raising.
  • aiosqlite: cancelling a task mid-statement no longer leaves the database file locked.
  • SQL Server: an INSERT whose scope_identity() returns NULL now gives None instead of a TypeError.
  • Events: a rare KeyError in a weakref callback after Engine.dispose() is fixed.

Takeaway

Upgrade to 2.1.10 (or 2.0.59) soon, mainly for the placeholder-token injection fix. Then re-run tests that cover bulk UPDATE with synchronize_session, self-referential selectinload with and_(), and any asyncpg code that catches OperationalError. Those are the three places where correct new behaviour can surprise you.