__init__.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. # orm/__init__.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. """
  8. Functional constructs for ORM configuration.
  9. See the SQLAlchemy object relational tutorial and mapper configuration
  10. documentation for an overview of how this module is used.
  11. """
  12. from . import exc
  13. from . import mapper as mapperlib
  14. from . import strategy_options
  15. from .attributes import AttributeEvent
  16. from .attributes import InstrumentedAttribute
  17. from .attributes import Mapped
  18. from .attributes import QueryableAttribute
  19. from .context import QueryContext
  20. from .decl_api import as_declarative
  21. from .decl_api import declarative_base
  22. from .decl_api import declarative_mixin
  23. from .decl_api import DeclarativeMeta
  24. from .decl_api import declared_attr
  25. from .decl_api import has_inherited_table
  26. from .decl_api import registry
  27. from .decl_api import synonym_for
  28. from .descriptor_props import CompositeProperty
  29. from .descriptor_props import SynonymProperty
  30. from .identity import IdentityMap
  31. from .instrumentation import ClassManager
  32. from .interfaces import EXT_CONTINUE
  33. from .interfaces import EXT_SKIP
  34. from .interfaces import EXT_STOP
  35. from .interfaces import InspectionAttr
  36. from .interfaces import InspectionAttrInfo
  37. from .interfaces import MANYTOMANY
  38. from .interfaces import MANYTOONE
  39. from .interfaces import MapperProperty
  40. from .interfaces import NOT_EXTENSION
  41. from .interfaces import ONETOMANY
  42. from .interfaces import PropComparator
  43. from .interfaces import UserDefinedOption
  44. from .loading import merge_frozen_result
  45. from .loading import merge_result
  46. from .mapper import class_mapper
  47. from .mapper import configure_mappers
  48. from .mapper import Mapper
  49. from .mapper import reconstructor
  50. from .mapper import validates
  51. from .properties import ColumnProperty
  52. from .query import AliasOption
  53. from .query import FromStatement
  54. from .query import Query
  55. from .relationships import foreign
  56. from .relationships import RelationshipProperty
  57. from .relationships import remote
  58. from .scoping import scoped_session
  59. from .session import close_all_sessions
  60. from .session import make_transient
  61. from .session import make_transient_to_detached
  62. from .session import object_session
  63. from .session import ORMExecuteState
  64. from .session import Session
  65. from .session import sessionmaker
  66. from .session import SessionTransaction
  67. from .state import AttributeState
  68. from .state import InstanceState
  69. from .strategy_options import Load
  70. from .unitofwork import UOWTransaction
  71. from .util import aliased
  72. from .util import Bundle
  73. from .util import CascadeOptions
  74. from .util import join
  75. from .util import LoaderCriteriaOption
  76. from .util import object_mapper
  77. from .util import outerjoin
  78. from .util import polymorphic_union
  79. from .util import was_deleted
  80. from .util import with_parent
  81. from .util import with_polymorphic
  82. from .. import sql as _sql
  83. from .. import util as _sa_util
  84. from ..util.langhelpers import public_factory
  85. def create_session(bind=None, **kwargs):
  86. r"""Create a new :class:`.Session`
  87. with no automation enabled by default.
  88. This function is used primarily for testing. The usual
  89. route to :class:`.Session` creation is via its constructor
  90. or the :func:`.sessionmaker` function.
  91. :param bind: optional, a single Connectable to use for all
  92. database access in the created
  93. :class:`~sqlalchemy.orm.session.Session`.
  94. :param \*\*kwargs: optional, passed through to the
  95. :class:`.Session` constructor.
  96. :returns: an :class:`~sqlalchemy.orm.session.Session` instance
  97. The defaults of create_session() are the opposite of that of
  98. :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
  99. False, ``autocommit`` is True. In this sense the session acts
  100. more like the "classic" SQLAlchemy 0.3 session with these.
  101. .. deprecated:: 1.4 The "autocommit" parameter will be removed in
  102. SQLAlchemy 2.0. :func:`_orm.create_session` will return a
  103. :class:`_orm.Session` that does not include "autocommit' behavior
  104. in release 2.0.
  105. Usage::
  106. >>> from sqlalchemy.orm import create_session
  107. >>> session = create_session()
  108. It is recommended to use :func:`sessionmaker` instead of
  109. create_session().
  110. """
  111. if kwargs.get("future", False):
  112. kwargs.setdefault("autocommit", False)
  113. else:
  114. kwargs.setdefault("autocommit", True)
  115. kwargs.setdefault("autoflush", False)
  116. kwargs.setdefault("expire_on_commit", False)
  117. return Session(bind=bind, **kwargs)
  118. with_loader_criteria = public_factory(LoaderCriteriaOption, ".orm")
  119. relationship = public_factory(RelationshipProperty, ".orm.relationship")
  120. @_sa_util.deprecated_20("relation", "Please use :func:`.relationship`.")
  121. def relation(*arg, **kw):
  122. """A synonym for :func:`relationship`."""
  123. return relationship(*arg, **kw)
  124. def dynamic_loader(argument, **kw):
  125. """Construct a dynamically-loading mapper property.
  126. This is essentially the same as
  127. using the ``lazy='dynamic'`` argument with :func:`relationship`::
  128. dynamic_loader(SomeClass)
  129. # is the same as
  130. relationship(SomeClass, lazy="dynamic")
  131. See the section :ref:`dynamic_relationship` for more details
  132. on dynamic loading.
  133. """
  134. kw["lazy"] = "dynamic"
  135. return relationship(argument, **kw)
  136. column_property = public_factory(ColumnProperty, ".orm.column_property")
  137. composite = public_factory(CompositeProperty, ".orm.composite")
  138. def backref(name, **kwargs):
  139. """Create a back reference with explicit keyword arguments, which are the
  140. same arguments one can send to :func:`relationship`.
  141. Used with the ``backref`` keyword argument to :func:`relationship` in
  142. place of a string argument, e.g.::
  143. 'items':relationship(
  144. SomeItem, backref=backref('parent', lazy='subquery'))
  145. .. seealso::
  146. :ref:`relationships_backref`
  147. """
  148. return (name, kwargs)
  149. def deferred(*columns, **kw):
  150. r"""Indicate a column-based mapped attribute that by default will
  151. not load unless accessed.
  152. :param \*columns: columns to be mapped. This is typically a single
  153. :class:`_schema.Column` object,
  154. however a collection is supported in order
  155. to support multiple columns mapped under the same attribute.
  156. :param raiseload: boolean, if True, indicates an exception should be raised
  157. if the load operation is to take place.
  158. .. versionadded:: 1.4
  159. .. seealso::
  160. :ref:`deferred_raiseload`
  161. :param \**kw: additional keyword arguments passed to
  162. :class:`.ColumnProperty`.
  163. .. seealso::
  164. :ref:`deferred`
  165. """
  166. return ColumnProperty(deferred=True, *columns, **kw)
  167. def query_expression(default_expr=_sql.null()):
  168. """Indicate an attribute that populates from a query-time SQL expression.
  169. :param default_expr: Optional SQL expression object that will be used in
  170. all cases if not assigned later with :func:`_orm.with_expression`.
  171. E.g.::
  172. from sqlalchemy.sql import literal
  173. class C(Base):
  174. #...
  175. my_expr = query_expression(literal(1))
  176. .. versionadded:: 1.3.18
  177. .. versionadded:: 1.2
  178. .. seealso::
  179. :ref:`mapper_querytime_expression`
  180. """
  181. prop = ColumnProperty(default_expr)
  182. prop.strategy_key = (("query_expression", True),)
  183. return prop
  184. mapper = public_factory(Mapper, ".orm.mapper")
  185. synonym = public_factory(SynonymProperty, ".orm.synonym")
  186. def clear_mappers():
  187. """Remove all mappers from all classes.
  188. .. versionchanged:: 1.4 This function now locates all
  189. :class:`_orm.registry` objects and calls upon the
  190. :meth:`_orm.registry.dispose` method of each.
  191. This function removes all instrumentation from classes and disposes
  192. of their associated mappers. Once called, the classes are unmapped
  193. and can be later re-mapped with new mappers.
  194. :func:`.clear_mappers` is *not* for normal use, as there is literally no
  195. valid usage for it outside of very specific testing scenarios. Normally,
  196. mappers are permanent structural components of user-defined classes, and
  197. are never discarded independently of their class. If a mapped class
  198. itself is garbage collected, its mapper is automatically disposed of as
  199. well. As such, :func:`.clear_mappers` is only for usage in test suites
  200. that re-use the same classes with different mappings, which is itself an
  201. extremely rare use case - the only such use case is in fact SQLAlchemy's
  202. own test suite, and possibly the test suites of other ORM extension
  203. libraries which intend to test various combinations of mapper construction
  204. upon a fixed set of classes.
  205. """
  206. mapperlib._dispose_registries(mapperlib._all_registries(), False)
  207. joinedload = strategy_options.joinedload._unbound_fn
  208. contains_eager = strategy_options.contains_eager._unbound_fn
  209. defer = strategy_options.defer._unbound_fn
  210. undefer = strategy_options.undefer._unbound_fn
  211. undefer_group = strategy_options.undefer_group._unbound_fn
  212. with_expression = strategy_options.with_expression._unbound_fn
  213. load_only = strategy_options.load_only._unbound_fn
  214. lazyload = strategy_options.lazyload._unbound_fn
  215. subqueryload = strategy_options.subqueryload._unbound_fn
  216. selectinload = strategy_options.selectinload._unbound_fn
  217. immediateload = strategy_options.immediateload._unbound_fn
  218. noload = strategy_options.noload._unbound_fn
  219. raiseload = strategy_options.raiseload._unbound_fn
  220. defaultload = strategy_options.defaultload._unbound_fn
  221. selectin_polymorphic = strategy_options.selectin_polymorphic._unbound_fn
  222. @_sa_util.deprecated_20("eagerload", "Please use :func:`_orm.joinedload`.")
  223. def eagerload(*args, **kwargs):
  224. """A synonym for :func:`joinedload()`."""
  225. return joinedload(*args, **kwargs)
  226. contains_alias = public_factory(AliasOption, ".orm.contains_alias")
  227. if True:
  228. from .events import AttributeEvents
  229. from .events import MapperEvents
  230. from .events import InstanceEvents
  231. from .events import InstrumentationEvents
  232. from .events import QueryEvents
  233. from .events import SessionEvents
  234. def __go(lcls):
  235. global __all__
  236. global AppenderQuery
  237. from .. import util as sa_util
  238. from . import dynamic
  239. from . import events
  240. from . import loading
  241. import inspect as _inspect
  242. from .dynamic import AppenderQuery
  243. __all__ = sorted(
  244. name
  245. for name, obj in lcls.items()
  246. if not (name.startswith("_") or _inspect.ismodule(obj))
  247. )
  248. _sa_util.preloaded.import_prefix("sqlalchemy.orm")
  249. _sa_util.preloaded.import_prefix("sqlalchemy.ext")
  250. __go(locals())