util.py 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # engine/util.py
  2. # Copyright (C) 2005-2025 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: https://www.opensource.org/licenses/mit-license.php
  7. from __future__ import annotations
  8. import typing
  9. from typing import Any
  10. from typing import Callable
  11. from typing import Optional
  12. from typing import TypeVar
  13. from .. import exc
  14. from .. import util
  15. from ..util._has_cy import HAS_CYEXTENSION
  16. from ..util.typing import Protocol
  17. from ..util.typing import Self
  18. if typing.TYPE_CHECKING or not HAS_CYEXTENSION:
  19. from ._py_util import _distill_params_20 as _distill_params_20
  20. from ._py_util import _distill_raw_params as _distill_raw_params
  21. else:
  22. from sqlalchemy.cyextension.util import ( # noqa: F401
  23. _distill_params_20 as _distill_params_20,
  24. )
  25. from sqlalchemy.cyextension.util import ( # noqa: F401
  26. _distill_raw_params as _distill_raw_params,
  27. )
  28. _C = TypeVar("_C", bound=Callable[[], Any])
  29. def connection_memoize(key: str) -> Callable[[_C], _C]:
  30. """Decorator, memoize a function in a connection.info stash.
  31. Only applicable to functions which take no arguments other than a
  32. connection. The memo will be stored in ``connection.info[key]``.
  33. """
  34. @util.decorator
  35. def decorated(fn, self, connection): # type: ignore
  36. connection = connection.connect()
  37. try:
  38. return connection.info[key]
  39. except KeyError:
  40. connection.info[key] = val = fn(self, connection)
  41. return val
  42. return decorated
  43. class _TConsSubject(Protocol):
  44. _trans_context_manager: Optional[TransactionalContext]
  45. class TransactionalContext:
  46. """Apply Python context manager behavior to transaction objects.
  47. Performs validation to ensure the subject of the transaction is not
  48. used if the transaction were ended prematurely.
  49. """
  50. __slots__ = ("_outer_trans_ctx", "_trans_subject", "__weakref__")
  51. _trans_subject: Optional[_TConsSubject]
  52. def _transaction_is_active(self) -> bool:
  53. raise NotImplementedError()
  54. def _transaction_is_closed(self) -> bool:
  55. raise NotImplementedError()
  56. def _rollback_can_be_called(self) -> bool:
  57. """indicates the object is in a state that is known to be acceptable
  58. for rollback() to be called.
  59. This does not necessarily mean rollback() will succeed or not raise
  60. an error, just that there is currently no state detected that indicates
  61. rollback() would fail or emit warnings.
  62. It also does not mean that there's a transaction in progress, as
  63. it is usually safe to call rollback() even if no transaction is
  64. present.
  65. .. versionadded:: 1.4.28
  66. """
  67. raise NotImplementedError()
  68. def _get_subject(self) -> _TConsSubject:
  69. raise NotImplementedError()
  70. def commit(self) -> None:
  71. raise NotImplementedError()
  72. def rollback(self) -> None:
  73. raise NotImplementedError()
  74. def close(self) -> None:
  75. raise NotImplementedError()
  76. @classmethod
  77. def _trans_ctx_check(cls, subject: _TConsSubject) -> None:
  78. trans_context = subject._trans_context_manager
  79. if trans_context:
  80. if not trans_context._transaction_is_active():
  81. raise exc.InvalidRequestError(
  82. "Can't operate on closed transaction inside context "
  83. "manager. Please complete the context manager "
  84. "before emitting further commands."
  85. )
  86. def __enter__(self) -> Self:
  87. subject = self._get_subject()
  88. # none for outer transaction, may be non-None for nested
  89. # savepoint, legacy nesting cases
  90. trans_context = subject._trans_context_manager
  91. self._outer_trans_ctx = trans_context
  92. self._trans_subject = subject
  93. subject._trans_context_manager = self
  94. return self
  95. def __exit__(self, type_: Any, value: Any, traceback: Any) -> None:
  96. subject = getattr(self, "_trans_subject", None)
  97. # simplistically we could assume that
  98. # "subject._trans_context_manager is self". However, any calling
  99. # code that is manipulating __exit__ directly would break this
  100. # assumption. alembic context manager
  101. # is an example of partial use that just calls __exit__ and
  102. # not __enter__ at the moment. it's safe to assume this is being done
  103. # in the wild also
  104. out_of_band_exit = (
  105. subject is None or subject._trans_context_manager is not self
  106. )
  107. if type_ is None and self._transaction_is_active():
  108. try:
  109. self.commit()
  110. except:
  111. with util.safe_reraise():
  112. if self._rollback_can_be_called():
  113. self.rollback()
  114. finally:
  115. if not out_of_band_exit:
  116. assert subject is not None
  117. subject._trans_context_manager = self._outer_trans_ctx
  118. self._trans_subject = self._outer_trans_ctx = None
  119. else:
  120. try:
  121. if not self._transaction_is_active():
  122. if not self._transaction_is_closed():
  123. self.close()
  124. else:
  125. if self._rollback_can_be_called():
  126. self.rollback()
  127. finally:
  128. if not out_of_band_exit:
  129. assert subject is not None
  130. subject._trans_context_manager = self._outer_trans_ctx
  131. self._trans_subject = self._outer_trans_ctx = None