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-nevaberry-plugins)
---
name: sqlalchemy-knowledge-patch
description: SQLAlchemy
version: "2.1.9"
license: MIT
metadata:
author: Nevaberry
---
# SQLAlchemy Knowledge Patch
Use this skill when upgrading SQLAlchemy or working on Declarative mappings,
relationship loading, SQL construction, connection lifecycles, or dialect-specific
behavior. The quick reference highlights upgrade changes and frequently used APIs;
open the topic references for complete guidance and examples.
## Reference index
| Reference | Topics |
| --- | --- |
| [Python, ORM, and Typing](references/python-orm-and-typing.md) | Runtime support, installation, annotations, dataclasses, composites, aliases, relationship loaders, ORM state, operator classes |
| [Engine, SQL, and Schema](references/engine-sql-and-schema.md) | URLs, logging, transactions, pools, cancellation, results, SQL text, value conversion, upserts, defaults, schema copying, constraints |
| [PostgreSQL](references/postgresql.md) | asyncpg isolation, JSONB indexes, constraint options, copied types, schema and index reflection |
| [MySQL, MariaDB, and SQLite](references/mysql-mariadb-and-sqlite.md) | Driver configuration, DML limits, locking reads, index options, type DDL, SQLite reflection |
| [Oracle and SQL Server](references/oracle-and-sql-server.md) | Vectors, async Oracle cleanup, ODBC configuration, bulk execution, decimals, datetimes, DDL, reflection |
## Breaking changes and deprecations
### Explicit subqueries for `aliased()`
Passing a `Select` or `CompoundSelect` directly to `aliased()` now produces a
deprecation warning and implicit subquery conversion in 2.0, and raises in 2.1. Call
`.subquery()` explicitly, as in `aliased(select(User).subquery())` or `aliased(User,
select(User).subquery())` for an ORM-mapped alias.
### Declarative columns excluded from ORM mapping
In 2.1.5, use `Unmapped[T]` with `unmapped_column()` to declare a table column that the
ORM excludes. Using `Mapper.include_properties` or `Mapper.exclude_properties` to
exclude class-declared attributes is deprecated. For columns supplied only by the table,
including reflected columns, use the mapper options.
### Loader-option wildcard validation
`Load(User).joinedload("addresses.*")` now raises `ArgumentError`. Use a mapped
attribute to select a relationship (`Load(User).joinedload(User.addresses)`) or a bare
`"*"` to apply a wildcard strategy (`Load(User).lazyload("*")`).
### Loading several subclasses through one relationship
In 2.0.56 and 2.1.7, applying multiple `of_type()` loader options with different
subclass targets to the same relationship raises `InvalidRequestError`. Pass a single
`with_polymorphic()` target that includes all the subclasses.
### Annotated Declarative type resolution
Type-map unions match the full set of member types, and `A | B` and `Union[A, B]` are
equivalent. A PEP 695 alias can resolve through an explicit map entry or its immediate
target, while implicit lookup through multiple aliases or through `NewType` is
deprecated in 2.0. Generic PEP 695 aliases can carry a reusable `mapped_column()`
declaration.
### PostgreSQL JSONB subscript indexes
On PostgreSQL 14 and later, SQLAlchemy 2.0.42 emits `data['a']` for JSONB subscripts, so
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.
### MariaDB index option prefixes
For the `mariadb://` dialect, set `mariadb_using` and `mariadb_with_parser` on indexes.
Code targeting both dialects can pass both prefixes, since supplying only the
corresponding `mysql_` options on MariaDB is deprecated.
### Equality and ordering operator classes
In 2.1.9, code declaring supported operators uses `OperatorClass.EQUALITY` and
`OperatorClass.ORDERING` in place of `OperatorClass.COMPARISON`. `HSTORE` and the type
produced by `FunctionElement.table_valued()` support `EQUALITY`. Since 2.1.7, `is_()`
and `is_not()` belong to `OperatorClass.BASE` and work for every SQL datatype.
## Mapping and relationship loading
### Reusing dataclass composites with column name templates
In 2.1, `composite(column_template=...)` generates column names for dataclass fields
without explicit column names. The template must contain exactly one `%s`, which
SQLAlchemy replaces with the field name.
### Composite attribute loader options
`defer()`, `undefer()`, and `load_only()` now accept mapped composite attributes. For
example, `select(Vertex).options(load_only(Vertex.start))` selects the component columns
of the `start` composite.
### Dataclass factories for custom relationship collections
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)` for
a dictionary keyed by each related object's name.
### Expiration after ORM UPDATE
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. Accessing those attributes reloads their database
values.
## Connections, async results, and SQL
### Raw connection context managers
Use `with engine.raw_connection() as dbapi_connection:` to return the raw connection to
the pool automatically at block exit.
### Inspecting acquired session connections
In 2.1.7, `SessionTransaction.connections` lists already acquired connections and
`bound_connection()` looks up an existing connection without checking one out. The root
transaction from `session.get_transaction()` reports all connections, while the
transaction from `session.begin_nested()` reports only those used within its SAVEPOINT.
`AsyncSessionTransaction` provides the same accessors with `AsyncConnection` objects.
### Async result filters and freezing
In 2.1.6, `AsyncResult.scalars()` and `.mappings()` carry forward `.unique()` and
`.columns()`, so 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`.
### Async cleanup on cancellation
In 2.0.55, async session and connection context managers finish closing before
propagating cancellation received during exit, so shutdown can await those tasks before
disposing of the engine. In 2.0.55 and 2.1.5, the pool discards invalidated connections
even if cancellation repeats during close and propagates `CancelledError` received while
cleaning up after a failed `PoolEvents.connect` handler.
### asyncpg isolation defaults
With no client-side `isolation_level` setting, asyncpg now uses the server's transaction
isolation default. Set `isolation_level="READ COMMITTED"` explicitly on the async engine
if the application depends on that level regardless of the server setting.
### Bind parameters in SQL template strings
Starting in 2.1.2, `tstring()` preserves `:name` and `\:` verbatim in the literal
portions of a Python template string. Interpolate `bindparam()` to add a bound
parameter.
### Text SQL and parameter-like literals
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. With positional paramstyles, literal `%(name)s` text is preserved in
`text()`, `literal_column()`, and values rendered with `literal_binds`.
## DML and vector search
### Bound parameters in PostgreSQL and SQLite upserts
Executemany upserts can now 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.
### MySQL and MariaDB DELETE limits
Use `table.delete().with_dialect_options(mysql_limit=100)` for MySQL or
`mariadb_limit=100` for the MariaDB dialect. Both limit options require an integer for
`UPDATE` and `DELETE` and raise `ValueError` for other values.
### Oracle vector columns and search
Oracle's `VECTOR` type exposes `l2_distance()`, `cosine_distance()`, and
`inner_product()`. Configure vector indexes through `Index(..., oracle_vector=...)`,
request approximate results with `fetch(..., oracle_fetch_approximate=True)`, and use
`VectorStorageType` and `SparseVector` for sparse storage and values.