Mike Bayer [Sat, 20 Sep 2025 20:22:28 +0000 (16:22 -0400)]
Improve asyncpg exception hierarchy and asyncio hierarchies overall
The "emulated" exception hierarchies for the asyncio
drivers such as asyncpg, aiomysql, aioodbc, etc. have been standardized
on a common base :class:`.EmulatedDBAPIException`, which is now what's
available from the :attr:`.StatementException.orig` attribute on a
SQLAlchemy :class:`.DBAPIException` object. Within :class:`.EmulatedDBAPIException`
and the subclasses in its hiearchy, the original driver-level exception is
also now avaliable via the :attr:`.EmulatedDBAPIException.orig` attribute,
and is also available from :class:`.DBAPIException` directly using the
:attr:`.DBAPIException.driver_exception` attribute.
Added additional emulated error classes for the subclasses of
``asyncpg.exception.IntegrityError`` including ``RestrictViolationError``,
``NotNullViolationError``, ``ForeignKeyViolationError``,
``UniqueViolationError`` ``CheckViolationError``,
``ExclusionViolationError``. These exceptions are not directly thrown by
SQLAlchemy's asyncio emulation, however are available from the
newly added :attr:`.DBAPIException.driver_exception` attribute when a
:class:`.IntegrityError` is caught.
Mike Bayer [Sun, 21 Sep 2025 16:13:21 +0000 (12:13 -0400)]
add create_type to Enum
Added new parameter :paramref:`.Enum.create_type` to the Core
:class:`.Enum` class. This parameter is automatically passed to the
corresponding :class:`_postgresql.ENUM` native type during DDL operations,
allowing control over whether the PostgreSQL ENUM type is implicitly
created or dropped within DDL operations that are otherwise targeting
tables only. This provides control over the
:paramref:`_postgresql.ENUM.create_type` behavior without requiring
explicit creation of a :class:`_postgresql.ENUM` object.
Mike Bayer [Sun, 21 Sep 2025 14:59:51 +0000 (10:59 -0400)]
Apply nested for joined eager m2o w/ GROUP BY, DISTINCT
Fixed issue where joined eager loading would fail to use the "nested" form
of the query when GROUP BY or DISTINCT were present if the eager joins
being added were many-to-ones, leading to additional columns in the columns
clause which would then cause errors. The check for "nested" is tuned to
be enabled for these queries even for many-to-one joined eager loaders, and
the "only do nested if it's one to many" aspect is now localized to when
the query only has LIMIT or OFFSET added.
Mike Bayer [Sat, 20 Sep 2025 22:31:25 +0000 (18:31 -0400)]
remove _py3k suffixes from test files
on the theme of 2.0/2.1 are relatively similar right now, do
some more cleanup removing the py3k suffixes that we dont need anymore.
I'm not sure that the logic that would search for these suffixes is
even present anymore and I would guess we removed it when we removed
py2k support. However, I am planning on possibly bringing it back
for some of the py314 stuff, so I still want to be able to do
suffix stuff. that will be for another patch.
The :meth:`_types.ARRAY.Comparator.any` and
:meth:`_types.ARRAY.Comparator.all` methods for the :class:`_types.ARRAY`
type are now deprecated for removal; these two methods along with
:func:`_postgresql.Any` and :func:`_postgresql.All` have been legacy for
some time as they are superseded by the :func:`_sql.any_` and
:func:`_sql.all_` functions, which feature more intutive use.
Mike Bayer [Sat, 20 Sep 2025 18:08:55 +0000 (14:08 -0400)]
Use ARRAY type for any_(), all_() coercion
Fixed issue where the :func:`_sql.any_` and :func:`_sql.all_` aggregation
operators would not correctly coerce the datatype of the compared value, in
those cases where the compared value were not a simple int/str etc., such
as a Python ``Enum`` or other custom value. This would lead to execution
time errors for these values. This issue is essentially the same as
:ticket:`6515` which was for the now-legacy :meth:`.ARRAY.any` and
:meth:`.ARRAY.all` methods.
raise for ENUM/DOMAIN with reserved type name and no schema
A :class:`.CompileError` is raised if attempting to create a PostgreSQL
:class:`_postgresql.ENUM` or :class:`_postgresql.DOMAIN` datatype using a
name that matches a known pg_catalog datatype name, and a default schema is
not specified. These types must be explicit within a schema in order to
be differentiated from the built-in pg_catalog type. The "public" or
otherwise default schema is not chosen by default here since the type can
only be reflected back using the explicit schema name as well (it is
otherwise not visible due to the pg_catalog name). Pull request courtesy
Kapil Dagur.
We originally thought we were going to do some default logic for the
default / "public" schema however this produces a type that is not
symmetric to its reflection, since the schema name must be explicit
for our current reflection queries.
So since it's an extremely bad idea to make an ENUM/DOMAIN with a
reserved type name anyway, we raise a compileerror if the type
has a known name. this is not robust against other names that
might exist in pg_catalog or other schemas that are in the search
path with these names. People just have to know what they're doing
here, the error here only covers a small subset of real world cases.
Mike Bayer [Sun, 31 Aug 2025 22:53:01 +0000 (18:53 -0400)]
add RegistryEvents
Added :class:`_orm.RegistryEvents` event class that allows event listeners
to be established on a :class:`_orm.registry` object. The new class
provides three events: :meth:`_orm.RegistryEvents.resolve_type_annotation`
which allows customization of type annotation resolution that can
supplement or replace the use of the
:paramref:`.registry.type_annotation_map` dictionary, including that it can
be helpful with custom resolution for complex types such as those of
:pep:`695`, as well as :meth:`_orm.RegistryEvents.before_configured` and
:meth:`_orm.RegistryEvents.after_configured`, which are registry-local
forms of the mapper-wide version of these hooks.
note this change was prematurely merged in 7111dc0cbaae and reverted
for re-review and additional changes.
Added new generalized aggregate function ordering to functions via the
:func:`_functions.FunctionElement.aggregate_order_by` method, which
receives an expression and generates the appropriate embedded "ORDER BY" or
"WITHIN GROUP (ORDER BY)" phrase depending on backend database. This new
function supersedes the use of the PostgreSQL
:func:`_postgresql.aggregate_order_by` function, which remains present for
backward compatibility. To complement the new parameter, the
:paramref:`_functions.aggregate_strings.order_by` which adds ORDER BY
capability to the :class:`_functions.aggregate_strings` dialect-agnostic
function which works for all included backends. Thanks much to Reuven
Starodubski with help on this patch.
Mike Bayer [Mon, 14 Jul 2025 17:50:09 +0000 (13:50 -0400)]
unmapped_dataclass
Reworked the handling of classes which extend from MappedAsDataclass but
are not themselves mapped, i.e. the declarative base as well as any
mixins or abstract classes. These classes as before are turned into
real dataclasses, however a scan now takes place across the mapped
elements such as mapped_column(), relationship(), etc. so that we may
also take into account dataclasses.field-specific parameters like
init=False, repr, etc. The main use case for this is so that mixin
dataclasses may make use of "default" in fields while not being rejected
by the dataclasses constructor. The generated classes are more
functional as dataclasses in a standalone fashion as well, even though
this is not their intended use. As a standalone dataclass, the one
feature that does not work is a field that has
a default with init=False, because we still need to have a
mapped_column() or similar present at the class level for the class
to work as a superclass.
The change also addes the :func:`_orm.unmapped_dataclass` decorator
function, which may be used
to create unmapped superclasses in a mapped hierarchy that is using the
:func:`_orm.mapped_dataclass` decorator to create mapped dataclasses.
Previously there was no way to use unmapped dataclass mixins with
the decorator approach.
Finally, the warning added in 2.0 for :ticket:`9350` is turned into
an error as mentioned for 2.1, since we're deep into dataclass hierarchy
changes here.
Tip ten Brink [Mon, 15 Sep 2025 12:58:40 +0000 (08:58 -0400)]
Fix get_columns sqlite reflection rejecting tables with WITHOUT_ROWID and/or STRICT for generated column case
Fixed issue where SQLite table reflection would fail for tables using
``WITHOUT ROWID`` and/or ``STRICT`` table options when the table contained
generated columns. The regular expression used to parse ``CREATE TABLE``
statements for generated column detection has been updated to properly
handle these SQLite table options that appear after the column definitions.
Pull request courtesy Tip ten Brink.
Mike Bayer [Tue, 9 Sep 2025 19:16:45 +0000 (15:16 -0400)]
Add function mapped_as_dataclass
Added new decorator :func:`_orm.mapped_as_dataclass`, which is a function
based form of :meth:`_orm.registry.mapped_as_dataclass`; the method form
:meth:`_orm.registry.mapped_as_dataclass` does not seem to be correctly
recognized within the scope of :pep:`681` in recent mypy versions.
The new function is tested and mentioned in the docs, in 2.1 in a
subsequent patch (probably the one that adds unmapped_dataclass also)
we'll switch this new decorator to be the prominent one.
also alphabetize mapping_api.rst. while the summary box at the top
auto-sorts, have the sidebar alpha also, it's kind of weird how
these were in no order at all
Mike Bayer [Sun, 31 Aug 2025 22:53:01 +0000 (18:53 -0400)]
add RegistryEvents
Added :class:`_orm.RegistryEvents` event class that allows event listeners
to be established on a :class:`_orm.registry` object. The new class
provides three events: :meth:`_orm.RegistryEvents.resolve_type_annotation`
which allows customization of type annotation resolution that can
supplement or replace the use of the
:paramref:`.registry.type_annotation_map` dictionary, including that it can
be helpful with custom resolution for complex types such as those of
:pep:`695`, as well as :meth:`_orm.RegistryEvents.before_configured` and
:meth:`_orm.RegistryEvents.after_configured`, which are registry-local
forms of the mapper-wide version of these hooks.
Mike Bayer [Sun, 7 Sep 2025 00:20:00 +0000 (20:20 -0400)]
doc updates, localize test fixtures
testing with types is inherently awkward and subject
to changes in python interpreters (such as all the recent python 3.14
stuff we had them fix), but in this suite we already have a lot of
types that are defined inline inside of test methods. so since that's
how many of the tests work anyway, organize the big series of pep-695
and pep-593 structures into fixtures or individual tests to make
the whole suite easier to follow. pyright complains quite a lot
about this, so if this becomes a bigger issue for say mypy /pep484
target, we may have to revisit (which I'd likely do with more ignores)
or if function/method-local type declarations with global becomes a runtime
issue in py3.15 or something, we can revisit then where we would in
theory need to convert the entire suite, which I'd do with a more
consistent naming style for everything.
but for now try to go with fixtures / local type declarations so that
we dont have to wonder where all these types are used.
Mike Bayer [Thu, 4 Sep 2025 01:44:33 +0000 (21:44 -0400)]
liberalize pep695 matching
after many days of discussion we are moving to liberalize the
matching rules used for pep695 to the simple rule that we will resolve
a pep695 type to its immediate ``__value__`` without requiring that
it be present in the type map, however without any further recursive
checks (that is, we will not resolve ``__value__`` of ``__value__``).
This allows the vast majority of simple uses of pep695 types to not
require entries in the type map, including when the type points
to a simple Python type or any type that is present in the type_map.
Also supported is resolution of generic pep695 types against the
right side, including for Annotated types.
The change here in 2.1 will form the base for a revised approach
to the RegistryEvents patch for #9832, which will still provide
the RegistryEvents.resolve_type_annotation hook. In 2.0, we need
to scale back the warnings that are emitted so portions of this patch
will also be backported including similar changes to the test suite.
Mike Bayer [Fri, 5 Sep 2025 13:29:34 +0000 (09:29 -0400)]
interpret NULL in PG enum array values
Fixed issue where selecting an enum array column containing NULL values
would fail to parse properly in the PostgreSQL dialect. The
:func:`._split_enum_values` function now correctly handles NULL entries by
converting them to Python ``None`` values.
Mike Bayer [Tue, 2 Sep 2025 16:26:06 +0000 (12:26 -0400)]
remove upfront sanitization of entities from joins
ORM entities can now be involved within the SQL expressions used within
:paramref:`_orm.relationship.primaryjoin` and
:paramref:`_orm.relationship.secondaryjoin` parameters without the ORM
entity information being implicitly sanitized, allowing ORM-specific
features such as single-inheritance criteria in subqueries to continue
working even when used in this context. This is made possible by overall
ORM simplifications that occurred as of the 2.0 series. The changes here
also provide a performance boost (up to 20%) for certain query compilation
scenarios.
Here we see that we're not only able to remove the
relationships deannotation steps, but we can also change
context -> _get_current_adapter() to be an unconditional
adapter, since the only remaining case where it was conditional
was the polymorphic_adapter. that adapter is itself
only used for exotic joined inh cases against select
statements (totally not used by anyone) or by abstract
concrete setups. That lets us remove a whole host
of orm_annotate stuff that doesn't apply anymore.
if this does lead to user regressions in 2.1 it will be
a good reason for us to revisit the complexity here in
any case.
Mike Bayer [Tue, 2 Sep 2025 15:10:51 +0000 (11:10 -0400)]
support omission of standard event listen example
The required targets for before_configured() and after_configured()
are the Mapper (and soon to include registry things as well in 2.1),
update the automatic doc example thing to be able to be skipped
when there are special instructions for the target.
Also updates the event docs a bit, which were very old and
written in more of that "disorganized wall of details" style
that was very hard to unlearn
Mike Bayer [Fri, 8 Aug 2025 16:17:16 +0000 (12:17 -0400)]
warn on failed aliased
The :func:`_orm.aliased` object now emits warnings when an attribute is
accessed on an aliased class that cannot be located in the target
selectable, for those cases where the :func:`_orm.aliased` is against a
different FROM clause than the regular mapped table (such as a subquery).
This helps users identify cases where column names don't match between the
aliased class and the underlying selectable. When
:paramref:`_orm.aliased.adapt_on_names` is ``True``, the warning suggests
checking the column name; when ``False``, it suggests using the
``adapt_on_names`` parameter for name-based matching.
Mike Bayer [Tue, 26 Aug 2025 20:54:39 +0000 (16:54 -0400)]
add session-wide execution_options
Added support for per-session execution options that are merged into all
queries executed within that session. The :class:`_orm.Session`,
:class:`_orm.sessionmaker`, :class:`_orm.scoped_session`,
:class:`_ext.asyncio.AsyncSession`, and
:class:`_ext.asyncio.async_sessionmaker` constructors now accept an
:paramref:`_orm.Session.execution_options` parameter that will be applied
to all explicit query executions (e.g. using :meth:`_orm.Session.execute`,
:meth:`_orm.Session.get`, :meth:`_orm.Session.scalars`) for that session
instance.
Mike Bayer [Tue, 26 Aug 2025 23:14:20 +0000 (19:14 -0400)]
use fixture_session() fixture, remove "future" terminology
Tests here are sporadically failing on aiosqlite and it
seems the use of Session() rather than fixture_session() may be
causing connections to be cleaned up in GC, leading to table
exists race conditions.
Remove the concept of "future" since everything is "future" now
Mike Bayer [Tue, 26 Aug 2025 18:47:34 +0000 (14:47 -0400)]
use _generate_columns_plus_names for ddl returning c populate
Improved the implementation of :meth:`.UpdateBase.returning` to use more
robust logic in setting up the ``.c`` collection of a derived statement
such as a CTE. This fixes issues related to RETURNING clauses that feature
expressions based on returned columns with or without qualifying labels.
Co-authored-by: Juhyeong Ko <dury.ko@gmail.com> Fixes: #12271
Change-Id: Id0d486d4304002f1affdec2e7662ac2965936f2a
Mike Bayer [Mon, 5 May 2025 12:36:05 +0000 (08:36 -0400)]
support configurable None behavior for composites
Added new parameter :paramref:`_orm.composite.return_none_on` to
:func:`_orm.composite`, which allows control over if and when this
composite attribute should resolve to ``None`` when queried or retrieved
from the object directly. By default, a composite object is always present
on the attribute, including for a pending object which is a behavioral
change since 2.0. When :paramref:`_orm.composite.return_none_on` is
specified, a callable is passed that returns True or False to indicate if
the given arguments indicate the composite should be returned as None. This
parameter may also be set automatically when ORM Annotated Declarative is
used; if the annotation is given as ``Mapped[SomeClass|None]``, a
:paramref:`_orm.composite.return_none_on` rule is applied that will return
``None`` if all contained columns are themselves ``None``.
Mike Bayer [Wed, 16 Jul 2025 16:14:27 +0000 (12:14 -0400)]
add OperatorClasses to gate mismatched operator use
Added a new concept of "operator classes" to the SQL operators supported by
SQLAlchemy, represented within the enum :class:`.OperatorClass`. The
purpose of this structure is to provide an extra layer of validation when a
particular kind of SQL operation is used with a particular datatype, to
catch early the use of an operator that does not have any relevance to the
datatype in use; a simple example is an integer or numeric column used with
a "string match" operator.
Mike Bayer [Fri, 22 Aug 2025 22:12:13 +0000 (18:12 -0400)]
ensure datatype roundtrips for JSON dialects
Improved the behavior of JSON accessors :meth:`.JSON.Comparator.as_string`,
:meth:`.JSON.Comparator.as_boolean`, :meth:`.JSON.Comparator.as_float`,
:meth:`.JSON.Comparator.as_integer` to use CAST in a similar way that
the PostgreSQL, MySQL and SQL Server dialects do to help enforce the
expected Python type is returned.
The :meth:`.JSON.Comparator.as_boolean` method when used on a JSON value on
SQL Server will now force a cast to occur for values that are not simple
`true`/`false` JSON literals, forcing SQL Server to attempt to interpret
the given value as a 1/0 BIT, or raise an error if not possible. Previously
the expression would return NULL.
Mike Bayer [Tue, 29 Jul 2025 18:19:34 +0000 (14:19 -0400)]
more extensibility for asc/desc
Improved the behavior of standalone "operators" like :func:`_sql.desc`,
:func:`_sql.asc`, :func:`_sql.all_`, etc. so that they consult the given
expression object for an overriding method for that operator, even if the
object is not itself a ``ClauseElement``, such as if it's an ORM attribute.
This allows custom comparators for things like :func:`_orm.composite` to
provide custom implementations of methods like ``desc()``, ``asc()``, etc.
Added default implementations of :meth:`.ColumnOperators.desc`,
:meth:`.ColumnOperators.asc`, :meth:`.ColumnOperators.nulls_first`,
:meth:`.ColumnOperators.nulls_last` to :func:`_orm.composite` attributes,
by default applying the modifier to all contained columns. Can be
overridden using a custom comparator.
Mike Bayer [Thu, 21 Aug 2025 15:20:11 +0000 (11:20 -0400)]
ensure assoc proxy from aliased() is generated in correct context
Improved association proxy to behave slightly better when the parent class
is used in an :func:`_orm.aliased` construct, so that the proxy as
delivered by the :class:`.Aliased` behaves appropriate in terms of that
aliased construct, including operators like ``.any()`` and ``.has()`` work
correctly.
Micah Denbraver [Wed, 20 Aug 2025 20:58:02 +0000 (16:58 -0400)]
Fix typing for `hybrid_property.__set__` to properly validate setter values
While iterating on some typing improvements, my colleague @seamuswn pointed out mypy wasn't catching when values with invalid types were set using a `hybrid_property` setter. I believe this is all that's needed to fix the typing.
### Description
Adjust `hybrid_property.__set__` to expect a value of the type that matches the generic's type variable.
### Checklist
<!-- go over following points. check them with an `x` if they do apply, (they turn into clickable checkboxes once the PR is submitted, so no need to do everything at once)
-->
This pull request is:
- [x] A documentation / typographical / small typing error fix
- Good to go, no issue or tests are needed
- [ ] A short code fix
- please include the issue number, and create an issue if none exists, which
must include a complete example of the issue. one line code fixes without an
issue and demonstration will not be accepted.
- Please include: `Fixes: #<issue number>` in the commit message
- please include tests. one line code fixes without tests will not be accepted.
- [ ] A new feature implementation
- please include the issue number, and create an issue if none exists, which must
include a complete example of how the feature would look.
- Please include: `Fixes: #<issue number>` in the commit message
- please include tests.
Federico Caselli [Thu, 14 Aug 2025 22:05:07 +0000 (00:05 +0200)]
restore functionality in list
Fixed issue caused by an unwanted functional change while typing
the :class:`.MutableList` class.
This change also reverts all other functional changes done in
the same change, commit ba0e508141206efc55cdab91df21c18e7dd63c80
Mike Bayer [Mon, 18 Aug 2025 15:01:47 +0000 (11:01 -0400)]
We can't promise CursorResult from session.execute()
Fixed typing bug where the :meth:`.Session.execute` method advertised that
it would return a :class:`.CursorResult` if given an insert/update/delete
statement. This is not the general case as several flavors of ORM
insert/update do not actually yield a :class:`.CursorResult` which cannot
be differentiated at the typing overload level, so the method now yields
:class:`.Result` in all cases. For those cases where
:class:`.CursorResult` is known to be returned and the ``.rowcount``
attribute is required, please use ``typing.cast()``.
Mike Bayer [Tue, 12 Aug 2025 19:25:15 +0000 (15:25 -0400)]
close aio cursors etc. that require await close
Improved the base implementation of the asyncio cursor such that it
includes the option for the underlying driver's cursor to be actively
closed in those cases where it requires ``await`` in order to complete the
close sequence, rather than relying on garbage collection to "close" it,
when a plain :class:`.Result` is returned that does not use ``await`` for
any of its methods. The previous approach of relying on gc was fine for
MySQL and SQLite dialects but has caused problems with the aioodbc
implementation on top of SQL Server. The new option is enabled
for those dialects which have an "awaitable" ``cursor.close()``, which
includes the aioodbc, aiomysql, and asyncmy dialects (aiosqlite is also
modified for 2.1 only).
suraj [Mon, 11 Aug 2025 12:21:46 +0000 (08:21 -0400)]
Fixes: #12711 Added sparse vector support in Oracle
Extended :class:`_oracle.VECTOR` to support sparse vectors. This update
introduces :class:_oracle.VectorStorageType to specify sparse or dense
storage and added :class:`_oracle.SparseVector`. Pull request courtesy
Suraj Shaw.
Mike Bayer [Tue, 5 Aug 2025 14:46:21 +0000 (10:46 -0400)]
implement skip_autocommit_rollback
Added new parameter :paramref:`.create_engine.skip_autocommit_rollback`
which provides for a per-dialect feature of preventing the DBAPI
``.rollback()`` from being called under any circumstances, if the
connection is detected as being in "autocommit" mode. This improves upon
a critical performance issue identified in MySQL dialects where the network
overhead of the ``.rollback()`` call remains prohibitive even if autocommit
mode is set.
Mike Bayer [Wed, 6 Aug 2025 14:19:39 +0000 (10:19 -0400)]
add chunking to selectin_polymorphic
Improved the implementation of the :func:`_orm.selectin_polymorphic`
inheritance loader strategy to properly render the IN expressions using
chunks of 500 records each, in the same manner as that of the
:func:`_orm.selectinload` relationship loader strategy. Previously, the IN
expression would be arbitrarily large, leading to failures on databases
that have limits on the size of IN expressions including Oracle Database.
Mike Bayer [Tue, 5 Aug 2025 21:11:50 +0000 (17:11 -0400)]
apply correct pre-fetch params to post updated rows
Fixed issue where using the ``post_update`` feature would apply incorrect
"pre-fetched" values to the ORM objects after a multi-row UPDATE process
completed. These "pre-fetched" values would come from any column that had
an :paramref:`.Column.onupdate` callable or a version id generator used by
:paramref:`.orm.Mapper.version_id_generator`; for a version id generator
that delivered random identifiers like timestamps or UUIDs, this incorrect
data would lead to a DELETE statement against those same rows to fail in
the next step.
Mike Bayer [Tue, 5 Aug 2025 18:05:49 +0000 (14:05 -0400)]
Fix use_existing_column with Annotated mapped_column in polymorphic inheritance
Fixed issue where :paramref:`_orm.mapped_column.use_existing_column`
parameter in :func:`_orm.mapped_column` would not work when the
:func:`_orm.mapped_column` is used inside of an ``Annotated`` type alias in
polymorphic inheritance scenarios. The parameter is now properly recognized
and processed during declarative mapping configuration.
Mike Bayer [Fri, 1 Aug 2025 16:48:15 +0000 (12:48 -0400)]
Fix PostgreSQL JSONB subscripting regression with functions
Fixed regression in PostgreSQL dialect where JSONB subscription syntax
would generate incorrect SQL for JSONB-returning functions, causing syntax
errors. The dialect now properly wraps function calls and expressions in
parentheses when using the ``[]`` subscription syntax, generating
``(function_call)[index]`` instead of ``function_call[index]`` to comply
with PostgreSQL syntax requirements.