characteristics.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # engine/characteristics.py
  2. # Copyright (C) 2005-2024 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 abc
  9. import typing
  10. from typing import Any
  11. from typing import ClassVar
  12. if typing.TYPE_CHECKING:
  13. from .interfaces import DBAPIConnection
  14. from .interfaces import Dialect
  15. class ConnectionCharacteristic(abc.ABC):
  16. """An abstract base for an object that can set, get and reset a
  17. per-connection characteristic, typically one that gets reset when the
  18. connection is returned to the connection pool.
  19. transaction isolation is the canonical example, and the
  20. ``IsolationLevelCharacteristic`` implementation provides this for the
  21. ``DefaultDialect``.
  22. The ``ConnectionCharacteristic`` class should call upon the ``Dialect`` for
  23. the implementation of each method. The object exists strictly to serve as
  24. a dialect visitor that can be placed into the
  25. ``DefaultDialect.connection_characteristics`` dictionary where it will take
  26. effect for calls to :meth:`_engine.Connection.execution_options` and
  27. related APIs.
  28. .. versionadded:: 1.4
  29. """
  30. __slots__ = ()
  31. transactional: ClassVar[bool] = False
  32. @abc.abstractmethod
  33. def reset_characteristic(
  34. self, dialect: Dialect, dbapi_conn: DBAPIConnection
  35. ) -> None:
  36. """Reset the characteristic on the connection to its default value."""
  37. @abc.abstractmethod
  38. def set_characteristic(
  39. self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any
  40. ) -> None:
  41. """set characteristic on the connection to a given value."""
  42. @abc.abstractmethod
  43. def get_characteristic(
  44. self, dialect: Dialect, dbapi_conn: DBAPIConnection
  45. ) -> Any:
  46. """Given a DBAPI connection, get the current value of the
  47. characteristic.
  48. """
  49. class IsolationLevelCharacteristic(ConnectionCharacteristic):
  50. transactional: ClassVar[bool] = True
  51. def reset_characteristic(
  52. self, dialect: Dialect, dbapi_conn: DBAPIConnection
  53. ) -> None:
  54. dialect.reset_isolation_level(dbapi_conn)
  55. def set_characteristic(
  56. self, dialect: Dialect, dbapi_conn: DBAPIConnection, value: Any
  57. ) -> None:
  58. dialect._assert_and_set_isolation_level(dbapi_conn, value)
  59. def get_characteristic(
  60. self, dialect: Dialect, dbapi_conn: DBAPIConnection
  61. ) -> Any:
  62. return dialect.get_isolation_level(dbapi_conn)