annotation.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. # sql/annotation.py
  2. # Copyright (C) 2005-2022 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. """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(
  194. element, annotations, exclude=None, detect_subquery_cols=False
  195. ):
  196. """Deep copy the given ClauseElement, annotating each element
  197. with the given annotations dictionary.
  198. Elements within the exclude collection will be cloned but not annotated.
  199. """
  200. # annotated objects hack the __hash__() method so if we want to
  201. # uniquely process them we have to use id()
  202. cloned_ids = {}
  203. def clone(elem, **kw):
  204. kw["detect_subquery_cols"] = detect_subquery_cols
  205. id_ = id(elem)
  206. if id_ in cloned_ids:
  207. return cloned_ids[id_]
  208. if (
  209. exclude
  210. and hasattr(elem, "proxy_set")
  211. and elem.proxy_set.intersection(exclude)
  212. ):
  213. newelem = elem._clone(clone=clone, **kw)
  214. elif annotations != elem._annotations:
  215. if detect_subquery_cols and elem._is_immutable:
  216. newelem = elem._clone(clone=clone, **kw)._annotate(annotations)
  217. else:
  218. newelem = elem._annotate(annotations)
  219. else:
  220. newelem = elem
  221. newelem._copy_internals(clone=clone)
  222. cloned_ids[id_] = newelem
  223. return newelem
  224. if element is not None:
  225. element = clone(element)
  226. clone = None # remove gc cycles
  227. return element
  228. def _deep_deannotate(element, values=None):
  229. """Deep copy the given element, removing annotations."""
  230. cloned = {}
  231. def clone(elem, **kw):
  232. if values:
  233. key = id(elem)
  234. else:
  235. key = elem
  236. if key not in cloned:
  237. newelem = elem._deannotate(values=values, clone=True)
  238. newelem._copy_internals(clone=clone)
  239. cloned[key] = newelem
  240. return newelem
  241. else:
  242. return cloned[key]
  243. if element is not None:
  244. element = clone(element)
  245. clone = None # remove gc cycles
  246. return element
  247. def _shallow_annotate(element, annotations):
  248. """Annotate the given ClauseElement and copy its internals so that
  249. internal objects refer to the new annotated object.
  250. Basically used to apply a "don't traverse" annotation to a
  251. selectable, without digging throughout the whole
  252. structure wasting time.
  253. """
  254. element = element._annotate(annotations)
  255. element._copy_internals()
  256. return element
  257. def _new_annotation_type(cls, base_cls):
  258. if issubclass(cls, Annotated):
  259. return cls
  260. elif cls in annotated_classes:
  261. return annotated_classes[cls]
  262. for super_ in cls.__mro__:
  263. # check if an Annotated subclass more specific than
  264. # the given base_cls is already registered, such
  265. # as AnnotatedColumnElement.
  266. if super_ in annotated_classes:
  267. base_cls = annotated_classes[super_]
  268. break
  269. annotated_classes[cls] = anno_cls = type(
  270. "Annotated%s" % cls.__name__, (base_cls, cls), {}
  271. )
  272. globals()["Annotated%s" % cls.__name__] = anno_cls
  273. if "_traverse_internals" in cls.__dict__:
  274. anno_cls._traverse_internals = list(cls._traverse_internals) + [
  275. ("_annotations", InternalTraversal.dp_annotations_key)
  276. ]
  277. elif cls.__dict__.get("inherit_cache", False):
  278. anno_cls._traverse_internals = list(cls._traverse_internals) + [
  279. ("_annotations", InternalTraversal.dp_annotations_key)
  280. ]
  281. # some classes include this even if they have traverse_internals
  282. # e.g. BindParameter, add it if present.
  283. if cls.__dict__.get("inherit_cache", False):
  284. anno_cls.inherit_cache = True
  285. anno_cls._is_column_operators = issubclass(cls, operators.ColumnOperators)
  286. return anno_cls
  287. def _prepare_annotations(target_hierarchy, base_cls):
  288. for cls in util.walk_subclasses(target_hierarchy):
  289. _new_annotation_type(cls, base_cls)