indexable.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # ext/indexable.py
  2. # Copyright (C) 2005-2026 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 attributes on ORM-mapped classes that have "index" attributes for
  8. columns with :class:`_types.Indexable` types.
  9. "index" means the attribute is associated with an element of an
  10. :class:`_types.Indexable` column with the predefined index to access it.
  11. The :class:`_types.Indexable` types include types such as
  12. :class:`_types.ARRAY`, :class:`_types.JSON` and
  13. :class:`_postgresql.HSTORE`.
  14. The :mod:`~sqlalchemy.ext.indexable` extension provides
  15. :class:`_schema.Column`-like interface for any element of an
  16. :class:`_types.Indexable` typed column. In simple cases, it can be
  17. treated as a :class:`_schema.Column` - mapped attribute.
  18. Synopsis
  19. ========
  20. Given ``Person`` as a model with a primary key and JSON data field.
  21. While this field may have any number of elements encoded within it,
  22. we would like to refer to the element called ``name`` individually
  23. as a dedicated attribute which behaves like a standalone column::
  24. from sqlalchemy import Column, JSON, Integer
  25. from sqlalchemy.ext.declarative import declarative_base
  26. from sqlalchemy.ext.indexable import index_property
  27. Base = declarative_base()
  28. class Person(Base):
  29. __tablename__ = "person"
  30. id = Column(Integer, primary_key=True)
  31. data = Column(JSON)
  32. name = index_property("data", "name")
  33. Above, the ``name`` attribute now behaves like a mapped column. We
  34. can compose a new ``Person`` and set the value of ``name``::
  35. >>> person = Person(name="Alchemist")
  36. The value is now accessible::
  37. >>> person.name
  38. 'Alchemist'
  39. Behind the scenes, the JSON field was initialized to a new blank dictionary
  40. and the field was set::
  41. >>> person.data
  42. {'name': 'Alchemist'}
  43. The field is mutable in place::
  44. >>> person.name = "Renamed"
  45. >>> person.name
  46. 'Renamed'
  47. >>> person.data
  48. {'name': 'Renamed'}
  49. When using :class:`.index_property`, the change that we make to the indexable
  50. structure is also automatically tracked as history; we no longer need
  51. to use :class:`~.mutable.MutableDict` in order to track this change
  52. for the unit of work.
  53. Deletions work normally as well::
  54. >>> del person.name
  55. >>> person.data
  56. {}
  57. Above, deletion of ``person.name`` deletes the value from the dictionary,
  58. but not the dictionary itself.
  59. A missing key will produce ``AttributeError``::
  60. >>> person = Person()
  61. >>> person.name
  62. AttributeError: 'name'
  63. Unless you set a default value::
  64. >>> class Person(Base):
  65. ... __tablename__ = "person"
  66. ...
  67. ... id = Column(Integer, primary_key=True)
  68. ... data = Column(JSON)
  69. ...
  70. ... name = index_property("data", "name", default=None) # See default
  71. >>> person = Person()
  72. >>> print(person.name)
  73. None
  74. The attributes are also accessible at the class level.
  75. Below, we illustrate ``Person.name`` used to generate
  76. an indexed SQL criteria::
  77. >>> from sqlalchemy.orm import Session
  78. >>> session = Session()
  79. >>> query = session.query(Person).filter(Person.name == "Alchemist")
  80. The above query is equivalent to::
  81. >>> query = session.query(Person).filter(Person.data["name"] == "Alchemist")
  82. Multiple :class:`.index_property` objects can be chained to produce
  83. multiple levels of indexing::
  84. from sqlalchemy import Column, JSON, Integer
  85. from sqlalchemy.ext.declarative import declarative_base
  86. from sqlalchemy.ext.indexable import index_property
  87. Base = declarative_base()
  88. class Person(Base):
  89. __tablename__ = "person"
  90. id = Column(Integer, primary_key=True)
  91. data = Column(JSON)
  92. birthday = index_property("data", "birthday")
  93. year = index_property("birthday", "year")
  94. month = index_property("birthday", "month")
  95. day = index_property("birthday", "day")
  96. Above, a query such as::
  97. q = session.query(Person).filter(Person.year == "1980")
  98. On a PostgreSQL backend, the above query will render as:
  99. .. sourcecode:: sql
  100. SELECT person.id, person.data
  101. FROM person
  102. WHERE person.data -> %(data_1)s -> %(param_1)s = %(param_2)s
  103. Default Values
  104. ==============
  105. :class:`.index_property` includes special behaviors for when the indexed
  106. data structure does not exist, and a set operation is called:
  107. * For an :class:`.index_property` that is given an integer index value,
  108. the default data structure will be a Python list of ``None`` values,
  109. at least as long as the index value; the value is then set at its
  110. place in the list. This means for an index value of zero, the list
  111. will be initialized to ``[None]`` before setting the given value,
  112. and for an index value of five, the list will be initialized to
  113. ``[None, None, None, None, None]`` before setting the fifth element
  114. to the given value. Note that an existing list is **not** extended
  115. in place to receive a value.
  116. * for an :class:`.index_property` that is given any other kind of index
  117. value (e.g. strings usually), a Python dictionary is used as the
  118. default data structure.
  119. * The default data structure can be set to any Python callable using the
  120. :paramref:`.index_property.datatype` parameter, overriding the previous
  121. rules.
  122. Subclassing
  123. ===========
  124. :class:`.index_property` can be subclassed, in particular for the common
  125. use case of providing coercion of values or SQL expressions as they are
  126. accessed. Below is a common recipe for use with a PostgreSQL JSON type,
  127. where we want to also include automatic casting plus ``astext()``::
  128. class pg_json_property(index_property):
  129. def __init__(self, attr_name, index, cast_type):
  130. super(pg_json_property, self).__init__(attr_name, index)
  131. self.cast_type = cast_type
  132. def expr(self, model):
  133. expr = super(pg_json_property, self).expr(model)
  134. return expr.astext.cast(self.cast_type)
  135. The above subclass can be used with the PostgreSQL-specific
  136. version of :class:`_postgresql.JSON`::
  137. from sqlalchemy import Column, Integer
  138. from sqlalchemy.ext.declarative import declarative_base
  139. from sqlalchemy.dialects.postgresql import JSON
  140. Base = declarative_base()
  141. class Person(Base):
  142. __tablename__ = "person"
  143. id = Column(Integer, primary_key=True)
  144. data = Column(JSON)
  145. age = pg_json_property("data", "age", Integer)
  146. The ``age`` attribute at the instance level works as before; however
  147. when rendering SQL, PostgreSQL's ``->>`` operator will be used
  148. for indexed access, instead of the usual index operator of ``->``::
  149. >>> query = session.query(Person).filter(Person.age < 20)
  150. The above query will render:
  151. .. sourcecode:: sql
  152. SELECT person.id, person.data
  153. FROM person
  154. WHERE CAST(person.data ->> %(data_1)s AS INTEGER) < %(param_1)s
  155. """ # noqa
  156. from __future__ import annotations
  157. from typing import Any
  158. from typing import Callable
  159. from typing import cast
  160. from typing import Optional
  161. from typing import TYPE_CHECKING
  162. from typing import TypeVar
  163. from typing import Union
  164. from .. import inspect
  165. from ..ext.hybrid import hybrid_property
  166. from ..orm.attributes import flag_modified
  167. if TYPE_CHECKING:
  168. from ..sql import SQLColumnExpression
  169. from ..sql._typing import _HasClauseElement
  170. __all__ = ["index_property"]
  171. _T = TypeVar("_T")
  172. class index_property(hybrid_property[_T]):
  173. """A property generator. The generated property describes an object
  174. attribute that corresponds to an :class:`_types.Indexable`
  175. column.
  176. .. seealso::
  177. :mod:`sqlalchemy.ext.indexable`
  178. """
  179. _NO_DEFAULT_ARGUMENT = cast(_T, object())
  180. def __init__(
  181. self,
  182. attr_name: str,
  183. index: Union[int, str],
  184. default: _T = _NO_DEFAULT_ARGUMENT,
  185. datatype: Optional[Callable[[], Any]] = None,
  186. mutable: bool = True,
  187. onebased: bool = True,
  188. ):
  189. """Create a new :class:`.index_property`.
  190. :param attr_name:
  191. An attribute name of an `Indexable` typed column, or other
  192. attribute that returns an indexable structure.
  193. :param index:
  194. The index to be used for getting and setting this value. This
  195. should be the Python-side index value for integers.
  196. :param default:
  197. A value which will be returned instead of `AttributeError`
  198. when there is not a value at given index.
  199. :param datatype: default datatype to use when the field is empty.
  200. By default, this is derived from the type of index used; a
  201. Python list for an integer index, or a Python dictionary for
  202. any other style of index. For a list, the list will be
  203. initialized to a list of None values that is at least
  204. ``index`` elements long.
  205. :param mutable: if False, writes and deletes to the attribute will
  206. be disallowed.
  207. :param onebased: assume the SQL representation of this value is
  208. one-based; that is, the first index in SQL is 1, not zero.
  209. """
  210. if mutable:
  211. super().__init__(self.fget, self.fset, self.fdel, self.expr)
  212. else:
  213. super().__init__(self.fget, None, None, self.expr)
  214. self.attr_name = attr_name
  215. self.index = index
  216. self.default = default
  217. is_numeric = isinstance(index, int)
  218. onebased = is_numeric and onebased
  219. if datatype is not None:
  220. self.datatype = datatype
  221. else:
  222. if is_numeric:
  223. self.datatype = lambda: [None for x in range(index + 1)] # type: ignore[operator] # noqa: E501
  224. else:
  225. self.datatype = dict
  226. self.onebased = onebased
  227. def _fget_default(self, err: Optional[BaseException] = None) -> _T:
  228. if self.default == self._NO_DEFAULT_ARGUMENT:
  229. raise AttributeError(self.attr_name) from err
  230. else:
  231. return self.default
  232. def fget(self, __instance: Any) -> _T:
  233. attr_name = self.attr_name
  234. column_value = getattr(__instance, attr_name)
  235. if column_value is None:
  236. return self._fget_default()
  237. try:
  238. value = column_value[self.index]
  239. except (KeyError, IndexError) as err:
  240. return self._fget_default(err)
  241. else:
  242. return value # type: ignore[no-any-return]
  243. def fset(self, instance: Any, value: _T) -> None:
  244. attr_name = self.attr_name
  245. column_value = getattr(instance, attr_name, None)
  246. if column_value is None:
  247. column_value = self.datatype()
  248. setattr(instance, attr_name, column_value)
  249. column_value[self.index] = value
  250. setattr(instance, attr_name, column_value)
  251. if attr_name in inspect(instance).mapper.attrs:
  252. flag_modified(instance, attr_name)
  253. def fdel(self, instance: Any) -> None:
  254. attr_name = self.attr_name
  255. column_value = getattr(instance, attr_name)
  256. if column_value is None:
  257. raise AttributeError(self.attr_name)
  258. try:
  259. del column_value[self.index]
  260. except KeyError as err:
  261. raise AttributeError(self.attr_name) from err
  262. else:
  263. setattr(instance, attr_name, column_value)
  264. flag_modified(instance, attr_name)
  265. def expr(
  266. self, model: Any
  267. ) -> Union[_HasClauseElement[_T], SQLColumnExpression[_T]]:
  268. column = getattr(model, self.attr_name)
  269. index = self.index
  270. if self.onebased:
  271. index += 1 # type: ignore[operator]
  272. return column[index] # type: ignore[no-any-return]