~ubuntu-branches/debian/jessie/sqlalchemy/jessie

« back to all changes in this revision

Viewing changes to lib/sqlalchemy/orm/__init__.py

  • Committer: Package Import Robot
  • Author(s): Piotr Ożarowski, Jakub Wilk, Piotr Ożarowski
  • Date: 2013-07-06 20:53:52 UTC
  • mfrom: (1.4.23) (16.1.17 experimental)
  • Revision ID: package-import@ubuntu.com-20130706205352-ryppl1eto3illd79
Tags: 0.8.2-1
[ Jakub Wilk ]
* Use canonical URIs for Vcs-* fields.

[ Piotr Ożarowski ]
* New upstream release
* Upload to unstable
* Build depend on python3-all instead of -dev, extensions are not built for
  Python 3.X 

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
1
# orm/__init__.py
2
 
# Copyright (C) 2005-2012 the SQLAlchemy authors and contributors <see AUTHORS file>
 
2
# Copyright (C) 2005-2013 the SQLAlchemy authors and contributors <see AUTHORS file>
3
3
#
4
4
# This module is part of SQLAlchemy and is released under
5
5
# the MIT License: http://www.opensource.org/licenses/mit-license.php
12
12
 
13
13
"""
14
14
 
15
 
from sqlalchemy.orm import exc
16
 
from sqlalchemy.orm.mapper import (
 
15
from . import exc
 
16
from .mapper import (
17
17
     Mapper,
18
18
     _mapper_registry,
19
19
     class_mapper,
20
 
     configure_mappers
 
20
     configure_mappers,
 
21
     reconstructor,
 
22
     validates
21
23
     )
22
 
from sqlalchemy.orm.interfaces import (
 
24
from .interfaces import (
23
25
     EXT_CONTINUE,
24
26
     EXT_STOP,
25
 
     InstrumentationManager,
26
27
     MapperExtension,
27
28
     PropComparator,
28
29
     SessionExtension,
29
30
     AttributeExtension,
30
31
     )
31
 
from sqlalchemy.orm.util import (
 
32
from .util import (
32
33
     aliased,
33
34
     join,
34
35
     object_mapper,
35
36
     outerjoin,
36
37
     polymorphic_union,
 
38
     was_deleted,
37
39
     with_parent,
 
40
     with_polymorphic,
38
41
     )
39
 
from sqlalchemy.orm.properties import (
 
42
from .properties import (
40
43
     ColumnProperty,
41
44
     ComparableProperty,
42
45
     CompositeProperty,
44
47
     PropertyLoader,
45
48
     SynonymProperty,
46
49
     )
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 (
 
51
    foreign,
 
52
    remote,
 
53
)
 
54
from .session import (
 
55
    Session,
 
56
    object_session,
 
57
    sessionmaker,
54
58
    make_transient
55
 
from sqlalchemy.orm.scoping import ScopedSession
56
 
from sqlalchemy import util as sa_util
 
59
)
 
60
from .scoping import (
 
61
    scoped_session
 
62
)
 
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
 
68
 
 
69
from . import interfaces
 
70
 
 
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
57
78
 
58
79
__all__ = (
59
80
    'EXT_CONTINUE',
60
81
    'EXT_STOP',
61
 
    'InstrumentationManager',
62
82
    'MapperExtension',
63
83
    'AttributeExtension',
64
84
    'PropComparator',
81
101
    'dynamic_loader',
82
102
    'eagerload',
83
103
    'eagerload_all',
 
104
    'foreign',
84
105
    'immediateload',
85
106
    'join',
86
107
    'joinedload',
96
117
    'reconstructor',
97
118
    'relationship',
98
119
    'relation',
 
120
    'remote',
99
121
    'scoped_session',
100
122
    'sessionmaker',
101
123
    'subqueryload',
103
125
    'synonym',
104
126
    'undefer',
105
127
    'undefer_group',
106
 
    'validates'
 
128
    'validates',
 
129
    'was_deleted',
 
130
    'with_polymorphic'
107
131
    )
108
132
 
109
133
 
110
 
def scoped_session(session_factory, scopefunc=None):
111
 
    """Provides thread-local or scoped management of :class:`.Session` objects.
112
 
 
113
 
    This is a front-end function to
114
 
    :class:`.ScopedSession`::
115
 
 
116
 
      Session = scoped_session(sessionmaker(autoflush=True))
117
 
 
118
 
    To instantiate a Session object which is part of the scoped context,
119
 
    instantiate normally::
120
 
 
121
 
      session = Session()
122
 
 
123
 
    Most session methods are available as classmethods from the scoped
124
 
    session::
125
 
 
126
 
      Session.commit()
127
 
      Session.close()
128
 
 
129
 
    See also: :ref:`unitofwork_contextual`.
130
 
 
131
 
    :param session_factory: a callable function that produces
132
 
      :class:`.Session` instances, such as :func:`sessionmaker`.
133
 
 
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.
137
 
 
138
 
    :returns: a :class:`.ScopedSession` instance
139
 
 
140
 
 
141
 
    """
142
 
    return ScopedSession(session_factory, scopefunc=scopefunc)
143
 
 
144
134
def create_session(bind=None, **kwargs):
145
135
    """Create a new :class:`.Session`
146
136
    with no automation enabled by default.
177
167
    kwargs.setdefault('expire_on_commit', False)
178
168
    return Session(bind=bind, **kwargs)
179
169
 
 
170
 
180
171
def relationship(argument, secondary=None, **kwargs):
181
172
    """Provide a relationship of a primary Mapper to a secondary Mapper.
182
173
 
183
 
    .. versionchanged:: 0.6
184
 
        :func:`relationship` is historically known as :func:`relation`.
185
 
 
186
174
    This corresponds to a parent-child or associative table relationship.  The
187
175
    constructed class is an instance of :class:`.RelationshipProperty`.
188
176
 
194
182
 
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::
202
190
 
203
191
        mapper(Parent, properties={
210
198
    These string arguments are converted into callables that evaluate
211
199
    the string as Python code, using the Declarative
212
200
    class-registry as a namespace.  This allows the lookup of related
213
 
    classes to be automatic via their string name, and removes the need to import
214
 
    related classes at all into the local module space::
 
201
    classes to be automatic via their string name, and removes the need to
 
202
    import related classes at all into the local module space::
215
203
 
216
204
        from sqlalchemy.ext.declarative import declarative_base
217
205
 
226
214
    :func:`.relationship` is at :ref:`relationship_config_toplevel`.
227
215
 
228
216
    :param argument:
229
 
      a mapped class, or actual :class:`.Mapper` instance, representing the target of
230
 
      the relationship.
 
217
      a mapped class, or actual :class:`.Mapper` instance, representing the
 
218
      target of the relationship.
231
219
 
232
220
      ``argument`` may also be passed as a callable function
233
221
      which is evaluated at mapper initialization time, and may be passed as a
363
351
      **Deprecated.**  Please see :class:`.AttributeEvents`.
364
352
 
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.
377
 
 
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``.
 
361
 
 
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
 
368
      needed when:
 
369
 
 
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
 
374
           here as "foreign".
 
375
 
 
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.
 
380
 
 
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).
 
386
 
 
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.
 
391
 
 
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
 
396
      not needed.
385
397
 
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.
389
401
 
 
402
      .. seealso::
 
403
 
 
404
        :ref:`relationship_foreign_keys`
 
405
 
 
406
        :ref:`relationship_custom_foreign`
 
407
 
 
408
        :func:`.foreign` - allows direct annotation of the "foreign" columns
 
409
        within a ``primaryjoin`` condition.
 
410
 
 
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".
 
416
 
 
417
    :param info: Optional data dictionary which will be populated into the
 
418
        :attr:`.MapperProperty.info` attribute of this object.
 
419
 
 
420
        .. versionadded:: 0.8
 
421
 
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
428
460
        the join is "outer" or not is determined by the ``innerjoin``
429
461
        parameter.
430
462
 
431
 
      * ``subquery`` - items should be loaded "eagerly" within the same
432
 
        query as that of the parent, using a second SQL statement
433
 
        which issues a JOIN to a subquery of the original
434
 
        statement.
 
463
      * ``subquery`` - items should be loaded "eagerly" as the parents are
 
464
        loaded, using one additional SQL statement, which issues a JOIN to a
 
465
        subquery of the original statement, for each collection requested.
435
466
 
436
467
      * ``noload`` - no loading should occur at any time.  This is to
437
468
        support "write-only" attributes, or attributes which are
449
480
 
450
481
      * None - a synonym for 'noload'
451
482
 
452
 
      Detailed discussion of loader strategies is at :ref:`loading_toplevel`.
 
483
      Detailed discussion of loader strategies is at :doc:`/orm/loading`.
453
484
 
454
485
    :param load_on_pending=False:
455
486
      Indicates loading behavior for transient or pending parent objects.
456
487
 
 
488
      .. versionchanged:: 0.8
 
489
          load_on_pending is superseded by
 
490
          :meth:`.Session.enable_relationship_loading`.
 
491
 
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.
464
 
 
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.
 
497
      collection.
470
498
 
471
499
      The load_on_pending flag does not improve behavior
472
500
      when the ORM is used normally - object references should be constructed
474
502
      are present in an ordinary way before flush() proceeds.  This flag
475
503
      is not not intended for general use.
476
504
 
477
 
      New in 0.6.5.
 
505
      .. versionadded:: 0.6.5
478
506
 
479
507
    :param order_by:
480
508
      indicates the ordering that should be applied when loading these
577
605
      which is evaluated at mapper initialization time, and may be passed as a
578
606
      Python-evaluable string when using Declarative.
579
607
 
 
608
      .. versionchanged:: 0.8
 
609
          The :func:`.remote` annotation can also be applied
 
610
          directly to the ``primaryjoin`` expression, which is an alternate,
 
611
          more specific system of describing which columns in a particular
 
612
          ``primaryjoin`` should be considered "remote".
 
613
 
580
614
    :param query_class:
581
615
      a :class:`.Query` subclass that will be used as the base of the
582
616
      "appender query" returned by a "dynamic" relationship, that
621
655
      not compile into eager or lazy loaders properly. If this is the
622
656
      case, use an alternative method.
623
657
 
 
658
    .. versionchanged:: 0.6
 
659
        :func:`relationship` was renamed from its previous name
 
660
        :func:`relation`.
 
661
 
624
662
    """
625
663
    return RelationshipProperty(argument, secondary=secondary, **kwargs)
626
664
 
 
665
 
627
666
def relation(*arg, **kw):
628
667
    """A synonym for :func:`relationship`."""
629
668
 
630
669
    return relationship(*arg, **kw)
631
670
 
 
671
 
632
672
def dynamic_loader(argument, **kw):
633
673
    """Construct a dynamically-loading mapper property.
634
674
 
648
688
    kw['lazy'] = 'dynamic'
649
689
    return relationship(argument, **kw)
650
690
 
 
691
 
651
692
def column_property(*cols, **kw):
652
693
    """Provide a column-level property for use with a Mapper.
653
694
 
709
750
 
710
751
        .. versionadded:: 0.7.3
711
752
 
 
753
    :param info: Optional data dictionary which will be populated into the
 
754
        :attr:`.MapperProperty.info` attribute of this object.
 
755
 
 
756
        .. versionadded:: 0.8
 
757
 
712
758
    :param extension:
713
759
        an
714
760
        :class:`.AttributeExtension`
717
763
        descriptor placed on the class.
718
764
        **Deprecated.** Please see :class:`.AttributeEvents`.
719
765
 
720
 
 
721
766
    """
722
767
 
723
768
    return ColumnProperty(*cols, **kw)
724
769
 
 
770
 
725
771
def composite(class_, *cols, **kwargs):
726
772
    """Return a composite column-based property for use with a Mapper.
727
773
 
728
774
    See the mapping documentation section :ref:`mapper_composite` for a full
729
775
    usage example.
730
776
 
 
777
    The :class:`.MapperProperty` returned by :func:`.composite`
 
778
    is the :class:`.CompositeProperty`.
 
779
 
731
780
    :param class\_:
732
781
      The "composite type" class.
733
782
 
759
808
      optional string that will be applied as the doc on the
760
809
      class-bound descriptor.
761
810
 
 
811
    :param info: Optional data dictionary which will be populated into the
 
812
        :attr:`.MapperProperty.info` attribute of this object.
 
813
 
 
814
        .. versionadded:: 0.8
 
815
 
762
816
    :param extension:
763
817
      an :class:`.AttributeExtension` instance,
764
818
      or list of extensions, which will be prepended to the list of
770
824
 
771
825
 
772
826
def backref(name, **kwargs):
773
 
    """Create a back reference with explicit keyword arguments, which are the same
774
 
    arguments one can send to :func:`relationship`.
 
827
    """Create a back reference with explicit keyword arguments, which are the
 
828
    same arguments one can send to :func:`relationship`.
775
829
 
776
830
    Used with the ``backref`` keyword argument to :func:`relationship` in
777
831
    place of a string argument, e.g.::
781
835
    """
782
836
    return (name, kwargs)
783
837
 
 
838
 
784
839
def deferred(*columns, **kwargs):
785
840
    """Return a :class:`.DeferredColumnProperty`, which indicates this
786
841
    object attributes should only be loaded from its corresponding
795
850
    """
796
851
    return ColumnProperty(deferred=True, *columns, **kwargs)
797
852
 
 
853
 
798
854
def mapper(class_, local_table=None, *args, **params):
799
855
    """Return a new :class:`~.Mapper` object.
800
856
 
850
906
           this mapper inherits from another mapper using single-table
851
907
           inheritance.   When using Declarative, this argument is
852
908
           automatically passed by the extension, based on what
853
 
           is configured via the ``__table__`` argument or via the :class:`.Table`
854
 
           produced as a result of the ``__tablename__`` and :class:`.Column`
855
 
           arguments present.
 
909
           is configured via the ``__table__`` argument or via the
 
910
           :class:`.Table` produced as a result of the ``__tablename__``
 
911
           and :class:`.Column` arguments present.
856
912
 
857
913
        :param always_refresh: If True, all query operations for this mapped
858
914
           class will overwrite all data within object instances that already
861
917
           flag is highly discouraged; as an alternative, see the method
862
918
           :meth:`.Query.populate_existing`.
863
919
 
864
 
        :param allow_null_pks: This flag is deprecated - this is stated as
865
 
           allow_partial_pks which defaults to True.
866
 
 
867
920
        :param allow_partial_pks: Defaults to True.  Indicates that a
868
921
           composite primary key with some NULL values should be considered as
869
922
           possibly existing within the database. This affects whether a
899
952
          See :ref:`include_exclude_cols` for an example.
900
953
 
901
954
        :param extension: A :class:`.MapperExtension` instance or
902
 
           list of :class:`.MapperExtension`
903
 
           instances which will be applied to all operations by this
904
 
           :class:`.Mapper`.  **Deprecated.**  Please see :class:`.MapperEvents`.
 
955
           list of :class:`.MapperExtension` instances which will be applied
 
956
           to all operations by this :class:`.Mapper`.  **Deprecated.**
 
957
           Please see :class:`.MapperEvents`.
905
958
 
906
959
        :param include_properties: An inclusive list or set of string column
907
960
          names to map.
910
963
 
911
964
        :param inherits: A mapped class or the corresponding :class:`.Mapper`
912
965
          of one indicating a superclass to which this :class:`.Mapper`
913
 
          should *inherit* from.   The mapped class here must be a subclass of the
914
 
          other mapper's class.   When using Declarative, this argument
 
966
          should *inherit* from.   The mapped class here must be a subclass
 
967
          of the other mapper's class.   When using Declarative, this argument
915
968
          is passed automatically as a result of the natural class
916
969
          hierarchy of the declared classes.
917
970
 
929
982
           this parameter can be used to specify which columns are "foreign".
930
983
           In most cases can be left as ``None``.
931
984
 
 
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.
 
997
 
 
998
          See the change note and example at :ref:`legacy_is_orphan_addition`
 
999
          for more detail on this change.
 
1000
 
 
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
 
1009
            legacy behavior.
 
1010
 
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
944
1023
           ordering.
945
1024
 
946
1025
        :param passive_updates: Indicates UPDATE behavior of foreign key
947
 
           columns when a primary key column changes on a joined-table inheritance
948
 
           mapping.   Defaults to ``True``.
 
1026
           columns when a primary key column changes on a joined-table
 
1027
           inheritance mapping.   Defaults to ``True``.
949
1028
 
950
1029
           When True, it is assumed that ON UPDATE CASCADE is configured on
951
1030
           the foreign key in the database, and that the database will handle
1081
1160
           that will be used to keep a running version id of mapped entities
1082
1161
           in the database.  This is used during save operations to ensure that
1083
1162
           no other thread or process has updated the instance during the
1084
 
           lifetime of the entity, else a :class:`~sqlalchemy.orm.exc.StaleDataError`
1085
 
           exception is
 
1163
           lifetime of the entity, else a
 
1164
           :class:`~sqlalchemy.orm.exc.StaleDataError` exception is
1086
1165
           thrown.  By default the column must be of :class:`.Integer` type,
1087
1166
           unless ``version_id_generator`` specifies a new generation
1088
1167
           algorithm.
1128
1207
    """
1129
1208
    return Mapper(class_, local_table, *args, **params)
1130
1209
 
 
1210
 
1131
1211
def synonym(name, map_column=False, descriptor=None,
1132
1212
                        comparator_factory=None, doc=None):
1133
1213
    """Denote an attribute name as a synonym to a mapped property.
1171
1251
                            comparator_factory=comparator_factory,
1172
1252
                            doc=doc)
1173
1253
 
 
1254
 
1174
1255
def comparable_property(comparator_factory, descriptor=None):
1175
1256
    """Provides a method of applying a :class:`.PropComparator`
1176
1257
    to any Python descriptor attribute.
1211
1292
            id = Column(Integer, primary_key=True)
1212
1293
            word = Column(String)
1213
1294
            word_insensitive = comparable_property(lambda prop, mapper:
1214
 
                                    CaseInsensitiveComparator(mapper.c.word, mapper)
1215
 
                                )
 
1295
                            CaseInsensitiveComparator(mapper.c.word, mapper)
 
1296
                        )
1216
1297
 
1217
1298
 
1218
1299
    A mapping like the above allows the ``word_insensitive`` attribute
1235
1316
    """
1236
1317
    return ComparableProperty(comparator_factory, descriptor)
1237
1318
 
 
1319
 
1238
1320
@sa_util.deprecated("0.7", message=":func:`.compile_mappers` "
1239
1321
                            "is renamed to :func:`.configure_mappers`")
1240
1322
def compile_mappers():
1241
 
    """Initialize the inter-mapper relationships of all mappers that have been defined."""
 
1323
    """Initialize the inter-mapper relationships of all mappers that have
 
1324
    been defined.
1242
1325
 
 
1326
    """
1243
1327
    configure_mappers()
1244
1328
 
 
1329
 
1245
1330
def clear_mappers():
1246
1331
    """Remove all mappers from all classes.
1247
1332
 
1262
1347
    set of classes.
1263
1348
 
1264
1349
    """
1265
 
    mapperlib._COMPILE_MUTEX.acquire()
 
1350
    mapperlib._CONFIGURE_MUTEX.acquire()
1266
1351
    try:
1267
1352
        while _mapper_registry:
1268
1353
            try:
1272
1357
            except KeyError:
1273
1358
                pass
1274
1359
    finally:
1275
 
        mapperlib._COMPILE_MUTEX.release()
 
1360
        mapperlib._CONFIGURE_MUTEX.release()
 
1361
 
1276
1362
 
1277
1363
def joinedload(*keys, **kw):
1278
1364
    """Return a ``MapperOption`` that will convert the property of the given
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.
1322
1409
 
1323
1410
    See also:  :func:`subqueryload`, :func:`lazyload`
1324
1411
 
1332
1419
    else:
1333
1420
        return strategies.EagerLazyOption(keys, lazy='joined')
1334
1421
 
 
1422
 
1335
1423
def joinedload_all(*keys, **kw):
1336
1424
    """Return a ``MapperOption`` that will convert all properties along the
1337
1425
    given dot-separated path or series of mapped attributes
1349
1437
 
1350
1438
        query.options(joinedload_all('orders.items.keywords'))...
1351
1439
 
1352
 
    will set all of ``orders``, ``orders.items``, and ``orders.items.keywords`` to
1353
 
    load in one joined eager load.
 
1440
    will set all of ``orders``, ``orders.items``, and
 
1441
    ``orders.items.keywords`` to load in one joined eager load.
1354
1442
 
1355
1443
    Individual descriptors are accepted as arguments as well::
1356
1444
 
1377
1465
    """A synonym for :func:`joinedload()`."""
1378
1466
    return joinedload(*args, **kwargs)
1379
1467
 
 
1468
 
1380
1469
def eagerload_all(*args, **kwargs):
1381
1470
    """A synonym for :func:`joinedload_all()`"""
1382
1471
    return joinedload_all(*args, **kwargs)
1383
1472
 
 
1473
 
1384
1474
def subqueryload(*keys):
1385
1475
    """Return a ``MapperOption`` that will convert the property
1386
1476
    of the given name or series of mapped attributes
1409
1499
    """
1410
1500
    return strategies.EagerLazyOption(keys, lazy="subquery")
1411
1501
 
 
1502
 
1412
1503
def subqueryload_all(*keys):
1413
1504
    """Return a ``MapperOption`` that will convert all properties along the
1414
1505
    given dot-separated path or series of mapped attributes
1420
1511
 
1421
1512
        query.options(subqueryload_all('orders.items.keywords'))...
1422
1513
 
1423
 
    will set all of ``orders``, ``orders.items``, and ``orders.items.keywords`` to
1424
 
    load in one subquery eager load.
 
1514
    will set all of ``orders``, ``orders.items``, and
 
1515
    ``orders.items.keywords`` to load in one subquery eager load.
1425
1516
 
1426
1517
    Individual descriptors are accepted as arguments as well::
1427
1518
 
1433
1524
    """
1434
1525
    return strategies.EagerLazyOption(keys, lazy="subquery", chained=True)
1435
1526
 
 
1527
 
1436
1528
def lazyload(*keys):
1437
1529
    """Return a ``MapperOption`` that will convert the property of the given
1438
1530
    name or series of mapped attributes into a lazy load.
1444
1536
    """
1445
1537
    return strategies.EagerLazyOption(keys, lazy=True)
1446
1538
 
 
1539
 
1447
1540
def lazyload_all(*keys):
1448
1541
    """Return a ``MapperOption`` that will convert all the properties
1449
1542
    along the given dot-separated path or series of mapped attributes
1456
1549
    """
1457
1550
    return strategies.EagerLazyOption(keys, lazy=True, chained=True)
1458
1551
 
 
1552
 
1459
1553
def noload(*keys):
1460
1554
    """Return a ``MapperOption`` that will convert the property of the
1461
1555
    given name or series of mapped attributes into a non-load.
1468
1562
    """
1469
1563
    return strategies.EagerLazyOption(keys, lazy=None)
1470
1564
 
 
1565
 
1471
1566
def immediateload(*keys):
1472
1567
    """Return a ``MapperOption`` that will convert the property of the given
1473
1568
    name or series of mapped attributes into an immediate load.
1492
1587
    """
1493
1588
    return strategies.EagerLazyOption(keys, lazy='immediate')
1494
1589
 
 
1590
 
1495
1591
def contains_alias(alias):
1496
1592
    """Return a :class:`.MapperOption` that will indicate to the query that
1497
1593
    the main table has been aliased.
1526
1622
    """
1527
1623
    return AliasOption(alias)
1528
1624
 
 
1625
 
1529
1626
def contains_eager(*keys, **kwargs):
1530
1627
    """Return a ``MapperOption`` that will indicate to the query that
1531
1628
    the given attribute should be eagerly loaded from columns currently
1563
1660
    """
1564
1661
    alias = kwargs.pop('alias', None)
1565
1662
    if kwargs:
1566
 
        raise exceptions.ArgumentError('Invalid kwargs for contains_eag'
1567
 
                'er: %r' % kwargs.keys())
 
1663
        raise exc.ArgumentError(
 
1664
                'Invalid kwargs for contains_eager: %r' % kwargs.keys())
1568
1665
    return strategies.EagerLazyOption(keys, lazy='joined',
1569
1666
            propagate_to_loaders=False, chained=True), \
1570
1667
        strategies.LoadEagerFromAliasOption(keys, alias=alias, chained=True)
1571
1668
 
 
1669
 
1572
1670
def defer(*key):
1573
1671
    """Return a :class:`.MapperOption` that will convert the column property
1574
1672
    of the given name into a deferred load.
1613
1711
    """
1614
1712
    return strategies.DeferredOption(key, defer=True)
1615
1713
 
 
1714
 
1616
1715
def undefer(*key):
1617
1716
    """Return a :class:`.MapperOption` that will convert the column property
1618
1717
    of the given name into a non-deferred (regular column) load.
1623
1722
 
1624
1723
        from sqlalchemy.orm import undefer
1625
1724
 
1626
 
        query(MyClass).options(undefer("attribute_one"),
1627
 
                                undefer("attribute_two"))
 
1725
        query(MyClass).options(
 
1726
                    undefer("attribute_one"),
 
1727
                    undefer("attribute_two"))
1628
1728
 
1629
1729
    A class bound descriptor is also accepted::
1630
1730
 
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))
1634
1734
 
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::
1638
1738
 
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"))
1642
1742
 
1643
1743
    To specify a path via class, send multiple arguments::
1644
1744
 
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))
1648
1748
 
1649
1749
    See also:
1650
1750
 
1660
1760
    """
1661
1761
    return strategies.DeferredOption(key, defer=False)
1662
1762
 
 
1763
 
1663
1764
def undefer_group(name):
1664
 
    """Return a :class:`.MapperOption` that will convert the given group of deferred
1665
 
    column properties into a non-deferred (regular column) load.
 
1765
    """Return a :class:`.MapperOption` that will convert the given group of
 
1766
    deferred column properties into a non-deferred (regular column) load.
1666
1767
 
1667
1768
    Used with :meth:`.Query.options`.
1668
1769