SQLAlchemy 2.1.8__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.
Files changed (56) hide show
  1. sqlalchemy/__init__.py +1 -1
  2. sqlalchemy/connectors/asyncio.py +20 -2
  3. sqlalchemy/dialects/mssql/base.py +14 -2
  4. sqlalchemy/dialects/mysql/pymysql.py +3 -1
  5. sqlalchemy/dialects/oracle/base.py +1 -1
  6. sqlalchemy/dialects/oracle/cx_oracle.py +1 -1
  7. sqlalchemy/dialects/postgresql/asyncpg.py +56 -2
  8. sqlalchemy/dialects/postgresql/base.py +4 -1
  9. sqlalchemy/dialects/postgresql/hstore.py +1 -0
  10. sqlalchemy/dialects/postgresql/psycopg.py +4 -3
  11. sqlalchemy/dialects/sqlite/aiosqlite.py +23 -0
  12. sqlalchemy/dialects/sqlite/pysqlite.py +38 -0
  13. sqlalchemy/engine/_row_cy.py +12 -0
  14. sqlalchemy/engine/interfaces.py +1 -1
  15. sqlalchemy/engine/result.py +4 -1
  16. sqlalchemy/engine/row.py +1 -1
  17. sqlalchemy/engine/url.py +28 -13
  18. sqlalchemy/event/registry.py +8 -4
  19. sqlalchemy/ext/asyncio/engine.py +158 -6
  20. sqlalchemy/ext/asyncio/result.py +2 -1
  21. sqlalchemy/ext/asyncio/scoping.py +1 -1
  22. sqlalchemy/ext/asyncio/session.py +1 -1
  23. sqlalchemy/ext/declarative/extensions.py +3 -2
  24. sqlalchemy/ext/hybrid.py +2 -2
  25. sqlalchemy/orm/attributes.py +7 -27
  26. sqlalchemy/orm/bulk_persistence.py +35 -8
  27. sqlalchemy/orm/context.py +92 -8
  28. sqlalchemy/orm/dependency.py +3 -0
  29. sqlalchemy/orm/evaluator.py +147 -29
  30. sqlalchemy/orm/events.py +4 -8
  31. sqlalchemy/orm/interfaces.py +24 -1
  32. sqlalchemy/orm/loading.py +24 -5
  33. sqlalchemy/orm/relationships.py +32 -5
  34. sqlalchemy/orm/strategies.py +61 -70
  35. sqlalchemy/orm/util.py +32 -0
  36. sqlalchemy/pool/base.py +21 -6
  37. sqlalchemy/sql/_annotated_cols.py +1 -1
  38. sqlalchemy/sql/compiler.py +42 -11
  39. sqlalchemy/sql/crud.py +1 -1
  40. sqlalchemy/sql/elements.py +16 -8
  41. sqlalchemy/sql/functions.py +21 -0
  42. sqlalchemy/sql/operators.py +28 -21
  43. sqlalchemy/sql/selectable.py +86 -18
  44. sqlalchemy/sql/sqltypes.py +1 -1
  45. sqlalchemy/sql/util.py +83 -0
  46. sqlalchemy/testing/provision.py +5 -5
  47. sqlalchemy/testing/suite/test_types.py +101 -0
  48. sqlalchemy/util/__init__.py +3 -0
  49. sqlalchemy/util/concurrency.py +4 -0
  50. sqlalchemy/util/langhelpers.py +1 -1
  51. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/METADATA +1 -1
  52. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/RECORD +56 -56
  53. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/WHEEL +0 -0
  54. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/licenses/AUTHORS +0 -0
  55. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/licenses/LICENSE +0 -0
  56. {sqlalchemy-2.1.8.dist-info → sqlalchemy-2.1.10.dist-info}/top_level.txt +0 -0
sqlalchemy/__init__.py CHANGED
@@ -285,7 +285,7 @@ from .types import Uuid as Uuid
285
285
  from .types import VARBINARY as VARBINARY
286
286
  from .types import VARCHAR as VARCHAR
287
287
 
288
- __version__ = "2.1.8"
288
+ __version__ = "2.1.10"
289
289
 
290
290
 
291
291
  def __go(lcls: Any) -> None:
@@ -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 Exception as error:
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 Exception as error:
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
- self._lastrowid = int(row[0]) if row else None
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 (
@@ -4267,6 +4271,14 @@ index_info AS (
4267
4271
  == sys_key_constraints.c.unique_index_id,
4268
4272
  ),
4269
4273
  )
4274
+ # a table with a primary key that another session is creating
4275
+ # within a transaction has its key constraint rows locked until
4276
+ # that transaction ends; the plan for this query can read those
4277
+ # rows even though the filter discards them, so skip them
4278
+ # rather than block on them. See #13789.
4279
+ .with_hint(
4280
+ sys_key_constraints, "WITH (READPAST)", dialect_name="mssql"
4281
+ )
4270
4282
  .where(
4271
4283
  sys_key_constraints.c.type == "PK",
4272
4284
  ischema.sys_schemas.c.name == sql.bindparam("owner"),
@@ -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 or "connection was killed" 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["literal_binds"] = True
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)
@@ -1485,7 +1485,7 @@ class OracleDialect_cx_oracle(OracleDialect):
1485
1485
  connection level.
1486
1486
 
1487
1487
  note that when using a Compiled statement that has types (e.g.
1488
- TypeEngine), we set up a per-cursor handler instead which supercedes
1488
+ TypeEngine), we set up a per-cursor handler instead which supersedes
1489
1489
  this one, using Oracle-specific TypeEngine handlers delivered by the
1490
1490
  _cx_oracle_outputtypehandler() method of each one.
1491
1491
 
@@ -174,6 +174,21 @@ client using this setting passed to :func:`_asyncio.create_async_engine`::
174
174
 
175
175
  https://github.com/MagicStack/asyncpg/issues/727
176
176
 
177
+ DBAPI Error Messages
178
+ ---------------------
179
+
180
+ The asyncpg error message are wrapped by in :class:`.EmulatedDBAPIException`
181
+ object providing a more consistent experience for the async drivers.
182
+ A side effect of this change is that the textual representation of
183
+ the error may be different than it was in previous sqlalchemy versions,
184
+ and the ``DETAIL`` line may be missing.
185
+ The original asyncpg exception can be accessed using the
186
+ :attr:`.DBAPIError.driver_exception` attribute.
187
+
188
+ .. versionchanged:: 2.1.0
189
+
190
+ The exceptions are wrapped in :class:`.EmulatedDBAPIException` objects.
191
+
177
192
  """ # noqa
178
193
 
179
194
  from __future__ import annotations
@@ -1054,9 +1069,9 @@ class AsyncAdapt_asyncpg_dbapi(AsyncAdapt_dbapi_module):
1054
1069
  def _asyncpg_error_translate(self):
1055
1070
  import asyncpg
1056
1071
 
1057
- return {
1072
+ translate = {
1058
1073
  asyncpg.exceptions.IntegrityConstraintViolationError: self.IntegrityError, # noqa: E501
1059
- asyncpg.exceptions.PostgresError: self.Error,
1074
+ asyncpg.exceptions.PostgresError: self.DatabaseError,
1060
1075
  asyncpg.exceptions.SyntaxOrAccessError: self.ProgrammingError,
1061
1076
  asyncpg.exceptions.InterfaceError: self.InterfaceError,
1062
1077
  asyncpg.exceptions.InvalidCachedStatementError: self.InvalidCachedStatementError, # noqa: E501
@@ -1068,8 +1083,47 @@ class AsyncAdapt_asyncpg_dbapi(AsyncAdapt_dbapi_module):
1068
1083
  asyncpg.exceptions.CheckViolationError: self.CheckViolationError,
1069
1084
  asyncpg.exceptions.ExclusionViolationError: self.ExclusionViolationError, # noqa: E501
1070
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,
1071
1115
  }
1072
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
+
1073
1127
  def Binary(self, value):
1074
1128
  return value
1075
1129
 
@@ -1653,7 +1653,7 @@ defined, so other SQL dialects may behave differently than PostgreSQL.
1653
1653
  The ``NULLS NOT DISTINCT`` clause can be used to change this behavior, treating
1654
1654
  null values as equal and preventing unintended duplicate rows. The opposite
1655
1655
  ``NULLS DISTINCT`` clause can also be used to make PostgreSQL's default behavior
1656
- explict.
1656
+ explicit.
1657
1657
 
1658
1658
  The ``postgresql_nulls_not_distinct`` parameter can be set to ``True`` to
1659
1659
  add the ``NULLS NOT DISTINCT`` clause, or ``False`` to add ``NULLS DISTINCT``.
@@ -1959,6 +1959,7 @@ from .types import REGCLASS as REGCLASS
1959
1959
  from .types import REGCONFIG as REGCONFIG # noqa: F401
1960
1960
  from .types import TIME as TIME
1961
1961
  from .types import TIMESTAMP as TIMESTAMP
1962
+ from .types import TSQUERY as TSQUERY
1962
1963
  from .types import TSVECTOR as TSVECTOR
1963
1964
  from ... import exc
1964
1965
  from ... import schema
@@ -2168,6 +2169,8 @@ ischema_names = {
2168
2169
  "boolean": BOOLEAN,
2169
2170
  "interval": INTERVAL,
2170
2171
  "tsvector": TSVECTOR,
2172
+ "tsquery": TSQUERY,
2173
+ "regconfig": REGCONFIG,
2171
2174
  }
2172
2175
 
2173
2176
 
@@ -115,6 +115,7 @@ class HSTORE(
115
115
 
116
116
  operator_classes = (
117
117
  OperatorClass.BASE
118
+ | OperatorClass.EQUALITY
118
119
  | OperatorClass.CONTAINS
119
120
  | OperatorClass.INDEXABLE
120
121
  | OperatorClass.CONCATENABLE
@@ -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
- and also remains the default dialect for the ``postgresql://`` dialect
22
- series.
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
 
@@ -19,6 +19,7 @@ from typing import Sequence
19
19
  from typing import Tuple
20
20
  from typing import Type
21
21
  from typing import TYPE_CHECKING
22
+ from typing import TypeVar
22
23
 
23
24
  if TYPE_CHECKING:
24
25
  from .result import _KeyType
@@ -43,6 +44,8 @@ def _is_compiled() -> bool:
43
44
 
44
45
  # END GENERATED CYTHON IMPORT
45
46
 
47
+ _BR = TypeVar("_BR", bound="BaseRow")
48
+
46
49
 
47
50
  @cython.cclass
48
51
  class BaseRow:
@@ -92,6 +95,15 @@ class BaseRow:
92
95
  object.__setattr__(self, "_key_to_index", key_to_index)
93
96
  object.__setattr__(self, "_data", data)
94
97
 
98
+ def _as_row_class(self, cls: Type[_BR]) -> _BR:
99
+ """Return a new object of the given :class:`.BaseRow` subclass
100
+ that shares this row's data, without re-applying processors.
101
+
102
+ """
103
+ new: BaseRow = cls.__new__(cls)
104
+ new._set_attrs(self._parent, self._key_to_index, self._data)
105
+ return new # type: ignore[return-value]
106
+
95
107
  def __reduce__(self) -> Tuple[Any, Any]:
96
108
  return (
97
109
  rowproxy_reconstructor,
@@ -1008,7 +1008,7 @@ class Dialect(EventTarget):
1008
1008
  inject this handler at the connection/cursor level, rather than
1009
1009
  having JSON data returned as a string to be handled by the type
1010
1010
 
1011
- ..versionadded:: 2.1
1011
+ .. versionadded:: 2.1
1012
1012
 
1013
1013
  """
1014
1014
 
@@ -1586,6 +1586,9 @@ class TupleResult(FilterResult[_R], util.TypingOnly):
1586
1586
  ...
1587
1587
 
1588
1588
 
1589
+ _row_to_mapping = operator.methodcaller("_as_row_class", RowMapping)
1590
+
1591
+
1589
1592
  class MappingResult(_WithKeys, FilterResult[RowMapping]):
1590
1593
  """A wrapper for a :class:`_engine.Result` that returns dictionary values
1591
1594
  rather than :class:`_engine.Row` values.
@@ -1599,7 +1602,7 @@ class MappingResult(_WithKeys, FilterResult[RowMapping]):
1599
1602
 
1600
1603
  _generate_rows = True
1601
1604
 
1602
- _post_creational_filter = operator.attrgetter("_mapping")
1605
+ _post_creational_filter = _row_to_mapping
1603
1606
 
1604
1607
  def __init__(self, result: Result[Unpack[TupleAny]]):
1605
1608
  self._real_result = result
sqlalchemy/engine/row.py CHANGED
@@ -184,7 +184,7 @@ class Row(BaseRow, _RowBase[Unpack[_Ts]], Generic[Unpack[_Ts]]): # type: ignore
184
184
  .. versionadded:: 1.4
185
185
 
186
186
  """
187
- return RowMapping(self._parent, None, self._key_to_index, self._data)
187
+ return self._as_row_class(RowMapping)
188
188
 
189
189
  def _filter_on_values(
190
190
  self, processor: Optional[_ProcessorsType]
sqlalchemy/engine/url.py CHANGED
@@ -414,7 +414,7 @@ class URL(NamedTuple):
414
414
 
415
415
  def update_query_pairs(
416
416
  self,
417
- key_value_pairs: Iterable[Tuple[str, Union[str, List[str]]]],
417
+ key_value_pairs: Iterable[Tuple[str, Union[str, Sequence[str]]]],
418
418
  append: bool = False,
419
419
  ) -> URL:
420
420
  """Return a new :class:`_engine.URL` object with the
@@ -435,8 +435,24 @@ class URL(NamedTuple):
435
435
  >>> str(url)
436
436
  'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
437
437
 
438
- :param key_value_pairs: A sequence of tuples containing two strings
439
- each.
438
+ A value may also be given as a sequence of strings, which is
439
+ equivalent to passing the same key once for each string; the
440
+ above example may also be expressed as::
441
+
442
+ >>> url = make_url("postgresql+psycopg2://user:pass@host/dbname")
443
+ >>> url = url.update_query_pairs(
444
+ ... [
445
+ ... ("alt_host", ["host1", "host2"]),
446
+ ... ("ssl_cipher", "/path/to/crt"),
447
+ ... ]
448
+ ... )
449
+ >>> str(url)
450
+ 'postgresql+psycopg2://user:pass@host/dbname?alt_host=host1&alt_host=host2&ssl_cipher=%2Fpath%2Fto%2Fcrt'
451
+
452
+ :param key_value_pairs: A sequence of tuples, each containing a
453
+ string key and a value that is either a string or a sequence of
454
+ strings. A key may appear more than once, in which case all of
455
+ its values are combined in the order given.
440
456
 
441
457
  :param append: if True, parameters in the existing query string will
442
458
  not be removed; new parameters will be in addition to those present.
@@ -445,6 +461,9 @@ class URL(NamedTuple):
445
461
 
446
462
  .. versionadded:: 1.4
447
463
 
464
+ .. versionchanged:: 2.0.58, 2.1.9 A value may be given as a sequence
465
+ of strings, including for a key that appears more than once.
466
+
448
467
  .. seealso::
449
468
 
450
469
  :attr:`_engine.URL.query`
@@ -456,12 +475,13 @@ class URL(NamedTuple):
456
475
  """ # noqa: E501
457
476
 
458
477
  existing_query = self.query
459
- new_keys: Dict[str, Union[str, List[str]]] = {}
478
+ new_keys: Dict[str, Union[str, Sequence[str]]] = {}
460
479
 
461
480
  for key, value in key_value_pairs:
462
481
  if key in new_keys:
463
- new_keys[key] = util.to_list(new_keys[key])
464
- cast("List[str]", new_keys[key]).append(cast(str, value))
482
+ current_as_list = util.to_list(new_keys[key])
483
+ current_as_list.extend(util.to_list(value))
484
+ new_keys[key] = current_as_list
465
485
  else:
466
486
  new_keys[key] = (
467
487
  list(value) if isinstance(value, (list, tuple)) else value
@@ -487,17 +507,12 @@ class URL(NamedTuple):
487
507
  }
488
508
  )
489
509
  else:
490
- new_query = self.query.union(
491
- {
492
- k: tuple(v) if isinstance(v, list) else v
493
- for k, v in new_keys.items()
494
- }
495
- )
510
+ new_query = {**self.query, **new_keys}
496
511
  return self.set(query=new_query)
497
512
 
498
513
  def update_query_dict(
499
514
  self,
500
- query_parameters: Mapping[str, Union[str, List[str]]],
515
+ query_parameters: Mapping[str, Union[str, Sequence[str]]],
501
516
  append: bool = False,
502
517
  ) -> URL:
503
518
  """Return a new :class:`_engine.URL` object with the
@@ -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: