indexable.py 11 KB

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