SQLAlchemy 0.5 Documentation - module sqlalchemy.orm.session

# SQLAlchemy 0.5 Documentation

Multiple Pages | One Page
Version: 0.5.0beta2 Last Updated: 07/14/08 16:12:25

### module sqlalchemy.orm.session

Provides the Session class and related utilities.

### class Session(object)

Manages persistence operations for ORM-mapped objects.

The Session is the front end to SQLAlchemy's Unit of Work implementation. The concept behind Unit of Work is to track modifications to a field of objects, and then be able to flush those changes to the database in a single operation.

SQLAlchemy's unit of work includes these functions:

- The ability to track in-memory changes on scalar- and collection-based object attributes, such that database persistence operations can be assembled based on those changes.
- The ability to organize individual SQL queries and population of newly generated primary and foreign key-holding attributes during a persist operation such that referential integrity is maintained at all times.
- The ability to maintain insert ordering against the order in which new instances were added to the session.
- An Identity Map, which is a dictionary keying instances to their unique primary key identity. This ensures that only one copy of a particular entity is ever present within the session, even if repeated load operations for the same entity occur. This allows many parts of an application to get a handle to a particular object without any chance of modifications going to two different places.

When dealing with instances of mapped classes, an instance may be attached to a particular Session, else it is unattached . An instance also may or may not correspond to an actual row in the database. These conditions break up into four distinct states:

- Transient - an instance that's not in a session, and is not saved to the database; i.e. it has no database identity. The only relationship such an object has to the ORM is that its class has a `mapper()` associated with it.
- Pending - when you `add()` a transient instance, it becomes pending. It still wasn't actually flushed to the database yet, but it will be when the next flush occurs.
- Persistent - An instance which is present in the session and has a record in the database. You get persistent instances by either flushing so that the pending instances become persistent, or by querying the database for existing instances (or moving persistent instances from other sessions into your local session).
- Detached - an instance which has a record in the database, but is not in any session. Theres nothing wrong with this, and you can use objects normally when they're detached, except they will not be able to issue any SQL in order to load collections or attributes which are not yet loaded, or were marked as "expired".

The session methods which control instance state include `add()`, `delete()`, `merge()`, and `expunge()`.

The Session object is generally not threadsafe. A session which is set to `autocommit` and is only read from may be used by concurrent threads if it's acceptable that some object instances may be loaded twice.

The typical pattern to managing Sessions in a multi-threaded environment is either to use mutexes to limit concurrent access to one thread at a time, or more commonly to establish a unique session for every thread, using a threadlocal variable. SQLAlchemy provides a thread-managed Session adapter, provided by the scoped_session() function.

def __init__(self, bind=None, autoflush=True, autoexpire=True, autocommit=False, twophase=False, echo_uow=False, weak_identity_map=True, binds=None, extension=None, query_cls=)

Construct a new Session.

Arguments to `Session` are described using the sessionmaker() function.

def add(self, instance, entity_name=None)

Add the given instance into this `Session`.

TODO: rephrase the below in user terms; possibly tie into future function that downgrades persistent to transient. [ticket:1052]

The non-None state key on the instance's state determines whether to `save()` or `update()` the instance.

def save_or_update(*args, **kwargs)

Use session.add() Add the given instance into this `Session`.

> TODO: rephrase the below in user terms; possibly tie into future function that downgrades persistent to transient. [ticket:1052]

> The non-None state key on the instance's state determines whether to `save()` or `update()` the instance.

def add_all(self, instances)

Add the given collection of instances to this `Session`.

def begin(self, subtransactions=False, nested=False, _autoflush=True)

Begin a transaction on this Session.

If this Session is already within a transaction, either a plain transaction or nested transaction, an error is raised, unless `subtransactions=True` or `nested=True` is specified.

The `subtransactions=True` flag indicates that this `begin()` can create a subtransaction if a transaction is already in progress. A subtransaction is a non-transactional, delimiting construct that allows matching begin()/commit() pairs to be nested together, with only the outermost begin/commit pair actually affecting transactional state. When a rollback is issued, the subtransaction will directly roll back the innermost real transaction, however each subtransaction still must be explicitly rolled back to maintain proper stacking of subtransactions.

If no transaction is in progress, then a real transaction is begun.

The `nested` flag begins a SAVEPOINT transaction and is equivalent to calling `begin_nested()`.

def begin_nested(self)

Begin a nested transaction on this Session.

The target database(s) must support SQL SAVEPOINTs or a SQLAlchemy-supported vendor implementation of the idea.

The nested transaction is a real transation, unlike a "subtransaction" which corresponds to multiple `begin()` calls. The next `rollback()` or `commit()` call will operate upon this nested transaction.

def bind_mapper(self, mapper, bind, entity_name=None)

Bind operations for a mapper to a Connectable.

mapper
  A mapper instance or mapped class
bind
  Any Connectable: a `Engine` or `Connection`.
entity_name
  Defaults to None.

All subsequent operations involving this mapper will use the given bind.

def bind_table(self, table, bind)

Bind operations on a Table to a Connectable.

table
  A `Table` instance
bind
  Any Connectable: a `Engine` or `Connection`.

All subsequent operations involving this `Table` will use the given bind.

def close(self)

Close this Session.

This clears all items and ends any transaction in progress.

If this session were created with `transactional=True`, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed.

def close_all(cls)

Close all sessions in memory.

def commit(self)

Flush pending changes and commit the current transaction.

If no transaction is in progress, this method raises an InvalidRequestError.

If a subtransaction is in effect (which occurs when begin() is called multiple times), the subtransaction will be closed, and the next call to `commit()` will operate on the enclosing transaction.

For a session configured with autocommit=False, a new transaction will be begun immediately after the commit, but note that the newly begun transaction does not use any connection resources until the first SQL is actually emitted.

def connection(self, mapper=None, clause=None, _state=None)

Return the active Connection.

Retrieves the `Connection` managing the current transaction. Any operations executed on the Connection will take place in the same transactional context as `Session` operations.

For `autocommit` Sessions with no active manual transaction, `connection()` is a passthrough to `contextual_connect()` on the underlying engine.

Ambiguity in multi-bind or unbound Sessions can be resolved through any of the optional keyword arguments. See `get_bind()` for more information.

mapper
  Optional, a `mapper` or mapped class
clause
  Optional, any `ClauseElement`

def delete(self, instance)

Mark an instance as deleted.

The database delete operation occurs upon `flush()`.

deleted = property()

Return a set of all instances marked as 'deleted' within this `Session`

dirty = property()

Return a set of all persistent instances considered dirty.

Instances are considered dirty when they were modified but not deleted.

Note that this 'dirty' calculation is 'optimistic'; most attribute-setting or collection modification operations will mark an instance as 'dirty' and place it in this set, even if there is no net change to the attribute's value. At flush time, the value of each attribute is compared to its previously saved value, and if there's no net change, no SQL operation will occur (this is a more expensive operation so it's only done at flush time).

To check if an instance has actionable net changes to its attributes, use the is_modified() method.

def execute(self, clause, params=None, mapper=None, _state=None)

Execute a clause within the current transaction.

Returns a `ResultProxy` of execution results. autocommit Sessions will create a transaction on the fly.

Connection ambiguity in multi-bind or unbound Sessions will be resolved by inspecting the clause for binds. The 'mapper' and 'instance' keyword arguments may be used if this is insufficient, See `get_bind()` for more information.

clause
  A ClauseElement (i.e. select(), text(), etc.) or string SQL statement to be executed
params
  Optional, a dictionary of bind parameters.
mapper
  Optional, a `mapper` or mapped class
_state
  Optional, an instance of a mapped class

def expire(self, instance, attribute_names=None)

Expire the attributes on an instance.

Marks the attributes of an instance as out of date. When an expired attribute is next accessed, query will be issued to the database and the attributes will be refreshed with their current database value. `expire()` is a lazy variant of `refresh()`.

The `attribute_names` argument is an iterable collection of attribute names indicating a subset of attributes to be expired.

def expire_all(self)

Expires all persistent instances within this Session.

def expunge(self, instance)

Remove the instance from this `Session`.

This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.

def expunge_all(self)

Remove all object instances from this `Session`.

This is equivalent to calling `expunge(obj)` on all objects in this `Session`.

def clear(self)

Remove all object instances from this `Session`.

This is equivalent to calling `expunge(obj)` on all objects in this `Session`.

def flush(self, objects=None)

Flush all the object changes to the database.

Writes out all pending object creations, deletions and modifications to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are automatically ordered by the Session's unit of work dependency solver..

Database operations will be issued in the current transactional context and do not affect the state of the transaction. You may flush() as often as you like within a transaction to move changes from Python to the database's transaction buffer.

For `autocommit` Sessions with no active manual transaction, flush() will create a transaction on the fly that surrounds the entire set of operations int the flush.

objects
  Optional; a list or tuple collection. Restricts the flush operation to only these objects, rather than all pending changes.

def get_bind(self, mapper, clause=None, _state=None)

Return an engine corresponding to the given arguments.

All arguments are optional.

mapper
  Optional, a `Mapper` or mapped class
clause
  Optional, A ClauseElement (i.e. select(), text(), etc.)
_state
  Optional, SA internal representation of a mapped instance

def identity_key(cls, *args, **kwargs)
is_active = property()

return True if this Session has an active transaction.

def is_modified(self, instance, include_collections=True, passive=False)

Return True if instance has modified attributes.

This method retrieves a history instance for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value. Note that instances present in the 'dirty' collection may result in a value of `False` when tested with this method.

include_collections indicates if multivalued collections should be included in the operation. Setting this to False is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush.

The passive flag indicates if unloaded attributes and collections should not be loaded in the course of performing this test.

def merge(self, instance, entity_name=None, dont_load=False, _recursive=None)

Copy the state an instance onto the persistent instance with the same identifier.

If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.

This operation cascades to associated instances if the association is mapped with `cascade="merge"`.

new = property()

Return a set of all instances marked as 'new' within this `Session`.

def object_session(cls, instance)

Return the `Session` to which an object belongs.

def prepare(self)

Prepare the current transaction in progress for two phase commit.

If no transaction is in progress, this method raises an InvalidRequestError.

Only root transactions of two phase sessions can be prepared. If the current transaction is not such, an InvalidRequestError is raised.

def prune(self)

Remove unreferenced instances cached in the identity map.

Note that this method is only meaningful if "weak_identity_map" is set to False. The default weak identity map is self-pruning.

Removes any object in this Session's identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned.

def query(self, *entities, **kwargs)

Return a new `Query` object corresponding to this `Session`.

def refresh(self, instance, attribute_names=None)

Refresh the attributes on the given instance.

A query will be issued to the database and all attributes will be refreshed with their current database value.

Lazy-loaded relational attributes will remain lazily loaded, so that the instance-wide refresh operation will be followed immediately by the lazy load of that attribute.

Eagerly-loaded relational attributes will eagerly load within the single refresh operation.

The `attribute_names` argument is an iterable collection of attribute names indicating a subset of attributes to be refreshed.

def rollback(self)

Rollback the current transaction in progress.

If no transaction is in progress, this method is a pass-through.

This method rolls back the current transaction or nested transaction regardless of subtransactions being in effect. All subtrasactions up to the first real transaction are closed. Subtransactions occur when begin() is called mulitple times.

def save(*args, **kwargs)

Use session.add() Add a transient (unsaved) instance to this `Session`.

> This operation cascades the save_or_update method to associated instances if the relation is mapped with `cascade="save-update"`.

> The entity_name keyword argument will further qualify the specific `Mapper` used to handle this instance.

def scalar(self, clause, params=None, mapper=None, _state=None)

Like execute() but return a scalar result.

def update(*args, **kwargs)

Use session.add() Bring a detached (saved) instance into this `Session`.

> If there is a persistent instance with the same instance key, but different identity already associated with this `Session`, an InvalidRequestError exception is thrown.

> This operation cascades the save_or_update method to associated instances if the relation is mapped with `cascade="save-update"`.

def __contains__(self, instance)

Return True if the instance is associated with this session.

The instance may be pending or persistent within the Session for a result of True.

def __iter__(self)

Iterate over all pending or persistent instances within this Session.

back to section top

### class SessionExtension(object)

An extension hook object for Sessions. Subclasses may be installed into a Session (or sessionmaker) using the `extension` keyword argument.

def after_begin(self, session, transaction, connection)

Execute after a transaction is begun on a connection

transaction is the SessionTransaction. This method is called after an engine level transaction is begun on a connection.

def after_commit(self, session)

Execute after a commit has occured.

Note that this may not be per-flush if a longer running transaction is ongoing.

def after_flush(self, session, flush_context)

Execute after flush has completed, but before commit has been called.

Note that the session's state is still in pre-flush, i.e. 'new', 'dirty', and 'deleted' lists still show pre-flush state as well as the history settings on instance attributes.

def after_flush_postexec(self, session, flush_context)

Execute after flush has completed, and after the post-exec state occurs.

This will be when the 'new', 'dirty', and 'deleted' lists are in their final state. An actual commit() may or may not have occured, depending on whether or not the flush started its own transaction or participated in a larger transaction.

def after_rollback(self, session)

Execute after a rollback has occured.

Note that this may not be per-flush if a longer running transaction is ongoing.

def before_commit(self, session)

Execute right before commit is called.

Note that this may not be per-flush if a longer running transaction is ongoing.

def before_flush(self, session, flush_context, instances)

Execute before flush process has started.

instances is an optional list of objects which were passed to the `flush()` method.

back to section top