annotation.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203
  1. # sql/annotation.py
  2. # Copyright (C) 2005-2017 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. """The :class:`.Annotated` class and related routines; creates hash-equivalent
  8. copies of SQL constructs which contain context-specific markers and
  9. associations.
  10. """
  11. from .. import util
  12. from . import operators
  13. class Annotated(object):
  14. """clones a ClauseElement and applies an 'annotations' dictionary.
  15. Unlike regular clones, this clone also mimics __hash__() and
  16. __cmp__() of the original element so that it takes its place
  17. in hashed collections.
  18. A reference to the original element is maintained, for the important
  19. reason of keeping its hash value current. When GC'ed, the
  20. hash value may be reused, causing conflicts.
  21. .. note:: The rationale for Annotated producing a brand new class,
  22. rather than placing the functionality directly within ClauseElement,
  23. is **performance**. The __hash__() method is absent on plain
  24. ClauseElement which leads to significantly reduced function call
  25. overhead, as the use of sets and dictionaries against ClauseElement
  26. objects is prevalent, but most are not "annotated".
  27. """
  28. def __new__(cls, *args):
  29. if not args:
  30. # clone constructor
  31. return object.__new__(cls)
  32. else:
  33. element, values = args
  34. # pull appropriate subclass from registry of annotated
  35. # classes
  36. try:
  37. cls = annotated_classes[element.__class__]
  38. except KeyError:
  39. cls = _new_annotation_type(element.__class__, cls)
  40. return object.__new__(cls)
  41. def __init__(self, element, values):
  42. self.__dict__ = element.__dict__.copy()
  43. self.__element = element
  44. self._annotations = values
  45. self._hash = hash(element)
  46. def _annotate(self, values):
  47. _values = self._annotations.copy()
  48. _values.update(values)
  49. return self._with_annotations(_values)
  50. def _with_annotations(self, values):
  51. clone = self.__class__.__new__(self.__class__)
  52. clone.__dict__ = self.__dict__.copy()
  53. clone._annotations = values
  54. return clone
  55. def _deannotate(self, values=None, clone=True):
  56. if values is None:
  57. return self.__element
  58. else:
  59. _values = self._annotations.copy()
  60. for v in values:
  61. _values.pop(v, None)
  62. return self._with_annotations(_values)
  63. def _compiler_dispatch(self, visitor, **kw):
  64. return self.__element.__class__._compiler_dispatch(
  65. self, visitor, **kw)
  66. @property
  67. def _constructor(self):
  68. return self.__element._constructor
  69. def _clone(self):
  70. clone = self.__element._clone()
  71. if clone is self.__element:
  72. # detect immutable, don't change anything
  73. return self
  74. else:
  75. # update the clone with any changes that have occurred
  76. # to this object's __dict__.
  77. clone.__dict__.update(self.__dict__)
  78. return self.__class__(clone, self._annotations)
  79. def __hash__(self):
  80. return self._hash
  81. def __eq__(self, other):
  82. if isinstance(self.__element, operators.ColumnOperators):
  83. return self.__element.__class__.__eq__(self, other)
  84. else:
  85. return hash(other) == hash(self)
  86. # hard-generate Annotated subclasses. this technique
  87. # is used instead of on-the-fly types (i.e. type.__new__())
  88. # so that the resulting objects are pickleable.
  89. annotated_classes = {}
  90. def _deep_annotate(element, annotations, exclude=None):
  91. """Deep copy the given ClauseElement, annotating each element
  92. with the given annotations dictionary.
  93. Elements within the exclude collection will be cloned but not annotated.
  94. """
  95. def clone(elem):
  96. if exclude and \
  97. hasattr(elem, 'proxy_set') and \
  98. elem.proxy_set.intersection(exclude):
  99. newelem = elem._clone()
  100. elif annotations != elem._annotations:
  101. newelem = elem._annotate(annotations)
  102. else:
  103. newelem = elem
  104. newelem._copy_internals(clone=clone)
  105. return newelem
  106. if element is not None:
  107. element = clone(element)
  108. return element
  109. def _deep_deannotate(element, values=None):
  110. """Deep copy the given element, removing annotations."""
  111. cloned = util.column_dict()
  112. def clone(elem):
  113. # if a values dict is given,
  114. # the elem must be cloned each time it appears,
  115. # as there may be different annotations in source
  116. # elements that are remaining. if totally
  117. # removing all annotations, can assume the same
  118. # slate...
  119. if values or elem not in cloned:
  120. newelem = elem._deannotate(values=values, clone=True)
  121. newelem._copy_internals(clone=clone)
  122. if not values:
  123. cloned[elem] = newelem
  124. return newelem
  125. else:
  126. return cloned[elem]
  127. if element is not None:
  128. element = clone(element)
  129. return element
  130. def _shallow_annotate(element, annotations):
  131. """Annotate the given ClauseElement and copy its internals so that
  132. internal objects refer to the new annotated object.
  133. Basically used to apply a "dont traverse" annotation to a
  134. selectable, without digging throughout the whole
  135. structure wasting time.
  136. """
  137. element = element._annotate(annotations)
  138. element._copy_internals()
  139. return element
  140. def _new_annotation_type(cls, base_cls):
  141. if issubclass(cls, Annotated):
  142. return cls
  143. elif cls in annotated_classes:
  144. return annotated_classes[cls]
  145. for super_ in cls.__mro__:
  146. # check if an Annotated subclass more specific than
  147. # the given base_cls is already registered, such
  148. # as AnnotatedColumnElement.
  149. if super_ in annotated_classes:
  150. base_cls = annotated_classes[super_]
  151. break
  152. annotated_classes[cls] = anno_cls = type(
  153. "Annotated%s" % cls.__name__,
  154. (base_cls, cls), {})
  155. globals()["Annotated%s" % cls.__name__] = anno_cls
  156. return anno_cls
  157. def _prepare_annotations(target_hierarchy, base_cls):
  158. stack = [target_hierarchy]
  159. while stack:
  160. cls = stack.pop()
  161. stack.extend(cls.__subclasses__())
  162. _new_annotation_type(cls, base_cls)