summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/__init__.py
diff options
context:
space:
mode:
authorMike Bayer <mike_mp@zzzcomputing.com>2007-02-25 22:44:52 +0000
committerMike Bayer <mike_mp@zzzcomputing.com>2007-02-25 22:44:52 +0000
commit962c22c9eda7d2ab7dc0b41bd1c7a52cf0c9d008 (patch)
treef0ab113c7947c80dfea42d4a1bef52217bf6ed96 /lib/sqlalchemy/orm/__init__.py
parent8fa3becd5fac57bb898a0090bafaac377b60f070 (diff)
downloadsqlalchemy-962c22c9eda7d2ab7dc0b41bd1c7a52cf0c9d008.tar.gz
migrated (most) docstrings to pep-257 format, docstring generator using straight <pre> + trim() func
for now. applies most of [ticket:214], compliemnts of Lele Gaifax
Diffstat (limited to 'lib/sqlalchemy/orm/__init__.py')
-rw-r--r--lib/sqlalchemy/orm/__init__.py235
1 files changed, 139 insertions, 96 deletions
diff --git a/lib/sqlalchemy/orm/__init__.py b/lib/sqlalchemy/orm/__init__.py
index 30070e8d7..4c87c4bdc 100644
--- a/lib/sqlalchemy/orm/__init__.py
+++ b/lib/sqlalchemy/orm/__init__.py
@@ -5,9 +5,10 @@
# the MIT License: http://www.opensource.org/licenses/mit-license.php
"""
-the mapper package provides object-relational functionality, building upon the schema and sql
+The mapper package provides object-relational functionality, building upon the schema and sql
packages and tying operations to class properties and constructors.
"""
+
from sqlalchemy import exceptions
from sqlalchemy import util as sautil
from sqlalchemy.orm.mapper import *
@@ -18,15 +19,17 @@ from sqlalchemy.orm import properties, strategies, interfaces
from sqlalchemy.orm.session import Session as create_session
from sqlalchemy.orm.session import object_session, attribute_manager
-__all__ = ['relation', 'backref', 'eagerload', 'lazyload', 'noload', 'deferred', 'defer', 'undefer', 'extension',
- 'mapper', 'clear_mappers', 'compile_mappers', 'clear_mapper', 'class_mapper', 'object_mapper', 'MapperExtension', 'Query',
+__all__ = ['relation', 'backref', 'eagerload', 'lazyload', 'noload', 'deferred', 'defer', 'undefer', 'extension',
+ 'mapper', 'clear_mappers', 'compile_mappers', 'clear_mapper', 'class_mapper', 'object_mapper', 'MapperExtension', 'Query',
'cascade_mappers', 'polymorphic_union', 'create_session', 'synonym', 'contains_alias', 'contains_eager', 'EXT_PASS', 'object_session'
]
def relation(*args, **kwargs):
- """provide a relationship of a primary Mapper to a secondary Mapper.
-
- This corresponds to a parent-child or associative table relationship."""
+ """Provide a relationship of a primary Mapper to a secondary Mapper.
+
+ This corresponds to a parent-child or associative table relationship.
+ """
+
if len(args) > 1 and isinstance(args[0], type):
raise exceptions.ArgumentError("relation(class, table, **kwargs) is deprecated. Please use relation(class, **kwargs) or relation(mapper, **kwargs).")
return _relation_loader(*args, **kwargs)
@@ -35,96 +38,123 @@ def _relation_loader(mapper, secondary=None, primaryjoin=None, secondaryjoin=Non
return properties.PropertyLoader(mapper, secondary, primaryjoin, secondaryjoin, lazy=lazy, **kwargs)
def backref(name, **kwargs):
- """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. """
+ """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.
+ """
+
return properties.BackRef(name, **kwargs)
-
+
def deferred(*columns, **kwargs):
- """return a DeferredColumnProperty, which indicates this object attributes should only be loaded
- from its corresponding table column when first accessed.
-
- used with the 'properties' dictionary sent to mapper()."""
+ """Return a ``DeferredColumnProperty``, which indicates this
+ object attributes should only be loaded from its corresponding
+ table column when first accessed.
+
+ Used with the `properties` dictionary sent to ``mapper()``.
+ """
+
return properties.ColumnProperty(deferred=True, *columns, **kwargs)
-
+
def mapper(class_, table=None, *args, **params):
- """return a new Mapper object.
-
- See the Mapper class for a description of arguments."""
+ """Return a new ``Mapper`` object.
+
+ See the ``Mapper`` class for a description of arguments.
+ """
+
return Mapper(class_, table, *args, **params)
def synonym(name, proxy=False):
- """set up 'name' as a synonym to another MapperProperty.
-
- Used with the 'properties' dictionary sent to mapper()."""
+ """Set up `name` as a synonym to another ``MapperProperty``.
+
+ Used with the `properties` dictionary sent to ``mapper()``.
+ """
+
return interfaces.SynonymProperty(name, proxy=proxy)
def compile_mappers():
- """compile all mappers that have been defined.
-
- this is equivalent to calling compile() on any individual mapper."""
+ """Compile all mappers that have been defined.
+
+ This is equivalent to calling ``compile()` on any individual mapper.
+ """
+
if not len(mapper_registry):
return
mapper_registry.values()[0].compile()
-
+
def clear_mappers():
- """remove all mappers that have been created thus far.
-
- when new mappers are created, they will be assigned to their classes as their primary mapper."""
+ """Remove all mappers that have been created thus far.
+
+ When new mappers are created, they will be assigned to their
+ classes as their primary mapper.
+ """
+
for mapper in mapper_registry.values():
attribute_manager.reset_class_managed(mapper.class_)
if hasattr(mapper.class_, 'c'):
del mapper.class_.c
mapper_registry.clear()
sautil.ArgSingleton.instances.clear()
-
+
def clear_mapper(m):
- """remove the given mapper from the storage of mappers.
-
- when a new mapper is created for the previous mapper's class, it will be used as that classes'
- new primary mapper."""
+ """Remove the given mapper from the storage of mappers.
+
+ When a new mapper is created for the previous mapper's class, it
+ will be used as that classes' new primary mapper.
+ """
+
del mapper_registry[m.class_key]
attribute_manager.reset_class_managed(m.class_)
if hasattr(m.class_, 'c'):
del m.class_.c
m.class_key.dispose()
-
+
def extension(ext):
- """return a MapperOption that will insert the given MapperExtension to the
- beginning of the list of extensions that will be called in the context of the Query.
-
- used with query.options()."""
+ """Return a ``MapperOption`` that will insert the given
+ ``MapperExtension`` to the beginning of the list of extensions
+ that will be called in the context of the ``Query``.
+
+ Used with ``query.options()``.
+ """
+
return ExtensionOption(ext)
-
+
def eagerload(name):
- """return a MapperOption that will convert the property of the given name
- into an eager load.
-
- used with query.options()."""
+ """Return a ``MapperOption`` that will convert the property of the
+ given name into an eager load.
+
+ Used with ``query.options()``.
+ """
+
return strategies.EagerLazyOption(name, lazy=False)
def lazyload(name):
- """return a MapperOption that will convert the property of the given name
- into a lazy load.
-
- used with query.options()."""
+ """Return a ``MapperOption`` that will convert the property of the
+ given name into a lazy load.
+
+ Used with ``query.options()``.
+ """
+
return strategies.EagerLazyOption(name, lazy=True)
def noload(name):
- """return a MapperOption that will convert the property of the given name
- into a non-load.
-
- used with query.options()."""
+ """Return a ``MapperOption`` that will convert the property of the
+ given name into a non-load.
+
+ Used with ``query.options()``.
+ """
+
return strategies.EagerLazyOption(name, lazy=None)
def contains_alias(alias):
- """return a MapperOption that will indicate to the query that the main table
- has been aliased.
-
- "alias" is the string name or Alias object representing the alias.
+ """Return a ``MapperOption`` that will indicate to the query that
+ the main table has been aliased.
+
+ `alias` is the string name or ``Alias`` object representing the
+ alias.
"""
+
class AliasedRow(MapperExtension):
def __init__(self, alias):
self.alias = alias
@@ -144,53 +174,66 @@ def contains_alias(alias):
if c2 and row.has_key(c2):
newrow[c] = row[c2]
return newrow
-
+
return ExtensionOption(AliasedRow(alias))
-
+
def contains_eager(key, alias=None, decorator=None):
- """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 isnt 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.
-
- "decorator" is mutually exclusive of "alias" and is a row-processing function which
- will be applied to the incoming row before sending to the eager load handler. use this
- for more sophisticated row adjustments beyond a straight alias."""
+ """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 isnt 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.
+
+ `decorator` is mutually exclusive of `alias` and is a
+ row-processing function which will be applied to the incoming row
+ before sending to the eager load handler. use this for more
+ sophisticated row adjustments beyond a straight alias.
+ """
+
return (strategies.EagerLazyOption(key, lazy=False), strategies.RowDecorateOption(key, alias=alias, decorator=decorator))
-
+
def defer(name):
- """return a MapperOption that will convert the column property of the given
- name into a deferred load.
-
- used with query.options()"""
+ """Return a ``MapperOption`` that will convert the column property
+ of the given name into a deferred load.
+
+ Used with ``query.options()``"""
return strategies.DeferredOption(name, defer=True)
+
def undefer(name):
- """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 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(name, defer=False)
-
+
def cascade_mappers(*classes_or_mappers):
- """attempt to create a series of relations() between mappers automatically, via
- introspecting the foreign key relationships of the underlying tables.
-
- given a list of classes and/or mappers, identifies the foreign key relationships
- between the given mappers or corresponding class mappers, and creates relation()
- objects representing those relationships, including a backreference. Attempts to find
- the "secondary" table in a many-to-many relationship as well. The names of the relations
- will be a lowercase version of the related class. In the case of one-to-many or many-to-many,
- the name will be "pluralized", which currently is based on the English language (i.e. an 's' or
- 'es' added to it).
-
- NOTE: this method usually works poorly, and its usage is generally not advised.
+ """Attempt to create a series of ``relations()`` between mappers
+ automatically, via introspecting the foreign key relationships of
+ the underlying tables.
+
+ Given a list of classes and/or mappers, identify the foreign key
+ relationships between the given mappers or corresponding class
+ mappers, and create ``relation()`` objects representing those
+ relationships, including a backreference. Attempt to find the
+ *secondary* table in a many-to-many relationship as well.
+
+ The names of the relations will be a lowercase version of the
+ related class. In the case of one-to-many or many-to-many, the
+ name will be *pluralized*, which currently is based on the English
+ language (i.e. an 's' or 'es' added to it).
+
+ NOTE: this method usually works poorly, and its usage is generally
+ not advised.
"""
+
table_to_mapper = {}
for item in classes_or_mappers:
if isinstance(item, Mapper):
@@ -199,12 +242,14 @@ def cascade_mappers(*classes_or_mappers):
klass = item
m = class_mapper(klass)
table_to_mapper[m.mapped_table] = m
+
def pluralize(name):
# oh crap, do we need locale stuff now
if name[-1] == 's':
return name + "es"
else:
return name + "s"
+
for table,mapper in table_to_mapper.iteritems():
for fk in table.foreign_keys:
if fk.column.table is table:
@@ -229,5 +274,3 @@ def cascade_mappers(*classes_or_mappers):
propname = m2.class_.__name__.lower()
propname2 = pluralize(mapper.class_.__name__.lower())
mapper.add_property(propname, relation(m2, secondary=secondary, backref=propname2))
-
- \ No newline at end of file