-# mapper/__init__.py
+# sqlalchemy/orm/__init__.py
# Copyright (C) 2005, 2006, 2007, 2008 Michael Bayer mike_mp@zzzcomputing.com
#
# This module is part of SQLAlchemy and is released under
from sqlalchemy.orm.scoping import ScopedSession
from sqlalchemy import util as sa_util
+
__all__ = (
'EXT_CONTINUE',
'EXT_STOP',
join condition, or to override the table-defined foreign keys.
join_depth=None
- when non-``None``, an integer value indicating how many levels
- deep eagerload joins should be constructed on a self-referring
- or cyclical relationship. The number counts how many times
- the same Mapper shall be present in the loading condition along
- a particular join branch. When left at its default of ``None``,
- eager loads will automatically stop chaining joins when they encounter
- a mapper which is already higher up in the chain.
+ when non-``None``, an integer value indicating how many levels deep
+ eagerload joins should be constructed on a self-referring or
+ cyclical relationship. The number counts how many times the same
+ Mapper shall be present in the loading condition along a particular
+ join branch. When left at its default of ``None``, eager loads will
+ automatically stop chaining joins when they encounter a mapper which
+ is already higher up in the chain.
lazy=(True|False|None|'dynamic')
specifies how the related items should be loaded. Values include:
of the parent, using a JOIN or LEFT OUTER JOIN.
None - no loading should occur at any time. This is to support
- "write-only" attributes, or attributes which are populated in
- some manner specific to the application.
+ "write-only" attributes, or attributes which are populated
+ in some manner specific to the application.
'dynamic' - a ``DynaLoader`` will be attached, which returns a
- ``Query`` object for all read operations. The dynamic-
- collection supports only ``append()`` and ``remove()``
- for write operations; changes to the dynamic property
- will not be visible until the data is flushed to the
- database.
+ ``Query`` object for all read operations. The
+ dynamic- collection supports only ``append()`` and
+ ``remove()`` for write operations; changes to the
+ dynamic property will not be visible until the data is
+ flushed to the database.
order_by
- indicates the ordering that should be applied when loading these items.
+ indicates the ordering that should be applied when loading these
+ items.
passive_deletes=False
Indicates loading behavior during delete operations.
- A value of True indicates that unloaded child items should not be loaded
- during a delete operation on the parent. Normally, when a parent
- item is deleted, all child items are loaded so that they can either be
- marked as deleted, or have their foreign key to the parent set to NULL.
- Marking this flag as True usually implies an ON DELETE <CASCADE|SET NULL>
- rule is in place which will handle updating/deleting child rows on the
- database side.
-
- Additionally, setting the flag to the string value 'all' will disable
- the "nulling out" of the child foreign keys, when there is no delete or
- delete-orphan cascade enabled. This is typically used when a triggering
- or error raise scenario is in place on the database side. Note that
- the foreign key attributes on in-session child objects will not be changed
- after a flush occurs so this is a very special use-case setting.
+ A value of True indicates that unloaded child items should not be
+ loaded during a delete operation on the parent. Normally, when a
+ parent item is deleted, all child items are loaded so that they can
+ either be marked as deleted, or have their foreign key to the parent
+ set to NULL. Marking this flag as True usually implies an ON DELETE
+ <CASCADE|SET NULL> rule is in place which will handle
+ updating/deleting child rows on the database side.
+
+ Additionally, setting the flag to the string value 'all' will
+ disable the "nulling out" of the child foreign keys, when there is
+ no delete or delete-orphan cascade enabled. This is typically used
+ when a triggering or error raise scenario is in place on the
+ database side. Note that the foreign key attributes on in-session
+ child objects will not be changed after a flush occurs so this is a
+ very special use-case setting.
passive_updates=True
Indicates loading and INSERT/UPDATE/DELETE behavior when the source
primaryjoin
a ClauseElement that will be used as the primary join of this child
- object against the parent object, or in a many-to-many relationship the
- join of the primary object to the association table. By default, this
- value is computed based on the foreign key relationships of the parent
- and child tables (or association table).
+ object against the parent object, or in a many-to-many relationship
+ the join of the primary object to the association table. By default,
+ this value is computed based on the foreign key relationships of the
+ parent and child tables (or association table).
remote_side
- used for self-referential relationships, indicates the column or list
- of columns that form the "remote side" of the relationship.
+ used for self-referential relationships, indicates the column or
+ list of columns that form the "remote side" of the relationship.
secondaryjoin
- a ClauseElement that will be used as the join of an association table
- to the child object. By default, this value is computed based on the
- foreign key relationships of the association and child tables.
+ a ClauseElement that will be used as the join of an association
+ table to the child object. By default, this value is computed based
+ on the foreign key relationships of the association and child
+ tables.
uselist=(True|False)
- a boolean that indicates if this property should be loaded as a list or
- a scalar. In most cases, this value is determined automatically by
- ``relation()``, based on the type and direction of the relationship - one
- to many forms a list, many to one forms a scalar, many to many is a
- list. If a scalar is desired where normally a list would be present,
- such as a bi-directional one-to-one relationship, set uselist to False.
+ a boolean that indicates if this property should be loaded as a list
+ or a scalar. In most cases, this value is determined automatically
+ by ``relation()``, based on the type and direction of the
+ relationship - one to many forms a list, many to one forms a scalar,
+ many to many is a list. If a scalar is desired where normally a list
+ would be present, such as a bi-directional one-to-one relationship,
+ set uselist to False.
viewonly=False
- when set to True, the relation is used only for loading objects within
- the relationship, and has no effect on the unit-of-work flush process.
- Relations with viewonly can specify any kind of join conditions to
- provide additional views of related objects onto a parent object. Note
- that the functionality of a viewonly relationship has its limits -
- complicated join conditions may not compile into eager or lazy loaders
- properly. If this is the case, use an alternative method.
+ when set to True, the relation is used only for loading objects
+ within the relationship, and has no effect on the unit-of-work flush
+ process. Relations with viewonly can specify any kind of join
+ conditions to provide additional views of related objects onto a
+ parent object. Note that the functionality of a viewonly
+ relationship has its limits - complicated join conditions may not
+ compile into eager or lazy loaders properly. If this is the case,
+ use an alternative method.
"""
return PropertyLoader(argument, secondary=secondary, **kwargs)
def dynamic_loader(argument, secondary=None, primaryjoin=None, secondaryjoin=None, entity_name=None,
foreign_keys=None, backref=None, post_update=False, cascade=None, remote_side=None, enable_typechecks=True,
passive_deletes=False, order_by=None):
- """construct a dynamically-loading mapper property.
+ """Construct a dynamically-loading mapper property.
- This property is similar to relation(), except read operations
- return an active Query object, which reads from the database in all
- cases. Items may be appended to the attribute via append(), or
- removed via remove(); changes will be persisted
- to the database during a flush(). However, no other list mutation
- operations are available.
+ This property is similar to relation(), except read operations return an
+ active Query object, which reads from the database in all cases. Items
+ may be appended to the attribute via append(), or removed via remove();
+ changes will be persisted to the database during a flush(). However, no
+ other list mutation operations are available.
A subset of arguments available to relation() are available here.
Column-based properties can normally be applied to the mapper's
``properties`` dictionary using the ``schema.Column`` element directly.
- Use this function when the given column is not directly present within
- the mapper's selectable; examples include SQL expressions, functions,
- and scalar SELECT queries.
+ Use this function when the given column is not directly present within the
+ mapper's selectable; examples include SQL expressions, functions, and
+ scalar SELECT queries.
Columns that aren't present in the mapper's selectable won't be persisted
by the mapper and are effectively "read-only" attributes.
def composite(class_, *cols, **kwargs):
"""Return a composite column-based property for use with a Mapper.
- This is very much like a column-based property except the given class
- is used to represent "composite" values composed of one or more columns.
+ This is very much like a column-based property except the given class is
+ used to represent "composite" values composed of one or more columns.
The class must implement a constructor with positional arguments matching
the order of columns supplied here, as well as a __composite_values__()
A group name for this property when marked as deferred.
deferred
- When True, the column property is "deferred", meaning that
- it does not load immediately, and is instead loaded when the
- attribute is first accessed on an instance. See also
- [sqlalchemy.orm#deferred()].
+ When True, the column property is "deferred", meaning that it does not
+ load immediately, and is instead loaded when the attribute is first
+ accessed on an instance. See also [sqlalchemy.orm#deferred()].
comparator
- An optional instance of [sqlalchemy.orm#PropComparator] which
- provides SQL expression generation functions for this composite
- type.
+ An optional instance of [sqlalchemy.orm#PropComparator] which provides
+ SQL expression generation functions for this composite type.
"""
return CompositeProperty(class_, *cols, **kwargs)
def backref(name, **kwargs):
- """Create a BackRef object with explicit arguments, which are the same arguments one
- can send to ``relation()``.
+ """Create a BackRef object with explicit arguments, which are the same
+ arguments one can send to ``relation()``.
Used with the `backref` keyword argument to ``relation()`` in
place of a string argument.
The class to be mapped.
local_table
- The table to which the class is mapped, or None if this
- mapper inherits from another mapper using concrete table
- inheritance.
+ The table to which the class is mapped, or None if this mapper
+ inherits from another mapper using concrete table inheritance.
entity_name
- A name to be associated with the `class`, to allow alternate
- mappings for a single class.
+ A name to be associated with the `class`, to allow alternate mappings
+ for a single class.
always_refresh
- If True, all query operations for this mapped class will
- overwrite all data within object instances that already
- exist within the session, erasing any in-memory changes with
- whatever information was loaded from the database. Usage
- of this flag is highly discouraged; as an alternative,
- see the method `populate_existing()` on [sqlalchemy.orm.query#Query].
+ If True, all query operations for this mapped class will overwrite all
+ data within object instances that already exist within the session,
+ erasing any in-memory changes with whatever information was loaded
+ from the database. Usage of this flag is highly discouraged; as an
+ alternative, see the method `populate_existing()` on
+ [sqlalchemy.orm.query#Query].
allow_column_override
If True, allows the usage of a ``relation()`` which has the
will no longer be mapped.
allow_null_pks
- Indicates that composite primary keys where one or more (but
- not all) columns contain NULL is a valid primary key.
- Primary keys which contain NULL values usually indicate that
- a result row does not contain an entity and should be
- skipped.
+ Indicates that composite primary keys where one or more (but not all)
+ columns contain NULL is a valid primary key. Primary keys which
+ contain NULL values usually indicate that a result row does not
+ contain an entity and should be skipped.
batch
- Indicates that save operations of multiple entities can be
- batched together for efficiency. setting to False indicates
- that an instance will be fully saved before saving the next
- instance, which includes inserting/updating all table rows
- corresponding to the entity as well as calling all
- ``MapperExtension`` methods corresponding to the save
+ Indicates that save operations of multiple entities can be batched
+ together for efficiency. setting to False indicates that an instance
+ will be fully saved before saving the next instance, which includes
+ inserting/updating all table rows corresponding to the entity as well
+ as calling all ``MapperExtension`` methods corresponding to the save
operation.
column_prefix
- A string which will be prepended to the `key` name of all
- Columns when creating column-based properties from the given
- Table. Does not affect explicitly specified column-based
- properties
+ A string which will be prepended to the `key` name of all Columns when
+ creating column-based properties from the given Table. Does not
+ affect explicitly specified column-based properties
concrete
- If True, indicates this mapper should use concrete table
- inheritance with its parent mapper.
+ If True, indicates this mapper should use concrete table inheritance
+ with its parent mapper.
extension
A [sqlalchemy.orm#MapperExtension] instance or list of
operations by this ``Mapper``.
inherits
- Another ``Mapper`` for which this ``Mapper`` will have an
- inheritance relationship with.
+ Another ``Mapper`` for which this ``Mapper`` will have an inheritance
+ relationship with.
inherit_condition
For joined table inheritance, a SQL expression (constructed
- ``ClauseElement``) which will define how the two tables are
- joined; defaults to a natural join between the two tables.
+ ``ClauseElement``) which will define how the two tables are joined;
+ defaults to a natural join between the two tables.
inherit_foreign_keys
when inherit_condition is used and the condition contains no
order_by
A single ``Column`` or list of ``Columns`` for which
- selection operations should use as the default ordering for
- entities. Defaults to the OID/ROWID of the table if any, or
- the first primary key column of the table.
+ selection operations should use as the default ordering for entities.
+ Defaults to the OID/ROWID of the table if any, or the first primary
+ key column of the table.
non_primary
- Construct a ``Mapper`` that will define only the selection
- of instances, not their persistence. Any number of non_primary
- mappers may be created for a particular class.
+ Construct a ``Mapper`` that will define only the selection of
+ instances, not their persistence. Any number of non_primary mappers
+ may be created for a particular class.
polymorphic_on
- Used with mappers in an inheritance relationship, a ``Column``
- which will identify the class/mapper combination to be used
- with a particular row. Requires the ``polymorphic_identity``
- value to be set for all mappers in the inheritance
- hierarchy. The column specified by ``polymorphic_on`` is
- usually a column that resides directly within the base
- mapper's mapped table; alternatively, it may be a column
- that is only present within the <selectable> portion
- of the ``with_polymorphic`` argument.
+ Used with mappers in an inheritance relationship, a ``Column`` which
+ will identify the class/mapper combination to be used with a
+ particular row. Requires the ``polymorphic_identity`` value to be set
+ for all mappers in the inheritance hierarchy. The column specified by
+ ``polymorphic_on`` is usually a column that resides directly within
+ the base mapper's mapped table; alternatively, it may be a column that
+ is only present within the <selectable> portion of the
+ ``with_polymorphic`` argument.
_polymorphic_map
- Used internally to propagate the full map of polymorphic
- identifiers to surrogate mappers.
+ Used internally to propagate the full map of polymorphic identifiers
+ to surrogate mappers.
polymorphic_identity
- A value which will be stored in the Column denoted by
- polymorphic_on, corresponding to the *class identity* of
- this mapper.
+ A value which will be stored in the Column denoted by polymorphic_on,
+ corresponding to the *class identity* of this mapper.
polymorphic_fetch
- specifies how subclasses mapped through joined-table
- inheritance will be fetched. options are 'union',
- 'select', and 'deferred'. if the 'with_polymorphic' argument
- is present, defaults to 'union', otherwise defaults to
- 'select'.
+ specifies how subclasses mapped through joined-table inheritance will
+ be fetched. options are 'union', 'select', and 'deferred'. if the
+ 'with_polymorphic' argument is present, defaults to 'union', otherwise
+ defaults to 'select'.
properties
- A dictionary mapping the string names of object attributes
- to ``MapperProperty`` instances, which define the
- persistence behavior of that attribute. Note that the
- columns in the mapped table are automatically converted into
- ``ColumnProperty`` instances based on the `key` property of
- each ``Column`` (although they can be overridden using this
- dictionary).
+ A dictionary mapping the string names of object attributes to
+ ``MapperProperty`` instances, which define the persistence behavior of
+ that attribute. Note that the columns in the mapped table are
+ automatically converted into ``ColumnProperty`` instances based on the
+ `key` property of each ``Column`` (although they can be overridden
+ using this dictionary).
include_properties
- An inclusive list of properties to map. Columns present in the
- mapped table but not present in this list will not be automatically
- converted into properties.
+ An inclusive list of properties to map. Columns present in the mapped
+ table but not present in this list will not be automatically converted
+ into properties.
exclude_properties
- A list of properties not to map. Columns present in the
- mapped table and present in this list will not be automatically
- converted into properties. Note that neither this option nor
- include_properties will allow an end-run around Python inheritance.
- If mapped class ``B`` inherits from mapped class ``A``, no combination
- of includes or excludes will allow ``B`` to have fewer properties
- than its superclass, ``A``.
+ A list of properties not to map. Columns present in the mapped table
+ and present in this list will not be automatically converted into
+ properties. Note that neither this option nor include_properties will
+ allow an end-run around Python inheritance. If mapped class ``B``
+ inherits from mapped class ``A``, no combination of includes or
+ excludes will allow ``B`` to have fewer properties than its
+ superclass, ``A``.
primary_key
- A list of ``Column`` objects which define the *primary key*
- to be used against this mapper's selectable unit. This is
- normally simply the primary key of the `local_table`, but
- can be overridden here.
+ A list of ``Column`` objects which define the *primary key* to be used
+ against this mapper's selectable unit. This is normally simply the
+ primary key of the `local_table`, but can be overridden here.
with_polymorphic
A tuple in the form ``(<classes>, <selectable>)`` indicating the
- default style of "polymorphic" loading, that is, which tables
- are queried at once. <classes> is any single or list of mappers
- and/or classes indicating the inherited classes that should be
- loaded at once. The special value ``'*'`` may be used to indicate
- all descending classes should be loaded immediately. The second
- tuple argument <selectable> indicates a selectable that will be
- used to query for multiple classes. Normally, it is left as
- None, in which case this mapper will form an outer join from
- the base mapper's table to that of all desired sub-mappers.
- When specified, it provides the selectable to be used for
- polymorphic loading. When with_polymorphic includes mappers
- which load from a "concrete" inheriting table, the <selectable>
- argument is required, since it usually requires more complex
- UNION queries.
+ default style of "polymorphic" loading, that is, which tables are
+ queried at once. <classes> is any single or list of mappers and/or
+ classes indicating the inherited classes that should be loaded at
+ once. The special value ``'*'`` may be used to indicate all descending
+ classes should be loaded immediately. The second tuple argument
+ <selectable> indicates a selectable that will be used to query for
+ multiple classes. Normally, it is left as None, in which case this
+ mapper will form an outer join from the base mapper's table to that of
+ all desired sub-mappers. When specified, it provides the selectable
+ to be used for polymorphic loading. When with_polymorphic includes
+ mappers which load from a "concrete" inheriting table, the
+ <selectable> argument is required, since it usually requires more
+ complex UNION queries.
select_table
Deprecated. Synonymous with
``with_polymorphic=('*', <selectable>)``.
version_id_col
- A ``Column`` which must have an integer type that will be
- used to keep a running *version id* of mapped entities in
- the database. this is used during save operations to ensure
- that no other thread or process has updated the instance
- during the lifetime of the entity, else a
+ A ``Column`` which must have an integer type that will be used to keep
+ a running *version id* of mapped entities in the database. this is
+ used during save operations to ensure that no other thread or process
+ has updated the instance during the lifetime of the entity, else a
``ConcurrentModificationError`` exception is thrown.
"""
Used with the ``properties`` dictionary sent to [sqlalchemy.orm#mapper()].
Any existing attributes on the class which map the key name sent
- to the ``properties`` dictionary will be used by the synonym to
- provide instance-attribute behavior (that is, any Python property object,
- provided by the ``property`` builtin or providing a ``__get__()``,
- ``__set__()`` and ``__del__()`` method). If no name exists for the key,
- the ``synonym()`` creates a default getter/setter object automatically
- and applies it to the class.
+ to the ``properties`` dictionary will be used by the synonym to provide
+ instance-attribute behavior (that is, any Python property object, provided
+ by the ``property`` builtin or providing a ``__get__()``, ``__set__()``
+ and ``__del__()`` method). If no name exists for the key, the
+ ``synonym()`` creates a default getter/setter object automatically and
+ applies it to the class.
- `name` refers to the name of the existing mapped property, which
- can be any other ``MapperProperty`` including column-based
- properties and relations.
+ `name` refers to the name of the existing mapped property, which can be
+ any other ``MapperProperty`` including column-based properties and
+ relations.
If `map_column` is ``True``, an additional ``ColumnProperty`` is created
on the mapper automatically, using the synonym's name as the keyname of
The `proxy` keyword argument is deprecated and currently does nothing;
synonyms now always establish an attribute getter/setter function if one
is not already available.
- """
+ """
return SynonymProperty(name, map_column=map_column, descriptor=descriptor)
def comparable_property(comparator_factory, descriptor=None):
Allows a regular Python @property (descriptor) to be used in Queries and
SQL constructs like a managed attribute. comparable_property wraps a
descriptor with a proxy that directs operator overrides such as ==
- (__eq__) to the supplied comparator but proxies everything else through
- to the original descriptor::
+ (__eq__) to the supplied comparator but proxies everything else through to
+ the original descriptor::
class MyClass(object):
@property
The like-named descriptor will be automatically retreived from the
mapped class if left blank in a ``properties`` declaration.
+
"""
return ComparableProperty(comparator_factory, descriptor)
"""Compile all mappers that have been defined.
This is equivalent to calling ``compile()`` on any individual mapper.
- """
+ """
for m in list(_mapper_registry):
m.compile()
def clear_mappers():
"""Remove all mappers that have been created thus far.
- The mapped classes will return to their initial "unmapped"
- state and can be re-mapped with new mappers.
+ The mapped classes will return to their initial "unmapped" state and can
+ be re-mapped with new mappers.
+
"""
mapperlib._COMPILE_MUTEX.acquire()
try:
that will be called in the context of the ``Query``.
Used with ``query.options()``.
- """
+ """
return ExtensionOption(ext)
def eagerload(*keys):
- """Return a ``MapperOption`` that will convert the property of the given name into an eager load.
+ """Return a ``MapperOption`` that will convert the property of the given
+ name into an eager load.
Used with ``query.options()``.
- """
+ """
return strategies.EagerLazyOption(keys, lazy=False)
eagerload = sa_util.array_as_starargs_fn_decorator(eagerload)
def eagerload_all(*keys):
- """Return a ``MapperOption`` that will convert all properties along the given dot-separated path into an eager load.
+ """Return a ``MapperOption`` that will convert all properties along the
+ given dot-separated path into an eager load.
For example, this::
query.options(eagerload_all('orders.items.keywords'))...
- will set all of 'orders', 'orders.items', and 'orders.items.keywords'
- to load in one eager load.
+ will set all of 'orders', 'orders.items', and 'orders.items.keywords' to
+ load in one eager load.
Used with ``query.options()``.
- """
+ """
return strategies.EagerLazyOption(keys, lazy=False, chained=True)
eagerload_all = sa_util.array_as_starargs_fn_decorator(eagerload_all)
def lazyload(*keys):
- """Return a ``MapperOption`` that will convert the property of the
- given name into a lazy load.
+ """Return a ``MapperOption`` that will convert the property of the given
+ name into a lazy load.
Used with ``query.options()``.
- """
+ """
return strategies.EagerLazyOption(keys, lazy=True)
lazyload = sa_util.array_as_starargs_fn_decorator(lazyload)
given name into a non-load.
Used with ``query.options()``.
- """
+ """
return strategies.EagerLazyOption(keys, lazy=None)
def contains_alias(alias):
`alias` is the string name or ``Alias`` object representing the
alias.
- """
+ """
return AliasOption(alias)
def contains_eager(*keys, **kwargs):
"""Return a ``MapperOption`` that will indicate to the query that
the given attribute will be eagerly loaded.
- Used when feeding SQL result sets directly into
- ``query.instances()``. Also bundles an ``EagerLazyOption`` to
- turn on eager loading in case it isn't already.
+ Used when feeding SQL result sets directly into ``query.instances()``.
+ Also bundles an ``EagerLazyOption`` to turn on eager loading in case it
+ isn't already.
+
+ `alias` is the string name of an alias, **or** an ``sql.Alias`` object,
+ which represents the aliased columns in the query. This argument is
+ optional.
- `alias` is the string name of an alias, **or** an ``sql.Alias``
- object, which represents the aliased columns in the query. This
- argument is optional.
"""
alias = kwargs.pop('alias', None)
if kwargs:
raise exceptions.ArgumentError("Invalid kwargs for contains_eager: %r" % kwargs.keys())
-
+
return (strategies.EagerLazyOption(keys, lazy=False), strategies.LoadEagerFromAliasOption(keys, alias=alias))
contains_eager = sa_util.array_as_starargs_fn_decorator(contains_eager)
def defer(*keys):
- """Return a ``MapperOption`` that will convert the column property
- of the given name into a deferred load.
+ """Return a ``MapperOption`` that will convert the column property of the
+ given name into a deferred load.
- Used with ``query.options()``"""
+ Used with ``query.options()``
+ """
return strategies.DeferredOption(keys, defer=True)
defer = sa_util.array_as_starargs_fn_decorator(defer)
def undefer(*keys):
- """Return a ``MapperOption`` that will convert the column property
- of the given name into a non-deferred (regular column) load.
+ """Return a ``MapperOption`` that will convert the column property of the
+ given name into a non-deferred (regular column) load.
Used with ``query.options()``.
- """
+ """
return strategies.DeferredOption(keys, defer=False)
undefer = sa_util.array_as_starargs_fn_decorator(undefer)
def undefer_group(name):
- """Return a ``MapperOption`` that will convert the given
- group of deferred column properties into a non-deferred (regular column) load.
+ """Return a ``MapperOption`` that will convert the given group of deferred
+ column properties into a non-deferred (regular column) load.
Used with ``query.options()``.
+
"""
return strategies.UndeferGroupOption(name)