row.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. # engine/row.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. """Define row constructs including :class:`.Row`."""
  8. from __future__ import annotations
  9. from abc import ABC
  10. import collections.abc as collections_abc
  11. import operator
  12. import typing
  13. from typing import Any
  14. from typing import Callable
  15. from typing import Dict
  16. from typing import Generic
  17. from typing import Iterator
  18. from typing import List
  19. from typing import Mapping
  20. from typing import NoReturn
  21. from typing import Optional
  22. from typing import overload
  23. from typing import Sequence
  24. from typing import Tuple
  25. from typing import TYPE_CHECKING
  26. from typing import TypeVar
  27. from typing import Union
  28. from ..sql import util as sql_util
  29. from ..util import deprecated
  30. from ..util._has_cy import HAS_CYEXTENSION
  31. if TYPE_CHECKING or not HAS_CYEXTENSION:
  32. from ._py_row import BaseRow as BaseRow
  33. else:
  34. from sqlalchemy.cyextension.resultproxy import BaseRow as BaseRow
  35. if TYPE_CHECKING:
  36. from .result import _KeyType
  37. from .result import _ProcessorsType
  38. from .result import RMKeyView
  39. _T = TypeVar("_T", bound=Any)
  40. _TP = TypeVar("_TP", bound=Tuple[Any, ...])
  41. class Row(BaseRow, Sequence[Any], Generic[_TP]):
  42. """Represent a single result row.
  43. The :class:`.Row` object represents a row of a database result. It is
  44. typically associated in the 1.x series of SQLAlchemy with the
  45. :class:`_engine.CursorResult` object, however is also used by the ORM for
  46. tuple-like results as of SQLAlchemy 1.4.
  47. The :class:`.Row` object seeks to act as much like a Python named
  48. tuple as possible. For mapping (i.e. dictionary) behavior on a row,
  49. such as testing for containment of keys, refer to the :attr:`.Row._mapping`
  50. attribute.
  51. .. seealso::
  52. :ref:`tutorial_selecting_data` - includes examples of selecting
  53. rows from SELECT statements.
  54. .. versionchanged:: 1.4
  55. Renamed ``RowProxy`` to :class:`.Row`. :class:`.Row` is no longer a
  56. "proxy" object in that it contains the final form of data within it,
  57. and now acts mostly like a named tuple. Mapping-like functionality is
  58. moved to the :attr:`.Row._mapping` attribute. See
  59. :ref:`change_4710_core` for background on this change.
  60. """
  61. __slots__ = ()
  62. def __setattr__(self, name: str, value: Any) -> NoReturn:
  63. raise AttributeError("can't set attribute")
  64. def __delattr__(self, name: str) -> NoReturn:
  65. raise AttributeError("can't delete attribute")
  66. def _tuple(self) -> _TP:
  67. """Return a 'tuple' form of this :class:`.Row`.
  68. At runtime, this method returns "self"; the :class:`.Row` object is
  69. already a named tuple. However, at the typing level, if this
  70. :class:`.Row` is typed, the "tuple" return type will be a :pep:`484`
  71. ``Tuple`` datatype that contains typing information about individual
  72. elements, supporting typed unpacking and attribute access.
  73. .. versionadded:: 2.0.19 - The :meth:`.Row._tuple` method supersedes
  74. the previous :meth:`.Row.tuple` method, which is now underscored
  75. to avoid name conflicts with column names in the same way as other
  76. named-tuple methods on :class:`.Row`.
  77. .. seealso::
  78. :attr:`.Row._t` - shorthand attribute notation
  79. :meth:`.Result.tuples`
  80. """
  81. return self # type: ignore
  82. @deprecated(
  83. "2.0.19",
  84. "The :meth:`.Row.tuple` method is deprecated in favor of "
  85. ":meth:`.Row._tuple`; all :class:`.Row` "
  86. "methods and library-level attributes are intended to be underscored "
  87. "to avoid name conflicts. Please use :meth:`Row._tuple`.",
  88. )
  89. def tuple(self) -> _TP:
  90. """Return a 'tuple' form of this :class:`.Row`.
  91. .. versionadded:: 2.0
  92. """
  93. return self._tuple()
  94. @property
  95. def _t(self) -> _TP:
  96. """A synonym for :meth:`.Row._tuple`.
  97. .. versionadded:: 2.0.19 - The :attr:`.Row._t` attribute supersedes
  98. the previous :attr:`.Row.t` attribute, which is now underscored
  99. to avoid name conflicts with column names in the same way as other
  100. named-tuple methods on :class:`.Row`.
  101. .. seealso::
  102. :attr:`.Result.t`
  103. """
  104. return self # type: ignore
  105. @property
  106. @deprecated(
  107. "2.0.19",
  108. "The :attr:`.Row.t` attribute is deprecated in favor of "
  109. ":attr:`.Row._t`; all :class:`.Row` "
  110. "methods and library-level attributes are intended to be underscored "
  111. "to avoid name conflicts. Please use :attr:`Row._t`.",
  112. )
  113. def t(self) -> _TP:
  114. """A synonym for :meth:`.Row._tuple`.
  115. .. versionadded:: 2.0
  116. """
  117. return self._t
  118. @property
  119. def _mapping(self) -> RowMapping:
  120. """Return a :class:`.RowMapping` for this :class:`.Row`.
  121. This object provides a consistent Python mapping (i.e. dictionary)
  122. interface for the data contained within the row. The :class:`.Row`
  123. by itself behaves like a named tuple.
  124. .. seealso::
  125. :attr:`.Row._fields`
  126. .. versionadded:: 1.4
  127. """
  128. return RowMapping(self._parent, None, self._key_to_index, self._data)
  129. def _filter_on_values(
  130. self, processor: Optional[_ProcessorsType]
  131. ) -> Row[Any]:
  132. return Row(self._parent, processor, self._key_to_index, self._data)
  133. if not TYPE_CHECKING:
  134. def _special_name_accessor(name: str) -> Any:
  135. """Handle ambiguous names such as "count" and "index" """
  136. @property
  137. def go(self: Row) -> Any:
  138. if self._parent._has_key(name):
  139. return self.__getattr__(name)
  140. else:
  141. def meth(*arg: Any, **kw: Any) -> Any:
  142. return getattr(collections_abc.Sequence, name)(
  143. self, *arg, **kw
  144. )
  145. return meth
  146. return go
  147. count = _special_name_accessor("count")
  148. index = _special_name_accessor("index")
  149. def __contains__(self, key: Any) -> bool:
  150. return key in self._data
  151. def _op(self, other: Any, op: Callable[[Any, Any], bool]) -> bool:
  152. return (
  153. op(self._to_tuple_instance(), other._to_tuple_instance())
  154. if isinstance(other, Row)
  155. else op(self._to_tuple_instance(), other)
  156. )
  157. __hash__ = BaseRow.__hash__
  158. if TYPE_CHECKING:
  159. @overload
  160. def __getitem__(self, index: int) -> Any: ...
  161. @overload
  162. def __getitem__(self, index: slice) -> Sequence[Any]: ...
  163. def __getitem__(self, index: Union[int, slice]) -> Any: ...
  164. def __lt__(self, other: Any) -> bool:
  165. return self._op(other, operator.lt)
  166. def __le__(self, other: Any) -> bool:
  167. return self._op(other, operator.le)
  168. def __ge__(self, other: Any) -> bool:
  169. return self._op(other, operator.ge)
  170. def __gt__(self, other: Any) -> bool:
  171. return self._op(other, operator.gt)
  172. def __eq__(self, other: Any) -> bool:
  173. return self._op(other, operator.eq)
  174. def __ne__(self, other: Any) -> bool:
  175. return self._op(other, operator.ne)
  176. def __repr__(self) -> str:
  177. return repr(sql_util._repr_row(self))
  178. @property
  179. def _fields(self) -> Tuple[str, ...]:
  180. """Return a tuple of string keys as represented by this
  181. :class:`.Row`.
  182. The keys can represent the labels of the columns returned by a core
  183. statement or the names of the orm classes returned by an orm
  184. execution.
  185. This attribute is analogous to the Python named tuple ``._fields``
  186. attribute.
  187. .. versionadded:: 1.4
  188. .. seealso::
  189. :attr:`.Row._mapping`
  190. """
  191. return tuple([k for k in self._parent.keys if k is not None])
  192. def _asdict(self) -> Dict[str, Any]:
  193. """Return a new dict which maps field names to their corresponding
  194. values.
  195. This method is analogous to the Python named tuple ``._asdict()``
  196. method, and works by applying the ``dict()`` constructor to the
  197. :attr:`.Row._mapping` attribute.
  198. .. versionadded:: 1.4
  199. .. seealso::
  200. :attr:`.Row._mapping`
  201. """
  202. return dict(self._mapping)
  203. BaseRowProxy = BaseRow
  204. RowProxy = Row
  205. class ROMappingView(ABC):
  206. __slots__ = ()
  207. _items: Sequence[Any]
  208. _mapping: Mapping["_KeyType", Any]
  209. def __init__(
  210. self, mapping: Mapping["_KeyType", Any], items: Sequence[Any]
  211. ):
  212. self._mapping = mapping # type: ignore[misc]
  213. self._items = items # type: ignore[misc]
  214. def __len__(self) -> int:
  215. return len(self._items)
  216. def __repr__(self) -> str:
  217. return "{0.__class__.__name__}({0._mapping!r})".format(self)
  218. def __iter__(self) -> Iterator[Any]:
  219. return iter(self._items)
  220. def __contains__(self, item: Any) -> bool:
  221. return item in self._items
  222. def __eq__(self, other: Any) -> bool:
  223. return list(other) == list(self)
  224. def __ne__(self, other: Any) -> bool:
  225. return list(other) != list(self)
  226. class ROMappingKeysValuesView(
  227. ROMappingView, typing.KeysView["_KeyType"], typing.ValuesView[Any]
  228. ):
  229. __slots__ = ("_items",) # mapping slot is provided by KeysView
  230. class ROMappingItemsView(ROMappingView, typing.ItemsView["_KeyType", Any]):
  231. __slots__ = ("_items",) # mapping slot is provided by ItemsView
  232. class RowMapping(BaseRow, typing.Mapping["_KeyType", Any]):
  233. """A ``Mapping`` that maps column names and objects to :class:`.Row`
  234. values.
  235. The :class:`.RowMapping` is available from a :class:`.Row` via the
  236. :attr:`.Row._mapping` attribute, as well as from the iterable interface
  237. provided by the :class:`.MappingResult` object returned by the
  238. :meth:`_engine.Result.mappings` method.
  239. :class:`.RowMapping` supplies Python mapping (i.e. dictionary) access to
  240. the contents of the row. This includes support for testing of
  241. containment of specific keys (string column names or objects), as well
  242. as iteration of keys, values, and items::
  243. for row in result:
  244. if "a" in row._mapping:
  245. print("Column 'a': %s" % row._mapping["a"])
  246. print("Column b: %s" % row._mapping[table.c.b])
  247. .. versionadded:: 1.4 The :class:`.RowMapping` object replaces the
  248. mapping-like access previously provided by a database result row,
  249. which now seeks to behave mostly like a named tuple.
  250. """
  251. __slots__ = ()
  252. if TYPE_CHECKING:
  253. def __getitem__(self, key: _KeyType) -> Any: ...
  254. else:
  255. __getitem__ = BaseRow._get_by_key_impl_mapping
  256. def _values_impl(self) -> List[Any]:
  257. return list(self._data)
  258. def __iter__(self) -> Iterator[str]:
  259. return (k for k in self._parent.keys if k is not None)
  260. def __len__(self) -> int:
  261. return len(self._data)
  262. def __contains__(self, key: object) -> bool:
  263. return self._parent._has_key(key)
  264. def __repr__(self) -> str:
  265. return repr(dict(self))
  266. def items(self) -> ROMappingItemsView:
  267. """Return a view of key/value tuples for the elements in the
  268. underlying :class:`.Row`.
  269. """
  270. return ROMappingItemsView(
  271. self, [(key, self[key]) for key in self.keys()]
  272. )
  273. def keys(self) -> RMKeyView:
  274. """Return a view of 'keys' for string column names represented
  275. by the underlying :class:`.Row`.
  276. """
  277. return self._parent.keys
  278. def values(self) -> ROMappingKeysValuesView:
  279. """Return a view of values for the values represented in the
  280. underlying :class:`.Row`.
  281. """
  282. return ROMappingKeysValuesView(self, self._values_impl())