Added long-requested case-insensitive string operators
:meth:`_sql.ColumnOperators.icontains`,
:meth:`_sql.ColumnOperators.istartswith`,
:meth:`_sql.ColumnOperators.iendswith`, which produce case-insensitive
LIKE compositions (using ILIKE on PostgreSQL, and the LOWER() function on
all other backends) to complement the existing LIKE composition operators
:meth:`_sql.ColumnOperators.contains`,
:meth:`_sql.ColumnOperators.startswith`, etc. Huge thanks to Matias
Martinez Rebori for their meticulous and complete efforts in implementing
these new methods.
Ensure that all cython extension are imported by the compied detection logic.
This is required since cython extensions moduels are marked as optional
in the install, so it's possible that only some of them are compiled.
The extensions are enabled only if all of them are correctly compiled
Fixed regression caused by the fix for :ticket:`8231` released in 1.4.40
where connection would fail if the user does not have permission to query
the dm_exec_sessions or dm_pdw_nodes_exec_sessions system view when trying
to determine the current transaction isolation level.
Peter Schutt [Thu, 1 Sep 2022 23:11:40 +0000 (19:11 -0400)]
Detection of PEP 604 union syntax.
### Description
Fixes #8478
Handle `UnionType` as arguments to `Mapped`, e.g., `Mapped[str | None]`:
- adds `utils.typing.is_optional_union()` used to detect if a column should be nullable.
- adds `"UnionType"` to `utils.typing.is_optional()` names.
- uses `get_origin()` in `utils.typing.is_origin_of()` as `UnionType` has no `__origin__` attribute.
- tests with runtime type and postponed annotations and guard the tests running with `compat.py310`.
### 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:
- [ ] A documentation / typographical error fix
- Good to go, no issue or tests are needed
- [x] 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.
Mike Bayer [Wed, 31 Aug 2022 15:07:23 +0000 (11:07 -0400)]
run update_subclass anytime we add new clslevel dispatch
Fixed event listening issue where event listeners added to a superclass
would be lost if a subclass were created which then had its own listeners
associated. The practical example is that of the :class:`.sessionmaker`
class created after events have been associated with the
:class:`_orm.Session` class.
Mike Bayer [Tue, 30 Aug 2022 14:47:24 +0000 (10:47 -0400)]
include TableClause.schema in cache key
Fixed issue where use of the :func:`_sql.table` construct, passing a string
for the :paramref:`_sql.table.schema` parameter, would fail to take the
"schema" string into account when producing a cache key, thus leading to
caching collisions if multiple, same-named :func:`_sql.table` constructs
with different schemas were used.
Mike Bayer [Tue, 30 Aug 2022 14:25:47 +0000 (10:25 -0400)]
implement event for merge/load=False for mutable state setup
Fixed issue in :mod:`sqlalchemy.ext.mutable` extension where collection
links to the parent object would be lost if the object were merged with
:meth:`.Session.merge` while also passing :paramref:`.Session.merge.load`
as False.
The event added here is currently private for expediency, but
is acceptable to become a public event at some point.
Mike Bayer [Tue, 30 Aug 2022 13:50:03 +0000 (09:50 -0400)]
apply consistent ORM mutable notes for all mutable SQL types
in
https://github.com/sqlalchemy/sqlalchemy/discussions/8447
I was surprised that we didnt have any notes about using Mutable
for ARRAY classes, since we have them for HSTORE and JSON.
Add a consistent topic box for these so we have something to
point towards.
Mike Bayer [Mon, 29 Aug 2022 14:43:36 +0000 (10:43 -0400)]
refine ruleset to determine when poly adaption should be used
Fixed regression appearing in the 1.4 series where a joined-inheritance
query placed as a subquery within an enclosing query for that same entity
would fail to render the JOIN correctly for the inner query. The issue
manifested in two different ways prior and subsequent to version 1.4.18
(related issue #6595), in one case rendering JOIN twice, in the other
losing the JOIN entirely. To resolve, the conditions under which
"polymorphic loading" are applied have been scaled back to not be invoked
for simple joined inheritance queries.
Trevor Gross [Wed, 24 Aug 2022 10:32:31 +0000 (06:32 -0400)]
Use cibuildwheel to create wheels
Using cibuildwheel the following wheels are created:
- windows x64 and x84
- macos x64 and arm
- linux x64 and arm on manylinux and mosulinux (for alpine)
- create a pure python wheel (for pypy and other archs)
Mike Bayer [Wed, 24 Aug 2022 17:06:09 +0000 (13:06 -0400)]
fix mock issue in pool test
Due to the change for #5648 in ad14471bc99c2fb2315d3333a95dd,
the mock in test_recycle_pool_no_race needs to implement
an empty handle_error dispatcher.
the exception was in a thread so did not interrupt the
test suite:
File "/home/classic/dev/sqlalchemy/lib/sqlalchemy/engine/base.py", line 2059, in _handle_dbapi_exception
for fn in self.dialect.dispatch.handle_error:
TypeError: 'Mock' object is not iterable
Mike Bayer [Tue, 23 Aug 2022 13:28:06 +0000 (09:28 -0400)]
integrate connection.terminate() for supporting dialects
Integrated support for asyncpg's ``terminate()`` method call for cases
where the connection pool is recycling a possibly timed-out connection,
where a connection is being garbage collected that wasn't gracefully
closed, as well as when the connection has been invalidated. This allows
asyncpg to abandon the connection without waiting for a response that may
incur long timeouts.
Mike Bayer [Mon, 22 Aug 2022 17:43:59 +0000 (13:43 -0400)]
reformat functions.rst; document coalsce
this file was all over the place autodocumenting all the
contents of functions.py with no regards to the heading
paragraph which seemed to be introducing the generic functions.
Use specific autoclass/autofunc docs as automodule is generally
unworkable.
Mike Bayer [Sun, 21 Aug 2022 15:58:20 +0000 (11:58 -0400)]
Column._copy() duplicates "user defined" nullable state exactly
To accommodate how mapped_column() works, after many
attempts to get this working it became clear that _copy()
should just transfer "nullable" state exactly as it was,
including the state where .nullable was set but user_defined_nullable
remains at not user set.
additionally, added a similar step to _merge() that was needed
to preserve the nullability behavior when Identity is present.
server / client default objects are not copied within column._copy()
and this should be fixed.
Mike Bayer [Tue, 16 Aug 2022 14:44:48 +0000 (10:44 -0400)]
support create/drop events for all CREATE/DROP
Implemented the DDL event hooks :meth:`.DDLEvents.before_create`,
:meth:`.DDLEvents.after_create`, :meth:`.DDLEvents.before_drop`,
:meth:`.DDLEvents.after_drop` for all :class:`.SchemaItem` objects that
include a distinct CREATE or DROP step, when that step is invoked as a
distinct SQL statement, including for :class:`.ForeignKeyConstraint`,
:class:`.Sequence`, :class:`.Index`, and PostgreSQL's
:class:`_postgresql.ENUM`.
Mike Bayer [Fri, 19 Aug 2022 15:12:41 +0000 (11:12 -0400)]
remove narrative "reconstructor" document
this event hook is not commonly used and this page does not
fit into the current narrative very well. We should possibly
write a new paragraph regarding how instances load
at some point though the best place to put it is not clear.
Mike Bayer [Fri, 19 Aug 2022 13:49:25 +0000 (09:49 -0400)]
fix some inaccuracies in with_variant doc
* the table wont create on mysql/mariadb b.c. user_name had
no length
* "utf-8" is not recognized by mysql/mariadb, use "utf8"
* mysql or mariadb name match is determined by the URL, not the
actual DB that is detected (I know I made it work that way but
I forgot)
* for the 1.4 backport only, will remove the "mariadb" part
as we dont support that API, #8408
Mike Bayer [Wed, 17 Aug 2022 21:47:19 +0000 (17:47 -0400)]
improve abstractconcretebase
try to limit the attributes on the base and set up wpoly
etc so that things still work the way we want.
It seems like I've tried this in the past before so not sure
if this is actually working or if there are problems. it needs
a little more strictness on how you set up your base since
attributes are no longer implicit. So, it seems like perhaps
the new behavior should be on a flag or something like
"strict_attributes=True", something like that, so that nothing
breaks for existing users and we can slowly deal with the new
way being a little bit less worse than the old way.
Mike Bayer [Tue, 9 Aug 2022 17:31:14 +0000 (13:31 -0400)]
validate mapped collection key is loaded
Changed the attribute access method used by
:func:`_orm.attribute_mapped_collection` and
:func:`_orm.column_mapped_collection`, used when populating the dictionary,
to assert that the data value on the object to be used as the dictionary
key is actually present, and is not instead using "None" due to the
attribute never being actually assigned. This is used to prevent a
mis-population of None for a key when assigning via a backref where the
"key" attribute on the object is not yet assigned.
As the failure mode here is a transitory condition that is not typically
persisted to the database, and is easy to produce via the constructor of
the class based on the order in which parameters are assigned, it is very
possible that many applications include this behavior already which is
silently passed over. To accommodate for applications where this error is
now raised, a new parameter
:paramref:`_orm.attribute_mapped_collection.ignore_unpopulated_attribute`
is also added to both :func:`_orm.attribute_mapped_collection` and
:func:`_orm.column_mapped_collection` that instead causes the erroneous
backref assignment to be skipped.
Mike Bayer [Tue, 16 Aug 2022 18:25:12 +0000 (14:25 -0400)]
refine transfer of cached ORM options for selectin, lazy
Fixed issue involving :func:`_orm.with_loader_criteria` where a closure
variable used as bound parameter value within the lambda would not carry
forward correctly into additional relationship loaders such as
:func:`_orm.selectinload` and :func:`_orm.lazyload` after the statement
were cached, using the stale originally-cached value instead.
This change brings forth a good refinement where we finally realize
we shouldn't be testing every ORM option with lots of switches, we
just let the option itself be given "here is your uncached version,
you are cached, tell us what to do!". the current decision is
that strategy loader options used the cached in all cases as they
always have, with_loader_criteria uses the uncached, because the
uncached will have been invoked with new closure state that we
definitely need. The only
edge that might not work is if with_loader_criteria referenced
an entity that is local to the query, namely a specific AliasedInsp,
however that's not a documented case for this. if we had to do that,
then we perhaps would introduce a more complex reconcilation
logic, and this would also give us the hook to do that.
Mike Bayer [Wed, 17 Aug 2022 17:06:51 +0000 (13:06 -0400)]
fill out all distinguising fields for AliasedInsp
Hardened the cache key strategy for the :func:`_orm.aliased` and
:func:`_orm.with_polymorphic` constructs. While no issue involving actual
statements being cached can easily be demonstrated (if at all), these two
constructs were not including enough of what makes them unique in their
cache keys for caching on the aliased construct alone to be accurate.
Introduced the type :class:`_postgresql.JSONPATH` that can be used
in cast expressions. This is required by some PostgreSQL dialects
when using functions such as ``jsonb_path_exists`` or
``jsonb_path_match`` that accept a ``jsonpath`` as input.
Mike Bayer [Wed, 10 Aug 2022 14:53:11 +0000 (10:53 -0400)]
Propagate key for collection events
Added new parameter :paramref:`_orm.AttributeEvents.include_key`, which
will include the dictionary or list key for operations such as
``__setitem__()`` (e.g. ``obj[key] = value``) and ``__delitem__()`` (e.g.
``del obj[key]``), using a new keyword parameter "key" or "keys", depending
on event, e.g. :paramref:`_orm.AttributeEvents.append.key`,
:paramref:`_orm.AttributeEvents.bulk_replace.keys`. This allows event
handlers to take into account the key that was passed to the operation and
is of particular importance for dictionary operations working with
:class:`_orm.MappedCollection`.
Mike Bayer [Fri, 12 Aug 2022 22:35:14 +0000 (18:35 -0400)]
restore Connectable and other changes for oslo.db
at this point oslo.db should be passing tests however
they seem to be importing "Connectable", which we had
temporarily removed, it's now a different kind of object
but restore it to the engine import space which seems
to be where they're pulling it from to see if oslo.db
can run some tests now.
RamonWill [Tue, 25 Aug 2020 00:17:19 +0000 (20:17 -0400)]
Add support for Partitioning and Sample pages on mysql
Add support for Partitioning and Sample pages on MySQL and MariaDB
reflected options.
The options are stored in the table dialect options dictionary, so
the following keyword need to be prefixed with ``mysql_`` or ``mariadb_``
depending on the backend.
Supported options are:
These options are also reflected when loading a table from database,
and will populate the table :attr:`_schema.Table.dialect_options`.
Pull request courtesy of Ramon Will.
Mike Bayer [Thu, 11 Aug 2022 14:20:49 +0000 (10:20 -0400)]
reorg bulk persistence into a separate module
This restores persistence.py to only functions that are used
by unitofwork.py, and all the "bulk" stuff gets its own
module bulk_persistence.py. Also fixes up the ORM context
class hierarchy for bulk.
This is all ahead of the ORM-insert changes coming in, so that
the later review can be about logic and not about reorganization.
Daniel Hall [Sat, 30 Jul 2022 19:12:20 +0000 (15:12 -0400)]
Support comments on MSSQL
Added support table and column comments on MSSQL when
creating a table. Added support for reflecting table comments.
Thanks to Daniel Hall for the help in this pull request.
Mike Bayer [Wed, 10 Aug 2022 16:40:17 +0000 (12:40 -0400)]
doc fixes
* fixed erroneous use of mapped_column() in m2m relationship Table
* Fill in full imports for some relationship examples that had
partial imports; examples that have no imports, leave empty for now
* converted joined/single inh mappings to annotated style
* We have a problem with @declared_attr in that the error message
is wrong if the mapped_column() returned doesnt have a type, and/or
mapped_column() with @declared_attr doesnt use the annotation
* fix thing where sphinx with undoc-members global setting seems to
no longer tolerate ":attribute:" entries in autodoc classes, which
is fine we can document the annotations now
* Fix mapper params in inheritance to be on Mapper
* add missing changelog file for instances remove
Mike Bayer [Tue, 9 Aug 2022 13:50:57 +0000 (09:50 -0400)]
improve names for datatypes section
Continuing along #8362, if we look at the document here without
"this is the same text I've read for 14 years", we begin to see
that the title "Column and Data types" makes no sense at all,
is there a "column type" and a "Data type"? I guess what I was
thinking at that time is that a type can be placed on a
Column, or it can be used whenever you have, you know, "data".
The phrase "SQL expression" wasn't discovered yet.
"SQL Datatype" is not spectacular but at least it's one term.
the new intro then is focused on the hierarchy layout so let's
name it that.
not amazing, but better than the duplicate name that made
no sense before.
Mike Bayer [Fri, 5 Aug 2022 21:25:05 +0000 (17:25 -0400)]
deep compare CTEs before considering them conflicting
Fixed issue where referencing a CTE multiple times in conjunction with a
polymorphic SELECT could result in multiple "clones" of the same CTE being
constructed, which would then trigger these two CTEs as duplicates. To
resolve, the two CTEs are deep-compared when this occurs to ensure that
they are equivalent, then are treated as equivalent.
Mike Bayer [Wed, 3 Aug 2022 20:55:23 +0000 (16:55 -0400)]
translate joined inheritance cols in UPDATE/DELETE
Fixed issue in ORM enabled UPDATE when the statement is created against a
joined-inheritance subclass, updating only local table columns, where the
"fetch" synchronization strategy would not render the correct RETURNING
clause for databases that use RETURNING for fetch synchronization.
Also adjusts the strategy used for RETURNING in UPDATE FROM and
DELETE FROM statements.
Also fixes MariaDB which does not support RETURNING with
DELETE..USING. this was not caught in tests because
"fetch" strategy wasn't tested. so also adjust the ORMDMLState
classes to look for "extra froms" first before adding
RETURNING, add new parameters to interfaces for
"update_returning_multitable" and "delete_returning_multitable".
A new execution option is_delete_using=True, described in the
changelog message, is added to allow the ORM to know up front
if a certain statement should have a SELECT up front
for "fetch" strategy.
Mike Bayer [Thu, 4 Aug 2022 14:27:59 +0000 (10:27 -0400)]
implement PG ranges/multiranges agnostically
Ranges now work using a new Range object,
multiranges as lists of Range objects (this is what
asyncpg does. not sure why psycopg has a "Multirange"
type).
psycopg, psycopg2, and asyncpg are currently supported.
It's not clear how to make ranges work with pg8000, likely
needs string conversion; this is straightforward with the
new archicture and can be added later.
Mike Bayer [Tue, 2 Aug 2022 20:18:18 +0000 (16:18 -0400)]
include column.default, column.onupdate in eager_defaults
Fixed bug in the behavior of the :paramref:`_orm.Mapper.eager_defaults`
parameter such that client-side SQL default or onupdate expressions in the
table definition alone will trigger a fetch operation using RETURNING or
SELECT when the ORM emits an INSERT or UPDATE for the row. Previously, only
server side defaults established as part of table DDL and/or server-side
onupdate expressions would trigger this fetch, even though client-side SQL
expressions would be included when the fetch was rendered.
zeeeeb [Tue, 28 Jun 2022 23:05:08 +0000 (19:05 -0400)]
fixes: #7156 - Adds support for PostgreSQL MultiRange type
This adds functionality for PostgreSQL MultiRange type, as discussed in Issue #7156.
As far as I can tell, only psycopg provides a [Multirange adaptation](https://www.psycopg.org/psycopg3/docs/basic/pgtypes.html#multirange-adaptation). Psycopg2 only supports a [Range adaptation/data type](https://www.psycopg.org/psycopg3/docs/basic/pgtypes.html#multirange-adaptation).
This pull request is:
- [ ] A documentation / typographical 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.
- [x] 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.
Mike Bayer [Wed, 3 Aug 2022 22:59:05 +0000 (18:59 -0400)]
deprecate Query.instances()
this method no longer does the thing that it was originally
intended to do, which is to get ORM results from arbitrary
result sets. Modern patterns should supersede the
use of this construct.
Mike Bayer [Wed, 3 Aug 2022 18:08:32 +0000 (14:08 -0400)]
ensure RETURNING renders in stringify w/ no server version
just in my own testing, if I say insert().return_defaults()
and stringify, I should see it, so make sure all the dialects
default to "insert_returning" etc. , with downgrade on
server version check.
Mike Bayer [Wed, 3 Aug 2022 16:08:54 +0000 (12:08 -0400)]
send in the dragons on async_scoped_session
make it clear that async_scoped_session.remove() must
be called, else memory will build up. Generally
discourage the whole pattern as well, as this is a
"framework" pattern and we don't really want to be supporting
frameworks. Also indicate that scopefunc must be idempotent
and lightweight.
Mike Bayer [Tue, 2 Aug 2022 18:51:49 +0000 (14:51 -0400)]
reword yield_per a bit more
I'm still not satisified with this section as it is still
too wordy and dense, but at least let's put a better description
of what yield_per actually is and why one might use it at the top.
Fixed issue where the SQL Server dialect's query for the current isolation
level would fail on Azure Synapse Analytics, due to the way in which this
database handles transaction rollbacks after an error has occurred. The
initial query has been modified to no longer rely upon catching an error
when attempting to detect the appropriate system view. Additionally, to
better support this database's very specific "rollback" behavior,
implemented new parameter ``ignore_no_transaction_on_rollback`` indicating
that a rollback should ignore Azure Synapse error 'No corresponding
transaction found. (111214)', which is raised if no transaction is present
in conflict with the Python DBAPI.
Mike Bayer [Tue, 2 Aug 2022 15:34:35 +0000 (11:34 -0400)]
fix up SAVEPOINT docs
these contained a factual error that the entire session is
expired, which is no longer the case (I can't find exactly
when this was changed). Additionally, added a PostgreSQL
specific example w/ IntegrityError as this is the most
common case for this. Tried to tighten up other language
and make it as clear as possible.
Added new parameter to SQLite for reflection methods called
``sqlite_include_internal=True``; when omitted, local tables that start
with the prefix ``sqlite_``, which per SQLite documentation are noted as
"internal schema" tables such as the ``sqlite_sequence`` table generated to
support "AUTOINCREMENT" columns, will not be included in reflection methods
that return lists of local objects. This prevents issues for example when
using Alembic autogenerate, which previously would consider these
SQLite-generated tables as being remove from the model.