47
from sqlalchemy.orm import mapper as mapperlib
48
from sqlalchemy.orm.mapper import reconstructor, validates
49
from sqlalchemy.orm import strategies
50
from sqlalchemy.orm.query import AliasOption, Query
51
from sqlalchemy.sql import util as sql_util
52
from sqlalchemy.orm.session import Session
53
from sqlalchemy.orm.session import object_session, sessionmaker, \
50
from .relationships import (
54
from .session import (
55
from sqlalchemy.orm.scoping import ScopedSession
56
from sqlalchemy import util as sa_util
60
from .scoping import (
63
from . import mapper as mapperlib
64
from . import strategies
65
from .query import AliasOption, Query
66
from ..sql import util as sql_util
67
from .. import util as sa_util
69
from . import interfaces
71
# here, we can establish InstrumentationManager back
72
# in sqlalchemy.orm and sqlalchemy.orm.interfaces, which
73
# also re-establishes the extended instrumentation system.
74
#from ..ext import instrumentation as _ext_instrumentation
75
#InstrumentationManager = \
76
# interfaces.InstrumentationManager = \
77
# _ext_instrumentation.InstrumentationManager
61
'InstrumentationManager',
63
83
'AttributeExtension',
110
def scoped_session(session_factory, scopefunc=None):
111
"""Provides thread-local or scoped management of :class:`.Session` objects.
113
This is a front-end function to
114
:class:`.ScopedSession`::
116
Session = scoped_session(sessionmaker(autoflush=True))
118
To instantiate a Session object which is part of the scoped context,
119
instantiate normally::
123
Most session methods are available as classmethods from the scoped
129
See also: :ref:`unitofwork_contextual`.
131
:param session_factory: a callable function that produces
132
:class:`.Session` instances, such as :func:`sessionmaker`.
134
:param scopefunc: Optional "scope" function which would be
135
passed to the :class:`.ScopedRegistry`. If None, the
136
:class:`.ThreadLocalRegistry` is used by default.
138
:returns: a :class:`.ScopedSession` instance
142
return ScopedSession(session_factory, scopefunc=scopefunc)
144
134
def create_session(bind=None, **kwargs):
145
135
"""Create a new :class:`.Session`
146
136
with no automation enabled by default.
195
183
Some arguments accepted by :func:`.relationship` optionally accept a
196
184
callable function, which when called produces the desired value.
197
The callable is invoked by the parent :class:`.Mapper` at "mapper initialization"
198
time, which happens only when mappers are first used, and is assumed
199
to be after all mappings have been constructed. This can be used
200
to resolve order-of-declaration and other dependency issues, such as
185
The callable is invoked by the parent :class:`.Mapper` at "mapper
186
initialization" time, which happens only when mappers are first used, and
187
is assumed to be after all mappings have been constructed. This can be
188
used to resolve order-of-declaration and other dependency issues, such as
201
189
if ``Child`` is declared below ``Parent`` in the same file::
203
191
mapper(Parent, properties={
363
351
**Deprecated.** Please see :class:`.AttributeEvents`.
365
353
:param foreign_keys:
366
a list of columns which are to be used as "foreign key" columns.
367
Normally, :func:`relationship` uses the :class:`.ForeignKey`
368
and :class:`.ForeignKeyConstraint` objects present within the
369
mapped or secondary :class:`.Table` to determine the "foreign" side of
370
the join condition. This is used to construct SQL clauses in order
371
to load objects, as well as to "synchronize" values from
372
primary key columns to referencing foreign key columns.
373
The ``foreign_keys`` parameter overrides the notion of what's
374
"foreign" in the table metadata, allowing the specification
375
of a list of :class:`.Column` objects that should be considered
376
part of the foreign key.
378
There are only two use cases for ``foreign_keys`` - one, when it is not
379
convenient for :class:`.Table` metadata to contain its own foreign key
380
metadata (which should be almost never, unless reflecting a large amount of
381
tables from a MySQL MyISAM schema, or a schema that doesn't actually
382
have foreign keys on it). The other is for extremely
383
rare and exotic composite foreign key setups where some columns
384
should artificially not be considered as foreign.
354
a list of columns which are to be used as "foreign key" columns,
355
or columns which refer to the value in a remote column, within the
356
context of this :func:`.relationship` object's ``primaryjoin``
357
condition. That is, if the ``primaryjoin`` condition of this
358
:func:`.relationship` is ``a.id == b.a_id``, and the values in ``b.a_id``
359
are required to be present in ``a.id``, then the "foreign key" column
360
of this :func:`.relationship` is ``b.a_id``.
362
In normal cases, the ``foreign_keys`` parameter is **not required.**
363
:func:`.relationship` will **automatically** determine which columns
364
in the ``primaryjoin`` conditition are to be considered "foreign key"
365
columns based on those :class:`.Column` objects that specify
366
:class:`.ForeignKey`, or are otherwise listed as referencing columns
367
in a :class:`.ForeignKeyConstraint` construct. ``foreign_keys`` is only
370
1. There is more than one way to construct a join from the local
371
table to the remote table, as there are multiple foreign key
372
references present. Setting ``foreign_keys`` will limit the
373
:func:`.relationship` to consider just those columns specified
376
.. versionchanged:: 0.8
377
A multiple-foreign key join ambiguity can be resolved by
378
setting the ``foreign_keys`` parameter alone, without the
379
need to explicitly set ``primaryjoin`` as well.
381
2. The :class:`.Table` being mapped does not actually have
382
:class:`.ForeignKey` or :class:`.ForeignKeyConstraint`
383
constructs present, often because the table
384
was reflected from a database that does not support foreign key
385
reflection (MySQL MyISAM).
387
3. The ``primaryjoin`` argument is used to construct a non-standard
388
join condition, which makes use of columns or expressions that do
389
not normally refer to their "parent" column, such as a join condition
390
expressed by a complex comparison using a SQL function.
392
The :func:`.relationship` construct will raise informative error messages
393
that suggest the use of the ``foreign_keys`` parameter when presented
394
with an ambiguous condition. In typical cases, if :func:`.relationship`
395
doesn't raise any exceptions, the ``foreign_keys`` parameter is usually
386
398
``foreign_keys`` may also be passed as a callable function
387
399
which is evaluated at mapper initialization time, and may be passed as a
388
400
Python-evaluable string when using Declarative.
404
:ref:`relationship_foreign_keys`
406
:ref:`relationship_custom_foreign`
408
:func:`.foreign` - allows direct annotation of the "foreign" columns
409
within a ``primaryjoin`` condition.
411
.. versionadded:: 0.8
412
The :func:`.foreign` annotation can also be applied
413
directly to the ``primaryjoin`` expression, which is an alternate,
414
more specific system of describing which columns in a particular
415
``primaryjoin`` should be considered "foreign".
417
:param info: Optional data dictionary which will be populated into the
418
:attr:`.MapperProperty.info` attribute of this object.
420
.. versionadded:: 0.8
390
422
:param innerjoin=False:
391
423
when ``True``, joined eager loads will use an inner join to join
392
424
against related tables instead of an outer join. The purpose
450
481
* None - a synonym for 'noload'
452
Detailed discussion of loader strategies is at :ref:`loading_toplevel`.
483
Detailed discussion of loader strategies is at :doc:`/orm/loading`.
454
485
:param load_on_pending=False:
455
486
Indicates loading behavior for transient or pending parent objects.
488
.. versionchanged:: 0.8
489
load_on_pending is superseded by
490
:meth:`.Session.enable_relationship_loading`.
457
492
When set to ``True``, causes the lazy-loader to
458
493
issue a query for a parent object that is not persistent, meaning it has
459
494
never been flushed. This may take effect for a pending object when
460
495
autoflush is disabled, or for a transient object that has been
461
496
"attached" to a :class:`.Session` but is not part of its pending
462
collection. Attachment of transient objects to the session without
463
moving to the "pending" state is not a supported behavior at this time.
465
Note that the load of related objects on a pending or transient object
466
also does not trigger any attribute change events - no user-defined
467
events will be emitted for these attributes, and if and when the
468
object is ultimately flushed, only the user-specific foreign key
469
attributes will be part of the modified state.
471
499
The load_on_pending flag does not improve behavior
472
500
when the ORM is used normally - object references should be constructed
929
982
this parameter can be used to specify which columns are "foreign".
930
983
In most cases can be left as ``None``.
985
:param legacy_is_orphan: Boolean, defaults to ``False``.
986
When ``True``, specifies that "legacy" orphan consideration
987
is to be applied to objects mapped by this mapper, which means
988
that a pending (that is, not persistent) object is auto-expunged
989
from an owning :class:`.Session` only when it is de-associated
990
from *all* parents that specify a ``delete-orphan`` cascade towards
991
this mapper. The new default behavior is that the object is auto-expunged
992
when it is de-associated with *any* of its parents that specify
993
``delete-orphan`` cascade. This behavior is more consistent with
994
that of a persistent object, and allows behavior to be consistent
995
in more scenarios independently of whether or not an orphanable
996
object has been flushed yet or not.
998
See the change note and example at :ref:`legacy_is_orphan_addition`
999
for more detail on this change.
1001
.. versionadded:: 0.8 - the consideration of a pending object as
1002
an "orphan" has been modified to more closely match the
1003
behavior as that of persistent objects, which is that the object
1004
is expunged from the :class:`.Session` as soon as it is
1005
de-associated from any of its orphan-enabled parents. Previously,
1006
the pending object would be expunged only if de-associated
1007
from all of its orphan-enabled parents. The new flag ``legacy_is_orphan``
1008
is added to :func:`.orm.mapper` which re-establishes the
932
1011
:param non_primary: Specify that this :class:`.Mapper` is in addition
933
1012
to the "primary" mapper, that is, the one used for persistence.
934
1013
The :class:`.Mapper` created here may be used for ad-hoc
1313
1399
it **does not affect the query results**. An :meth:`.Query.order_by`
1314
1400
or :meth:`.Query.filter` call **cannot** reference these aliased
1315
1401
tables - so-called "user space" joins are constructed using
1316
:meth:`.Query.join`. The rationale for this is that :func:`joinedload` is only
1317
applied in order to affect how related objects or collections are loaded
1318
as an optimizing detail - it can be added or removed with no impact
1319
on actual results. See the section :ref:`zen_of_eager_loading` for
1320
a detailed description of how this is used, including how to use a single
1321
explicit JOIN for filtering/ordering and eager loading simultaneously.
1402
:meth:`.Query.join`. The rationale for this is that
1403
:func:`joinedload` is only applied in order to affect how related
1404
objects or collections are loaded as an optimizing detail - it can be
1405
added or removed with no impact on actual results. See the section
1406
:ref:`zen_of_eager_loading` for a detailed description of how this is
1407
used, including how to use a single explicit JOIN for
1408
filtering/ordering and eager loading simultaneously.
1323
1410
See also: :func:`subqueryload`, :func:`lazyload`
1624
1723
from sqlalchemy.orm import undefer
1626
query(MyClass).options(undefer("attribute_one"),
1627
undefer("attribute_two"))
1725
query(MyClass).options(
1726
undefer("attribute_one"),
1727
undefer("attribute_two"))
1629
1729
A class bound descriptor is also accepted::
1631
1731
query(MyClass).options(
1632
undefer(MyClass.attribute_one),
1633
undefer(MyClass.attribute_two))
1732
undefer(MyClass.attribute_one),
1733
undefer(MyClass.attribute_two))
1635
1735
A "path" can be specified onto a related or collection object using a
1636
1736
dotted name. The :func:`.orm.undefer` option will be applied to that
1637
1737
object when loaded::
1639
1739
query(MyClass).options(
1640
undefer("related.attribute_one"),
1641
undefer("related.attribute_two"))
1740
undefer("related.attribute_one"),
1741
undefer("related.attribute_two"))
1643
1743
To specify a path via class, send multiple arguments::
1645
1745
query(MyClass).options(
1646
undefer(MyClass.related, MyOtherClass.attribute_one),
1647
undefer(MyClass.related, MyOtherClass.attribute_two))
1746
undefer(MyClass.related, MyOtherClass.attribute_one),
1747
undefer(MyClass.related, MyOtherClass.attribute_two))