PageRenderTime 54ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/Windows/Python3.8/WPy64-3830/WPy64-3830/python-3.8.3.amd64/Lib/site-packages/sqlalchemy/ext/orderinglist.py

https://gitlab.com/abhi1tb/build
Python | 389 lines | 352 code | 4 blank | 33 comment | 5 complexity | 398c52b38fbcadb36c65ec5185a13726 MD5 | raw file
  1. # ext/orderinglist.py
  2. # Copyright (C) 2005-2020 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. """A custom list that manages index/position information for contained
  8. elements.
  9. :author: Jason Kirtland
  10. ``orderinglist`` is a helper for mutable ordered relationships. It will
  11. intercept list operations performed on a :func:`_orm.relationship`-managed
  12. collection and
  13. automatically synchronize changes in list position onto a target scalar
  14. attribute.
  15. Example: A ``slide`` table, where each row refers to zero or more entries
  16. in a related ``bullet`` table. The bullets within a slide are
  17. displayed in order based on the value of the ``position`` column in the
  18. ``bullet`` table. As entries are reordered in memory, the value of the
  19. ``position`` attribute should be updated to reflect the new sort order::
  20. Base = declarative_base()
  21. class Slide(Base):
  22. __tablename__ = 'slide'
  23. id = Column(Integer, primary_key=True)
  24. name = Column(String)
  25. bullets = relationship("Bullet", order_by="Bullet.position")
  26. class Bullet(Base):
  27. __tablename__ = 'bullet'
  28. id = Column(Integer, primary_key=True)
  29. slide_id = Column(Integer, ForeignKey('slide.id'))
  30. position = Column(Integer)
  31. text = Column(String)
  32. The standard relationship mapping will produce a list-like attribute on each
  33. ``Slide`` containing all related ``Bullet`` objects,
  34. but coping with changes in ordering is not handled automatically.
  35. When appending a ``Bullet`` into ``Slide.bullets``, the ``Bullet.position``
  36. attribute will remain unset until manually assigned. When the ``Bullet``
  37. is inserted into the middle of the list, the following ``Bullet`` objects
  38. will also need to be renumbered.
  39. The :class:`.OrderingList` object automates this task, managing the
  40. ``position`` attribute on all ``Bullet`` objects in the collection. It is
  41. constructed using the :func:`.ordering_list` factory::
  42. from sqlalchemy.ext.orderinglist import ordering_list
  43. Base = declarative_base()
  44. class Slide(Base):
  45. __tablename__ = 'slide'
  46. id = Column(Integer, primary_key=True)
  47. name = Column(String)
  48. bullets = relationship("Bullet", order_by="Bullet.position",
  49. collection_class=ordering_list('position'))
  50. class Bullet(Base):
  51. __tablename__ = 'bullet'
  52. id = Column(Integer, primary_key=True)
  53. slide_id = Column(Integer, ForeignKey('slide.id'))
  54. position = Column(Integer)
  55. text = Column(String)
  56. With the above mapping the ``Bullet.position`` attribute is managed::
  57. s = Slide()
  58. s.bullets.append(Bullet())
  59. s.bullets.append(Bullet())
  60. s.bullets[1].position
  61. >>> 1
  62. s.bullets.insert(1, Bullet())
  63. s.bullets[2].position
  64. >>> 2
  65. The :class:`.OrderingList` construct only works with **changes** to a
  66. collection, and not the initial load from the database, and requires that the
  67. list be sorted when loaded. Therefore, be sure to specify ``order_by`` on the
  68. :func:`_orm.relationship` against the target ordering attribute, so that the
  69. ordering is correct when first loaded.
  70. .. warning::
  71. :class:`.OrderingList` only provides limited functionality when a primary
  72. key column or unique column is the target of the sort. Operations
  73. that are unsupported or are problematic include:
  74. * two entries must trade values. This is not supported directly in the
  75. case of a primary key or unique constraint because it means at least
  76. one row would need to be temporarily removed first, or changed to
  77. a third, neutral value while the switch occurs.
  78. * an entry must be deleted in order to make room for a new entry.
  79. SQLAlchemy's unit of work performs all INSERTs before DELETEs within a
  80. single flush. In the case of a primary key, it will trade
  81. an INSERT/DELETE of the same primary key for an UPDATE statement in order
  82. to lessen the impact of this limitation, however this does not take place
  83. for a UNIQUE column.
  84. A future feature will allow the "DELETE before INSERT" behavior to be
  85. possible, alleviating this limitation, though this feature will require
  86. explicit configuration at the mapper level for sets of columns that
  87. are to be handled in this way.
  88. :func:`.ordering_list` takes the name of the related object's ordering
  89. attribute as an argument. By default, the zero-based integer index of the
  90. object's position in the :func:`.ordering_list` is synchronized with the
  91. ordering attribute: index 0 will get position 0, index 1 position 1, etc. To
  92. start numbering at 1 or some other integer, provide ``count_from=1``.
  93. """
  94. from .. import util
  95. from ..orm.collections import collection
  96. from ..orm.collections import collection_adapter
  97. __all__ = ["ordering_list"]
  98. def ordering_list(attr, count_from=None, **kw):
  99. """Prepares an :class:`OrderingList` factory for use in mapper definitions.
  100. Returns an object suitable for use as an argument to a Mapper
  101. relationship's ``collection_class`` option. e.g.::
  102. from sqlalchemy.ext.orderinglist import ordering_list
  103. class Slide(Base):
  104. __tablename__ = 'slide'
  105. id = Column(Integer, primary_key=True)
  106. name = Column(String)
  107. bullets = relationship("Bullet", order_by="Bullet.position",
  108. collection_class=ordering_list('position'))
  109. :param attr:
  110. Name of the mapped attribute to use for storage and retrieval of
  111. ordering information
  112. :param count_from:
  113. Set up an integer-based ordering, starting at ``count_from``. For
  114. example, ``ordering_list('pos', count_from=1)`` would create a 1-based
  115. list in SQL, storing the value in the 'pos' column. Ignored if
  116. ``ordering_func`` is supplied.
  117. Additional arguments are passed to the :class:`.OrderingList` constructor.
  118. """
  119. kw = _unsugar_count_from(count_from=count_from, **kw)
  120. return lambda: OrderingList(attr, **kw)
  121. # Ordering utility functions
  122. def count_from_0(index, collection):
  123. """Numbering function: consecutive integers starting at 0."""
  124. return index
  125. def count_from_1(index, collection):
  126. """Numbering function: consecutive integers starting at 1."""
  127. return index + 1
  128. def count_from_n_factory(start):
  129. """Numbering function: consecutive integers starting at arbitrary start."""
  130. def f(index, collection):
  131. return index + start
  132. try:
  133. f.__name__ = "count_from_%i" % start
  134. except TypeError:
  135. pass
  136. return f
  137. def _unsugar_count_from(**kw):
  138. """Builds counting functions from keyword arguments.
  139. Keyword argument filter, prepares a simple ``ordering_func`` from a
  140. ``count_from`` argument, otherwise passes ``ordering_func`` on unchanged.
  141. """
  142. count_from = kw.pop("count_from", None)
  143. if kw.get("ordering_func", None) is None and count_from is not None:
  144. if count_from == 0:
  145. kw["ordering_func"] = count_from_0
  146. elif count_from == 1:
  147. kw["ordering_func"] = count_from_1
  148. else:
  149. kw["ordering_func"] = count_from_n_factory(count_from)
  150. return kw
  151. class OrderingList(list):
  152. """A custom list that manages position information for its children.
  153. The :class:`.OrderingList` object is normally set up using the
  154. :func:`.ordering_list` factory function, used in conjunction with
  155. the :func:`_orm.relationship` function.
  156. """
  157. def __init__(
  158. self, ordering_attr=None, ordering_func=None, reorder_on_append=False
  159. ):
  160. """A custom list that manages position information for its children.
  161. ``OrderingList`` is a ``collection_class`` list implementation that
  162. syncs position in a Python list with a position attribute on the
  163. mapped objects.
  164. This implementation relies on the list starting in the proper order,
  165. so be **sure** to put an ``order_by`` on your relationship.
  166. :param ordering_attr:
  167. Name of the attribute that stores the object's order in the
  168. relationship.
  169. :param ordering_func: Optional. A function that maps the position in
  170. the Python list to a value to store in the
  171. ``ordering_attr``. Values returned are usually (but need not be!)
  172. integers.
  173. An ``ordering_func`` is called with two positional parameters: the
  174. index of the element in the list, and the list itself.
  175. If omitted, Python list indexes are used for the attribute values.
  176. Two basic pre-built numbering functions are provided in this module:
  177. ``count_from_0`` and ``count_from_1``. For more exotic examples
  178. like stepped numbering, alphabetical and Fibonacci numbering, see
  179. the unit tests.
  180. :param reorder_on_append:
  181. Default False. When appending an object with an existing (non-None)
  182. ordering value, that value will be left untouched unless
  183. ``reorder_on_append`` is true. This is an optimization to avoid a
  184. variety of dangerous unexpected database writes.
  185. SQLAlchemy will add instances to the list via append() when your
  186. object loads. If for some reason the result set from the database
  187. skips a step in the ordering (say, row '1' is missing but you get
  188. '2', '3', and '4'), reorder_on_append=True would immediately
  189. renumber the items to '1', '2', '3'. If you have multiple sessions
  190. making changes, any of whom happen to load this collection even in
  191. passing, all of the sessions would try to "clean up" the numbering
  192. in their commits, possibly causing all but one to fail with a
  193. concurrent modification error.
  194. Recommend leaving this with the default of False, and just call
  195. ``reorder()`` if you're doing ``append()`` operations with
  196. previously ordered instances or when doing some housekeeping after
  197. manual sql operations.
  198. """
  199. self.ordering_attr = ordering_attr
  200. if ordering_func is None:
  201. ordering_func = count_from_0
  202. self.ordering_func = ordering_func
  203. self.reorder_on_append = reorder_on_append
  204. # More complex serialization schemes (multi column, e.g.) are possible by
  205. # subclassing and reimplementing these two methods.
  206. def _get_order_value(self, entity):
  207. return getattr(entity, self.ordering_attr)
  208. def _set_order_value(self, entity, value):
  209. setattr(entity, self.ordering_attr, value)
  210. def reorder(self):
  211. """Synchronize ordering for the entire collection.
  212. Sweeps through the list and ensures that each object has accurate
  213. ordering information set.
  214. """
  215. for index, entity in enumerate(self):
  216. self._order_entity(index, entity, True)
  217. # As of 0.5, _reorder is no longer semi-private
  218. _reorder = reorder
  219. def _order_entity(self, index, entity, reorder=True):
  220. have = self._get_order_value(entity)
  221. # Don't disturb existing ordering if reorder is False
  222. if have is not None and not reorder:
  223. return
  224. should_be = self.ordering_func(index, self)
  225. if have != should_be:
  226. self._set_order_value(entity, should_be)
  227. def append(self, entity):
  228. super(OrderingList, self).append(entity)
  229. self._order_entity(len(self) - 1, entity, self.reorder_on_append)
  230. def _raw_append(self, entity):
  231. """Append without any ordering behavior."""
  232. super(OrderingList, self).append(entity)
  233. _raw_append = collection.adds(1)(_raw_append)
  234. def insert(self, index, entity):
  235. super(OrderingList, self).insert(index, entity)
  236. self._reorder()
  237. def remove(self, entity):
  238. super(OrderingList, self).remove(entity)
  239. adapter = collection_adapter(self)
  240. if adapter and adapter._referenced_by_owner:
  241. self._reorder()
  242. def pop(self, index=-1):
  243. entity = super(OrderingList, self).pop(index)
  244. self._reorder()
  245. return entity
  246. def __setitem__(self, index, entity):
  247. if isinstance(index, slice):
  248. step = index.step or 1
  249. start = index.start or 0
  250. if start < 0:
  251. start += len(self)
  252. stop = index.stop or len(self)
  253. if stop < 0:
  254. stop += len(self)
  255. for i in range(start, stop, step):
  256. self.__setitem__(i, entity[i])
  257. else:
  258. self._order_entity(index, entity, True)
  259. super(OrderingList, self).__setitem__(index, entity)
  260. def __delitem__(self, index):
  261. super(OrderingList, self).__delitem__(index)
  262. self._reorder()
  263. def __setslice__(self, start, end, values):
  264. super(OrderingList, self).__setslice__(start, end, values)
  265. self._reorder()
  266. def __delslice__(self, start, end):
  267. super(OrderingList, self).__delslice__(start, end)
  268. self._reorder()
  269. def __reduce__(self):
  270. return _reconstitute, (self.__class__, self.__dict__, list(self))
  271. for func_name, func in list(locals().items()):
  272. if (
  273. util.callable(func)
  274. and func.__name__ == func_name
  275. and not func.__doc__
  276. and hasattr(list, func_name)
  277. ):
  278. func.__doc__ = getattr(list, func_name).__doc__
  279. del func_name, func
  280. def _reconstitute(cls, dict_, items):
  281. """ Reconstitute an :class:`.OrderingList`.
  282. This is the adjoint to :meth:`.OrderingList.__reduce__`. It is used for
  283. unpickling :class:`.OrderingList` objects.
  284. """
  285. obj = cls.__new__(cls)
  286. obj.__dict__.update(dict_)
  287. list.extend(obj, items)
  288. return obj