SQLAlchemy 2.1.9__py3-none-any.whl → 2.1.10__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/connectors/asyncio.py +20 -2
- sqlalchemy/dialects/mssql/base.py +6 -2
- sqlalchemy/dialects/mysql/pymysql.py +3 -1
- sqlalchemy/dialects/oracle/base.py +1 -1
- sqlalchemy/dialects/postgresql/asyncpg.py +41 -2
- sqlalchemy/dialects/postgresql/psycopg.py +4 -3
- sqlalchemy/dialects/sqlite/aiosqlite.py +23 -0
- sqlalchemy/dialects/sqlite/pysqlite.py +38 -0
- sqlalchemy/event/registry.py +8 -4
- sqlalchemy/ext/asyncio/engine.py +158 -6
- sqlalchemy/orm/attributes.py +7 -27
- sqlalchemy/orm/bulk_persistence.py +35 -8
- sqlalchemy/orm/context.py +26 -8
- sqlalchemy/orm/evaluator.py +147 -29
- sqlalchemy/orm/interfaces.py +13 -0
- sqlalchemy/orm/relationships.py +16 -5
- sqlalchemy/orm/strategies.py +10 -1
- sqlalchemy/orm/util.py +7 -0
- sqlalchemy/sql/compiler.py +42 -11
- sqlalchemy/sql/crud.py +1 -1
- sqlalchemy/sql/functions.py +21 -0
- sqlalchemy/testing/provision.py +5 -5
- sqlalchemy/testing/suite/test_types.py +101 -0
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/METADATA +1 -1
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/RECORD +30 -30
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/WHEEL +0 -0
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/licenses/AUTHORS +0 -0
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/licenses/LICENSE +0 -0
- {sqlalchemy-2.1.9.dist-info → sqlalchemy-2.1.10.dist-info}/top_level.txt +0 -0
sqlalchemy/__init__.py
CHANGED
sqlalchemy/connectors/asyncio.py
CHANGED
|
@@ -254,7 +254,10 @@ class AsyncAdapt_dbapi_cursor:
|
|
|
254
254
|
) -> Any:
|
|
255
255
|
try:
|
|
256
256
|
return await_(self._execute_async(operation, parameters))
|
|
257
|
-
except
|
|
257
|
+
except BaseException as error:
|
|
258
|
+
self._handle_execute_exception(error)
|
|
259
|
+
if not isinstance(error, Exception):
|
|
260
|
+
raise
|
|
258
261
|
self._adapt_connection._handle_exception(error)
|
|
259
262
|
|
|
260
263
|
def executemany(
|
|
@@ -266,9 +269,24 @@ class AsyncAdapt_dbapi_cursor:
|
|
|
266
269
|
return await_(
|
|
267
270
|
self._executemany_async(operation, seq_of_parameters)
|
|
268
271
|
)
|
|
269
|
-
except
|
|
272
|
+
except BaseException as error:
|
|
273
|
+
self._handle_execute_exception(error)
|
|
274
|
+
if not isinstance(error, Exception):
|
|
275
|
+
raise
|
|
270
276
|
self._adapt_connection._handle_exception(error)
|
|
271
277
|
|
|
278
|
+
def _handle_execute_exception(self, error: BaseException) -> None:
|
|
279
|
+
"""Called with any exception raised by execute() or executemany(),
|
|
280
|
+
before it's propagated. No-op by default.
|
|
281
|
+
|
|
282
|
+
When the exception is an exit exception such as
|
|
283
|
+
asyncio.CancelledError, the connection is then invalidated without
|
|
284
|
+
the cursor being closed; a dialect may implement this method to
|
|
285
|
+
release resources held by the cursor that invalidating the
|
|
286
|
+
connection doesn't.
|
|
287
|
+
|
|
288
|
+
"""
|
|
289
|
+
|
|
272
290
|
async def _execute_async(
|
|
273
291
|
self, operation: Any, parameters: Optional[_DBAPISingleExecuteParams]
|
|
274
292
|
) -> Any:
|
|
@@ -1938,7 +1938,11 @@ class MSExecutionContext(default.DefaultExecutionContext):
|
|
|
1938
1938
|
else:
|
|
1939
1939
|
self.cursor.nextset()
|
|
1940
1940
|
|
|
1941
|
-
|
|
1941
|
+
# scope_identity() is NULL if no identity was generated in this
|
|
1942
|
+
# scope, e.g. IGNORE_DUP_KEY, INSTEAD OF trigger
|
|
1943
|
+
self._lastrowid = (
|
|
1944
|
+
int(row[0]) if row and row[0] is not None else None
|
|
1945
|
+
)
|
|
1942
1946
|
|
|
1943
1947
|
self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
|
|
1944
1948
|
|
|
@@ -1956,7 +1960,7 @@ class MSExecutionContext(default.DefaultExecutionContext):
|
|
|
1956
1960
|
)
|
|
1957
1961
|
# fetchall() ensures the cursor is consumed without closing it
|
|
1958
1962
|
row = self.cursor.fetchall()[0]
|
|
1959
|
-
self._lastrowid = int(row[0])
|
|
1963
|
+
self._lastrowid = int(row[0]) if row[0] is not None else None
|
|
1960
1964
|
|
|
1961
1965
|
self.cursor_fetch_strategy = _cursor._NO_CURSOR_DML
|
|
1962
1966
|
elif (
|
|
@@ -174,7 +174,9 @@ class MySQLDialect_pymysql(MySQLDialect_mysqldb):
|
|
|
174
174
|
elif isinstance(e, self.loaded_dbapi.Error):
|
|
175
175
|
str_e = str(e).lower()
|
|
176
176
|
return (
|
|
177
|
-
"already closed" in str_e
|
|
177
|
+
"already closed" in str_e
|
|
178
|
+
or "connection was killed" in str_e
|
|
179
|
+
or "packet sequence number wrong" in str_e
|
|
178
180
|
)
|
|
179
181
|
else:
|
|
180
182
|
return False
|
|
@@ -1836,7 +1836,7 @@ class OracleCompiler(compiler.SQLCompiler):
|
|
|
1836
1836
|
|
|
1837
1837
|
def _render_json_extract_from_binary(self, binary, operator, **kw):
|
|
1838
1838
|
literal_kw = kw.copy()
|
|
1839
|
-
literal_kw["
|
|
1839
|
+
literal_kw["literal_execute"] = True
|
|
1840
1840
|
|
|
1841
1841
|
left = self.process(binary.left, **kw)
|
|
1842
1842
|
right = self.process(binary.right, **literal_kw)
|
|
@@ -1069,9 +1069,9 @@ class AsyncAdapt_asyncpg_dbapi(AsyncAdapt_dbapi_module):
|
|
|
1069
1069
|
def _asyncpg_error_translate(self):
|
|
1070
1070
|
import asyncpg
|
|
1071
1071
|
|
|
1072
|
-
|
|
1072
|
+
translate = {
|
|
1073
1073
|
asyncpg.exceptions.IntegrityConstraintViolationError: self.IntegrityError, # noqa: E501
|
|
1074
|
-
asyncpg.exceptions.PostgresError: self.
|
|
1074
|
+
asyncpg.exceptions.PostgresError: self.DatabaseError,
|
|
1075
1075
|
asyncpg.exceptions.SyntaxOrAccessError: self.ProgrammingError,
|
|
1076
1076
|
asyncpg.exceptions.InterfaceError: self.InterfaceError,
|
|
1077
1077
|
asyncpg.exceptions.InvalidCachedStatementError: self.InvalidCachedStatementError, # noqa: E501
|
|
@@ -1083,8 +1083,47 @@ class AsyncAdapt_asyncpg_dbapi(AsyncAdapt_dbapi_module):
|
|
|
1083
1083
|
asyncpg.exceptions.CheckViolationError: self.CheckViolationError,
|
|
1084
1084
|
asyncpg.exceptions.ExclusionViolationError: self.ExclusionViolationError, # noqa: E501
|
|
1085
1085
|
asyncpg.exceptions.InternalClientError: self.InternalClientError,
|
|
1086
|
+
asyncpg.exceptions.PostgresConnectionError: self.OperationalError,
|
|
1087
|
+
asyncpg.exceptions.FeatureNotSupportedError: self.NotSupportedError, # noqa: E501
|
|
1088
|
+
asyncpg.exceptions.CaseNotFoundError: self.ProgrammingError,
|
|
1089
|
+
asyncpg.exceptions.CardinalityViolationError: self.ProgrammingError, # noqa: E501
|
|
1090
|
+
asyncpg.exceptions.DataError: self.DataError,
|
|
1091
|
+
asyncpg.exceptions.InvalidCursorStateError: self.InternalError,
|
|
1092
|
+
asyncpg.exceptions.InvalidTransactionStateError: self.InternalError, # noqa: E501
|
|
1093
|
+
asyncpg.exceptions.InvalidSQLStatementNameError: self.ProgrammingError, # noqa: E501
|
|
1094
|
+
asyncpg.exceptions.TriggeredDataChangeViolationError: self.OperationalError, # noqa: E501
|
|
1095
|
+
asyncpg.exceptions.InvalidAuthorizationSpecificationError: self.OperationalError, # noqa: E501
|
|
1096
|
+
asyncpg.exceptions.DependentPrivilegeDescriptorsStillExistError: self.InternalError, # noqa: E501
|
|
1097
|
+
asyncpg.exceptions.InvalidTransactionTerminationError: self.InternalError, # noqa: E501
|
|
1098
|
+
asyncpg.exceptions.SQLRoutineError: self.OperationalError,
|
|
1099
|
+
asyncpg.exceptions.InvalidCursorNameError: self.ProgrammingError,
|
|
1100
|
+
asyncpg.exceptions.ExternalRoutineError: self.OperationalError,
|
|
1101
|
+
asyncpg.exceptions.ExternalRoutineInvocationError: self.OperationalError, # noqa: E501
|
|
1102
|
+
asyncpg.exceptions.SavepointError: self.OperationalError,
|
|
1103
|
+
asyncpg.exceptions.InvalidCatalogNameError: self.ProgrammingError,
|
|
1104
|
+
asyncpg.exceptions.InvalidSchemaNameError: self.ProgrammingError,
|
|
1105
|
+
asyncpg.exceptions.TransactionRollbackError: self.OperationalError,
|
|
1106
|
+
asyncpg.exceptions.WithCheckOptionViolationError: self.ProgrammingError, # noqa: E501
|
|
1107
|
+
asyncpg.exceptions.InsufficientResourcesError: self.OperationalError, # noqa: E501
|
|
1108
|
+
asyncpg.exceptions.ProgramLimitExceededError: self.OperationalError, # noqa: E501
|
|
1109
|
+
asyncpg.exceptions.ObjectNotInPrerequisiteStateError: self.OperationalError, # noqa: E501
|
|
1110
|
+
asyncpg.exceptions.OperatorInterventionError: self.OperationalError, # noqa: E501
|
|
1111
|
+
asyncpg.exceptions.PostgresSystemError: self.OperationalError,
|
|
1112
|
+
asyncpg.exceptions.ConfigFileError: self.OperationalError,
|
|
1113
|
+
asyncpg.exceptions.FDWError: self.OperationalError,
|
|
1114
|
+
asyncpg.exceptions.PLPGSQLError: self.ProgrammingError,
|
|
1086
1115
|
}
|
|
1087
1116
|
|
|
1117
|
+
# class 10 (XQuery) has an exception class only as of asyncpg 0.30.0
|
|
1118
|
+
# (https://github.com/MagicStack/asyncpg/pull/1189)
|
|
1119
|
+
xquery_error = getattr(
|
|
1120
|
+
asyncpg.exceptions, "InvalidArgumentForXqueryError", None
|
|
1121
|
+
)
|
|
1122
|
+
if xquery_error is not None:
|
|
1123
|
+
translate[xquery_error] = self.ProgrammingError
|
|
1124
|
+
|
|
1125
|
+
return translate
|
|
1126
|
+
|
|
1088
1127
|
def Binary(self, value):
|
|
1089
1128
|
return value
|
|
1090
1129
|
|
|
@@ -17,9 +17,10 @@ r"""
|
|
|
17
17
|
database driver, formerly known as ``psycopg2``. This driver is different
|
|
18
18
|
enough from its ``psycopg2`` predecessor that SQLAlchemy supports it
|
|
19
19
|
via a totally separate dialect; support for ``psycopg2`` is expected to remain
|
|
20
|
-
for as long as that package continues to function for modern Python versions
|
|
21
|
-
|
|
22
|
-
|
|
20
|
+
for as long as that package continues to function for modern Python versions.
|
|
21
|
+
|
|
22
|
+
.. versionchanged:: 2.1 ``psycopg`` is now the default dialect for the
|
|
23
|
+
``postgresql://`` dialect series, replacing ``psycopg2``.
|
|
23
24
|
|
|
24
25
|
The SQLAlchemy ``psycopg`` dialect provides both a sync and an async
|
|
25
26
|
implementation under the same dialect name. The proper version is
|
|
@@ -152,13 +152,36 @@ if TYPE_CHECKING:
|
|
|
152
152
|
from ...pool.base import PoolProxiedConnection
|
|
153
153
|
|
|
154
154
|
|
|
155
|
+
def _close_interrupted_cursor(
|
|
156
|
+
cursor: AsyncAdapt_dbapi_cursor, error: BaseException
|
|
157
|
+
) -> None:
|
|
158
|
+
# an exit exception such as asyncio.CancelledError invalidates the
|
|
159
|
+
# connection without the cursor being closed. sqlite3 as of
|
|
160
|
+
# Python 3.11 does not finalize a closed connection's statements,
|
|
161
|
+
# so a cursor left open keeps the database file locked until it's
|
|
162
|
+
# garbage collected. close it here; aiosqlite runs the close on
|
|
163
|
+
# its worker thread after the interrupted statement completes.
|
|
164
|
+
# see #13831
|
|
165
|
+
if util.is_exit_exception(error):
|
|
166
|
+
try:
|
|
167
|
+
cursor.close()
|
|
168
|
+
except Exception:
|
|
169
|
+
pass
|
|
170
|
+
|
|
171
|
+
|
|
155
172
|
class AsyncAdapt_aiosqlite_cursor(AsyncAdapt_dbapi_cursor):
|
|
156
173
|
__slots__ = ()
|
|
157
174
|
|
|
175
|
+
def _handle_execute_exception(self, error: BaseException) -> None:
|
|
176
|
+
_close_interrupted_cursor(self, error)
|
|
177
|
+
|
|
158
178
|
|
|
159
179
|
class AsyncAdapt_aiosqlite_ss_cursor(AsyncAdapt_dbapi_ss_cursor):
|
|
160
180
|
__slots__ = ()
|
|
161
181
|
|
|
182
|
+
def _handle_execute_exception(self, error: BaseException) -> None:
|
|
183
|
+
_close_interrupted_cursor(self, error)
|
|
184
|
+
|
|
162
185
|
|
|
163
186
|
class AsyncAdapt_aiosqlite_connection(
|
|
164
187
|
AsyncAdapt_terminate, AsyncAdapt_dbapi_connection
|
|
@@ -276,6 +276,44 @@ connection reuse implemented by :class:`.QueuePool`. However, it still
|
|
|
276
276
|
may be beneficial to use this class if the application is experiencing
|
|
277
277
|
issues with files being locked.
|
|
278
278
|
|
|
279
|
+
.. _pysqlite_freethreaded:
|
|
280
|
+
|
|
281
|
+
Free-Threaded Python and "database is locked" Errors
|
|
282
|
+
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
283
|
+
|
|
284
|
+
On free-threaded builds of Python, the ``sqlite3`` driver may stall and then
|
|
285
|
+
raise ``database is locked`` when a connection is used by different threads
|
|
286
|
+
over time, as occurs when using :class:`.QueuePool`, even though only one
|
|
287
|
+
thread makes use of the connection at once. When a statement is evicted from
|
|
288
|
+
the driver's per-connection statement cache, its finalization may be deferred
|
|
289
|
+
to the thread which created it; if that thread holds SQLite's write lock on
|
|
290
|
+
another connection, while the thread that evicted the statement is waiting for
|
|
291
|
+
that same lock, neither thread can proceed until the SQLite busy timeout
|
|
292
|
+
expires.
|
|
293
|
+
|
|
294
|
+
This is an issue in the ``sqlite3`` driver itself, tracked at
|
|
295
|
+
https://github.com/python/cpython/issues/162919. It has been observed to
|
|
296
|
+
depend on the Python build in use and not on whether the GIL is enabled at
|
|
297
|
+
runtime, so ``PYTHON_GIL=1`` should not be relied upon as a workaround.
|
|
298
|
+
|
|
299
|
+
The issue may be avoided by disabling the statement cache of the ``sqlite3``
|
|
300
|
+
driver, which allows connection pooling to be retained::
|
|
301
|
+
|
|
302
|
+
engine = create_engine(
|
|
303
|
+
"sqlite:///myfile.db", connect_args={"cached_statements": 0}
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
Alternatively, :class:`.NullPool` may be used, so that connections are not
|
|
307
|
+
reused among threads::
|
|
308
|
+
|
|
309
|
+
from sqlalchemy import NullPool
|
|
310
|
+
|
|
311
|
+
engine = create_engine("sqlite:///myfile.db", poolclass=NullPool)
|
|
312
|
+
|
|
313
|
+
.. seealso::
|
|
314
|
+
|
|
315
|
+
:ticket:`13825`
|
|
316
|
+
|
|
279
317
|
Using a Memory Database in Multiple Threads or Coroutines
|
|
280
318
|
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
|
281
319
|
|
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:
|
sqlalchemy/ext/asyncio/engine.py
CHANGED
|
@@ -13,6 +13,7 @@ from typing import Callable
|
|
|
13
13
|
from typing import Concatenate
|
|
14
14
|
from typing import Dict
|
|
15
15
|
from typing import Generator
|
|
16
|
+
from typing import List
|
|
16
17
|
from typing import NoReturn
|
|
17
18
|
from typing import Optional
|
|
18
19
|
from typing import overload
|
|
@@ -40,6 +41,7 @@ from ...engine import create_pool_from_url as _create_pool_from_url
|
|
|
40
41
|
from ...engine import Engine
|
|
41
42
|
from ...engine.base import NestedTransaction
|
|
42
43
|
from ...engine.base import Transaction
|
|
44
|
+
from ...engine.base import TwoPhaseTransaction
|
|
43
45
|
from ...exc import ArgumentError
|
|
44
46
|
from ...util import immutabledict
|
|
45
47
|
from ...util.concurrency import greenlet_spawn
|
|
@@ -345,6 +347,71 @@ class AsyncConnection( # type: ignore[misc]
|
|
|
345
347
|
assert self._proxied
|
|
346
348
|
return AsyncTransaction(self, nested=True)
|
|
347
349
|
|
|
350
|
+
def begin_twophase(self, xid: Optional[Any] = None) -> AsyncTransaction:
|
|
351
|
+
"""Begin a two-phase or XA transaction and return a transaction
|
|
352
|
+
handle.
|
|
353
|
+
|
|
354
|
+
The returned object is an instance of :class:`.AsyncTransaction`,
|
|
355
|
+
which provides the :meth:`_asyncio.AsyncTransaction.prepare` method
|
|
356
|
+
in addition to the usual transaction methods.
|
|
357
|
+
|
|
358
|
+
:param xid: the two phase transaction id. If not supplied, a
|
|
359
|
+
random id will be generated. The accepted type and value depends on
|
|
360
|
+
the driver in use.
|
|
361
|
+
|
|
362
|
+
.. seealso::
|
|
363
|
+
|
|
364
|
+
:meth:`_engine.Connection.begin_twophase`
|
|
365
|
+
|
|
366
|
+
.. versionadded:: 2.1.10
|
|
367
|
+
|
|
368
|
+
"""
|
|
369
|
+
assert self._proxied
|
|
370
|
+
return AsyncTransaction(self, is_two_phase=True, xid=xid)
|
|
371
|
+
|
|
372
|
+
async def recover_twophase(self) -> List[Any]:
|
|
373
|
+
"""Return a list of prepared two-phase transaction identifiers.
|
|
374
|
+
|
|
375
|
+
.. seealso::
|
|
376
|
+
|
|
377
|
+
:meth:`_engine.Connection.recover_twophase`
|
|
378
|
+
|
|
379
|
+
.. versionadded:: 2.1.10
|
|
380
|
+
|
|
381
|
+
"""
|
|
382
|
+
|
|
383
|
+
return await greenlet_spawn(self._proxied.recover_twophase)
|
|
384
|
+
|
|
385
|
+
async def rollback_prepared(self, xid: Any, recover: bool = False) -> None:
|
|
386
|
+
"""Roll back a prepared two-phase transaction.
|
|
387
|
+
|
|
388
|
+
.. seealso::
|
|
389
|
+
|
|
390
|
+
:meth:`_engine.Connection.rollback_prepared`
|
|
391
|
+
|
|
392
|
+
.. versionadded:: 2.1.10
|
|
393
|
+
|
|
394
|
+
"""
|
|
395
|
+
|
|
396
|
+
await greenlet_spawn(
|
|
397
|
+
self._proxied.rollback_prepared, xid, recover=recover
|
|
398
|
+
)
|
|
399
|
+
|
|
400
|
+
async def commit_prepared(self, xid: Any, recover: bool = False) -> None:
|
|
401
|
+
"""Commit a prepared two-phase transaction.
|
|
402
|
+
|
|
403
|
+
.. seealso::
|
|
404
|
+
|
|
405
|
+
:meth:`_engine.Connection.commit_prepared`
|
|
406
|
+
|
|
407
|
+
.. versionadded:: 2.1.10
|
|
408
|
+
|
|
409
|
+
"""
|
|
410
|
+
|
|
411
|
+
await greenlet_spawn(
|
|
412
|
+
self._proxied.commit_prepared, xid, recover=recover
|
|
413
|
+
)
|
|
414
|
+
|
|
348
415
|
async def invalidate(
|
|
349
416
|
self, exception: Optional[BaseException] = None
|
|
350
417
|
) -> None:
|
|
@@ -1349,18 +1416,46 @@ class AsyncEngine(ProxyComparable[Engine], AsyncConnectable): # type: ignore[mi
|
|
|
1349
1416
|
class AsyncTransaction(
|
|
1350
1417
|
ProxyComparable[Transaction], StartableContext["AsyncTransaction"]
|
|
1351
1418
|
):
|
|
1352
|
-
"""An asyncio proxy for a :class:`_engine.Transaction`.
|
|
1419
|
+
"""An asyncio proxy for a :class:`_engine.Transaction`.
|
|
1420
|
+
|
|
1421
|
+
When the transaction refers to a two-phase transaction created by
|
|
1422
|
+
:meth:`_asyncio.AsyncConnection.begin_twophase`,
|
|
1423
|
+
:attr:`_asyncio.AsyncTransaction.is_two_phase` will be ``True``,
|
|
1424
|
+
:attr:`_asyncio.AsyncTransaction.xid` refers to the transaction id,
|
|
1425
|
+
and the :meth:`_asyncio.AsyncTransaction.prepare` method may also be
|
|
1426
|
+
used.
|
|
1353
1427
|
|
|
1354
|
-
|
|
1428
|
+
"""
|
|
1429
|
+
|
|
1430
|
+
__slots__ = (
|
|
1431
|
+
"connection",
|
|
1432
|
+
"sync_transaction",
|
|
1433
|
+
"nested",
|
|
1434
|
+
"_is_two_phase",
|
|
1435
|
+
"_begin_xid",
|
|
1436
|
+
)
|
|
1355
1437
|
|
|
1356
1438
|
sync_transaction: Optional[Transaction]
|
|
1357
1439
|
connection: AsyncConnection
|
|
1358
1440
|
nested: bool
|
|
1441
|
+
_is_two_phase: bool
|
|
1442
|
+
_begin_xid: Optional[Any]
|
|
1359
1443
|
|
|
1360
|
-
def __init__(
|
|
1444
|
+
def __init__(
|
|
1445
|
+
self,
|
|
1446
|
+
connection: AsyncConnection,
|
|
1447
|
+
nested: bool = False,
|
|
1448
|
+
is_two_phase: bool = False,
|
|
1449
|
+
xid: Optional[Any] = None,
|
|
1450
|
+
):
|
|
1361
1451
|
self.connection = connection
|
|
1362
1452
|
self.sync_transaction = None
|
|
1363
1453
|
self.nested = nested
|
|
1454
|
+
self._is_two_phase = is_two_phase
|
|
1455
|
+
|
|
1456
|
+
# the xid to pass to Connection.begin_twophase() when started;
|
|
1457
|
+
# the actual xid lives on the TwoPhaseTransaction from then on
|
|
1458
|
+
self._begin_xid = xid
|
|
1364
1459
|
|
|
1365
1460
|
@classmethod
|
|
1366
1461
|
def _regenerate_proxy_for_target(
|
|
@@ -1379,8 +1474,41 @@ class AsyncTransaction(
|
|
|
1379
1474
|
obj.connection = async_connection
|
|
1380
1475
|
obj.sync_transaction = obj._assign_proxied(sync_transaction)
|
|
1381
1476
|
obj.nested = nested
|
|
1477
|
+
obj._is_two_phase = isinstance(target, TwoPhaseTransaction)
|
|
1478
|
+
obj._begin_xid = None
|
|
1382
1479
|
return obj
|
|
1383
1480
|
|
|
1481
|
+
@property
|
|
1482
|
+
def is_two_phase(self) -> bool:
|
|
1483
|
+
"""True if this transaction is a two-phase transaction.
|
|
1484
|
+
|
|
1485
|
+
.. versionadded:: 2.1.10
|
|
1486
|
+
|
|
1487
|
+
.. seealso::
|
|
1488
|
+
|
|
1489
|
+
:meth:`_asyncio.AsyncConnection.begin_twophase`
|
|
1490
|
+
|
|
1491
|
+
"""
|
|
1492
|
+
return self._is_two_phase
|
|
1493
|
+
|
|
1494
|
+
@property
|
|
1495
|
+
def xid(self) -> Optional[Any]:
|
|
1496
|
+
"""The transaction id of a two-phase transaction, or ``None`` for
|
|
1497
|
+
a transaction that is not two-phase.
|
|
1498
|
+
|
|
1499
|
+
This is the id held by the underlying :class:`.TwoPhaseTransaction`,
|
|
1500
|
+
including one that was generated when no id was passed to
|
|
1501
|
+
:meth:`_asyncio.AsyncConnection.begin_twophase`.
|
|
1502
|
+
|
|
1503
|
+
.. versionadded:: 2.1.10
|
|
1504
|
+
|
|
1505
|
+
"""
|
|
1506
|
+
proxied = self._proxied
|
|
1507
|
+
if isinstance(proxied, TwoPhaseTransaction):
|
|
1508
|
+
return proxied.xid
|
|
1509
|
+
else:
|
|
1510
|
+
return None
|
|
1511
|
+
|
|
1384
1512
|
@util.ro_non_memoized_property
|
|
1385
1513
|
def _proxied(self) -> Transaction:
|
|
1386
1514
|
if not self.sync_transaction:
|
|
@@ -1417,19 +1545,43 @@ class AsyncTransaction(
|
|
|
1417
1545
|
|
|
1418
1546
|
await greenlet_spawn(self._proxied.commit)
|
|
1419
1547
|
|
|
1548
|
+
async def prepare(self) -> None:
|
|
1549
|
+
"""Prepare this two-phase :class:`.AsyncTransaction`.
|
|
1550
|
+
|
|
1551
|
+
After a PREPARE, the transaction can be committed.
|
|
1552
|
+
|
|
1553
|
+
.. versionadded:: 2.1.10
|
|
1554
|
+
|
|
1555
|
+
.. seealso::
|
|
1556
|
+
|
|
1557
|
+
:meth:`.TwoPhaseTransaction.prepare`
|
|
1558
|
+
|
|
1559
|
+
"""
|
|
1560
|
+
proxied = self._proxied
|
|
1561
|
+
if not isinstance(proxied, TwoPhaseTransaction):
|
|
1562
|
+
raise exc.InvalidRequestError(
|
|
1563
|
+
"This transaction is not a two phase transaction"
|
|
1564
|
+
)
|
|
1565
|
+
await greenlet_spawn(proxied.prepare)
|
|
1566
|
+
|
|
1420
1567
|
async def start(self, is_ctxmanager: bool = False) -> AsyncTransaction:
|
|
1421
1568
|
"""Start this :class:`_asyncio.AsyncTransaction` object's context
|
|
1422
1569
|
outside of using a Python ``with:`` block.
|
|
1423
1570
|
|
|
1424
1571
|
"""
|
|
1425
1572
|
|
|
1426
|
-
|
|
1427
|
-
|
|
1573
|
+
sync_transaction: Transaction
|
|
1574
|
+
if self._is_two_phase:
|
|
1575
|
+
sync_transaction = await greenlet_spawn(
|
|
1576
|
+
self.connection._proxied.begin_twophase, self._begin_xid
|
|
1577
|
+
)
|
|
1578
|
+
else:
|
|
1579
|
+
sync_transaction = await greenlet_spawn(
|
|
1428
1580
|
self.connection._proxied.begin_nested
|
|
1429
1581
|
if self.nested
|
|
1430
1582
|
else self.connection._proxied.begin
|
|
1431
1583
|
)
|
|
1432
|
-
)
|
|
1584
|
+
self.sync_transaction = self._assign_proxied(sync_transaction)
|
|
1433
1585
|
if is_ctxmanager:
|
|
1434
1586
|
self.sync_transaction.__enter__()
|
|
1435
1587
|
return self
|
sqlalchemy/orm/attributes.py
CHANGED
|
@@ -17,12 +17,10 @@ defines a large part of the ORM's interactivity.
|
|
|
17
17
|
|
|
18
18
|
from __future__ import annotations
|
|
19
19
|
|
|
20
|
-
import dataclasses
|
|
21
20
|
import operator
|
|
22
21
|
from typing import Any
|
|
23
22
|
from typing import Callable
|
|
24
23
|
from typing import cast
|
|
25
|
-
from typing import ClassVar
|
|
26
24
|
from typing import Dict
|
|
27
25
|
from typing import Iterable
|
|
28
26
|
from typing import List
|
|
@@ -90,8 +88,6 @@ from ..sql import coercions
|
|
|
90
88
|
from ..sql import roles
|
|
91
89
|
from ..sql import visitors
|
|
92
90
|
from ..sql.cache_key import HasCacheKey
|
|
93
|
-
from ..sql.visitors import _TraverseInternalsType
|
|
94
|
-
from ..sql.visitors import InternalTraversal
|
|
95
91
|
from ..util.typing import Self
|
|
96
92
|
|
|
97
93
|
if TYPE_CHECKING:
|
|
@@ -334,16 +330,17 @@ class QueryableAttribute(
|
|
|
334
330
|
# ideally Proxy() would have a separate set of methods to deal
|
|
335
331
|
# with this case.
|
|
336
332
|
entity_namespace = self._entity_namespace
|
|
337
|
-
assert isinstance(entity_namespace, HasCacheKey)
|
|
338
333
|
|
|
339
334
|
if self.key is _UNKNOWN_ATTR_KEY:
|
|
340
|
-
annotations = {
|
|
335
|
+
annotations = {}
|
|
341
336
|
else:
|
|
342
337
|
annotations = {
|
|
343
338
|
"proxy_key": self.key,
|
|
344
339
|
"proxy_owner": self._parententity,
|
|
345
|
-
"entity_namespace": entity_namespace,
|
|
346
340
|
}
|
|
341
|
+
if entity_namespace is not None:
|
|
342
|
+
assert isinstance(entity_namespace, HasCacheKey)
|
|
343
|
+
annotations["entity_namespace"] = entity_namespace
|
|
347
344
|
|
|
348
345
|
ce = self.comparator.__clause_element__()
|
|
349
346
|
try:
|
|
@@ -575,23 +572,6 @@ class InstrumentedAttribute(QueryableAttribute[_T_co]):
|
|
|
575
572
|
return self.impl.get(state, dict_) # type: ignore[no-any-return]
|
|
576
573
|
|
|
577
574
|
|
|
578
|
-
@dataclasses.dataclass(frozen=True)
|
|
579
|
-
class _AdHocHasEntityNamespace(HasCacheKey):
|
|
580
|
-
_traverse_internals: ClassVar[_TraverseInternalsType] = [
|
|
581
|
-
("_entity_namespace", InternalTraversal.dp_has_cache_key),
|
|
582
|
-
]
|
|
583
|
-
|
|
584
|
-
# py37 compat, no slots=True on dataclass
|
|
585
|
-
__slots__ = ("_entity_namespace",)
|
|
586
|
-
_entity_namespace: _InternalEntityType[Any]
|
|
587
|
-
is_mapper: ClassVar[bool] = False
|
|
588
|
-
is_aliased_class: ClassVar[bool] = False
|
|
589
|
-
|
|
590
|
-
@property
|
|
591
|
-
def entity_namespace(self):
|
|
592
|
-
return self._entity_namespace.entity_namespace
|
|
593
|
-
|
|
594
|
-
|
|
595
575
|
def _create_proxied_attribute(
|
|
596
576
|
descriptor: Any,
|
|
597
577
|
) -> Callable[..., QueryableAttribute[Any]]:
|
|
@@ -669,9 +649,9 @@ def _create_proxied_attribute(
|
|
|
669
649
|
if hasattr(self._comparator, "_parententity"):
|
|
670
650
|
return self._comparator._parententity
|
|
671
651
|
else:
|
|
672
|
-
# used by hybrid attributes
|
|
673
|
-
#
|
|
674
|
-
return
|
|
652
|
+
# used by hybrid attributes; the parent entity is None
|
|
653
|
+
# for a hybrid on an unmapped class
|
|
654
|
+
return self._parententity
|
|
675
655
|
|
|
676
656
|
@property
|
|
677
657
|
def property(self):
|
|
@@ -1788,12 +1788,22 @@ class _BulkORMUpdate(_BulkUDCompileState, UpdateDMLState):
|
|
|
1788
1788
|
session.identity_map.all_states(),
|
|
1789
1789
|
)
|
|
1790
1790
|
|
|
1791
|
+
to_update = []
|
|
1792
|
+
for obj, state, dict_, is_partially_expired in matched_objects:
|
|
1793
|
+
if is_partially_expired:
|
|
1794
|
+
# the criteria read expired attributes, so it's not known
|
|
1795
|
+
# if the row matched; expire the object, as is the case
|
|
1796
|
+
# for DELETE
|
|
1797
|
+
state._expire(dict_, session.identity_map._modified)
|
|
1798
|
+
else:
|
|
1799
|
+
to_update.append((obj, state, dict_))
|
|
1800
|
+
|
|
1791
1801
|
cls._apply_update_set_values_to_objects(
|
|
1792
1802
|
session,
|
|
1793
1803
|
update_options,
|
|
1794
1804
|
statement,
|
|
1795
1805
|
result.context.compiled_parameters[0],
|
|
1796
|
-
|
|
1806
|
+
to_update,
|
|
1797
1807
|
result.prefetch_cols(),
|
|
1798
1808
|
result.postfetch_cols(),
|
|
1799
1809
|
)
|
|
@@ -1909,6 +1919,28 @@ class _BulkORMUpdate(_BulkUDCompileState, UpdateDMLState):
|
|
|
1909
1919
|
]
|
|
1910
1920
|
|
|
1911
1921
|
for obj, state, dict_ in matched_objects:
|
|
1922
|
+
to_evaluate = state.unmodified.intersection(evaluated_keys)
|
|
1923
|
+
|
|
1924
|
+
# evaluate all SET values against the object as it was before
|
|
1925
|
+
# the UPDATE, before any of them are applied, as the database
|
|
1926
|
+
# does; only run eval for attributes that are present.
|
|
1927
|
+
evaluated_values = {
|
|
1928
|
+
key: value_evaluators[key](obj)
|
|
1929
|
+
for key in to_evaluate
|
|
1930
|
+
if key in dict_
|
|
1931
|
+
}
|
|
1932
|
+
|
|
1933
|
+
# a SET value that read an expired attribute can't be known;
|
|
1934
|
+
# expire the target attribute
|
|
1935
|
+
expired_values = {
|
|
1936
|
+
key
|
|
1937
|
+
for key, value in evaluated_values.items()
|
|
1938
|
+
if value is evaluator._EXPIRED_OBJECT
|
|
1939
|
+
}
|
|
1940
|
+
if expired_values:
|
|
1941
|
+
to_evaluate.difference_update(expired_values)
|
|
1942
|
+
for key in expired_values:
|
|
1943
|
+
del evaluated_values[key]
|
|
1912
1944
|
|
|
1913
1945
|
dict_.update(
|
|
1914
1946
|
{
|
|
@@ -1917,14 +1949,9 @@ class _BulkORMUpdate(_BulkUDCompileState, UpdateDMLState):
|
|
|
1917
1949
|
}
|
|
1918
1950
|
)
|
|
1919
1951
|
|
|
1920
|
-
state._expire_attributes(
|
|
1921
|
-
|
|
1922
|
-
to_evaluate = state.unmodified.intersection(evaluated_keys)
|
|
1952
|
+
state._expire_attributes(dict_, to_expire.union(expired_values))
|
|
1923
1953
|
|
|
1924
|
-
|
|
1925
|
-
if key in dict_:
|
|
1926
|
-
# only run eval for attributes that are present.
|
|
1927
|
-
dict_[key] = value_evaluators[key](obj)
|
|
1954
|
+
dict_.update(evaluated_values)
|
|
1928
1955
|
|
|
1929
1956
|
state.manager.dispatch.refresh(state, None, to_evaluate)
|
|
1930
1957
|
|