You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

353 lines
11KB

  1. # ext/index.py
  2. # Copyright (C) 2005-2021 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: http://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. .. versionadded:: 1.1
  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. ...
  64. AttributeError: 'name'
  65. Unless you set a default value::
  66. >>> class Person(Base):
  67. >>> __tablename__ = 'person'
  68. >>>
  69. >>> id = Column(Integer, primary_key=True)
  70. >>> data = Column(JSON)
  71. >>>
  72. >>> name = index_property('data', 'name', default=None) # See default
  73. >>> person = Person()
  74. >>> print(person.name)
  75. None
  76. The attributes are also accessible at the class level.
  77. Below, we illustrate ``Person.name`` used to generate
  78. an indexed SQL criteria::
  79. >>> from sqlalchemy.orm import Session
  80. >>> session = Session()
  81. >>> query = session.query(Person).filter(Person.name == 'Alchemist')
  82. The above query is equivalent to::
  83. >>> query = session.query(Person).filter(Person.data['name'] == 'Alchemist')
  84. Multiple :class:`.index_property` objects can be chained to produce
  85. multiple levels of indexing::
  86. from sqlalchemy import Column, JSON, Integer
  87. from sqlalchemy.ext.declarative import declarative_base
  88. from sqlalchemy.ext.indexable import index_property
  89. Base = declarative_base()
  90. class Person(Base):
  91. __tablename__ = 'person'
  92. id = Column(Integer, primary_key=True)
  93. data = Column(JSON)
  94. birthday = index_property('data', 'birthday')
  95. year = index_property('birthday', 'year')
  96. month = index_property('birthday', 'month')
  97. day = index_property('birthday', 'day')
  98. Above, a query such as::
  99. q = session.query(Person).filter(Person.year == '1980')
  100. On a PostgreSQL backend, the above query will render as::
  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. 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 absolute_import
  157. from .. import inspect
  158. from .. import util
  159. from ..ext.hybrid import hybrid_property
  160. from ..orm.attributes import flag_modified
  161. __all__ = ["index_property"]
  162. class index_property(hybrid_property): # noqa
  163. """A property generator. The generated property describes an object
  164. attribute that corresponds to an :class:`_types.Indexable`
  165. column.
  166. .. versionadded:: 1.1
  167. .. seealso::
  168. :mod:`sqlalchemy.ext.indexable`
  169. """
  170. _NO_DEFAULT_ARGUMENT = object()
  171. def __init__(
  172. self,
  173. attr_name,
  174. index,
  175. default=_NO_DEFAULT_ARGUMENT,
  176. datatype=None,
  177. mutable=True,
  178. onebased=True,
  179. ):
  180. """Create a new :class:`.index_property`.
  181. :param attr_name:
  182. An attribute name of an `Indexable` typed column, or other
  183. attribute that returns an indexable structure.
  184. :param index:
  185. The index to be used for getting and setting this value. This
  186. should be the Python-side index value for integers.
  187. :param default:
  188. A value which will be returned instead of `AttributeError`
  189. when there is not a value at given index.
  190. :param datatype: default datatype to use when the field is empty.
  191. By default, this is derived from the type of index used; a
  192. Python list for an integer index, or a Python dictionary for
  193. any other style of index. For a list, the list will be
  194. initialized to a list of None values that is at least
  195. ``index`` elements long.
  196. :param mutable: if False, writes and deletes to the attribute will
  197. be disallowed.
  198. :param onebased: assume the SQL representation of this value is
  199. one-based; that is, the first index in SQL is 1, not zero.
  200. """
  201. if mutable:
  202. super(index_property, self).__init__(
  203. self.fget, self.fset, self.fdel, self.expr
  204. )
  205. else:
  206. super(index_property, self).__init__(
  207. self.fget, None, None, self.expr
  208. )
  209. self.attr_name = attr_name
  210. self.index = index
  211. self.default = default
  212. is_numeric = isinstance(index, int)
  213. onebased = is_numeric and onebased
  214. if datatype is not None:
  215. self.datatype = datatype
  216. else:
  217. if is_numeric:
  218. self.datatype = lambda: [None for x in range(index + 1)]
  219. else:
  220. self.datatype = dict
  221. self.onebased = onebased
  222. def _fget_default(self, err=None):
  223. if self.default == self._NO_DEFAULT_ARGUMENT:
  224. util.raise_(AttributeError(self.attr_name), replace_context=err)
  225. else:
  226. return self.default
  227. def fget(self, instance):
  228. attr_name = self.attr_name
  229. column_value = getattr(instance, attr_name)
  230. if column_value is None:
  231. return self._fget_default()
  232. try:
  233. value = column_value[self.index]
  234. except (KeyError, IndexError) as err:
  235. return self._fget_default(err)
  236. else:
  237. return value
  238. def fset(self, instance, value):
  239. attr_name = self.attr_name
  240. column_value = getattr(instance, attr_name, None)
  241. if column_value is None:
  242. column_value = self.datatype()
  243. setattr(instance, attr_name, column_value)
  244. column_value[self.index] = value
  245. setattr(instance, attr_name, column_value)
  246. if attr_name in inspect(instance).mapper.attrs:
  247. flag_modified(instance, attr_name)
  248. def fdel(self, instance):
  249. attr_name = self.attr_name
  250. column_value = getattr(instance, attr_name)
  251. if column_value is None:
  252. raise AttributeError(self.attr_name)
  253. try:
  254. del column_value[self.index]
  255. except KeyError as err:
  256. util.raise_(AttributeError(self.attr_name), replace_context=err)
  257. else:
  258. setattr(instance, attr_name, column_value)
  259. flag_modified(instance, attr_name)
  260. def expr(self, model):
  261. column = getattr(model, self.attr_name)
  262. index = self.index
  263. if self.onebased:
  264. index += 1
  265. return column[index]