Coverage for /home/martinb/.local/share/virtualenvs/camcops/lib/python3.6/site-packages/sqlalchemy/orm/__init__.py : 79%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1# orm/__init__.py
2# Copyright (C) 2005-2020 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
8"""
9Functional constructs for ORM configuration.
11See the SQLAlchemy object relational tutorial and mapper configuration
12documentation for an overview of how this module is used.
14"""
16from . import exc # noqa
17from . import mapper as mapperlib # noqa
18from . import strategy_options
19from .deprecated_interfaces import AttributeExtension # noqa
20from .deprecated_interfaces import MapperExtension # noqa
21from .deprecated_interfaces import SessionExtension # noqa
22from .descriptor_props import ComparableProperty # noqa
23from .descriptor_props import CompositeProperty # noqa
24from .descriptor_props import SynonymProperty # noqa
25from .interfaces import EXT_CONTINUE # noqa
26from .interfaces import EXT_SKIP # noqa
27from .interfaces import EXT_STOP # noqa
28from .interfaces import PropComparator # noqa
29from .mapper import _mapper_registry
30from .mapper import class_mapper # noqa
31from .mapper import configure_mappers # noqa
32from .mapper import Mapper # noqa
33from .mapper import reconstructor # noqa
34from .mapper import validates # noqa
35from .properties import ColumnProperty # noqa
36from .query import AliasOption # noqa
37from .query import Bundle # noqa
38from .query import Query # noqa
39from .relationships import foreign # noqa
40from .relationships import RelationshipProperty # noqa
41from .relationships import remote # noqa
42from .scoping import scoped_session # noqa
43from .session import close_all_sessions # noqa
44from .session import make_transient # noqa
45from .session import make_transient_to_detached # noqa
46from .session import object_session # noqa
47from .session import Session # noqa
48from .session import sessionmaker # noqa
49from .strategy_options import Load # noqa
50from .util import aliased # noqa
51from .util import join # noqa
52from .util import object_mapper # noqa
53from .util import outerjoin # noqa
54from .util import polymorphic_union # noqa
55from .util import was_deleted # noqa
56from .util import with_parent # noqa
57from .util import with_polymorphic # noqa
58from .. import sql as _sql
59from .. import util as _sa_util
60from ..util.langhelpers import public_factory
63def create_session(bind=None, **kwargs):
64 r"""Create a new :class:`.Session`
65 with no automation enabled by default.
67 This function is used primarily for testing. The usual
68 route to :class:`.Session` creation is via its constructor
69 or the :func:`.sessionmaker` function.
71 :param bind: optional, a single Connectable to use for all
72 database access in the created
73 :class:`~sqlalchemy.orm.session.Session`.
75 :param \*\*kwargs: optional, passed through to the
76 :class:`.Session` constructor.
78 :returns: an :class:`~sqlalchemy.orm.session.Session` instance
80 The defaults of create_session() are the opposite of that of
81 :func:`sessionmaker`; ``autoflush`` and ``expire_on_commit`` are
82 False, ``autocommit`` is True. In this sense the session acts
83 more like the "classic" SQLAlchemy 0.3 session with these.
85 Usage::
87 >>> from sqlalchemy.orm import create_session
88 >>> session = create_session()
90 It is recommended to use :func:`sessionmaker` instead of
91 create_session().
93 """
94 kwargs.setdefault("autoflush", False)
95 kwargs.setdefault("autocommit", True)
96 kwargs.setdefault("expire_on_commit", False)
97 return Session(bind=bind, **kwargs)
100relationship = public_factory(RelationshipProperty, ".orm.relationship")
103def relation(*arg, **kw):
104 """A synonym for :func:`relationship`."""
106 return relationship(*arg, **kw)
109def dynamic_loader(argument, **kw):
110 """Construct a dynamically-loading mapper property.
112 This is essentially the same as
113 using the ``lazy='dynamic'`` argument with :func:`relationship`::
115 dynamic_loader(SomeClass)
117 # is the same as
119 relationship(SomeClass, lazy="dynamic")
121 See the section :ref:`dynamic_relationship` for more details
122 on dynamic loading.
124 """
125 kw["lazy"] = "dynamic"
126 return relationship(argument, **kw)
129column_property = public_factory(ColumnProperty, ".orm.column_property")
130composite = public_factory(CompositeProperty, ".orm.composite")
133def backref(name, **kwargs):
134 """Create a back reference with explicit keyword arguments, which are the
135 same arguments one can send to :func:`relationship`.
137 Used with the ``backref`` keyword argument to :func:`relationship` in
138 place of a string argument, e.g.::
140 'items':relationship(
141 SomeItem, backref=backref('parent', lazy='subquery'))
143 .. seealso::
145 :ref:`relationships_backref`
147 """
149 return (name, kwargs)
152def deferred(*columns, **kw):
153 r"""Indicate a column-based mapped attribute that by default will
154 not load unless accessed.
156 :param \*columns: columns to be mapped. This is typically a single
157 :class:`_schema.Column` object,
158 however a collection is supported in order
159 to support multiple columns mapped under the same attribute.
161 :param \**kw: additional keyword arguments passed to
162 :class:`.ColumnProperty`.
164 .. seealso::
166 :ref:`deferred`
168 """
169 return ColumnProperty(deferred=True, *columns, **kw)
172def query_expression(default_expr=_sql.null()):
173 """Indicate an attribute that populates from a query-time SQL expression.
175 :param default_expr: Optional SQL expression object that will be used in
176 all cases if not assigned later with :func:`_orm.with_expression`.
177 E.g.::
179 from sqlalchemy.sql import literal
181 class C(Base):
182 #...
183 my_expr = query_expression(literal(1))
185 .. versionadded:: 1.3.18
188 .. versionadded:: 1.2
190 .. seealso::
192 :ref:`mapper_querytime_expression`
194 """
195 prop = ColumnProperty(default_expr)
196 prop.strategy_key = (("query_expression", True),)
197 return prop
200mapper = public_factory(Mapper, ".orm.mapper")
202synonym = public_factory(SynonymProperty, ".orm.synonym")
204comparable_property = public_factory(
205 ComparableProperty, ".orm.comparable_property"
206)
209@_sa_util.deprecated(
210 "0.7",
211 message=":func:`.compile_mappers` is deprecated and will be removed "
212 "in a future release. Please use :func:`.configure_mappers`",
213)
214def compile_mappers():
215 """Initialize the inter-mapper relationships of all mappers that have
216 been defined.
218 """
219 configure_mappers()
222def clear_mappers():
223 """Remove all mappers from all classes.
225 This function removes all instrumentation from classes and disposes
226 of their associated mappers. Once called, the classes are unmapped
227 and can be later re-mapped with new mappers.
229 :func:`.clear_mappers` is *not* for normal use, as there is literally no
230 valid usage for it outside of very specific testing scenarios. Normally,
231 mappers are permanent structural components of user-defined classes, and
232 are never discarded independently of their class. If a mapped class
233 itself is garbage collected, its mapper is automatically disposed of as
234 well. As such, :func:`.clear_mappers` is only for usage in test suites
235 that re-use the same classes with different mappings, which is itself an
236 extremely rare use case - the only such use case is in fact SQLAlchemy's
237 own test suite, and possibly the test suites of other ORM extension
238 libraries which intend to test various combinations of mapper construction
239 upon a fixed set of classes.
241 """
242 mapperlib._CONFIGURE_MUTEX.acquire()
243 try:
244 while _mapper_registry:
245 try:
246 # can't even reliably call list(weakdict) in jython
247 mapper, b = _mapper_registry.popitem()
248 mapper.dispose()
249 except KeyError:
250 pass
251 finally:
252 mapperlib._CONFIGURE_MUTEX.release()
255joinedload = strategy_options.joinedload._unbound_fn
256joinedload_all = strategy_options.joinedload._unbound_all_fn
257contains_eager = strategy_options.contains_eager._unbound_fn
258defer = strategy_options.defer._unbound_fn
259undefer = strategy_options.undefer._unbound_fn
260undefer_group = strategy_options.undefer_group._unbound_fn
261with_expression = strategy_options.with_expression._unbound_fn
262load_only = strategy_options.load_only._unbound_fn
263lazyload = strategy_options.lazyload._unbound_fn
264lazyload_all = strategy_options.lazyload_all._unbound_all_fn
265subqueryload = strategy_options.subqueryload._unbound_fn
266subqueryload_all = strategy_options.subqueryload_all._unbound_all_fn
267selectinload = strategy_options.selectinload._unbound_fn
268selectinload_all = strategy_options.selectinload_all._unbound_all_fn
269immediateload = strategy_options.immediateload._unbound_fn
270noload = strategy_options.noload._unbound_fn
271raiseload = strategy_options.raiseload._unbound_fn
272defaultload = strategy_options.defaultload._unbound_fn
273selectin_polymorphic = strategy_options.selectin_polymorphic._unbound_fn
276def eagerload(*args, **kwargs):
277 """A synonym for :func:`joinedload()`."""
278 return joinedload(*args, **kwargs)
281def eagerload_all(*args, **kwargs):
282 """A synonym for :func:`joinedload_all()`"""
283 return joinedload_all(*args, **kwargs)
286contains_alias = public_factory(AliasOption, ".orm.contains_alias")
289def __go(lcls):
290 global __all__
291 from .. import util as sa_util # noqa
292 from . import dynamic # noqa
293 from . import events # noqa
294 from . import loading # noqa
295 import inspect as _inspect
297 __all__ = sorted(
298 name
299 for name, obj in lcls.items()
300 if not (name.startswith("_") or _inspect.ismodule(obj))
301 )
303 _sa_util.dependencies.resolve_all("sqlalchemy.orm")
304 _sa_util.dependencies.resolve_all("sqlalchemy.ext")
307__go(locals())