summaryrefslogtreecommitdiff
path: root/lib/sqlalchemy/orm/session.py
diff options
context:
space:
mode:
Diffstat (limited to 'lib/sqlalchemy/orm/session.py')
-rw-r--r--lib/sqlalchemy/orm/session.py127
1 files changed, 66 insertions, 61 deletions
diff --git a/lib/sqlalchemy/orm/session.py b/lib/sqlalchemy/orm/session.py
index 77cd6628b..036045dba 100644
--- a/lib/sqlalchemy/orm/session.py
+++ b/lib/sqlalchemy/orm/session.py
@@ -24,7 +24,8 @@ from .unitofwork import UOWTransaction
from . import state as statelib
import sys
-__all__ = ['Session', 'SessionTransaction', 'SessionExtension', 'sessionmaker']
+__all__ = ['Session', 'SessionTransaction',
+ 'SessionExtension', 'sessionmaker']
_sessions = weakref.WeakValueDictionary()
"""Weak-referencing dictionary of :class:`.Session` objects.
@@ -274,7 +275,7 @@ class SessionTransaction(object):
for s in set(self._deleted).union(self.session._deleted):
if s.deleted:
- #assert s in self._deleted
+ # assert s in self._deleted
del s.deleted
self.session._update_impl(s, discard_existing=True)
@@ -501,16 +502,16 @@ class Session(_SessionClassMethods):
.. warning::
- The autocommit flag is **not for general use**, and if it is used,
- queries should only be invoked within the span of a
- :meth:`.Session.begin` / :meth:`.Session.commit` pair. Executing
+ The autocommit flag is **not for general use**, and if it is
+ used, queries should only be invoked within the span of a
+ :meth:`.Session.begin` / :meth:`.Session.commit` pair. Executing
queries outside of a demarcated transaction is a legacy mode
of usage, and can in some cases lead to concurrent connection
checkouts.
Defaults to ``False``. When ``True``, the
- :class:`.Session` does not keep a persistent transaction running, and
- will acquire connections from the engine on an as-needed basis,
+ :class:`.Session` does not keep a persistent transaction running,
+ and will acquire connections from the engine on an as-needed basis,
returning them immediately after their use. Flushes will begin and
commit (or possibly rollback) their own transaction if no
transaction is present. When using this mode, the
@@ -525,8 +526,8 @@ class Session(_SessionClassMethods):
:meth:`~.Session.flush` call to this ``Session`` before proceeding.
This is a convenience feature so that :meth:`~.Session.flush` need
not be called repeatedly in order for database queries to retrieve
- results. It's typical that ``autoflush`` is used in conjunction with
- ``autocommit=False``. In this scenario, explicit calls to
+ results. It's typical that ``autoflush`` is used in conjunction
+ with ``autocommit=False``. In this scenario, explicit calls to
:meth:`~.Session.flush` are rarely needed; you usually only need to
call :meth:`~.Session.commit` (which flushes) to finalize changes.
@@ -542,8 +543,8 @@ class Session(_SessionClassMethods):
:class:`.Engine` or :class:`.Connection` objects. Operations which
proceed relative to a particular :class:`.Mapper` will consult this
dictionary for the direct :class:`.Mapper` instance as
- well as the mapper's ``mapped_table`` attribute in order to locate a
- connectable to use. The full resolution is described in the
+ well as the mapper's ``mapped_table`` attribute in order to locate
+ a connectable to use. The full resolution is described in the
:meth:`.Session.get_bind`.
Usage looks like::
@@ -566,8 +567,8 @@ class Session(_SessionClassMethods):
legacy-only flag which when ``False`` disables *all* 0.5-style
object accounting on transaction boundaries, including auto-expiry
of instances on rollback and commit, maintenance of the "new" and
- "deleted" lists upon rollback, and autoflush of pending changes upon
- :meth:`~.Session.begin`, all of which are interdependent.
+ "deleted" lists upon rollback, and autoflush of pending changes
+ upon :meth:`~.Session.begin`, all of which are interdependent.
:param expire_on_commit: Defaults to ``True``. When ``True``, all
instances will be fully expired after each :meth:`~.commit`,
@@ -581,25 +582,26 @@ class Session(_SessionClassMethods):
Please see :class:`.SessionEvents`.
:param info: optional dictionary of arbitrary data to be associated
- with this :class:`.Session`. Is available via the :attr:`.Session.info`
- attribute. Note the dictionary is copied at construction time so
- that modifications to the per-:class:`.Session` dictionary will be local
- to that :class:`.Session`.
+ with this :class:`.Session`. Is available via the
+ :attr:`.Session.info` attribute. Note the dictionary is copied at
+ construction time so that modifications to the per-
+ :class:`.Session` dictionary will be local to that
+ :class:`.Session`.
.. versionadded:: 0.9.0
:param query_cls: Class which should be used to create new Query
- objects, as returned by the :meth:`~.Session.query` method. Defaults
- to :class:`.Query`.
+ objects, as returned by the :meth:`~.Session.query` method.
+ Defaults to :class:`.Query`.
:param twophase: When ``True``, all transactions will be started as
a "two phase" transaction, i.e. using the "two phase" semantics
of the database in use along with an XID. During a
:meth:`~.commit`, after :meth:`~.flush` has been issued for all
- attached databases, the :meth:`~.TwoPhaseTransaction.prepare` method
- on each database's :class:`.TwoPhaseTransaction` will be called.
- This allows each database to roll back the entire transaction,
- before each transaction is committed.
+ attached databases, the :meth:`~.TwoPhaseTransaction.prepare`
+ method on each database's :class:`.TwoPhaseTransaction` will be
+ called. This allows each database to roll back the entire
+ transaction, before each transaction is committed.
:param weak_identity_map: Defaults to ``True`` - when set to
``False``, objects placed in the :class:`.Session` will be
@@ -829,12 +831,12 @@ class Session(_SessionClassMethods):
etc.) which will be used to locate a bind, if a bind
cannot otherwise be identified.
- :param close_with_result: Passed to :meth:`.Engine.connect`, indicating
- the :class:`.Connection` should be considered "single use",
- automatically closing when the first result set is closed. This
- flag only has an effect if this :class:`.Session` is configured with
- ``autocommit=True`` and does not already have a transaction
- in progress.
+ :param close_with_result: Passed to :meth:`.Engine.connect`,
+ indicating the :class:`.Connection` should be considered
+ "single use", automatically closing when the first result set is
+ closed. This flag only has an effect if this :class:`.Session` is
+ configured with ``autocommit=True`` and does not already have a
+ transaction in progress.
:param \**kw:
Additional keyword arguments are sent to :meth:`get_bind()`,
@@ -869,8 +871,8 @@ class Session(_SessionClassMethods):
user_table.select().where(user_table.c.id == 5)
)
- :meth:`~.Session.execute` accepts any executable clause construct, such
- as :func:`~.sql.expression.select`,
+ :meth:`~.Session.execute` accepts any executable clause construct,
+ such as :func:`~.sql.expression.select`,
:func:`~.sql.expression.insert`,
:func:`~.sql.expression.update`,
:func:`~.sql.expression.delete`, and
@@ -899,7 +901,8 @@ class Session(_SessionClassMethods):
cursor's ``execute()`` or ``executemany()`` is used to execute the
statement. An INSERT construct may be invoked for a single row::
- result = session.execute(users.insert(), {"id": 7, "name": "somename"})
+ result = session.execute(
+ users.insert(), {"id": 7, "name": "somename"})
or for multiple rows::
@@ -917,8 +920,9 @@ class Session(_SessionClassMethods):
:class:`.Connection`, which in the average case is derived directly
from the "bind" of the :class:`.Session` itself, and in other cases
can be based on the :func:`.mapper`
- and :class:`.Table` objects passed to the method; see the documentation
- for :meth:`.Session.get_bind` for a full description of this scheme.
+ and :class:`.Table` objects passed to the method; see the
+ documentation for :meth:`.Session.get_bind` for a full description of
+ this scheme.
The :meth:`.Session.execute` method does *not* invoke autoflush.
@@ -980,8 +984,8 @@ class Session(_SessionClassMethods):
if bind is None:
bind = self.get_bind(mapper, clause=clause, **kw)
- return self._connection_for_bind(bind, close_with_result=True).execute(
- clause, params or {})
+ return self._connection_for_bind(
+ bind, close_with_result=True).execute(clause, params or {})
def scalar(self, clause, params=None, mapper=None, bind=None, **kw):
"""Like :meth:`~.Session.execute` but return a scalar result."""
@@ -1551,10 +1555,10 @@ class Session(_SessionClassMethods):
same primary key in the session. If not found locally, it attempts
to load the object from the database based on primary key, and if
none can be located, creates a new instance. The state of each
- attribute on the source instance is then copied to the target instance.
- The resulting target instance is then returned by the method; the
- original source instance is left unmodified, and un-associated with the
- :class:`.Session` if not already.
+ attribute on the source instance is then copied to the target
+ instance. The resulting target instance is then returned by the
+ method; the original source instance is left unmodified, and
+ un-associated with the :class:`.Session` if not already.
This operation cascades to associated instances if the association is
mapped with ``cascade="merge"``.
@@ -1582,7 +1586,8 @@ class Session(_SessionClassMethods):
any existing related objects or collections that might not
be loaded. The resulting objects from ``load=False`` are always
produced as "clean", so it is only appropriate that the given objects
- should be "clean" as well, else this suggests a mis-use of the method.
+ should be "clean" as well, else this suggests a mis-use of the
+ method.
"""
@@ -1713,8 +1718,8 @@ class Session(_SessionClassMethods):
def _save_impl(self, state):
if state.key is not None:
raise sa_exc.InvalidRequestError(
- "Object '%s' already has an identity - it can't be registered "
- "as pending" % state_str(state))
+ "Object '%s' already has an identity - "
+ "it can't be registered as pending" % state_str(state))
self._before_attach(state)
if state not in self._new:
@@ -1790,8 +1795,8 @@ class Session(_SessionClassMethods):
is what was already loaded from a foreign-key-holding value.
The :meth:`.Session.enable_relationship_loading` method is
- similar to the ``load_on_pending`` flag on :func:`.relationship`. Unlike
- that flag, :meth:`.Session.enable_relationship_loading` allows
+ similar to the ``load_on_pending`` flag on :func:`.relationship`.
+ Unlike that flag, :meth:`.Session.enable_relationship_loading` allows
an object to remain transient while still being able to load
related items.
@@ -1827,10 +1832,10 @@ class Session(_SessionClassMethods):
if state.key and \
state.key in self.identity_map and \
not self.identity_map.contains_state(state):
- raise sa_exc.InvalidRequestError("Can't attach instance "
- "%s; another instance with key %s is already "
- "present in this session."
- % (state_str(state), state.key))
+ raise sa_exc.InvalidRequestError(
+ "Can't attach instance "
+ "%s; another instance with key %s is already "
+ "present in this session." % (state_str(state), state.key))
if state.session_id and \
state.session_id is not self.hash_key and \
@@ -2007,8 +2012,8 @@ class Session(_SessionClassMethods):
instance_dict=self.identity_map)
util.warn("Attribute history events accumulated on %d "
"previously clean instances "
- "within inner-flush event handlers have been reset, "
- "and will not result in database updates. "
+ "within inner-flush event handlers have been "
+ "reset, and will not result in database updates. "
"Consider using set_committed_value() within "
"inner-flush event handlers to avoid this warning."
% len_)
@@ -2057,12 +2062,12 @@ class Session(_SessionClassMethods):
A few caveats to this method apply:
- * Instances present in the :attr:`.Session.dirty` collection may report
- ``False`` when tested with this method. This is because
- the object may have received change events via attribute
- mutation, thus placing it in :attr:`.Session.dirty`,
- but ultimately the state is the same as that loaded from
- the database, resulting in no net change here.
+ * Instances present in the :attr:`.Session.dirty` collection may
+ report ``False`` when tested with this method. This is because
+ the object may have received change events via attribute mutation,
+ thus placing it in :attr:`.Session.dirty`, but ultimately the state
+ is the same as that loaded from the database, resulting in no net
+ change here.
* Scalar attributes may not have recorded the previously set
value when a new value was applied, if the attribute was not loaded,
or was expired, at the time the new value was received - in these
@@ -2148,8 +2153,8 @@ class Session(_SessionClassMethods):
call :meth:`.Session.rollback`, in order to close out the
transaction stack. It is in this "partial rollback" period that the
:attr:`.is_active` flag returns False. After the call to
- :meth:`.Session.rollback`, the :class:`.SessionTransaction` is replaced
- with a new one and :attr:`.is_active` returns ``True`` again.
+ :meth:`.Session.rollback`, the :class:`.SessionTransaction` is
+ replaced with a new one and :attr:`.is_active` returns ``True`` again.
When a :class:`.Session` is used in ``autocommit=True`` mode, the
:class:`.SessionTransaction` is only instantiated within the scope
@@ -2315,8 +2320,8 @@ class sessionmaker(_SessionClassMethods):
.. versionadded:: 0.9.0
- :param \**kw: all other keyword arguments are passed to the constructor
- of newly created :class:`.Session` objects.
+ :param \**kw: all other keyword arguments are passed to the
+ constructor of newly created :class:`.Session` objects.
"""
kw['bind'] = bind