Installs into .claude/skills of the current project.
Sponsors
SSkills DirectorySkills Directory
Know which skills are safe — weekly.
SSkills DirectorySkills Directory
Is that skill safe to install?
Are you the author of Sqlalchemy Knowledge Patch?
Add the live security badge to your README. It updates with every re-scan.
[](https://www.skillsdirectory.com/skills/nevaberry-sqlalchemy-knowledge-patch)
---
name: sqlalchemy-knowledge-patch
description: SQLAlchemy
version: "2.1.9"
license: MIT
metadata:
author: Nevaberry
---
# SQLAlchemy compatibility guidance
Load this skill when changing SQLAlchemy mappings, loader options, SQL expressions,
schema reflection, connections, or database-specific behavior.
Use the topic references for complete guidance, examples, and release attribution.
## Reference index
| Reference | Topics |
| --- | --- |
| [Python, ORM, and Typing](references/python-orm-and-typing.md) | Python support and installation; Declarative annotations; dataclasses; aliases; loaders; ORM state changes |
| [Engine, SQL, and Schema](references/engine-sql-and-schema.md) | URLs; connections and transactions; cancellation; results; SQL expressions; DML; constraint DDL and schema copies |
| [PostgreSQL](references/postgresql.md) | asyncpg isolation; JSONB indexes; covering constraints; reflection; domain and enum copies |
| [MySQL, MariaDB, and SQLite](references/mysql-mariadb-and-sqlite.md) | Driver options; write limits; shared locks; index prefixes; enum escaping; SQLite reflection |
| [Oracle and SQL Server](references/oracle-and-sql-server.md) | Oracle vectors and async cleanup; SQL Server drivers, binding, division, index drops, and reflection |
## Breaking changes and deprecations
### Make subqueries explicit for ORM aliases
Passing a `Select` or `CompoundSelect` directly to `aliased()` produces a
deprecation warning and implicit subquery conversion in 2.0, and raises in 2.1.
Use `aliased(select(User).subquery())`, or
`aliased(User, select(User).subquery())` for an ORM-mapped alias.
### Declare excluded class columns explicitly
In 2.1.5, use `Unmapped[T]` with `unmapped_column()` for a table column excluded
from ORM mapping. Using `Mapper.include_properties` or `Mapper.exclude_properties`
to exclude class-declared attributes is deprecated. Use those mapper options for
columns supplied only by the table, including reflected columns.
### Validate loader targets and wildcards
`Load(User).joinedload("addresses.*")` raises `ArgumentError`.
Use `Load(User).joinedload(User.addresses)` to select a relationship or
`Load(User).lazyload("*")` to apply a wildcard strategy.
In 2.0.56 and 2.1.7, multiple `of_type()` loader options targeting different
subclasses of the same relationship raise `InvalidRequestError`.
Pass one `with_polymorphic()` target containing all the subclasses:
```python
from sqlalchemy import select
from sqlalchemy.orm import selectinload, with_polymorphic
staff = with_polymorphic(Employee, [Engineer, Manager])
stmt = select(Company).options(selectinload(Company.employees.of_type(staff)))
```
### Resolve mapped aliases and operator classes
Type-map unions match the full set of member types; `A | B` and `Union[A, B]`
are equivalent. A PEP 695 alias can resolve through an explicit map entry or its
immediate target. Implicit lookup through multiple aliases or through `NewType`
is deprecated in 2.0.
In 2.1.9, declare supported operators with `OperatorClass.EQUALITY` and
`OperatorClass.ORDERING` in place of `OperatorClass.COMPARISON`.
Since 2.1.7, `is_()` and `is_not()` belong to `OperatorClass.BASE` and work for
every SQL datatype.
### Recreate affected PostgreSQL JSONB indexes
On PostgreSQL 14 and later, SQLAlchemy 2.0.42 renders JSONB subscripts as
`data['a']`. A query such as `data['a'] ->> 'b'` no longer matches an expression
index built on `(data -> 'a') ->> 'b'`. Drop and recreate affected expression
indexes with the new syntax during the upgrade.
### Choose isolation and dialect options explicitly
Without a client-side `isolation_level`, asyncpg uses the server's transaction
isolation default. Set `isolation_level="READ COMMITTED"` on the async engine if
the application depends on that level regardless of the server setting.
For `mariadb://` indexes, use `mariadb_using` and `mariadb_with_parser`.
Code targeting both dialects can pass both prefixes; supplying only the
corresponding `mysql_` options on MariaDB is deprecated.
### Account for DML result typing and ambiguous names
`Session.execute()` for DML is annotated as `Result`. When a particular execution
is known to return a `CursorResult`, typed code can access its row count through
`cast(CursorResult, session.execute(stmt)).rowcount`.
Duplicate column names raise `InvalidRequestError` on key-based access in thawed
and pickled results, matching the original cursor result. Give selected columns
distinct labels when accessing them by name.
### Preserve schema details during recreation
`AddConstraint(constraint)` and `DropConstraint(constraint)` default to isolating
the constraint from inline `CREATE TABLE` DDL. Pass `isolate_from_table=False`
to keep it eligible for inline creation.
In 2.0.55, PostgreSQL 18 and later `PERIOD` foreign keys reflect as plain foreign
keys. Use explicit DDL to retain `PERIOD` when recreating a reflected table.
For repeated source columns in a foreign key, 2.0.53 warns and skips the
constraint during reflection; 2.1 supports reflection and construction.
## Mapping and loading quick reference
### Reuse annotated columns and dataclass composites
Generic PEP 695 aliases can carry a reusable `mapped_column()` declaration:
```python
from typing import Annotated
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
type PrimaryKey[T] = Annotated[T, mapped_column(primary_key=True)]
class Base(DeclarativeBase):
pass
class Widget(Base):
__tablename__ = "widget"
id: Mapped[PrimaryKey[int]]
```
In 2.1, `composite(column_template=...)` generates names for dataclass fields
without explicit column names. The template must contain exactly one `%s`,
replaced with the field name, as in `column_template="start_%s"`.
`defer()`, `undefer()`, and `load_only()` accept mapped composites.
`select(Vertex).options(load_only(Vertex.start))` selects the component columns
of the `start` composite.
### Configure dataclass collections and SQL defaults
In 2.1.7, a mapped dataclass relationship accepts the plain `dict`, `list`, or
`set` underlying a custom collection class as its `default_factory`. For example,
use `relationship(collection_class=attribute_keyed_dict("name"), default_factory=dict)`.
In 2.1.9, `ColumnDefault` and `Sequence` supplied as `mapped_column(default=...)`,
and the default from `orm_insert_sentinel()`, apply at the column level.
The Python attribute remains `None` until flush.
### Track updates and in-place changes
In 2.0.55 and 2.1.5, a synchronized ORM `update()` with WHERE criteria expires
server-side `onupdate` attributes and attributes assigned SQL expressions on
every matched object already in the session. Access reloads their database values.
In 2.0.55 and 2.1.4, `MutableDict` with `|=` and `MutableList` with `*=` emit change
events, so the ORM persists those in-place changes on flush.
## Connections, async results, and SQL quick reference
### Manage acquired connections and cleanup
Use `with engine.raw_connection() as dbapi_connection:` to return the raw
connection to the pool automatically at block exit.
In 2.1.7, `SessionTransaction.connections` lists acquired connections, and
`bound_connection()` looks up an existing connection without checking one out.
The root transaction from `session.get_transaction()` reports all connections;
the transaction from `session.begin_nested()` reports only those used within its
SAVEPOINT. `AsyncSessionTransaction` provides the same accessors with
`AsyncConnection` objects.
In 2.0.55, async session and connection context managers finish closing before
propagating cancellation received during exit. Shutdown can await those tasks
before disposing of the engine.
In 2.0.56 and 2.1.7 on Python 3.11, cancellation reaches an
`AsyncAdaptedQueuePool` waiter even when a connection returns in the same
event-loop iteration. The race can still suppress cancellation on Python 3.10
and earlier.
### Preserve async result filters
In 2.1.6, `AsyncResult.scalars()` and `.mappings()` carry forward `.unique()` and
`.columns()`. A collection joined eager load can use
`(await session.stream(stmt)).unique().scalars()`.
`await result.freeze()` consumes the async result with those filters applied
and returns a callable `FrozenResult`.
### Preserve URL query values
In 2.1.6, `keep_blank_values=True` on `make_url()` or `URL.update_query_string()`
retains `key=` as an empty string in `URL.query`, including a round trip through
`URL.render_as_string()` and `make_url()`.
In 2.0.58 and 2.1.9, `URL.update_query_pairs()` combines repeated keys with
sequence values into a flat sequence rendered as repeated URL parameters.
Both `update_query_pairs()` and `update_query_dict()` accept any sequence of
strings as a value.
### Bind parameters in template strings and textual SQL
Starting in 2.1.2, `tstring()` preserves `:name` and `\:` verbatim in literal
portions of a Python template string. Interpolate `bindparam()` to add a bound
parameter:
```python
from sqlalchemy import bindparam, tstring
stmt = tstring(t"SELECT {bindparam('p')}")
```
In 2.0.55, `text()` treats `:foo$bar` as bind `foo` followed by literal `$bar`,
and treats `:val::int` as literal SQL. Use `text("SELECT CAST(:val AS int)")`
to bind and cast a value.
### Supply per-row upsert values
PostgreSQL and SQLite executemany upserts can supply per-row bind parameters
in the `set_` mapping of `on_conflict_do_update()`. This also works with
`RETURNING`, where SQLAlchemy runs those parameter sets one row at a time.