Provides the Session class and related utilities.
Encapsulates a set of objects being operated upon within an object-relational operation.
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:
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:
The session methods which control instance state include save(), update(), save_or_update(), delete(), merge(), and expunge().
The Session object is not threadsafe, particularly during flush operations. A session which is only read from (i.e. is never flushed) can 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.
Construct a new Session.
A session is usually constructed using the create_session() function, or its more "automated" variant sessionmaker().
An optional dictionary, which contains more granular "bind" information than the bind parameter provides. This dictionary can map individual Table instances as well as Mapper instances to individual Engine or Connection objects. Operations which proceed relative to a particular Mapper will consult this dictionary for the direct Mapper instance as well as the mapper's mapped_table attribute in order to locate an connectable to use. The full resolution is described in the get_bind() method of Session. Usage looks like:
sess = Session(binds={ SomeMappedClass : create_engine('postgres://engine1'), somemapper : create_engine('postgres://engine2'), some_table : create_engine('postgres://engine3'), })
Also see the bind_mapper() and bind_table() methods.
Add the given instance into this Session.
This provides forwards compatibility with 0.5.
Add the given collection of instances to this Session.
This provides forwards compatibility with 0.5.
Begin a nested transaction on this Session.
This utilizes a SAVEPOINT transaction for databases which support this feature.
Bind the given mapper or class to the given Engine or Connection.
All subsequent operations involving this Mapper will use the given bind.
Bind the given table to the given Engine or Connection.
All subsequent operations involving this Table will use the given bind.
Remove all object instances from this Session.
This is equivalent to calling expunge() for all objects in this Session.
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.
Commit the current transaction in progress.
If no transaction is in progress, this method raises an InvalidRequestError.
If the begin() method was called on this Session additional times subsequent to its first call, commit() will not actually commit, and instead pops an internal SessionTransaction off its internal stack of transactions. Only when the "root" SessionTransaction is reached does an actual database-level commit occur.
Return a Connection corresponding to this session's transactional context, if any.
If this Session is transactional, the connection will be in the context of this session's transaction. Otherwise, the connection is returned by the contextual_connect() method on the engine.
The mapper argument is a class or mapper to which a bound engine will be located; use this when the Session itself is either bound to multiple engines or connections, or is not bound to any connectable.
**kwargs are additional arguments which will be passed to get_bind(). See the get_bind() method for details. Note that the ShardedSession subclass takes a different get_bind() argument signature.
Mark the given instance as deleted.
The delete operation occurs upon flush().
Return a Set of all instances marked as 'dirty' within this Session.
Note that the 'dirty' state here 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.
Execute the given clause, using the current transaction (if any).
Returns a ResultProxy corresponding to the execution's results.
Expire the attributes on the given instance.
The instance's attributes are instrumented such that when an attribute is next accessed, a query will be issued to the database which will refresh all attributes with their current value.
The attribute_names argument is an iterable collection of attribute names indicating a subset of attributes to be expired.
Remove the given instance from this Session.
This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.
Flush all the object modifications present in this session to the database.
objects is a collection or iterator of objects specifically to be flushed; if None, all new and modified objects are flushed.
Return an instance of the object based on the given identifier, or None if not found.
DEPRECATED. use session.query(class_).get(ident)
Return an engine corresponding to the given arguments.
Get an identity key.
Valid call signatures:
identity_key(class, ident, entity_name=None)
mapped class (must be a positional argument)
primary key, if the key is composite this is a tuple
optional entity name
identity_key(instance=instance)
object instance (must be given as a keyword arg)
identity_key(class, row=row, entity_name=None)
mapped class (must be a positional argument)
result proxy row (must be given as a keyword arg)
optional entity name (must be given as a keyword arg)
Return True if the given 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.
Return an instance of the object based on the given identifier.
DEPRECATED. use session.query(class_).populate_existing().get(ident).
Copy the state of the given 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".
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.
Remove unreferenced instances cached in the identity map.
Note that this method is only meaningful if "weak_identity_map" is set to False.
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.
Return a new Query object corresponding to this Session and the mapper, or the classes' primary mapper.
Refresh the attributes on the given instance.
When called, a query will be issued to the database which will refresh all attributes with their current 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.
Rollback the current transaction in progress.
If no transaction is in progress, this method is a pass-thru.
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.
Save or update the given instance into this Session.
The presence of an _instance_key attribute on the instance determines whether to save() or update() the instance.
Like execute() but return a scalar result.
Bring the given 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".
Return True if the given instance is associated with this session.
The instance may be pending or persistent within the Session for a result of True.
Return an iterator of all instances which are pending or persistent within this Session.
An extension hook object for Sessions. Subclasses may be installed into a Session (or sessionmaker) using the extension keyword argument.
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.
Execute after a commit has occured.
Note that this may not be per-flush if a longer running transaction is ongoing.
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.
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.
Execute after a rollback has occured.
Note that this may not be per-flush if a longer running transaction is ongoing.
Execute right before commit is called.
Note that this may not be per-flush if a longer running transaction is ongoing.
Execute before flush process has started.
instances is an optional list of objects which were passed to the flush() method.