__init__.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. # orm/__init__.py
  2. # Copyright (C) 2005-2017 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. """
  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 .mapper import (
  14. Mapper,
  15. _mapper_registry,
  16. class_mapper,
  17. configure_mappers,
  18. reconstructor,
  19. validates
  20. )
  21. from .interfaces import (
  22. EXT_CONTINUE,
  23. EXT_STOP,
  24. PropComparator,
  25. )
  26. from .deprecated_interfaces import (
  27. MapperExtension,
  28. SessionExtension,
  29. AttributeExtension,
  30. )
  31. from .util import (
  32. aliased,
  33. join,
  34. object_mapper,
  35. outerjoin,
  36. polymorphic_union,
  37. was_deleted,
  38. with_parent,
  39. with_polymorphic,
  40. )
  41. from .properties import ColumnProperty
  42. from .relationships import RelationshipProperty
  43. from .descriptor_props import (
  44. ComparableProperty,
  45. CompositeProperty,
  46. SynonymProperty,
  47. )
  48. from .relationships import (
  49. foreign,
  50. remote,
  51. )
  52. from .session import (
  53. Session,
  54. object_session,
  55. sessionmaker,
  56. make_transient,
  57. make_transient_to_detached
  58. )
  59. from .scoping import (
  60. scoped_session
  61. )
  62. from . import mapper as mapperlib
  63. from .query import AliasOption, Query, Bundle
  64. from ..util.langhelpers import public_factory
  65. from .. import util as _sa_util
  66. from . import strategies as _strategies
  67. def create_session(bind=None, **kwargs):
  68. r"""Create a new :class:`.Session`
  69. with no automation enabled by default.
  70. This function is used primarily for testing. The usual
  71. route to :class:`.Session` creation is via its constructor
  72. or the :func:`.sessionmaker` function.
  73. :param bind: optional, a single Connectable to use for all
  74. database access in the created
  75. :class:`~sqlalchemy.orm.session.Session`.
  76. :param \*\*kwargs: optional, passed through to the
  77. :class:`.Session` constructor.
  78. :returns: an :class:`~sqlalchemy.orm.session.Session` instance
  79. The defaults of create_session() are the opposite of that of
  80. :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
  81. False, ``autocommit`` is True. In this sense the session acts
  82. more like the "classic" SQLAlchemy 0.3 session with these.
  83. Usage::
  84. >>> from sqlalchemy.orm import create_session
  85. >>> session = create_session()
  86. It is recommended to use :func:`sessionmaker` instead of
  87. create_session().
  88. """
  89. kwargs.setdefault('autoflush', False)
  90. kwargs.setdefault('autocommit', True)
  91. kwargs.setdefault('expire_on_commit', False)
  92. return Session(bind=bind, **kwargs)
  93. relationship = public_factory(RelationshipProperty, ".orm.relationship")
  94. def relation(*arg, **kw):
  95. """A synonym for :func:`relationship`."""
  96. return relationship(*arg, **kw)
  97. def dynamic_loader(argument, **kw):
  98. """Construct a dynamically-loading mapper property.
  99. This is essentially the same as
  100. using the ``lazy='dynamic'`` argument with :func:`relationship`::
  101. dynamic_loader(SomeClass)
  102. # is the same as
  103. relationship(SomeClass, lazy="dynamic")
  104. See the section :ref:`dynamic_relationship` for more details
  105. on dynamic loading.
  106. """
  107. kw['lazy'] = 'dynamic'
  108. return relationship(argument, **kw)
  109. column_property = public_factory(ColumnProperty, ".orm.column_property")
  110. composite = public_factory(CompositeProperty, ".orm.composite")
  111. def backref(name, **kwargs):
  112. """Create a back reference with explicit keyword arguments, which are the
  113. same arguments one can send to :func:`relationship`.
  114. Used with the ``backref`` keyword argument to :func:`relationship` in
  115. place of a string argument, e.g.::
  116. 'items':relationship(
  117. SomeItem, backref=backref('parent', lazy='subquery'))
  118. .. seealso::
  119. :ref:`relationships_backref`
  120. """
  121. return (name, kwargs)
  122. def deferred(*columns, **kw):
  123. r"""Indicate a column-based mapped attribute that by default will
  124. not load unless accessed.
  125. :param \*columns: columns to be mapped. This is typically a single
  126. :class:`.Column` object, however a collection is supported in order
  127. to support multiple columns mapped under the same attribute.
  128. :param \**kw: additional keyword arguments passed to
  129. :class:`.ColumnProperty`.
  130. .. seealso::
  131. :ref:`deferred`
  132. """
  133. return ColumnProperty(deferred=True, *columns, **kw)
  134. mapper = public_factory(Mapper, ".orm.mapper")
  135. synonym = public_factory(SynonymProperty, ".orm.synonym")
  136. comparable_property = public_factory(ComparableProperty,
  137. ".orm.comparable_property")
  138. @_sa_util.deprecated("0.7", message=":func:`.compile_mappers` "
  139. "is renamed to :func:`.configure_mappers`")
  140. def compile_mappers():
  141. """Initialize the inter-mapper relationships of all mappers that have
  142. been defined.
  143. """
  144. configure_mappers()
  145. def clear_mappers():
  146. """Remove all mappers from all classes.
  147. This function removes all instrumentation from classes and disposes
  148. of their associated mappers. Once called, the classes are unmapped
  149. and can be later re-mapped with new mappers.
  150. :func:`.clear_mappers` is *not* for normal use, as there is literally no
  151. valid usage for it outside of very specific testing scenarios. Normally,
  152. mappers are permanent structural components of user-defined classes, and
  153. are never discarded independently of their class. If a mapped class
  154. itself is garbage collected, its mapper is automatically disposed of as
  155. well. As such, :func:`.clear_mappers` is only for usage in test suites
  156. that re-use the same classes with different mappings, which is itself an
  157. extremely rare use case - the only such use case is in fact SQLAlchemy's
  158. own test suite, and possibly the test suites of other ORM extension
  159. libraries which intend to test various combinations of mapper construction
  160. upon a fixed set of classes.
  161. """
  162. mapperlib._CONFIGURE_MUTEX.acquire()
  163. try:
  164. while _mapper_registry:
  165. try:
  166. # can't even reliably call list(weakdict) in jython
  167. mapper, b = _mapper_registry.popitem()
  168. mapper.dispose()
  169. except KeyError:
  170. pass
  171. finally:
  172. mapperlib._CONFIGURE_MUTEX.release()
  173. from . import strategy_options
  174. joinedload = strategy_options.joinedload._unbound_fn
  175. joinedload_all = strategy_options.joinedload._unbound_all_fn
  176. contains_eager = strategy_options.contains_eager._unbound_fn
  177. defer = strategy_options.defer._unbound_fn
  178. undefer = strategy_options.undefer._unbound_fn
  179. undefer_group = strategy_options.undefer_group._unbound_fn
  180. load_only = strategy_options.load_only._unbound_fn
  181. lazyload = strategy_options.lazyload._unbound_fn
  182. lazyload_all = strategy_options.lazyload_all._unbound_all_fn
  183. subqueryload = strategy_options.subqueryload._unbound_fn
  184. subqueryload_all = strategy_options.subqueryload_all._unbound_all_fn
  185. immediateload = strategy_options.immediateload._unbound_fn
  186. noload = strategy_options.noload._unbound_fn
  187. raiseload = strategy_options.raiseload._unbound_fn
  188. defaultload = strategy_options.defaultload._unbound_fn
  189. from .strategy_options import Load
  190. def eagerload(*args, **kwargs):
  191. """A synonym for :func:`joinedload()`."""
  192. return joinedload(*args, **kwargs)
  193. def eagerload_all(*args, **kwargs):
  194. """A synonym for :func:`joinedload_all()`"""
  195. return joinedload_all(*args, **kwargs)
  196. contains_alias = public_factory(AliasOption, ".orm.contains_alias")
  197. def __go(lcls):
  198. global __all__
  199. from .. import util as sa_util
  200. from . import dynamic
  201. from . import events
  202. import inspect as _inspect
  203. __all__ = sorted(name for name, obj in lcls.items()
  204. if not (name.startswith('_') or _inspect.ismodule(obj)))
  205. _sa_util.dependencies.resolve_all("sqlalchemy.orm")
  206. __go(locals())