Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

567 rindas
15KB

  1. # orm/base.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. """Constants and rudimental functions used throughout the ORM.
  8. """
  9. import operator
  10. from . import exc
  11. from .. import exc as sa_exc
  12. from .. import inspection
  13. from .. import util
  14. PASSIVE_NO_RESULT = util.symbol(
  15. "PASSIVE_NO_RESULT",
  16. """Symbol returned by a loader callable or other attribute/history
  17. retrieval operation when a value could not be determined, based
  18. on loader callable flags.
  19. """,
  20. )
  21. PASSIVE_CLASS_MISMATCH = util.symbol(
  22. "PASSIVE_CLASS_MISMATCH",
  23. """Symbol indicating that an object is locally present for a given
  24. primary key identity but it is not of the requested class. The
  25. return value is therefore None and no SQL should be emitted.""",
  26. )
  27. ATTR_WAS_SET = util.symbol(
  28. "ATTR_WAS_SET",
  29. """Symbol returned by a loader callable to indicate the
  30. retrieved value, or values, were assigned to their attributes
  31. on the target object.
  32. """,
  33. )
  34. ATTR_EMPTY = util.symbol(
  35. "ATTR_EMPTY",
  36. """Symbol used internally to indicate an attribute had no callable.""",
  37. )
  38. NO_VALUE = util.symbol(
  39. "NO_VALUE",
  40. """Symbol which may be placed as the 'previous' value of an attribute,
  41. indicating no value was loaded for an attribute when it was modified,
  42. and flags indicated we were not to load it.
  43. """,
  44. )
  45. NEVER_SET = NO_VALUE
  46. """
  47. Synonymous with NO_VALUE
  48. .. versionchanged:: 1.4 NEVER_SET was merged with NO_VALUE
  49. """
  50. NO_CHANGE = util.symbol(
  51. "NO_CHANGE",
  52. """No callables or SQL should be emitted on attribute access
  53. and no state should change
  54. """,
  55. canonical=0,
  56. )
  57. CALLABLES_OK = util.symbol(
  58. "CALLABLES_OK",
  59. """Loader callables can be fired off if a value
  60. is not present.
  61. """,
  62. canonical=1,
  63. )
  64. SQL_OK = util.symbol(
  65. "SQL_OK",
  66. """Loader callables can emit SQL at least on scalar value attributes.""",
  67. canonical=2,
  68. )
  69. RELATED_OBJECT_OK = util.symbol(
  70. "RELATED_OBJECT_OK",
  71. """Callables can use SQL to load related objects as well
  72. as scalar value attributes.
  73. """,
  74. canonical=4,
  75. )
  76. INIT_OK = util.symbol(
  77. "INIT_OK",
  78. """Attributes should be initialized with a blank
  79. value (None or an empty collection) upon get, if no other
  80. value can be obtained.
  81. """,
  82. canonical=8,
  83. )
  84. NON_PERSISTENT_OK = util.symbol(
  85. "NON_PERSISTENT_OK",
  86. """Callables can be emitted if the parent is not persistent.""",
  87. canonical=16,
  88. )
  89. LOAD_AGAINST_COMMITTED = util.symbol(
  90. "LOAD_AGAINST_COMMITTED",
  91. """Callables should use committed values as primary/foreign keys during a
  92. load.
  93. """,
  94. canonical=32,
  95. )
  96. NO_AUTOFLUSH = util.symbol(
  97. "NO_AUTOFLUSH",
  98. """Loader callables should disable autoflush.""",
  99. canonical=64,
  100. )
  101. NO_RAISE = util.symbol(
  102. "NO_RAISE",
  103. """Loader callables should not raise any assertions""",
  104. canonical=128,
  105. )
  106. # pre-packaged sets of flags used as inputs
  107. PASSIVE_OFF = util.symbol(
  108. "PASSIVE_OFF",
  109. "Callables can be emitted in all cases.",
  110. canonical=(
  111. RELATED_OBJECT_OK | NON_PERSISTENT_OK | INIT_OK | CALLABLES_OK | SQL_OK
  112. ),
  113. )
  114. PASSIVE_RETURN_NO_VALUE = util.symbol(
  115. "PASSIVE_RETURN_NO_VALUE",
  116. """PASSIVE_OFF ^ INIT_OK""",
  117. canonical=PASSIVE_OFF ^ INIT_OK,
  118. )
  119. PASSIVE_NO_INITIALIZE = util.symbol(
  120. "PASSIVE_NO_INITIALIZE",
  121. "PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK",
  122. canonical=PASSIVE_RETURN_NO_VALUE ^ CALLABLES_OK,
  123. )
  124. PASSIVE_NO_FETCH = util.symbol(
  125. "PASSIVE_NO_FETCH", "PASSIVE_OFF ^ SQL_OK", canonical=PASSIVE_OFF ^ SQL_OK
  126. )
  127. PASSIVE_NO_FETCH_RELATED = util.symbol(
  128. "PASSIVE_NO_FETCH_RELATED",
  129. "PASSIVE_OFF ^ RELATED_OBJECT_OK",
  130. canonical=PASSIVE_OFF ^ RELATED_OBJECT_OK,
  131. )
  132. PASSIVE_ONLY_PERSISTENT = util.symbol(
  133. "PASSIVE_ONLY_PERSISTENT",
  134. "PASSIVE_OFF ^ NON_PERSISTENT_OK",
  135. canonical=PASSIVE_OFF ^ NON_PERSISTENT_OK,
  136. )
  137. DEFAULT_MANAGER_ATTR = "_sa_class_manager"
  138. DEFAULT_STATE_ATTR = "_sa_instance_state"
  139. EXT_CONTINUE = util.symbol("EXT_CONTINUE")
  140. EXT_STOP = util.symbol("EXT_STOP")
  141. EXT_SKIP = util.symbol("EXT_SKIP")
  142. ONETOMANY = util.symbol(
  143. "ONETOMANY",
  144. """Indicates the one-to-many direction for a :func:`_orm.relationship`.
  145. This symbol is typically used by the internals but may be exposed within
  146. certain API features.
  147. """,
  148. )
  149. MANYTOONE = util.symbol(
  150. "MANYTOONE",
  151. """Indicates the many-to-one direction for a :func:`_orm.relationship`.
  152. This symbol is typically used by the internals but may be exposed within
  153. certain API features.
  154. """,
  155. )
  156. MANYTOMANY = util.symbol(
  157. "MANYTOMANY",
  158. """Indicates the many-to-many direction for a :func:`_orm.relationship`.
  159. This symbol is typically used by the internals but may be exposed within
  160. certain API features.
  161. """,
  162. )
  163. NOT_EXTENSION = util.symbol(
  164. "NOT_EXTENSION",
  165. """Symbol indicating an :class:`InspectionAttr` that's
  166. not part of sqlalchemy.ext.
  167. Is assigned to the :attr:`.InspectionAttr.extension_type`
  168. attribute.
  169. """,
  170. )
  171. _never_set = frozenset([NEVER_SET])
  172. _none_set = frozenset([None, NEVER_SET, PASSIVE_NO_RESULT])
  173. _SET_DEFERRED_EXPIRED = util.symbol("SET_DEFERRED_EXPIRED")
  174. _DEFER_FOR_STATE = util.symbol("DEFER_FOR_STATE")
  175. _RAISE_FOR_STATE = util.symbol("RAISE_FOR_STATE")
  176. def _assertions(*assertions):
  177. @util.decorator
  178. def generate(fn, *args, **kw):
  179. self = args[0]
  180. for assertion in assertions:
  181. assertion(self, fn.__name__)
  182. fn(self, *args[1:], **kw)
  183. return generate
  184. # these can be replaced by sqlalchemy.ext.instrumentation
  185. # if augmented class instrumentation is enabled.
  186. def manager_of_class(cls):
  187. return cls.__dict__.get(DEFAULT_MANAGER_ATTR, None)
  188. instance_state = operator.attrgetter(DEFAULT_STATE_ATTR)
  189. instance_dict = operator.attrgetter("__dict__")
  190. def instance_str(instance):
  191. """Return a string describing an instance."""
  192. return state_str(instance_state(instance))
  193. def state_str(state):
  194. """Return a string describing an instance via its InstanceState."""
  195. if state is None:
  196. return "None"
  197. else:
  198. return "<%s at 0x%x>" % (state.class_.__name__, id(state.obj()))
  199. def state_class_str(state):
  200. """Return a string describing an instance's class via its
  201. InstanceState.
  202. """
  203. if state is None:
  204. return "None"
  205. else:
  206. return "<%s>" % (state.class_.__name__,)
  207. def attribute_str(instance, attribute):
  208. return instance_str(instance) + "." + attribute
  209. def state_attribute_str(state, attribute):
  210. return state_str(state) + "." + attribute
  211. def object_mapper(instance):
  212. """Given an object, return the primary Mapper associated with the object
  213. instance.
  214. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  215. if no mapping is configured.
  216. This function is available via the inspection system as::
  217. inspect(instance).mapper
  218. Using the inspection system will raise
  219. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  220. not part of a mapping.
  221. """
  222. return object_state(instance).mapper
  223. def object_state(instance):
  224. """Given an object, return the :class:`.InstanceState`
  225. associated with the object.
  226. Raises :class:`sqlalchemy.orm.exc.UnmappedInstanceError`
  227. if no mapping is configured.
  228. Equivalent functionality is available via the :func:`_sa.inspect`
  229. function as::
  230. inspect(instance)
  231. Using the inspection system will raise
  232. :class:`sqlalchemy.exc.NoInspectionAvailable` if the instance is
  233. not part of a mapping.
  234. """
  235. state = _inspect_mapped_object(instance)
  236. if state is None:
  237. raise exc.UnmappedInstanceError(instance)
  238. else:
  239. return state
  240. @inspection._inspects(object)
  241. def _inspect_mapped_object(instance):
  242. try:
  243. return instance_state(instance)
  244. except (exc.UnmappedClassError,) + exc.NO_STATE:
  245. return None
  246. def _class_to_mapper(class_or_mapper):
  247. insp = inspection.inspect(class_or_mapper, False)
  248. if insp is not None:
  249. return insp.mapper
  250. else:
  251. raise exc.UnmappedClassError(class_or_mapper)
  252. def _mapper_or_none(entity):
  253. """Return the :class:`_orm.Mapper` for the given class or None if the
  254. class is not mapped.
  255. """
  256. insp = inspection.inspect(entity, False)
  257. if insp is not None:
  258. return insp.mapper
  259. else:
  260. return None
  261. def _is_mapped_class(entity):
  262. """Return True if the given object is a mapped class,
  263. :class:`_orm.Mapper`, or :class:`.AliasedClass`.
  264. """
  265. insp = inspection.inspect(entity, False)
  266. return (
  267. insp is not None
  268. and not insp.is_clause_element
  269. and (insp.is_mapper or insp.is_aliased_class)
  270. )
  271. def _orm_columns(entity):
  272. insp = inspection.inspect(entity, False)
  273. if hasattr(insp, "selectable") and hasattr(insp.selectable, "c"):
  274. return [c for c in insp.selectable.c]
  275. else:
  276. return [entity]
  277. def _is_aliased_class(entity):
  278. insp = inspection.inspect(entity, False)
  279. return insp is not None and getattr(insp, "is_aliased_class", False)
  280. def _entity_descriptor(entity, key):
  281. """Return a class attribute given an entity and string name.
  282. May return :class:`.InstrumentedAttribute` or user-defined
  283. attribute.
  284. """
  285. insp = inspection.inspect(entity)
  286. if insp.is_selectable:
  287. description = entity
  288. entity = insp.c
  289. elif insp.is_aliased_class:
  290. entity = insp.entity
  291. description = entity
  292. elif hasattr(insp, "mapper"):
  293. description = entity = insp.mapper.class_
  294. else:
  295. description = entity
  296. try:
  297. return getattr(entity, key)
  298. except AttributeError as err:
  299. util.raise_(
  300. sa_exc.InvalidRequestError(
  301. "Entity '%s' has no property '%s'" % (description, key)
  302. ),
  303. replace_context=err,
  304. )
  305. _state_mapper = util.dottedgetter("manager.mapper")
  306. @inspection._inspects(type)
  307. def _inspect_mapped_class(class_, configure=False):
  308. try:
  309. class_manager = manager_of_class(class_)
  310. if not class_manager.is_mapped:
  311. return None
  312. mapper = class_manager.mapper
  313. except exc.NO_STATE:
  314. return None
  315. else:
  316. if configure:
  317. mapper._check_configure()
  318. return mapper
  319. def class_mapper(class_, configure=True):
  320. """Given a class, return the primary :class:`_orm.Mapper` associated
  321. with the key.
  322. Raises :exc:`.UnmappedClassError` if no mapping is configured
  323. on the given class, or :exc:`.ArgumentError` if a non-class
  324. object is passed.
  325. Equivalent functionality is available via the :func:`_sa.inspect`
  326. function as::
  327. inspect(some_mapped_class)
  328. Using the inspection system will raise
  329. :class:`sqlalchemy.exc.NoInspectionAvailable` if the class is not mapped.
  330. """
  331. mapper = _inspect_mapped_class(class_, configure=configure)
  332. if mapper is None:
  333. if not isinstance(class_, type):
  334. raise sa_exc.ArgumentError(
  335. "Class object expected, got '%r'." % (class_,)
  336. )
  337. raise exc.UnmappedClassError(class_)
  338. else:
  339. return mapper
  340. class InspectionAttr(object):
  341. """A base class applied to all ORM objects that can be returned
  342. by the :func:`_sa.inspect` function.
  343. The attributes defined here allow the usage of simple boolean
  344. checks to test basic facts about the object returned.
  345. While the boolean checks here are basically the same as using
  346. the Python isinstance() function, the flags here can be used without
  347. the need to import all of these classes, and also such that
  348. the SQLAlchemy class system can change while leaving the flags
  349. here intact for forwards-compatibility.
  350. """
  351. __slots__ = ()
  352. is_selectable = False
  353. """Return True if this object is an instance of
  354. :class:`_expression.Selectable`."""
  355. is_aliased_class = False
  356. """True if this object is an instance of :class:`.AliasedClass`."""
  357. is_instance = False
  358. """True if this object is an instance of :class:`.InstanceState`."""
  359. is_mapper = False
  360. """True if this object is an instance of :class:`_orm.Mapper`."""
  361. is_bundle = False
  362. """True if this object is an instance of :class:`.Bundle`."""
  363. is_property = False
  364. """True if this object is an instance of :class:`.MapperProperty`."""
  365. is_attribute = False
  366. """True if this object is a Python :term:`descriptor`.
  367. This can refer to one of many types. Usually a
  368. :class:`.QueryableAttribute` which handles attributes events on behalf
  369. of a :class:`.MapperProperty`. But can also be an extension type
  370. such as :class:`.AssociationProxy` or :class:`.hybrid_property`.
  371. The :attr:`.InspectionAttr.extension_type` will refer to a constant
  372. identifying the specific subtype.
  373. .. seealso::
  374. :attr:`_orm.Mapper.all_orm_descriptors`
  375. """
  376. _is_internal_proxy = False
  377. """True if this object is an internal proxy object.
  378. .. versionadded:: 1.2.12
  379. """
  380. is_clause_element = False
  381. """True if this object is an instance of
  382. :class:`_expression.ClauseElement`."""
  383. extension_type = NOT_EXTENSION
  384. """The extension type, if any.
  385. Defaults to :data:`.interfaces.NOT_EXTENSION`
  386. .. seealso::
  387. :data:`.HYBRID_METHOD`
  388. :data:`.HYBRID_PROPERTY`
  389. :data:`.ASSOCIATION_PROXY`
  390. """
  391. class InspectionAttrInfo(InspectionAttr):
  392. """Adds the ``.info`` attribute to :class:`.InspectionAttr`.
  393. The rationale for :class:`.InspectionAttr` vs. :class:`.InspectionAttrInfo`
  394. is that the former is compatible as a mixin for classes that specify
  395. ``__slots__``; this is essentially an implementation artifact.
  396. """
  397. @util.memoized_property
  398. def info(self):
  399. """Info dictionary associated with the object, allowing user-defined
  400. data to be associated with this :class:`.InspectionAttr`.
  401. The dictionary is generated when first accessed. Alternatively,
  402. it can be specified as a constructor argument to the
  403. :func:`.column_property`, :func:`_orm.relationship`, or
  404. :func:`.composite`
  405. functions.
  406. .. versionchanged:: 1.0.0 :attr:`.MapperProperty.info` is also
  407. available on extension types via the
  408. :attr:`.InspectionAttrInfo.info` attribute, so that it can apply
  409. to a wider variety of ORM and extension constructs.
  410. .. seealso::
  411. :attr:`.QueryableAttribute.info`
  412. :attr:`.SchemaItem.info`
  413. """
  414. return {}
  415. class _MappedAttribute(object):
  416. """Mixin for attributes which should be replaced by mapper-assigned
  417. attributes.
  418. """
  419. __slots__ = ()