SQLAlchemy 2.0.57__py3-none-any.whl → 2.0.59__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- sqlalchemy/__init__.py +1 -1
- sqlalchemy/dialects/mssql/base.py +1 -1
- sqlalchemy/dialects/mssql/pyodbc.py +3 -1
- sqlalchemy/dialects/mysql/pymysql.py +3 -1
- sqlalchemy/dialects/postgresql/asyncpg.py +41 -2
- sqlalchemy/dialects/postgresql/base.py +4 -1
- sqlalchemy/dialects/sqlite/aiosqlite.py +30 -2
- sqlalchemy/dialects/sqlite/pysqlite.py +38 -0
- sqlalchemy/engine/url.py +28 -13
- sqlalchemy/event/registry.py +8 -4
- sqlalchemy/ext/asyncio/scoping.py +1 -1
- sqlalchemy/ext/asyncio/session.py +1 -1
- sqlalchemy/ext/declarative/extensions.py +3 -2
- sqlalchemy/orm/bulk_persistence.py +35 -8
- sqlalchemy/orm/context.py +67 -1
- sqlalchemy/orm/dependency.py +3 -0
- sqlalchemy/orm/evaluator.py +147 -29
- sqlalchemy/orm/events.py +4 -8
- sqlalchemy/orm/loading.py +24 -5
- sqlalchemy/orm/strategies.py +40 -69
- sqlalchemy/orm/util.py +3 -0
- sqlalchemy/pool/base.py +21 -6
- sqlalchemy/sql/compiler.py +41 -10
- sqlalchemy/sql/elements.py +16 -8
- sqlalchemy/sql/functions.py +21 -0
- sqlalchemy/sql/selectable.py +86 -18
- sqlalchemy/util/__init__.py +3 -0
- sqlalchemy/util/concurrency.py +4 -0
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/METADATA +1 -1
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/RECORD +34 -34
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/WHEEL +0 -0
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/licenses/AUTHORS +0 -0
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/licenses/LICENSE +0 -0
- {sqlalchemy-2.0.57.dist-info → sqlalchemy-2.0.59.dist-info}/top_level.txt +0 -0
sqlalchemy/__init__.py
CHANGED
|
@@ -1948,7 +1948,7 @@ class MSExecutionContext(default.DefaultExecutionContext):
|
|
|
1948
1948
|
)
|
|
1949
1949
|
# fetchall() ensures the cursor is consumed without closing it
|
|
1950
1950
|
row = self.cursor.fetchall()[0]
|
|
1951
|
-
self._lastrowid = int(row[0])
|
|
1951
|
+
self._lastrowid = int(row[0]) if row[0] is not None else None
|
|
1952
1952
|
|
|
1953
1953
|
self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
|
|
1954
1954
|
elif (
|
|
@@ -609,7 +609,9 @@ class MSExecutionContext_pyodbc(MSExecutionContext):
|
|
|
609
609
|
row = rows[0]
|
|
610
610
|
break
|
|
611
611
|
|
|
612
|
-
|
|
612
|
+
# scope_identity() is NULL if no identity was generated in this
|
|
613
|
+
# scope, e.g. IGNORE_DUP_KEY, INSTEAD OF trigger
|
|
614
|
+
self._lastrowid = int(row[0]) if row[0] is not None else None
|
|
613
615
|
|
|
614
616
|
self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
|
|
615
617
|
else:
|
|
@@ -165,7 +165,9 @@ class MySQLDialect_pymysql(MySQLDialect_mysqldb):
|
|
|
165
165
|
elif isinstance(e, self.loaded_dbapi.Error):
|
|
166
166
|
str_e = str(e).lower()
|
|
167
167
|
return (
|
|
168
|
-
"already closed" in str_e
|
|
168
|
+
"already closed" in str_e
|
|
169
|
+
or "connection was killed" in str_e
|
|
170
|
+
or "packet sequence number wrong" in str_e
|
|
169
171
|
)
|
|
170
172
|
else:
|
|
171
173
|
return False
|
|
@@ -1010,16 +1010,55 @@ class AsyncAdapt_asyncpg_dbapi:
|
|
|
1010
1010
|
def _asyncpg_error_translate(self):
|
|
1011
1011
|
import asyncpg
|
|
1012
1012
|
|
|
1013
|
-
|
|
1013
|
+
translate = {
|
|
1014
1014
|
asyncpg.exceptions.IntegrityConstraintViolationError: self.IntegrityError, # noqa: E501
|
|
1015
|
-
asyncpg.exceptions.PostgresError: self.
|
|
1015
|
+
asyncpg.exceptions.PostgresError: self.DatabaseError,
|
|
1016
1016
|
asyncpg.exceptions.SyntaxOrAccessError: self.ProgrammingError,
|
|
1017
1017
|
asyncpg.exceptions.InterfaceError: self.InterfaceError,
|
|
1018
1018
|
asyncpg.exceptions.InvalidCachedStatementError: self.InvalidCachedStatementError, # noqa: E501
|
|
1019
1019
|
asyncpg.exceptions.InternalServerError: self.InternalServerError,
|
|
1020
1020
|
asyncpg.exceptions.InternalClientError: self.InternalClientError,
|
|
1021
|
+
asyncpg.exceptions.PostgresConnectionError: self.OperationalError,
|
|
1022
|
+
asyncpg.exceptions.FeatureNotSupportedError: self.NotSupportedError, # noqa: E501
|
|
1023
|
+
asyncpg.exceptions.CaseNotFoundError: self.ProgrammingError,
|
|
1024
|
+
asyncpg.exceptions.CardinalityViolationError: self.ProgrammingError, # noqa: E501
|
|
1025
|
+
asyncpg.exceptions.DataError: self.DataError,
|
|
1026
|
+
asyncpg.exceptions.InvalidCursorStateError: self.InternalError,
|
|
1027
|
+
asyncpg.exceptions.InvalidTransactionStateError: self.InternalError, # noqa: E501
|
|
1028
|
+
asyncpg.exceptions.InvalidSQLStatementNameError: self.ProgrammingError, # noqa: E501
|
|
1029
|
+
asyncpg.exceptions.TriggeredDataChangeViolationError: self.OperationalError, # noqa: E501
|
|
1030
|
+
asyncpg.exceptions.InvalidAuthorizationSpecificationError: self.OperationalError, # noqa: E501
|
|
1031
|
+
asyncpg.exceptions.DependentPrivilegeDescriptorsStillExistError: self.InternalError, # noqa: E501
|
|
1032
|
+
asyncpg.exceptions.InvalidTransactionTerminationError: self.InternalError, # noqa: E501
|
|
1033
|
+
asyncpg.exceptions.SQLRoutineError: self.OperationalError,
|
|
1034
|
+
asyncpg.exceptions.InvalidCursorNameError: self.ProgrammingError,
|
|
1035
|
+
asyncpg.exceptions.ExternalRoutineError: self.OperationalError,
|
|
1036
|
+
asyncpg.exceptions.ExternalRoutineInvocationError: self.OperationalError, # noqa: E501
|
|
1037
|
+
asyncpg.exceptions.SavepointError: self.OperationalError,
|
|
1038
|
+
asyncpg.exceptions.InvalidCatalogNameError: self.ProgrammingError,
|
|
1039
|
+
asyncpg.exceptions.InvalidSchemaNameError: self.ProgrammingError,
|
|
1040
|
+
asyncpg.exceptions.TransactionRollbackError: self.OperationalError,
|
|
1041
|
+
asyncpg.exceptions.WithCheckOptionViolationError: self.ProgrammingError, # noqa: E501
|
|
1042
|
+
asyncpg.exceptions.InsufficientResourcesError: self.OperationalError, # noqa: E501
|
|
1043
|
+
asyncpg.exceptions.ProgramLimitExceededError: self.OperationalError, # noqa: E501
|
|
1044
|
+
asyncpg.exceptions.ObjectNotInPrerequisiteStateError: self.OperationalError, # noqa: E501
|
|
1045
|
+
asyncpg.exceptions.OperatorInterventionError: self.OperationalError, # noqa: E501
|
|
1046
|
+
asyncpg.exceptions.PostgresSystemError: self.OperationalError,
|
|
1047
|
+
asyncpg.exceptions.ConfigFileError: self.OperationalError,
|
|
1048
|
+
asyncpg.exceptions.FDWError: self.OperationalError,
|
|
1049
|
+
asyncpg.exceptions.PLPGSQLError: self.ProgrammingError,
|
|
1021
1050
|
}
|
|
1022
1051
|
|
|
1052
|
+
# class 10 (XQuery) has an exception class only as of asyncpg 0.30.0
|
|
1053
|
+
# (https://github.com/MagicStack/asyncpg/pull/1189)
|
|
1054
|
+
xquery_error = getattr(
|
|
1055
|
+
asyncpg.exceptions, "InvalidArgumentForXqueryError", None
|
|
1056
|
+
)
|
|
1057
|
+
if xquery_error is not None:
|
|
1058
|
+
translate[xquery_error] = self.ProgrammingError
|
|
1059
|
+
|
|
1060
|
+
return translate
|
|
1061
|
+
|
|
1023
1062
|
def Binary(self, value):
|
|
1024
1063
|
return value
|
|
1025
1064
|
|
|
@@ -1443,7 +1443,7 @@ defined, so other SQL dialects may behave differently than PostgreSQL.
|
|
|
1443
1443
|
The ``NULLS NOT DISTINCT`` clause can be used to change this behavior, treating
|
|
1444
1444
|
null values as equal and preventing unintended duplicate rows. The opposite
|
|
1445
1445
|
``NULLS DISTINCT`` clause can also be used to make PostgreSQL's default behavior
|
|
1446
|
-
|
|
1446
|
+
explicit.
|
|
1447
1447
|
|
|
1448
1448
|
The ``postgresql_nulls_not_distinct`` parameter can be set to ``True`` to
|
|
1449
1449
|
add the ``NULLS NOT DISTINCT`` clause, or ``False`` to add ``NULLS DISTINCT``.
|
|
@@ -1718,6 +1718,7 @@ from .types import REGCLASS as REGCLASS
|
|
|
1718
1718
|
from .types import REGCONFIG as REGCONFIG # noqa: F401
|
|
1719
1719
|
from .types import TIME as TIME
|
|
1720
1720
|
from .types import TIMESTAMP as TIMESTAMP
|
|
1721
|
+
from .types import TSQUERY as TSQUERY
|
|
1721
1722
|
from .types import TSVECTOR as TSVECTOR
|
|
1722
1723
|
from ... import exc
|
|
1723
1724
|
from ... import schema
|
|
@@ -1927,6 +1928,8 @@ ischema_names = {
|
|
|
1927
1928
|
"boolean": BOOLEAN,
|
|
1928
1929
|
"interval": INTERVAL,
|
|
1929
1930
|
"tsvector": TSVECTOR,
|
|
1931
|
+
"tsquery": TSQUERY,
|
|
1932
|
+
"regconfig": REGCONFIG,
|
|
1930
1933
|
}
|
|
1931
1934
|
|
|
1932
1935
|
|
|
@@ -186,8 +186,10 @@ class AsyncAdapt_aiosqlite_cursor:
|
|
|
186
186
|
parameters: Optional[_DBAPISingleExecuteParams] = None,
|
|
187
187
|
) -> Any:
|
|
188
188
|
|
|
189
|
+
driver_cursor: Optional[AsyncIODBAPICursor] = None
|
|
189
190
|
try:
|
|
190
191
|
_cursor: AsyncIODBAPICursor = self.await_(self._connection.cursor()) # type: ignore[arg-type] # noqa: E501
|
|
192
|
+
driver_cursor = _cursor
|
|
191
193
|
|
|
192
194
|
if parameters is None:
|
|
193
195
|
self.await_(_cursor.execute(operation))
|
|
@@ -209,7 +211,11 @@ class AsyncAdapt_aiosqlite_cursor:
|
|
|
209
211
|
self.await_(_cursor.close())
|
|
210
212
|
else:
|
|
211
213
|
self._cursor = _cursor # type: ignore[misc]
|
|
212
|
-
except
|
|
214
|
+
except BaseException as error:
|
|
215
|
+
if driver_cursor is not None:
|
|
216
|
+
self._close_interrupted(driver_cursor, error)
|
|
217
|
+
if not isinstance(error, Exception):
|
|
218
|
+
raise
|
|
213
219
|
self._adapt_connection._handle_exception(error)
|
|
214
220
|
|
|
215
221
|
def executemany(
|
|
@@ -217,16 +223,38 @@ class AsyncAdapt_aiosqlite_cursor:
|
|
|
217
223
|
operation: Any,
|
|
218
224
|
seq_of_parameters: _DBAPIMultiExecuteParams,
|
|
219
225
|
) -> Any:
|
|
226
|
+
driver_cursor: Optional[AsyncIODBAPICursor] = None
|
|
220
227
|
try:
|
|
221
228
|
_cursor: AsyncIODBAPICursor = self.await_(self._connection.cursor()) # type: ignore[arg-type] # noqa: E501
|
|
229
|
+
driver_cursor = _cursor
|
|
222
230
|
self.await_(_cursor.executemany(operation, seq_of_parameters))
|
|
223
231
|
self.description = None
|
|
224
232
|
self.lastrowid = _cursor.lastrowid
|
|
225
233
|
self.rowcount = _cursor.rowcount
|
|
226
234
|
self.await_(_cursor.close())
|
|
227
|
-
except
|
|
235
|
+
except BaseException as error:
|
|
236
|
+
if driver_cursor is not None:
|
|
237
|
+
self._close_interrupted(driver_cursor, error)
|
|
238
|
+
if not isinstance(error, Exception):
|
|
239
|
+
raise
|
|
228
240
|
self._adapt_connection._handle_exception(error)
|
|
229
241
|
|
|
242
|
+
def _close_interrupted(
|
|
243
|
+
self, cursor: AsyncIODBAPICursor, error: BaseException
|
|
244
|
+
) -> None:
|
|
245
|
+
# an exit exception such as asyncio.CancelledError invalidates the
|
|
246
|
+
# connection without the cursor being closed. sqlite3 as of
|
|
247
|
+
# Python 3.11 does not finalize a closed connection's statements,
|
|
248
|
+
# so a cursor left open keeps the database file locked until it's
|
|
249
|
+
# garbage collected. close it here; aiosqlite runs the close on
|
|
250
|
+
# its worker thread after the interrupted statement completes.
|
|
251
|
+
# see #13831
|
|
252
|
+
if util.is_exit_exception(error):
|
|
253
|
+
try:
|
|
254
|
+
self.await_(cursor.close())
|
|
255
|
+
except Exception:
|
|
256
|
+
pass
|
|
257
|
+
|
|
230
258
|
def setinputsizes(self, *inputsizes: Any) -> None:
|
|
231
259
|
pass
|
|
232
260
|
|
|
@@ -261,6 +261,44 @@ connection reuse implemented by :class:`.QueuePool`. However, it still
|
|
|
261
261
|
may be beneficial to use this class if the application is experiencing
|
|
262
262
|
issues with files being locked.
|
|
263
263
|
|
|
264
|
+
.. _pysqlite_freethreaded:
|
|
265
|
+
|
|
266
|
+
Free-Threaded Python and "database is locked" Errors
|
|
267
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
268
|
+
|
|
269
|
+
On free-threaded builds of Python, the ``sqlite3`` driver may stall and then
|
|
270
|
+
raise ``database is locked`` when a connection is used by different threads
|
|
271
|
+
over time, as occurs when using :class:`.QueuePool`, even though only one
|
|
272
|
+
thread makes use of the connection at once. When a statement is evicted from
|
|
273
|
+
the driver's per-connection statement cache, its finalization may be deferred
|
|
274
|
+
to the thread which created it; if that thread holds SQLite's write lock on
|
|
275
|
+
another connection, while the thread that evicted the statement is waiting for
|
|
276
|
+
that same lock, neither thread can proceed until the SQLite busy timeout
|
|
277
|
+
expires.
|
|
278
|
+
|
|
279
|
+
This is an issue in the ``sqlite3`` driver itself, tracked at
|
|
280
|
+
https://github.com/python/cpython/issues/162919. It has been observed to
|
|
281
|
+
depend on the Python build in use and not on whether the GIL is enabled at
|
|
282
|
+
runtime, so ``PYTHON_GIL=1`` should not be relied upon as a workaround.
|
|
283
|
+
|
|
284
|
+
The issue may be avoided by disabling the statement cache of the ``sqlite3``
|
|
285
|
+
driver, which allows connection pooling to be retained::
|
|
286
|
+
|
|
287
|
+
engine = create_engine(
|
|
288
|
+
"sqlite:///myfile.db", connect_args={"cached_statements": 0}
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
Alternatively, :class:`.NullPool` may be used, so that connections are not
|
|
292
|
+
reused among threads::
|
|
293
|
+
|
|
294
|
+
from sqlalchemy import NullPool
|
|
295
|
+
|
|
296
|
+
engine = create_engine("sqlite:///myfile.db", poolclass=NullPool)
|
|
297
|
+
|
|
298
|
+
.. seealso::
|
|
299
|
+
|
|
300
|
+
:ticket:`13825`
|
|
301
|
+
|
|
264
302
|
Using a Memory Database in Multiple Threads or Coroutines
|
|
265
303
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
266
304
|
|
sqlalchemy/engine/url.py
CHANGED
|
@@ -400,7 +400,7 @@ class URL(NamedTuple):
|
|
|
400
400
|
|
|
401
401
|
def update_query_pairs(
|
|
402
402
|
self,
|
|
403
|
-
key_value_pairs: Iterable[Tuple[str, Union[str,
|
|
403
|
+
key_value_pairs: Iterable[Tuple[str, Union[str, Sequence[str]]]],
|
|
404
404
|
append: bool = False,
|
|
405
405
|
) -> URL:
|
|
406
406
|
"""Return a new :class:`_engine.URL` object with the
|
|
@@ -421,8 +421,24 @@ class URL(NamedTuple):
|
|
|
421
421
|
>>> str(url)
|
|
422
422
|
'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
|
|
423
423
|
|
|
424
|
-
|
|
425
|
-
|
|
424
|
+
A value may also be given as a sequence of strings, which is
|
|
425
|
+
equivalent to passing the same key once for each string; the
|
|
426
|
+
above example may also be expressed as::
|
|
427
|
+
|
|
428
|
+
>>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
|
|
429
|
+
>>> url = url.update_query_pairs(
|
|
430
|
+
... [
|
|
431
|
+
... ("alt_host", ["host1", "host2"]),
|
|
432
|
+
... ("ssl_cipher", "/path/to/crt"),
|
|
433
|
+
... ]
|
|
434
|
+
... )
|
|
435
|
+
>>> str(url)
|
|
436
|
+
'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
|
|
437
|
+
|
|
438
|
+
:param key_value_pairs: A sequence of tuples, each containing a
|
|
439
|
+
string key and a value that is either a string or a sequence of
|
|
440
|
+
strings. A key may appear more than once, in which case all of
|
|
441
|
+
its values are combined in the order given.
|
|
426
442
|
|
|
427
443
|
:param append: if True, parameters in the existing query string will
|
|
428
444
|
not be removed; new parameters will be in addition to those present.
|
|
@@ -431,6 +447,9 @@ class URL(NamedTuple):
|
|
|
431
447
|
|
|
432
448
|
.. versionadded:: 1.4
|
|
433
449
|
|
|
450
|
+
.. versionchanged:: 2.0.58, 2.1.9 A value may be given as a sequence
|
|
451
|
+
of strings, including for a key that appears more than once.
|
|
452
|
+
|
|
434
453
|
.. seealso::
|
|
435
454
|
|
|
436
455
|
:attr:`_engine.URL.query`
|
|
@@ -442,12 +461,13 @@ class URL(NamedTuple):
|
|
|
442
461
|
""" # noqa: E501
|
|
443
462
|
|
|
444
463
|
existing_query = self.query
|
|
445
|
-
new_keys: Dict[str, Union[str,
|
|
464
|
+
new_keys: Dict[str, Union[str, Sequence[str]]] = {}
|
|
446
465
|
|
|
447
466
|
for key, value in key_value_pairs:
|
|
448
467
|
if key in new_keys:
|
|
449
|
-
|
|
450
|
-
|
|
468
|
+
current_as_list = util.to_list(new_keys[key])
|
|
469
|
+
current_as_list.extend(util.to_list(value))
|
|
470
|
+
new_keys[key] = current_as_list
|
|
451
471
|
else:
|
|
452
472
|
new_keys[key] = (
|
|
453
473
|
list(value) if isinstance(value, (list, tuple)) else value
|
|
@@ -473,17 +493,12 @@ class URL(NamedTuple):
|
|
|
473
493
|
}
|
|
474
494
|
)
|
|
475
495
|
else:
|
|
476
|
-
new_query = self.query
|
|
477
|
-
{
|
|
478
|
-
k: tuple(v) if isinstance(v, list) else v
|
|
479
|
-
for k, v in new_keys.items()
|
|
480
|
-
}
|
|
481
|
-
)
|
|
496
|
+
new_query = {**self.query, **new_keys}
|
|
482
497
|
return self.set(query=new_query)
|
|
483
498
|
|
|
484
499
|
def update_query_dict(
|
|
485
500
|
self,
|
|
486
|
-
query_parameters: Mapping[str, Union[str,
|
|
501
|
+
query_parameters: Mapping[str, Union[str, Sequence[str]]],
|
|
487
502
|
append: bool = False,
|
|
488
503
|
) -> URL:
|
|
489
504
|
"""Return a new :class:`_engine.URL` object with the
|
sqlalchemy/event/registry.py
CHANGED
|
@@ -123,11 +123,14 @@ def _stored_in_collection(
|
|
|
123
123
|
) -> bool:
|
|
124
124
|
key = event_key._key
|
|
125
125
|
|
|
126
|
-
dispatch_reg = _key_to_collection[key]
|
|
127
|
-
|
|
128
126
|
owner_ref = owner.ref
|
|
129
127
|
listen_ref = weakref.ref(event_key._listen_fn)
|
|
130
128
|
|
|
129
|
+
# look up dispatch_reg only after allocating the weakref; the allocation
|
|
130
|
+
# can run the cyclic collector, which may detach this dict from
|
|
131
|
+
# _key_to_collection via _collection_gced, see #13805
|
|
132
|
+
dispatch_reg = _key_to_collection[key]
|
|
133
|
+
|
|
131
134
|
if owner_ref in dispatch_reg:
|
|
132
135
|
return False
|
|
133
136
|
|
|
@@ -144,10 +147,11 @@ def _removed_from_collection(
|
|
|
144
147
|
) -> None:
|
|
145
148
|
key = event_key._key
|
|
146
149
|
|
|
147
|
-
dispatch_reg = _key_to_collection[key]
|
|
148
|
-
|
|
149
150
|
listen_ref = weakref.ref(event_key._listen_fn)
|
|
150
151
|
|
|
152
|
+
# look up dispatch_reg after allocating the weakref, see #13805
|
|
153
|
+
dispatch_reg = _key_to_collection[key]
|
|
154
|
+
|
|
151
155
|
owner_ref = owner.ref
|
|
152
156
|
dispatch_reg.pop(owner_ref, None)
|
|
153
157
|
if not dispatch_reg:
|
|
@@ -445,8 +445,9 @@ class DeferredReflection:
|
|
|
445
445
|
:param bind: :class:`_engine.Engine` or :class:`_engine.Connection`
|
|
446
446
|
instance
|
|
447
447
|
|
|
448
|
-
..versionchanged::
|
|
449
|
-
|
|
448
|
+
.. versionchanged::
|
|
449
|
+
|
|
450
|
+
2.0.16 a :class:`_engine.Connection` is also accepted.
|
|
450
451
|
|
|
451
452
|
:param \**reflect_kw: additional keyword arguments passed to
|
|
452
453
|
:meth:`_schema.MetaData.reflect`, such as
|
|
@@ -1771,12 +1771,22 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState):
|
|
|
1771
1771
|
session.identity_map.all_states(),
|
|
1772
1772
|
)
|
|
1773
1773
|
|
|
1774
|
+
to_update = []
|
|
1775
|
+
for obj, state, dict_, is_partially_expired in matched_objects:
|
|
1776
|
+
if is_partially_expired:
|
|
1777
|
+
# the criteria read expired attributes, so it's not known
|
|
1778
|
+
# if the row matched; expire the object, as is the case
|
|
1779
|
+
# for DELETE
|
|
1780
|
+
state._expire(dict_, session.identity_map._modified)
|
|
1781
|
+
else:
|
|
1782
|
+
to_update.append((obj, state, dict_))
|
|
1783
|
+
|
|
1774
1784
|
cls._apply_update_set_values_to_objects(
|
|
1775
1785
|
session,
|
|
1776
1786
|
update_options,
|
|
1777
1787
|
statement,
|
|
1778
1788
|
result.context.compiled_parameters[0],
|
|
1779
|
-
|
|
1789
|
+
to_update,
|
|
1780
1790
|
result.prefetch_cols(),
|
|
1781
1791
|
result.postfetch_cols(),
|
|
1782
1792
|
)
|
|
@@ -1892,6 +1902,28 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState):
|
|
|
1892
1902
|
]
|
|
1893
1903
|
|
|
1894
1904
|
for obj, state, dict_ in matched_objects:
|
|
1905
|
+
to_evaluate = state.unmodified.intersection(evaluated_keys)
|
|
1906
|
+
|
|
1907
|
+
# evaluate all SET values against the object as it was before
|
|
1908
|
+
# the UPDATE, before any of them are applied, as the database
|
|
1909
|
+
# does; only run eval for attributes that are present.
|
|
1910
|
+
evaluated_values = {
|
|
1911
|
+
key: value_evaluators[key](obj)
|
|
1912
|
+
for key in to_evaluate
|
|
1913
|
+
if key in dict_
|
|
1914
|
+
}
|
|
1915
|
+
|
|
1916
|
+
# a SET value that read an expired attribute can't be known;
|
|
1917
|
+
# expire the target attribute
|
|
1918
|
+
expired_values = {
|
|
1919
|
+
key
|
|
1920
|
+
for key, value in evaluated_values.items()
|
|
1921
|
+
if value is evaluator._EXPIRED_OBJECT
|
|
1922
|
+
}
|
|
1923
|
+
if expired_values:
|
|
1924
|
+
to_evaluate.difference_update(expired_values)
|
|
1925
|
+
for key in expired_values:
|
|
1926
|
+
del evaluated_values[key]
|
|
1895
1927
|
|
|
1896
1928
|
dict_.update(
|
|
1897
1929
|
{
|
|
@@ -1900,14 +1932,9 @@ class BulkORMUpdate(BulkUDCompileState, UpdateDMLState):
|
|
|
1900
1932
|
}
|
|
1901
1933
|
)
|
|
1902
1934
|
|
|
1903
|
-
state._expire_attributes(
|
|
1904
|
-
|
|
1905
|
-
to_evaluate = state.unmodified.intersection(evaluated_keys)
|
|
1935
|
+
state._expire_attributes(dict_, to_expire.union(expired_values))
|
|
1906
1936
|
|
|
1907
|
-
|
|
1908
|
-
if key in dict_:
|
|
1909
|
-
# only run eval for attributes that are present.
|
|
1910
|
-
dict_[key] = value_evaluators[key](obj)
|
|
1937
|
+
dict_.update(evaluated_values)
|
|
1911
1938
|
|
|
1912
1939
|
state.manager.dispatch.refresh(state, None, to_evaluate)
|
|
1913
1940
|
|
sqlalchemy/orm/context.py
CHANGED
|
@@ -57,6 +57,7 @@ from ..sql.base import Executable
|
|
|
57
57
|
from ..sql.base import Generative
|
|
58
58
|
from ..sql.base import Options
|
|
59
59
|
from ..sql.dml import UpdateBase
|
|
60
|
+
from ..sql.elements import ColumnClause
|
|
60
61
|
from ..sql.elements import GroupedElement
|
|
61
62
|
from ..sql.elements import TextClause
|
|
62
63
|
from ..sql.selectable import CompoundSelectState
|
|
@@ -80,6 +81,7 @@ if TYPE_CHECKING:
|
|
|
80
81
|
from ..engine import Result
|
|
81
82
|
from ..engine.interfaces import _CoreSingleExecuteParams
|
|
82
83
|
from ..sql._typing import _ColumnsClauseArgument
|
|
84
|
+
from ..sql.base import ExecutableOption
|
|
83
85
|
from ..sql.compiler import SQLCompiler
|
|
84
86
|
from ..sql.dml import _DMLTableElement
|
|
85
87
|
from ..sql.elements import ColumnElement
|
|
@@ -214,6 +216,39 @@ class QueryContext:
|
|
|
214
216
|
def _get_top_level_context(self) -> QueryContext:
|
|
215
217
|
return self.top_level_context or self
|
|
216
218
|
|
|
219
|
+
def _loader_strategy_options(self) -> Tuple[ExecutableOption, ...]:
|
|
220
|
+
"""Return the options to be used by a loader strategy that emits
|
|
221
|
+
a new statement on behalf of this query, such as a selectin
|
|
222
|
+
loader or a selectin polymorphic loader.
|
|
223
|
+
|
|
224
|
+
The loader strategy is given paths and entities in terms of the
|
|
225
|
+
cached statement, i.e. ``compile_state.select_statement``, which
|
|
226
|
+
may not be the statement passed by the user. While the two are of
|
|
227
|
+
identical structure, entities like :class:`.AliasedInsp` from
|
|
228
|
+
:func:`_orm.aliased` or :func:`_orm.with_polymorphic` will usually
|
|
229
|
+
be a different object identity in each, and will not match up with
|
|
230
|
+
paths and loader lookups. So options with paths need to come from
|
|
231
|
+
the cached statement, while other options like
|
|
232
|
+
:func:`_orm.with_loader_criteria` need the latest state from the
|
|
233
|
+
uncached statement; as of #8399 each option decides this for itself
|
|
234
|
+
given both versions of itself.
|
|
235
|
+
|
|
236
|
+
"""
|
|
237
|
+
orig_query = self.compile_state.select_statement
|
|
238
|
+
|
|
239
|
+
if orig_query is self.user_passed_query:
|
|
240
|
+
return orig_query._with_options
|
|
241
|
+
|
|
242
|
+
return tuple(
|
|
243
|
+
orig_opt._adapt_cached_option_to_uncached_option(
|
|
244
|
+
self, uncached_opt
|
|
245
|
+
)
|
|
246
|
+
for orig_opt, uncached_opt in zip(
|
|
247
|
+
orig_query._with_options,
|
|
248
|
+
self.user_passed_query._with_options,
|
|
249
|
+
)
|
|
250
|
+
)
|
|
251
|
+
|
|
217
252
|
|
|
218
253
|
_orm_load_exec_options = util.immutabledict(
|
|
219
254
|
{"_result_disable_adapt_to_context": True}
|
|
@@ -1622,12 +1657,43 @@ class ORMSelectCompileState(ORMCompileState, SelectState):
|
|
|
1622
1657
|
**self._select_args,
|
|
1623
1658
|
)
|
|
1624
1659
|
|
|
1660
|
+
# tables that are directly in the FROM list of the inner statement,
|
|
1661
|
+
# as opposed to being present only by way of an alias
|
|
1662
|
+
inner_tables = {
|
|
1663
|
+
elem
|
|
1664
|
+
for from_ in inner.get_final_froms()
|
|
1665
|
+
for elem in sql_util.surface_selectables(from_)
|
|
1666
|
+
if elem._is_table
|
|
1667
|
+
}
|
|
1668
|
+
|
|
1669
|
+
def _exclude_fn(elem):
|
|
1670
|
+
# a column of an un-aliased table is at the root of the lineage
|
|
1671
|
+
# of every column derived from that table, so
|
|
1672
|
+
# corresponding_column() can match it to a column of any alias
|
|
1673
|
+
# of that table; a column of an alias only matches columns
|
|
1674
|
+
# derived from that same alias. so skip adapting a column
|
|
1675
|
+
# that's attached to an un-aliased table when that table isn't
|
|
1676
|
+
# present as a plain table in the inner statement's FROM list,
|
|
1677
|
+
# either directly or within a join. the inner statement may
|
|
1678
|
+
# still have a column derived from that table by way of an
|
|
1679
|
+
# alias, such as that of an aliased() joined inheritance
|
|
1680
|
+
# subclass, but that alias refers to different rows, #13798
|
|
1681
|
+
return (
|
|
1682
|
+
isinstance(elem, ColumnClause)
|
|
1683
|
+
and elem.table is not None
|
|
1684
|
+
and elem.table._is_table
|
|
1685
|
+
and elem.table not in inner_tables
|
|
1686
|
+
)
|
|
1687
|
+
|
|
1625
1688
|
inner = inner.alias()
|
|
1626
1689
|
|
|
1627
1690
|
equivs = self._all_equivs()
|
|
1628
1691
|
|
|
1629
1692
|
self.compound_eager_adapter = ORMStatementAdapter(
|
|
1630
|
-
_TraceAdaptRole.COMPOUND_EAGER_STATEMENT,
|
|
1693
|
+
_TraceAdaptRole.COMPOUND_EAGER_STATEMENT,
|
|
1694
|
+
inner,
|
|
1695
|
+
equivalents=equivs,
|
|
1696
|
+
exclude_fn=_exclude_fn,
|
|
1631
1697
|
)
|
|
1632
1698
|
|
|
1633
1699
|
statement = future.select(
|
sqlalchemy/orm/dependency.py
CHANGED
|
@@ -353,6 +353,9 @@ class OneToManyDP(DependencyProcessor):
|
|
|
353
353
|
(child_saves, after_save),
|
|
354
354
|
(parent_saves, after_save),
|
|
355
355
|
(after_save, child_post_updates),
|
|
356
|
+
(child_saves, before_delete),
|
|
357
|
+
(before_delete, child_post_updates),
|
|
358
|
+
(child_post_updates, parent_deletes),
|
|
356
359
|
(before_delete, child_pre_updates),
|
|
357
360
|
(child_pre_updates, parent_deletes),
|
|
358
361
|
(child_pre_updates, child_deletes),
|