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.

359 lines
11KB

  1. # sql/annotation.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. """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 operators
  12. from .base import HasCacheKey
  13. from .traversals import anon_map
  14. from .visitors import InternalTraversal
  15. from .. import util
  16. EMPTY_ANNOTATIONS = util.immutabledict()
  17. class SupportsAnnotations(object):
  18. _annotations = EMPTY_ANNOTATIONS
  19. @util.memoized_property
  20. def _annotations_cache_key(self):
  21. anon_map_ = anon_map()
  22. return (
  23. "_annotations",
  24. tuple(
  25. (
  26. key,
  27. value._gen_cache_key(anon_map_, [])
  28. if isinstance(value, HasCacheKey)
  29. else value,
  30. )
  31. for key, value in [
  32. (key, self._annotations[key])
  33. for key in sorted(self._annotations)
  34. ]
  35. ),
  36. )
  37. class SupportsCloneAnnotations(SupportsAnnotations):
  38. _clone_annotations_traverse_internals = [
  39. ("_annotations", InternalTraversal.dp_annotations_key)
  40. ]
  41. def _annotate(self, values):
  42. """return a copy of this ClauseElement with annotations
  43. updated by the given dictionary.
  44. """
  45. new = self._clone()
  46. new._annotations = new._annotations.union(values)
  47. new.__dict__.pop("_annotations_cache_key", None)
  48. new.__dict__.pop("_generate_cache_key", None)
  49. return new
  50. def _with_annotations(self, values):
  51. """return a copy of this ClauseElement with annotations
  52. replaced by the given dictionary.
  53. """
  54. new = self._clone()
  55. new._annotations = util.immutabledict(values)
  56. new.__dict__.pop("_annotations_cache_key", None)
  57. new.__dict__.pop("_generate_cache_key", None)
  58. return new
  59. def _deannotate(self, values=None, clone=False):
  60. """return a copy of this :class:`_expression.ClauseElement`
  61. with annotations
  62. removed.
  63. :param values: optional tuple of individual values
  64. to remove.
  65. """
  66. if clone or self._annotations:
  67. # clone is used when we are also copying
  68. # the expression for a deep deannotation
  69. new = self._clone()
  70. new._annotations = util.immutabledict()
  71. new.__dict__.pop("_annotations_cache_key", None)
  72. return new
  73. else:
  74. return self
  75. class SupportsWrappingAnnotations(SupportsAnnotations):
  76. def _annotate(self, values):
  77. """return a copy of this ClauseElement with annotations
  78. updated by the given dictionary.
  79. """
  80. return Annotated(self, values)
  81. def _with_annotations(self, values):
  82. """return a copy of this ClauseElement with annotations
  83. replaced by the given dictionary.
  84. """
  85. return Annotated(self, values)
  86. def _deannotate(self, values=None, clone=False):
  87. """return a copy of this :class:`_expression.ClauseElement`
  88. with annotations
  89. removed.
  90. :param values: optional tuple of individual values
  91. to remove.
  92. """
  93. if clone:
  94. s = self._clone()
  95. return s
  96. else:
  97. return self
  98. class Annotated(object):
  99. """clones a SupportsAnnotated and applies an 'annotations' dictionary.
  100. Unlike regular clones, this clone also mimics __hash__() and
  101. __cmp__() of the original element so that it takes its place
  102. in hashed collections.
  103. A reference to the original element is maintained, for the important
  104. reason of keeping its hash value current. When GC'ed, the
  105. hash value may be reused, causing conflicts.
  106. .. note:: The rationale for Annotated producing a brand new class,
  107. rather than placing the functionality directly within ClauseElement,
  108. is **performance**. The __hash__() method is absent on plain
  109. ClauseElement which leads to significantly reduced function call
  110. overhead, as the use of sets and dictionaries against ClauseElement
  111. objects is prevalent, but most are not "annotated".
  112. """
  113. _is_column_operators = False
  114. def __new__(cls, *args):
  115. if not args:
  116. # clone constructor
  117. return object.__new__(cls)
  118. else:
  119. element, values = args
  120. # pull appropriate subclass from registry of annotated
  121. # classes
  122. try:
  123. cls = annotated_classes[element.__class__]
  124. except KeyError:
  125. cls = _new_annotation_type(element.__class__, cls)
  126. return object.__new__(cls)
  127. def __init__(self, element, values):
  128. self.__dict__ = element.__dict__.copy()
  129. self.__dict__.pop("_annotations_cache_key", None)
  130. self.__dict__.pop("_generate_cache_key", None)
  131. self.__element = element
  132. self._annotations = util.immutabledict(values)
  133. self._hash = hash(element)
  134. def _annotate(self, values):
  135. _values = self._annotations.union(values)
  136. return self._with_annotations(_values)
  137. def _with_annotations(self, values):
  138. clone = self.__class__.__new__(self.__class__)
  139. clone.__dict__ = self.__dict__.copy()
  140. clone.__dict__.pop("_annotations_cache_key", None)
  141. clone.__dict__.pop("_generate_cache_key", None)
  142. clone._annotations = values
  143. return clone
  144. def _deannotate(self, values=None, clone=True):
  145. if values is None:
  146. return self.__element
  147. else:
  148. return self._with_annotations(
  149. util.immutabledict(
  150. {
  151. key: value
  152. for key, value in self._annotations.items()
  153. if key not in values
  154. }
  155. )
  156. )
  157. def _compiler_dispatch(self, visitor, **kw):
  158. return self.__element.__class__._compiler_dispatch(self, visitor, **kw)
  159. @property
  160. def _constructor(self):
  161. return self.__element._constructor
  162. def _clone(self, **kw):
  163. clone = self.__element._clone(**kw)
  164. if clone is self.__element:
  165. # detect immutable, don't change anything
  166. return self
  167. else:
  168. # update the clone with any changes that have occurred
  169. # to this object's __dict__.
  170. clone.__dict__.update(self.__dict__)
  171. return self.__class__(clone, self._annotations)
  172. def __reduce__(self):
  173. return self.__class__, (self.__element, self._annotations)
  174. def __hash__(self):
  175. return self._hash
  176. def __eq__(self, other):
  177. if self._is_column_operators:
  178. return self.__element.__class__.__eq__(self, other)
  179. else:
  180. return hash(other) == hash(self)
  181. @property
  182. def entity_namespace(self):
  183. if "entity_namespace" in self._annotations:
  184. return self._annotations["entity_namespace"].entity_namespace
  185. else:
  186. return self.__element.entity_namespace
  187. # hard-generate Annotated subclasses. this technique
  188. # is used instead of on-the-fly types (i.e. type.__new__())
  189. # so that the resulting objects are pickleable; additionally, other
  190. # decisions can be made up front about the type of object being annotated
  191. # just once per class rather than per-instance.
  192. annotated_classes = {}
  193. def _deep_annotate(element, annotations, exclude=None):
  194. """Deep copy the given ClauseElement, annotating each element
  195. with the given annotations dictionary.
  196. Elements within the exclude collection will be cloned but not annotated.
  197. """
  198. # annotated objects hack the __hash__() method so if we want to
  199. # uniquely process them we have to use id()
  200. cloned_ids = {}
  201. def clone(elem, **kw):
  202. id_ = id(elem)
  203. if id_ in cloned_ids:
  204. return cloned_ids[id_]
  205. if (
  206. exclude
  207. and hasattr(elem, "proxy_set")
  208. and elem.proxy_set.intersection(exclude)
  209. ):
  210. newelem = elem._clone(**kw)
  211. elif annotations != elem._annotations:
  212. newelem = elem._annotate(annotations)
  213. else:
  214. newelem = elem
  215. newelem._copy_internals(clone=clone)
  216. cloned_ids[id_] = newelem
  217. return newelem
  218. if element is not None:
  219. element = clone(element)
  220. clone = None # remove gc cycles
  221. return element
  222. def _deep_deannotate(element, values=None):
  223. """Deep copy the given element, removing annotations."""
  224. cloned = {}
  225. def clone(elem, **kw):
  226. if values:
  227. key = id(elem)
  228. else:
  229. key = elem
  230. if key not in cloned:
  231. newelem = elem._deannotate(values=values, clone=True)
  232. newelem._copy_internals(clone=clone)
  233. cloned[key] = newelem
  234. return newelem
  235. else:
  236. return cloned[key]
  237. if element is not None:
  238. element = clone(element)
  239. clone = None # remove gc cycles
  240. return element
  241. def _shallow_annotate(element, annotations):
  242. """Annotate the given ClauseElement and copy its internals so that
  243. internal objects refer to the new annotated object.
  244. Basically used to apply a "don't traverse" annotation to a
  245. selectable, without digging throughout the whole
  246. structure wasting time.
  247. """
  248. element = element._annotate(annotations)
  249. element._copy_internals()
  250. return element
  251. def _new_annotation_type(cls, base_cls):
  252. if issubclass(cls, Annotated):
  253. return cls
  254. elif cls in annotated_classes:
  255. return annotated_classes[cls]
  256. for super_ in cls.__mro__:
  257. # check if an Annotated subclass more specific than
  258. # the given base_cls is already registered, such
  259. # as AnnotatedColumnElement.
  260. if super_ in annotated_classes:
  261. base_cls = annotated_classes[super_]
  262. break
  263. annotated_classes[cls] = anno_cls = type(
  264. "Annotated%s" % cls.__name__, (base_cls, cls), {}
  265. )
  266. globals()["Annotated%s" % cls.__name__] = anno_cls
  267. if "_traverse_internals" in cls.__dict__:
  268. anno_cls._traverse_internals = list(cls._traverse_internals) + [
  269. ("_annotations", InternalTraversal.dp_annotations_key)
  270. ]
  271. elif cls.__dict__.get("inherit_cache", False):
  272. anno_cls._traverse_internals = list(cls._traverse_internals) + [
  273. ("_annotations", InternalTraversal.dp_annotations_key)
  274. ]
  275. # some classes include this even if they have traverse_internals
  276. # e.g. BindParameter, add it if present.
  277. if cls.__dict__.get("inherit_cache", False):
  278. anno_cls.inherit_cache = True
  279. anno_cls._is_column_operators = issubclass(cls, operators.ColumnOperators)
  280. return anno_cls
  281. def _prepare_annotations(target_hierarchy, base_cls):
  282. for cls in util.walk_subclasses(target_hierarchy):
  283. _new_annotation_type(cls, base_cls)