import itertools
import operator
import weakref
-from sqlalchemy import exc
-from sqlalchemy import orm
-from sqlalchemy import util
-from sqlalchemy.orm import collections, ColumnProperty
-from sqlalchemy.sql import not_
+from .. import exc, orm, util
+from ..orm import collections
+from ..sql import not_
def association_proxy(target_collection, attr, **kw):
"""Return a Python property implementing a view of a target
- attribute which references an attribute on members of the
+ attribute which references an attribute on members of the
target.
-
+
The returned value is an instance of :class:`.AssociationProxy`.
-
+
Implements a Python property representing a relationship as a collection of
simpler values, or a scalar value. The proxied property will mimic the collection type of
the target (list, dict or set), or, in the case of a one to one relationship,
a simple scalar value.
- :param target_collection: Name of the attribute we'll proxy to.
+ :param target_collection: Name of the attribute we'll proxy to.
This attribute is typically mapped by
:func:`~sqlalchemy.orm.relationship` to link to a target collection, but
can also be a many-to-one or non-scalar relationship.
"""A descriptor that presents a read/write view of an object attribute."""
def __init__(self, target_collection, attr, creator=None,
- getset_factory=None, proxy_factory=None,
+ getset_factory=None, proxy_factory=None,
proxy_bulk_set=None):
"""Construct a new :class:`.AssociationProxy`.
-
+
The :func:`.association_proxy` function is provided as the usual
entrypoint here, though :class:`.AssociationProxy` can be instantiated
and/or subclassed directly.
- :param target_collection: Name of the collection we'll proxy to,
+ :param target_collection: Name of the collection we'll proxy to,
usually created with :func:`.relationship`.
:param attr: Attribute on the collected instances we'll proxy for. For example,
collection implementation, you may supply a factory function to
produce those collections. Only applicable to non-scalar relationships.
- :param proxy_bulk_set: Optional, use with proxy_factory. See
+ :param proxy_bulk_set: Optional, use with proxy_factory. See
the _set() method for details.
"""
def remote_attr(self):
"""The 'remote' :class:`.MapperProperty` referenced by this
:class:`.AssociationProxy`.
-
+
.. versionadded:: 0.7.3
-
+
See also:
-
+
:attr:`.AssociationProxy.attr`
:attr:`.AssociationProxy.local_attr`
:class:`.AssociationProxy`.
.. versionadded:: 0.7.3
-
+
See also:
-
+
:attr:`.AssociationProxy.attr`
:attr:`.AssociationProxy.remote_attr`
@property
def attr(self):
"""Return a tuple of ``(local_attr, remote_attr)``.
-
- This attribute is convenient when specifying a join
+
+ This attribute is convenient when specifying a join
using :meth:`.Query.join` across two relationships::
-
+
sess.query(Parent).join(*Parent.proxied.attr)
.. versionadded:: 0.7.3
-
+
See also:
-
+
:attr:`.AssociationProxy.local_attr`
:attr:`.AssociationProxy.remote_attr`
-
+
"""
return (self.local_attr, self.remote_attr)
@util.memoized_property
def target_class(self):
"""The intermediary class handled by this :class:`.AssociationProxy`.
-
+
Intercepted append/set/assignment events will result
in the generation of new instances of this class.
-
+
"""
return self._get_property().mapper.class_
def any(self, criterion=None, **kwargs):
"""Produce a proxied 'any' expression using EXISTS.
-
+
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
- and/or :meth:`.RelationshipProperty.Comparator.has`
+ and/or :meth:`.RelationshipProperty.Comparator.has`
operators of the underlying proxied attributes.
"""
def has(self, criterion=None, **kwargs):
"""Produce a proxied 'has' expression using EXISTS.
-
+
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
- and/or :meth:`.RelationshipProperty.Comparator.has`
+ and/or :meth:`.RelationshipProperty.Comparator.has`
operators of the underlying proxied attributes.
-
+
"""
return self._comparator.has(
def contains(self, obj):
"""Produce a proxied 'contains' expression using EXISTS.
-
+
This expression will be a composed product
using the :meth:`.RelationshipProperty.Comparator.any`
, :meth:`.RelationshipProperty.Comparator.has`,
"INSERT INTO mytable (SELECT mytable.x, mytable.y, mytable.z FROM mytable WHERE mytable.x > :x_1)"
-.. note::
+.. note::
- The above ``InsertFromSelect`` construct probably wants to have "autocommit"
+ The above ``InsertFromSelect`` construct probably wants to have "autocommit"
enabled. See :ref:`enabling_compiled_autocommit` for this step.
Cross Compiling between SQL and DDL compilers
Recall from the section :ref:`autocommit` that the :class:`.Engine`, when asked to execute
a construct in the absence of a user-defined transaction, detects if the given
-construct represents DML or DDL, that is, a data modification or data definition statement, which
+construct represents DML or DDL, that is, a data modification or data definition statement, which
requires (or may require, in the case of DDL) that the transaction generated by the DBAPI be committed
-(recall that DBAPI always has a transaction going on regardless of what SQLAlchemy does). Checking
+(recall that DBAPI always has a transaction going on regardless of what SQLAlchemy does). Checking
for this is actually accomplished
by checking for the "autocommit" execution option on the construct. When building a construct like
-an INSERT derivation, a new DDL type, or perhaps a stored procedure that alters data, the "autocommit"
+an INSERT derivation, a new DDL type, or perhaps a stored procedure that alters data, the "autocommit"
option needs to be set in order for the statement to function with "connectionless" execution
(as described in :ref:`dbengine_implicit`).
class MyInsertThing(UpdateBase):
def __init__(self, ...):
...
-
-
-
+
+
+
DDL elements that subclass :class:`.DDLElement` already have the "autocommit" flag turned on.
-
+
Changing the default compilation of existing constructs
the appropriate class (be sure to use the class, i.e. ``Insert`` or ``Select``, instead of the creation function such as ``insert()`` or ``select()``).
Within the new compilation function, to get at the "original" compilation routine,
-use the appropriate visit_XXX method - this because compiler.process() will call upon the
+use the appropriate visit_XXX method - this because compiler.process() will call upon the
overriding routine and cause an endless loop. Such as, to add "prefix" to all insert statements::
from sqlalchemy.sql.expression import Insert
expression class. Any SQL expression can be derived from this base, and is
probably the best choice for longer constructs such as specialized INSERT
statements.
-
+
* :class:`~sqlalchemy.sql.expression.ColumnElement` - The root of all
"column-like" elements. Anything that you'd place in the "columns" clause of
a SELECT statement (as well as order by and group by) can derive from this -
class timestamp(ColumnElement):
type = TIMESTAMP()
-
+
* :class:`~sqlalchemy.sql.expression.FunctionElement` - This is a hybrid of a
``ColumnElement`` and a "from clause" like object, and represents a SQL
function or stored procedure type of call. Since most databases support
* :class:`~sqlalchemy.sql.expression.Executable` - This is a mixin which should be
used with any expression class that represents a "standalone" SQL statement that
- can be passed directly to an ``execute()`` method. It is already implicit
+ can be passed directly to an ``execute()`` method. It is already implicit
within ``DDLElement`` and ``FunctionElement``.
Further Examples
so that the time is in UTC time. Timestamps are best stored in relational databases
as UTC, without time zones. UTC so that your database doesn't think time has gone
backwards in the hour when daylight savings ends, without timezones because timezones
-are like character encodings - they're best applied only at the endpoints of an
+are like character encodings - they're best applied only at the endpoints of an
application (i.e. convert to UTC upon user input, re-apply desired timezone upon display).
For Postgresql and Microsoft SQL Server::
-
+
from sqlalchemy.sql import expression
from sqlalchemy.ext.compiler import compiles
from sqlalchemy.types import DateTime
-
+
class utcnow(expression.FunctionElement):
type = DateTime()
return "GETUTCDATE()"
Example usage::
-
+
from sqlalchemy import (
Table, Column, Integer, String, DateTime, MetaData
)
-------------------
The "GREATEST" function is given any number of arguments and returns the one that is
-of the highest value - it's equivalent to Python's ``max`` function. A SQL
-standard version versus a CASE based version which only accommodates two
+of the highest value - it's equivalent to Python's ``max`` function. A SQL
+standard version versus a CASE based version which only accommodates two
arguments::
from sqlalchemy.sql import expression
Session.query(Account).\\
filter(
greatest(
- Account.checking_balance,
+ Account.checking_balance,
Account.savings_balance) > 10000
)
------------------
Render a "false" constant expression, rendering as "0" on platforms that don't have a "false" constant::
-
+
from sqlalchemy.sql import expression
from sqlalchemy.ext.compiler import compiles
-
+
class sql_false(expression.ColumnElement):
pass
return "0"
Example usage::
-
+
from sqlalchemy import select, union_all
exp = union_all(
select([users.c.name, sql_false().label("enrolled")]),
select([customers.c.name, customers.c.enrolled])
)
-
+
"""
-from sqlalchemy import exc
+from .. import exc
def compiles(class_, *specs):
def decorate(fn):
"""
-from sqlalchemy.schema import Table, Column, MetaData, _get_table_key
-from sqlalchemy.orm import synonym as _orm_synonym, mapper,\
+from ..schema import Table, Column, MetaData, _get_table_key
+from ..orm import synonym as _orm_synonym, mapper,\
comparable_property, class_mapper
-from sqlalchemy.orm.interfaces import MapperProperty
-from sqlalchemy.orm.properties import RelationshipProperty, ColumnProperty, CompositeProperty
-from sqlalchemy.orm.util import _is_mapped_class
-from sqlalchemy import util, exc
-from sqlalchemy.sql import util as sql_util, expression
-from sqlalchemy import event
-from sqlalchemy.orm.util import polymorphic_union, _mapper_or_none
+from ..orm.interfaces import MapperProperty
+from ..orm.properties import RelationshipProperty, ColumnProperty, CompositeProperty
+from ..orm.util import _is_mapped_class
+from .. import util, exc
+from ..sql import util as sql_util, expression
+from .. import event
+from ..orm.util import polymorphic_union, _mapper_or_none
import weakref
__all__ = 'declarative_base', 'synonym_for', \
Defines a rudimental 'horizontal sharding' system which allows a Session to
distribute queries and persistence operations across multiple databases.
-For a usage example, see the :ref:`examples_sharding` example included in
+For a usage example, see the :ref:`examples_sharding` example included in
the source distribution.
"""
-from sqlalchemy import exc as sa_exc
-from sqlalchemy import util
-from sqlalchemy.orm.session import Session
-from sqlalchemy.orm.query import Query
+from .. import exc as sa_exc
+from .. import util
+from ..orm.session import Session
+from ..orm.query import Query
__all__ = ['ShardedSession', 'ShardedQuery']
def set_shard(self, shard_id):
"""return a new query, limited to a single shard ID.
- all subsequent operations with the returned query will
+ all subsequent operations with the returned query will
be against the single shard regardless of other state.
"""
result = self._connection_from_session(
mapper=self._mapper_zero(),
shard_id=shard_id).execute(
- context.statement,
+ context.statement,
self._params)
return self.instances(result, context)
for shard_id in self.query_chooser(self):
partial.extend(iter_for_shard(shard_id))
- # if some kind of in memory 'sorting'
+ # if some kind of in memory 'sorting'
# were done, this is where it would happen
return iter(partial)
return None
class ShardedSession(Session):
- def __init__(self, shard_chooser, id_chooser, query_chooser, shards=None,
+ def __init__(self, shard_chooser, id_chooser, query_chooser, shards=None,
query_cls=ShardedQuery, **kwargs):
"""Construct a ShardedSession.
if self.transaction is not None:
return self.transaction.connection(mapper, shard_id=shard_id)
else:
- return self.get_bind(mapper,
- shard_id=shard_id,
+ return self.get_bind(mapper,
+ shard_id=shard_id,
instance=instance).contextual_connect(**kwargs)
def get_bind(self, mapper, shard_id=None, instance=None, clause=None, **kw):
there's probably a whole lot of amazing things it can be used for.
"""
-from sqlalchemy import util
-from sqlalchemy.orm import attributes, interfaces
+from .. import util
+from ..orm import attributes, interfaces
class hybrid_method(object):
"""A decorator which allows definition of a Python object method with both
===============================================
A typical example of a "mutable" structure is a Python dictionary.
-Following the example introduced in :ref:`types_toplevel`, we
-begin with a custom type that marshals Python dictionaries into
+Following the example introduced in :ref:`types_toplevel`, we
+begin with a custom type that marshals Python dictionaries into
JSON strings before being persisted::
from sqlalchemy.types import TypeDecorator, VARCHAR
value = json.loads(value)
return value
-The usage of ``json`` is only for the purposes of example. The :mod:`sqlalchemy.ext.mutable`
+The usage of ``json`` is only for the purposes of example. The :mod:`sqlalchemy.ext.mutable`
extension can be used
with any type whose target Python type may be mutable, including
:class:`.PickleType`, :class:`.postgresql.ARRAY`, etc.
built-in ``dict`` to produce a dict
subclass which routes all mutation events through ``__setitem__``. There are
many variants on this approach, such as subclassing ``UserDict.UserDict``,
-the newer ``collections.MutableMapping``, etc. The part that's important to this
+the newer ``collections.MutableMapping``, etc. The part that's important to this
example is that the :meth:`.Mutable.changed` method is called whenever an in-place change to the
datastructure takes place.
as the plain dictionaries returned by the ``json`` module, into the
appropriate type. Defining this method is optional; we could just as well created our
``JSONEncodedDict`` such that it always returns an instance of ``MutationDict``,
-and additionally ensured that all calling code uses ``MutationDict``
+and additionally ensured that all calling code uses ``MutationDict``
explicitly. When :meth:`.Mutable.coerce` is not overridden, any values
applied to a parent object which are not instances of the mutable type
will raise a ``ValueError``.
attribute. Such as, with classical table metadata::
from sqlalchemy import Table, Column, Integer
-
+
my_data = Table('my_data', metadata,
Column('id', Integer, primary_key=True),
Column('data', MutationDict.as_mutable(JSONEncodedDict))
)
Above, :meth:`~.Mutable.as_mutable` returns an instance of ``JSONEncodedDict``
-(if the type object was not an instance already), which will intercept any
+(if the type object was not an instance already), which will intercept any
attributes which are mapped against this type. Below we establish a simple
mapping against the ``my_data`` table::
The ``MutationDict`` can be associated with all future instances
of ``JSONEncodedDict`` in one step, using :meth:`~.Mutable.associate_with`. This
-is similar to :meth:`~.Mutable.as_mutable` except it will intercept
+is similar to :meth:`~.Mutable.as_mutable` except it will intercept
all occurrences of ``MutationDict`` in all mappings unconditionally, without
the need to declare it individually::
__tablename__ = 'my_data'
id = Column(Integer, primary_key=True)
data = Column(JSONEncodedDict)
-
-
+
+
Supporting Pickling
--------------------
class Point(MutableComposite):
# ...
-
+
def __getstate__(self):
return self.x, self.y
-
+
def __setstate__(self, state):
self.x, self.y = state
:meth:`.MutableBase._parents` collection is restored to all ``Point`` objects.
"""
-from sqlalchemy.orm.attributes import flag_modified
-from sqlalchemy import event, types
-from sqlalchemy.orm import mapper, object_mapper
-from sqlalchemy.util import memoized_property
+from ..orm.attributes import flag_modified
+from .. import event, types
+from ..orm import mapper, object_mapper
+from ..util import memoized_property
import weakref
class MutableBase(object):
@memoized_property
def _parents(self):
"""Dictionary of parent object->attribute name on the parent.
-
+
This attribute is a so-called "memoized" property. It initializes
itself with a new ``weakref.WeakKeyDictionary`` the first time
it is accessed, returning the same object upon subsequent access.
-
+
"""
return weakref.WeakKeyDictionary()
@classmethod
def _listen_on_attribute(cls, attribute, coerce, parent_cls):
- """Establish this type as a mutation listener for the given
+ """Establish this type as a mutation listener for the given
mapped descriptor.
"""
def load(state, *args):
"""Listen for objects loaded or refreshed.
- Wrap the target data member's value with
+ Wrap the target data member's value with
``Mutable``.
"""
data member.
Establish a weak reference to the parent object
- on the incoming value, remove it for the one
+ on the incoming value, remove it for the one
outgoing.
"""
@classmethod
def associate_with_attribute(cls, attribute):
- """Establish this type as a mutation listener for the given
+ """Establish this type as a mutation listener for the given
mapped descriptor.
"""
@classmethod
def associate_with(cls, sqltype):
- """Associate this wrapper with all future mapped columns
+ """Associate this wrapper with all future mapped columns
of the given type.
This is a convenience method that calls ``associate_with_attribute`` automatically.
- .. warning::
-
+ .. warning::
+
The listeners established by this method are *global*
- to all mappers, and are *not* garbage collected. Only use
+ to all mappers, and are *not* garbage collected. Only use
:meth:`.associate_with` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
in memory usage.
This establishes listeners that will detect ORM mappings against
the given type, adding mutation event trackers to those mappings.
- The type is returned, unconditionally as an instance, so that
+ The type is returned, unconditionally as an instance, so that
:meth:`.as_mutable` can be used inline::
Table('mytable', metadata,
is given, and that only columns which are declared specifically with that
type instance receive additional instrumentation.
- To associate a particular mutable type with all occurrences of a
+ To associate a particular mutable type with all occurrences of a
particular type, use the :meth:`.Mutable.associate_with` classmethod
of the particular :meth:`.Mutable` subclass to establish a global
association.
- .. warning::
-
+ .. warning::
+
The listeners established by this method are *global*
- to all mappers, and are *not* garbage collected. Only use
+ to all mappers, and are *not* garbage collected. Only use
:meth:`.as_mutable` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
in memory usage.
"""Mixin that defines transparent propagation of change
events on a SQLAlchemy "composite" object to its
owning parent or parents.
-
+
See the example in :ref:`mutable_composites` for usage information.
-
- .. warning::
-
+
+ .. warning::
+
The listeners established by the :class:`.MutableComposite`
- class are *global* to all mappers, and are *not* garbage collected. Only use
+ class are *global* to all mappers, and are *not* garbage collected. Only use
:class:`.MutableComposite` for types that are permanent to an application,
not with ad-hoc types else this will cause unbounded growth
in memory usage.
prop = object_mapper(parent).get_property(key)
for value, attr_name in zip(
- self.__composite_values__(),
+ self.__composite_values__(),
prop._attribute_keys):
setattr(parent, attr_name, value)
(as in the mapper example above). This implementation depends on the list
starting in the proper order, so be SURE to put an order_by on your relationship.
-.. warning::
+.. warning::
``ordering_list`` only provides limited functionality when a primary
- key column or unique column is the target of the sort. Since changing the order of
- entries often means that two rows must trade values, this is not possible when
+ key column or unique column is the target of the sort. Since changing the order of
+ entries often means that two rows must trade values, this is not possible when
the value is constrained by a primary key or unique constraint, since one of the rows
would temporarily have to point to a third available value so that the other row
- could take its old value. ``ordering_list`` doesn't do any of this for you,
+ could take its old value. ``ordering_list`` doesn't do any of this for you,
nor does SQLAlchemy itself.
``ordering_list`` takes the name of the related object's ordering attribute as
"""
-from sqlalchemy.orm.collections import collection
-from sqlalchemy import util
+from ..orm.collections import collection
+from .. import util
__all__ = [ 'ordering_list' ]
This implementation relies on the list starting in the proper order,
so be **sure** to put an ``order_by`` on your relationship.
- :param ordering_attr:
+ :param ordering_attr:
Name of the attribute that stores the object's order in the
relationship.
like stepped numbering, alphabetical and Fibonacci numbering, see
the unit tests.
- :param reorder_on_append:
+ :param reorder_on_append:
Default False. When appending an object with an existing (non-None)
ordering value, that value will be left untouched unless
``reorder_on_append`` is true. This is an optimization to avoid a
# This module is part of SQLAlchemy and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php
-"""Serializer/Deserializer objects for usage with SQLAlchemy query structures,
+"""Serializer/Deserializer objects for usage with SQLAlchemy query structures,
allowing "contextual" deserialization.
Any SQLAlchemy query structure, either based on sqlalchemy.sql.*
print query2.all()
-Similar restrictions as when using raw pickle apply; mapped classes must be
+Similar restrictions as when using raw pickle apply; mapped classes must be
themselves be pickleable, meaning they are importable from a module-level
namespace.
The serializer module is only appropriate for query structures. It is not
needed for:
-* instances of user-defined classes. These contain no references to engines,
+* instances of user-defined classes. These contain no references to engines,
sessions or expression constructs in the typical case and can be serialized directly.
* Table metadata that is to be loaded entirely from the serialized structure (i.e. is
- not already declared in the application). Regular pickle.loads()/dumps() can
- be used to fully dump any ``MetaData`` object, typically one which was reflected
+ not already declared in the application). Regular pickle.loads()/dumps() can
+ be used to fully dump any ``MetaData`` object, typically one which was reflected
from an existing database at some previous point in time. The serializer module
is specifically for the opposite case, where the Table metadata is already present
in memory.
"""
-from sqlalchemy.orm import class_mapper, Query
-from sqlalchemy.orm.session import Session
-from sqlalchemy.orm.mapper import Mapper
-from sqlalchemy.orm.attributes import QueryableAttribute
-from sqlalchemy import Table, Column
-from sqlalchemy.engine import Engine
-from sqlalchemy.util import pickle
+from ..orm import class_mapper, Query
+from ..orm.session import Session
+from ..orm.mapper import Mapper
+from ..orm.attributes import QueryableAttribute
+from .. import Table, Column
+from ..engine import Engine
+from ..util import pickle
import re
import base64
# Py3K
# the MIT License: http://www.opensource.org/licenses/mit-license.php
from .. import event, util
-from interfaces import EXT_CONTINUE
+from .interfaces import EXT_CONTINUE
class MapperExtension(object):
"""Base implementation for :class:`.Mapper` event hooks.
- .. note::
-
+ .. note::
+
:class:`.MapperExtension` is deprecated. Please
- refer to :func:`.event.listen` as well as
+ refer to :func:`.event.listen` as well as
:class:`.MapperEvents`.
New extension classes subclass :class:`.MapperExtension` and are specified
to the next ``MapperExtension`` for processing". For methods
that return objects like translated rows or new object
instances, EXT_CONTINUE means the result of the method
- should be ignored. In some cases it's required for a
- default mapper activity to be performed, such as adding a
+ should be ignored. In some cases it's required for a
+ default mapper activity to be performed, such as adding a
new instance to a result list.
The symbol EXT_STOP has significance within a chain
def reconstruct(instance, ctx):
ls_meth(self, instance)
return reconstruct
- event.listen(self.class_manager, 'load',
+ event.listen(self.class_manager, 'load',
go(ls_meth), raw=False, propagate=True)
elif meth == 'init_instance':
def go(ls_meth):
def init_instance(instance, args, kwargs):
- ls_meth(self, self.class_,
- self.class_manager.original_init,
+ ls_meth(self, self.class_,
+ self.class_manager.original_init,
instance, args, kwargs)
return init_instance
- event.listen(self.class_manager, 'init',
+ event.listen(self.class_manager, 'init',
go(ls_meth), raw=False, propagate=True)
elif meth == 'init_failed':
def go(ls_meth):
def init_failed(instance, args, kwargs):
- util.warn_exception(ls_meth, self, self.class_,
- self.class_manager.original_init,
+ util.warn_exception(ls_meth, self, self.class_,
+ self.class_manager.original_init,
instance, args, kwargs)
return init_failed
- event.listen(self.class_manager, 'init_failure',
+ event.listen(self.class_manager, 'init_failure',
go(ls_meth), raw=False, propagate=True)
else:
- event.listen(self, "%s" % meth, ls_meth,
+ event.listen(self, "%s" % meth, ls_meth,
raw=False, retval=True, propagate=True)
"""Receive a class when the mapper is first constructed, and has
applied instrumentation to the mapped class.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
def init_instance(self, mapper, class_, oldinit, instance, args, kwargs):
"""Receive an instance when it's constructor is called.
- This method is only called during a userland construction of
+ This method is only called during a userland construction of
an object. It is not called when an object is loaded from the
database.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
return EXT_CONTINUE
def init_failed(self, mapper, class_, oldinit, instance, args, kwargs):
- """Receive an instance when it's constructor has been called,
+ """Receive an instance when it's constructor has been called,
and raised an exception.
- This method is only called during a userland construction of
+ This method is only called during a userland construction of
an object. It is not called when an object is loaded from the
database.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
This is called when the mapper first receives a row, before
the object identity or the instance itself has been derived
- from that row. The given row may or may not be a
+ from that row. The given row may or may not be a
``RowProxy`` object - it will always be a dictionary-like
- object which contains mapped columns as keys. The
+ object which contains mapped columns as keys. The
returned object should also be a dictionary-like object
which recognizes mapped columns as keys.
"""
return EXT_CONTINUE
- def append_result(self, mapper, selectcontext, row, instance,
+ def append_result(self, mapper, selectcontext, row, instance,
result, **flags):
"""Receive an object instance before that instance is appended
to a result list.
return EXT_CONTINUE
- def populate_instance(self, mapper, selectcontext, row,
+ def populate_instance(self, mapper, selectcontext, row,
instance, **flags):
"""Receive an instance before that instance has
its attributes populated.
instance's lifetime.
Note that during a result-row load, this method is called upon
- the first row received for this instance. Note that some
- attributes and collections may or may not be loaded or even
+ the first row received for this instance. Note that some
+ attributes and collections may or may not be loaded or even
initialized, depending on what's present in the result rows.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
Column-based attributes can be modified within this method
which will result in the new value being inserted. However
- *no* changes to the overall flush plan can be made, and
+ *no* changes to the overall flush plan can be made, and
manipulation of the ``Session`` will not have the desired effect.
- To manipulate the ``Session`` within an extension, use
+ To manipulate the ``Session`` within an extension, use
``SessionExtension``.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
def after_insert(self, mapper, connection, instance):
"""Receive an object instance after that instance is inserted.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
Column-based attributes can be modified within this method
which will result in the new value being updated. However
- *no* changes to the overall flush plan can be made, and
+ *no* changes to the overall flush plan can be made, and
manipulation of the ``Session`` will not have the desired effect.
- To manipulate the ``Session`` within an extension, use
+ To manipulate the ``Session`` within an extension, use
``SessionExtension``.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
def after_update(self, mapper, connection, instance):
"""Receive an object instance after that instance is updated.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
desired effect. To manipulate the ``Session`` within an
extension, use ``SessionExtension``.
- The return value is only significant within the ``MapperExtension``
+ The return value is only significant within the ``MapperExtension``
chain; the parent mapper's behavior isn't modified by this method.
"""
"""Base implementation for :class:`.Session` event hooks.
- .. note::
-
+ .. note::
+
:class:`.SessionExtension` is deprecated. Please
- refer to :func:`.event.listen` as well as
+ refer to :func:`.event.listen` as well as
:class:`.SessionEvents`.
Subclasses may be installed into a :class:`.Session` (or
"""Base implementation for :class:`.AttributeImpl` event hooks, events
that fire upon attribute mutations in user code.
- .. note::
-
+ .. note::
+
:class:`.AttributeExtension` is deprecated. Please
- refer to :func:`.event.listen` as well as
+ refer to :func:`.event.listen` as well as
:class:`.AttributeEvents`.
:class:`.AttributeExtension` is used to listen for set,
active_history=listener.active_history,
raw=True, retval=True)
event.listen(self, 'remove', listener.remove,
- active_history=listener.active_history,
+ active_history=listener.active_history,
raw=True, retval=True)
event.listen(self, 'set', listener.set,
- active_history=listener.active_history,
+ active_history=listener.active_history,
raw=True, retval=True)
def append(self, state, value, initiator):
from .. import exc as sa_exc, util, inspect
from ..sql import operators
from collections import deque
-#from . import _instrumentation_ext
-#InstrumentationManager = _instrumentation_ext.InstrumentationManager
-#from ..ext.instrumentation import InstrumentationManager
orm_util = util.importlater('sqlalchemy.orm', 'util')
collections = util.importlater('sqlalchemy.orm', 'collections')
MANYTOONE = util.symbol('MANYTOONE')
MANYTOMANY = util.symbol('MANYTOMANY')
-from .deprecated_interfaces import AttributeExtension, SessionExtension, \
+from .deprecated_interfaces import AttributeExtension, \
+ SessionExtension, \
MapperExtension
class _InspectionAttr(object):