SQLAlchemy 0.4 Documentation - module sqlalchemy.orm.session

# SQLAlchemy 0.4 Documentation

Multiple Pages | One Page
Version: 0.4 Last Updated: 08/16/07 11:15:18

### module sqlalchemy.orm.session

### class Session(object)

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:

- 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 save() 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 `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.

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

Construct a new Session.

autoflush
  when `True`, all query operations will issue a `flush()` call to this `Session` before proceeding. This is a convenience feature so that `flush()` need not be called repeatedly in order for database queries to retrieve results. It's typical that `autoflush` is used in conjunction with `transactional=True`, so that `flush()` is never called; you just call `commit()` when changes are complete to finalize all changes to the database.
bind
  an optional `Engine` or `Connection` to which this `Session` should be bound. When specified, all SQL operations performed by this session will execute via this connectable.
binds

  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.

echo_uow
  When `True`, configure Python logging to dump all unit-of-work transactions. This is the equivalent of `logging.getLogger('sqlalchemy.orm.unitofwork').setLevel(logging.DEBUG)`.
extension
  an optional SessionExtension instance, which will receive pre- and post- commit and flush events, as well as a post-rollback event. User- defined code may be placed within these hooks using a user-defined subclass of `SessionExtension`.
transactional
  Set up this `Session` to automatically begin transactions. Setting this flag to `True` is the rough equivalent of calling `begin()` after each `commit()` operation, after each `rollback()`, and after each `close()`. Basically, this has the effect that all session operations are performed within the context of a transaction. Note that the `begin()` operation does not immediately utilize any connection resources; only when connection resources are first required do they get allocated into a transactional context.
twophase
  when `True`, all transactions will be started using [sqlalchemy.engine_TwoPhaseTransaction]. During a `commit()`, after `flush()` has been issued for all attached databaes, the `prepare()` method on each database's `TwoPhaseTransaction` will be called. This allows each database to roll back the entire transaction, before each transaction is committed.
weak_identity_map
  when `True`, use a `WeakValueDictionary` instead of a regular `dict` for this `Session` object's identity map. This will allow objects which fall out of scope to be automatically removed from the `Session`. However, objects who have been marked as "dirty" will also be garbage collected, and those changes will not be persisted.

def begin(self, **kwargs)

Begin a transaction on this Session.

def begin(self, **kwargs)

Begin a transaction on this Session.

def begin_nested(self)

begin a 'nested' transaction on this Session.

this utilizes a SAVEPOINT transaction for databases which support this feature.

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

Bind the given mapper or class to the given `Engine` or `Connection`.

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

def bind_table(self, table, bind)

Bind the given table to the given `Engine` or `Connection`.

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

def clear(self)

Remove all object instances from this `Session`.

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

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)

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.

def connection(self, mapper=None, **kwargs)

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, which some Engines override to return a thread-local connection, and will have close_with_result set to True.

The given **kwargs will be sent to the engine's `contextual_connect()` method, if no transaction is in progress.

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.

def delete(self, object)

Mark the given instance as deleted.

The delete operation occurs upon `flush()`.

deleted = property()

A `Set` of all objects marked as 'deleted' within this `Session`

dirty = property()

A `Set` of all objects marked as 'dirty' within this `Session`

echo_uow = property()
def execute(self, clause, params=None, mapper=None, **kwargs)

Using the given mapper to identify the appropriate `Engine` or `Connection` to be used for statement execution, execute the given `ClauseElement` using the provided parameter dictionary.

Return a `ResultProxy` corresponding to the execution's results.

If this method allocates a new `Connection` for the operation, then the `ResultProxy` 's `close()` method will release the resources of the underlying `Connection`.

def expire(self, obj)

Mark the given object as expired.

This will add an instrumentation to all mapped attributes on the instance such that when an attribute is next accessed, the session will reload all attributes on the instance from the database.

def expunge(self, object)

Remove the given object from this `Session`.

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

def flush(self, objects=None)

Flush all the object modifications present in this session to the database.

objects is a list or tuple of objects specifically to be flushed; if `None`, all new and modified objects are flushed.

def get(self, class_, ident, **kwargs)

Return an instance of the object based on the given identifier, or `None` if not found.

The ident argument is a scalar or tuple of primary key column values in the order of the table def's primary key columns.

The entity_name keyword argument may also be specified which further qualifies the underlying Mapper used to perform the query.

def get_bind(self, mapper, clause=None)
def has_key(self, key)

return True if the given identity key is present within this Session's identity map.

def identity_key(cls, *args, **kwargs)

Get an identity key.

Valid call signatures:

- `identity_key(class, ident, entity_name=None)`

  class

    mapped class (must be a positional argument)

  ident

    primary key, if the key is composite this is a tuple

  entity_name

    optional entity name

- `identity_key(instance=instance)`

  instance

    object instance (must be given as a keyword arg)

- `identity_key(class, row=row, entity_name=None)`

  class

    mapped class (must be a positional argument)

  row

    result proxy row (must be given as a keyword arg)

  entity_name

    optional entity name (must be given as a keyword arg)

identity_map = property()

A dictionary consisting of all objects within this `Session` keyed to their _instance_key value.

def import_instance(*args, **kwargs)

Deprecated. A synynom for `merge()`.

def is_expired(self, obj, unexpire=False)

Return True if the given object has been marked as expired.

def load(self, class_, ident, **kwargs)

Return an instance of the object based on the given identifier.

If not found, raises an exception. The method will remove all pending changes to the object already existing in the `Session`. The ident argument is a scalar or tuple of primary key columns in the order of the table def's primary key columns.

The entity_name keyword argument may also be specified which further qualifies the underlying `Mapper` used to perform the query.

def merge(self, object, entity_name=None, _recursive=None)

Copy the state of the given object onto the persistent object 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()

A `Set` of all objects marked as 'new' within this `Session`.

def object_session(cls, obj)

return the `Session` to which the given object belongs.

def query(self, mapper_or_class, *addtl_entities, **kwargs)

Return a new `Query` object corresponding to this `Session` and the mapper, or the classes' primary mapper.

def refresh(self, obj)

Reload the attributes for the given object from the database, clear any changes made.

def rollback(self)

rollback the current transaction in progress.

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

def save(self, object, entity_name=None)

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 save_or_update(self, object, entity_name=None)

Save or update the given object into this `Session`.

The presence of an _instance_key attribute on the instance determines whether to `save()` or `update()` the instance.

def scalar(self, clause, params=None, mapper=None, **kwargs)

Like execute() but return a scalar result.

sql = property()
def update(self, object, entity_name=None)

Bring the given detached (saved) instance into this `Session`.

If there is a persistent instance with the same identifier already associated with this `Session`, an 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, obj)

return True if the given object is associated with this session.

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

def __iter__(self)

return an iterator of all objects which are pending or persistent within this Session.

back to section top