PageRenderTime 52ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/HLI_ExomeseqQC_optimized/pymodules/python2.7/lib/python/SQLAlchemy-0.9.7-py2.7-linux-x86_64.egg/sqlalchemy/ext/declarative/clsregistry.py

https://gitlab.com/pooja043/Globus_Docker_4
Python | 312 lines | 224 code | 51 blank | 37 comment | 56 complexity | 80c45347e92cc9f335e85266c63848f8 MD5 | raw file
  1. # ext/declarative/clsregistry.py
  2. # Copyright (C) 2005-2014 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. """Routines to handle the string class registry used by declarative.
  8. This system allows specification of classes and expressions used in
  9. :func:`.relationship` using strings.
  10. """
  11. from ...orm.properties import ColumnProperty, RelationshipProperty, \
  12. SynonymProperty
  13. from ...schema import _get_table_key
  14. from ...orm import class_mapper, interfaces
  15. from ... import util
  16. from ... import inspection
  17. from ... import exc
  18. import weakref
  19. # strong references to registries which we place in
  20. # the _decl_class_registry, which is usually weak referencing.
  21. # the internal registries here link to classes with weakrefs and remove
  22. # themselves when all references to contained classes are removed.
  23. _registries = set()
  24. def add_class(classname, cls):
  25. """Add a class to the _decl_class_registry associated with the
  26. given declarative class.
  27. """
  28. if classname in cls._decl_class_registry:
  29. # class already exists.
  30. existing = cls._decl_class_registry[classname]
  31. if not isinstance(existing, _MultipleClassMarker):
  32. existing = \
  33. cls._decl_class_registry[classname] = \
  34. _MultipleClassMarker([cls, existing])
  35. else:
  36. cls._decl_class_registry[classname] = cls
  37. try:
  38. root_module = cls._decl_class_registry['_sa_module_registry']
  39. except KeyError:
  40. cls._decl_class_registry['_sa_module_registry'] = \
  41. root_module = _ModuleMarker('_sa_module_registry', None)
  42. tokens = cls.__module__.split(".")
  43. # build up a tree like this:
  44. # modulename: myapp.snacks.nuts
  45. #
  46. # myapp->snack->nuts->(classes)
  47. # snack->nuts->(classes)
  48. # nuts->(classes)
  49. #
  50. # this allows partial token paths to be used.
  51. while tokens:
  52. token = tokens.pop(0)
  53. module = root_module.get_module(token)
  54. for token in tokens:
  55. module = module.get_module(token)
  56. module.add_class(classname, cls)
  57. class _MultipleClassMarker(object):
  58. """refers to multiple classes of the same name
  59. within _decl_class_registry.
  60. """
  61. def __init__(self, classes, on_remove=None):
  62. self.on_remove = on_remove
  63. self.contents = set([
  64. weakref.ref(item, self._remove_item) for item in classes])
  65. _registries.add(self)
  66. def __iter__(self):
  67. return (ref() for ref in self.contents)
  68. def attempt_get(self, path, key):
  69. if len(self.contents) > 1:
  70. raise exc.InvalidRequestError(
  71. "Multiple classes found for path \"%s\" "
  72. "in the registry of this declarative "
  73. "base. Please use a fully module-qualified path." %
  74. (".".join(path + [key]))
  75. )
  76. else:
  77. ref = list(self.contents)[0]
  78. cls = ref()
  79. if cls is None:
  80. raise NameError(key)
  81. return cls
  82. def _remove_item(self, ref):
  83. self.contents.remove(ref)
  84. if not self.contents:
  85. _registries.discard(self)
  86. if self.on_remove:
  87. self.on_remove()
  88. def add_item(self, item):
  89. modules = set([cls().__module__ for cls in self.contents])
  90. if item.__module__ in modules:
  91. util.warn(
  92. "This declarative base already contains a class with the "
  93. "same class name and module name as %s.%s, and will "
  94. "be replaced in the string-lookup table." % (
  95. item.__module__,
  96. item.__name__
  97. )
  98. )
  99. self.contents.add(weakref.ref(item, self._remove_item))
  100. class _ModuleMarker(object):
  101. """"refers to a module name within
  102. _decl_class_registry.
  103. """
  104. def __init__(self, name, parent):
  105. self.parent = parent
  106. self.name = name
  107. self.contents = {}
  108. self.mod_ns = _ModNS(self)
  109. if self.parent:
  110. self.path = self.parent.path + [self.name]
  111. else:
  112. self.path = []
  113. _registries.add(self)
  114. def __contains__(self, name):
  115. return name in self.contents
  116. def __getitem__(self, name):
  117. return self.contents[name]
  118. def _remove_item(self, name):
  119. self.contents.pop(name, None)
  120. if not self.contents and self.parent is not None:
  121. self.parent._remove_item(self.name)
  122. _registries.discard(self)
  123. def resolve_attr(self, key):
  124. return getattr(self.mod_ns, key)
  125. def get_module(self, name):
  126. if name not in self.contents:
  127. marker = _ModuleMarker(name, self)
  128. self.contents[name] = marker
  129. else:
  130. marker = self.contents[name]
  131. return marker
  132. def add_class(self, name, cls):
  133. if name in self.contents:
  134. existing = self.contents[name]
  135. existing.add_item(cls)
  136. else:
  137. existing = self.contents[name] = \
  138. _MultipleClassMarker([cls],
  139. on_remove=lambda: self._remove_item(name))
  140. class _ModNS(object):
  141. def __init__(self, parent):
  142. self.__parent = parent
  143. def __getattr__(self, key):
  144. try:
  145. value = self.__parent.contents[key]
  146. except KeyError:
  147. pass
  148. else:
  149. if value is not None:
  150. if isinstance(value, _ModuleMarker):
  151. return value.mod_ns
  152. else:
  153. assert isinstance(value, _MultipleClassMarker)
  154. return value.attempt_get(self.__parent.path, key)
  155. raise AttributeError("Module %r has no mapped classes "
  156. "registered under the name %r" % (
  157. self.__parent.name, key))
  158. class _GetColumns(object):
  159. def __init__(self, cls):
  160. self.cls = cls
  161. def __getattr__(self, key):
  162. mp = class_mapper(self.cls, configure=False)
  163. if mp:
  164. if key not in mp.all_orm_descriptors:
  165. raise exc.InvalidRequestError(
  166. "Class %r does not have a mapped column named %r"
  167. % (self.cls, key))
  168. desc = mp.all_orm_descriptors[key]
  169. if desc.extension_type is interfaces.NOT_EXTENSION:
  170. prop = desc.property
  171. if isinstance(prop, SynonymProperty):
  172. key = prop.name
  173. elif not isinstance(prop, ColumnProperty):
  174. raise exc.InvalidRequestError(
  175. "Property %r is not an instance of"
  176. " ColumnProperty (i.e. does not correspond"
  177. " directly to a Column)." % key)
  178. return getattr(self.cls, key)
  179. inspection._inspects(_GetColumns)(
  180. lambda target: inspection.inspect(target.cls))
  181. class _GetTable(object):
  182. def __init__(self, key, metadata):
  183. self.key = key
  184. self.metadata = metadata
  185. def __getattr__(self, key):
  186. return self.metadata.tables[
  187. _get_table_key(key, self.key)
  188. ]
  189. def _determine_container(key, value):
  190. if isinstance(value, _MultipleClassMarker):
  191. value = value.attempt_get([], key)
  192. return _GetColumns(value)
  193. class _class_resolver(object):
  194. def __init__(self, cls, prop, fallback, arg):
  195. self.cls = cls
  196. self.prop = prop
  197. self.arg = self._declarative_arg = arg
  198. self.fallback = fallback
  199. self._dict = util.PopulateDict(self._access_cls)
  200. self._resolvers = ()
  201. def _access_cls(self, key):
  202. cls = self.cls
  203. if key in cls._decl_class_registry:
  204. return _determine_container(key, cls._decl_class_registry[key])
  205. elif key in cls.metadata.tables:
  206. return cls.metadata.tables[key]
  207. elif key in cls.metadata._schemas:
  208. return _GetTable(key, cls.metadata)
  209. elif '_sa_module_registry' in cls._decl_class_registry and \
  210. key in cls._decl_class_registry['_sa_module_registry']:
  211. registry = cls._decl_class_registry['_sa_module_registry']
  212. return registry.resolve_attr(key)
  213. elif self._resolvers:
  214. for resolv in self._resolvers:
  215. value = resolv(key)
  216. if value is not None:
  217. return value
  218. return self.fallback[key]
  219. def __call__(self):
  220. try:
  221. x = eval(self.arg, globals(), self._dict)
  222. if isinstance(x, _GetColumns):
  223. return x.cls
  224. else:
  225. return x
  226. except NameError as n:
  227. raise exc.InvalidRequestError(
  228. "When initializing mapper %s, expression %r failed to "
  229. "locate a name (%r). If this is a class name, consider "
  230. "adding this relationship() to the %r class after "
  231. "both dependent classes have been defined." %
  232. (self.prop.parent, self.arg, n.args[0], self.cls)
  233. )
  234. def _resolver(cls, prop):
  235. import sqlalchemy
  236. from sqlalchemy.orm import foreign, remote
  237. fallback = sqlalchemy.__dict__.copy()
  238. fallback.update({'foreign': foreign, 'remote': remote})
  239. def resolve_arg(arg):
  240. return _class_resolver(cls, prop, fallback, arg)
  241. return resolve_arg
  242. def _deferred_relationship(cls, prop):
  243. if isinstance(prop, RelationshipProperty):
  244. resolve_arg = _resolver(cls, prop)
  245. for attr in ('argument', 'order_by', 'primaryjoin', 'secondaryjoin',
  246. 'secondary', '_user_defined_foreign_keys', 'remote_side'):
  247. v = getattr(prop, attr)
  248. if isinstance(v, util.string_types):
  249. setattr(prop, attr, resolve_arg(v))
  250. if prop.backref and isinstance(prop.backref, tuple):
  251. key, kwargs = prop.backref
  252. for attr in ('primaryjoin', 'secondaryjoin', 'secondary',
  253. 'foreign_keys', 'remote_side', 'order_by'):
  254. if attr in kwargs and isinstance(kwargs[attr], str):
  255. kwargs[attr] = resolve_arg(kwargs[attr])
  256. return prop