# SQLAlchemy 0.6.3 Documentation

Search:
Version: 0.6.3 Last Updated: 07/15/2010 12:35:47

# Sessions

`sqlalchemy.orm.``create_session`(bind=None, **kwargs)

  Create a new `Session`.

  Parameters: | bind – optional, a single Connectable to use for all database access in the created `Session`. **kwargs – optional, passed through to the `Session` constructor.
  Returns: | an `Session` instance

  The defaults of create_session() are the opposite of that of `sessionmaker()`; `autoflush` and `expire_on_commit` are False, `autocommit` is True. In this sense the session acts more like the “classic” SQLAlchemy 0.3 session with these.

  Usage:

      >>> from sqlalchemy.orm import create_session
      >>> session = create_session()

  It is recommended to use `sessionmaker()` instead of create_session().

`sqlalchemy.orm.``make_transient`(instance)

  Make the given instance ‘transient’.

  This will remove its association with any session and additionally will remove its “identity key”, such that it’s as though the object were newly constructed, except retaining its values.

  Attributes which were “expired” or deferred at the instance level are reverted to undefined, and will not trigger any loads.

`sqlalchemy.orm.``scoped_session`(session_factory, scopefunc=None)

  Provides thread-local management of Sessions.

  This is a front-end function to `ScopedSession`.

  Parameters: | session_factory – a callable function that produces `Session` instances, such as `sessionmaker()` or `create_session()`. scopefunc – optional, TODO
  Returns: | an `ScopedSession` instance

  Usage:

      Session = scoped_session(sessionmaker(autoflush=True))

  To instantiate a Session object which is part of the scoped context, instantiate normally:

      session = Session()

  Most session methods are available as classmethods from the scoped session:

      Session.commit()
      Session.close()

`sqlalchemy.orm.``sessionmaker`(bind=None, class_=None, autoflush=True, autocommit=False, expire_on_commit=True, **kwargs)

  Generate a custom-configured `Session` class.

  The returned object is a subclass of `Session`, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments.

  It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.

  e.g.:

      # global scope
      Session = sessionmaker(autoflush=False)

      # later, in a local scope, create and use a session:
      sess = Session()

  Any keyword arguments sent to the constructor itself will override the “configured” keywords:

      Session = sessionmaker()

      # bind an individual session to a connection
      sess = Session(bind=connection)

  The class also includes a special classmethod `configure()`, which allows additional configurational options to take place after the custom `Session` class has been generated. This is useful particularly for defining the specific `Engine` (or engines) to which new instances of `Session` should be bound:

      Session = sessionmaker()
      Session.configure(bind=create_engine('sqlite:///foo.db'))

      sess = Session()

  Options:

  -   Parameters: | autocommit – Defaults to `False`. When `True`, the `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 session.begin() method may be used to begin a transaction explicitly. Leaving it on its default value of `False` means that the `Session` will acquire a connection and begin a transaction the first time it is used, which it will maintain persistently until `rollback()`, `commit()`, or `close()` is called. When the transaction is released by any of these methods, the `Session` is ready for the next usage, which will again acquire and maintain a new connection/transaction. 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 `autocommit=False`. In this scenario, explicit calls to `flush()` are rarely needed; you usually only need to call `commit()` (which flushes) to finalize changes. 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('postgresql://engine1'),
              somemapper: create_engine('postgresql://engine2'),
              some_table: create_engine('postgresql://engine3'),
              })
  Also see the `bind_mapper()` and `bind_table()` methods. class_ – Specify an alternate class other than `sqlalchemy.orm.session.Session` which should be used by the returned class. This is the only argument that is local to the `sessionmaker()` function, and is not sent directly to the constructor for `Session`. _enable_transaction_accounting – Defaults to `True`. A 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 begin(), all of which are interdependent. expire_on_commit – Defaults to `True`. When `True`, all instances will be fully expired after each `commit()`, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state. extension – An optional `SessionExtension` instance, or a list of such instances, 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`. query_cls – Class which should be used to create new Query objects, as returned by the `query()` method. Defaults to `Query`. twophase – When `True`, all transactions will be started using `engine_TwoPhaseTransaction`. During a `commit()`, after `flush()` has been issued for all attached databases, 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 set to the default value of `True`, a weak-referencing map is used; instances which are not externally referenced will be garbage collected immediately. For dereferenced instances which have pending changes present, the attribute management system will create a temporary strong-reference to the object which lasts until the changes are flushed to the database, at which point it’s again dereferenced. Alternatively, when using the value `False`, the identity map uses a regular Python dictionary to store instances. The session will maintain all instances present until they are removed using expunge(), clear(), or purge().

class `sqlalchemy.orm.session.``Session`(bind=None, autoflush=True, expire_on_commit=True, _enable_transaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=True, binds=None, extension=None, query_cls=<class 'sqlalchemy.orm.query.Query'>)

  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.

  `__init__`(bind=None, autoflush=True, expire_on_commit=True, _enable_transaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=True, binds=None, extension=None, query_cls=<class 'sqlalchemy.orm.query.Query'>)

    Construct a new Session.

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

  `add`(instance)

    Place an object in the `Session`.

    Its state will be persisted to the database on the next flush operation.

    Repeated calls to `add()` will be ignored. The opposite of `add()` is `expunge()`.

  `add_all`(instances)

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

  `begin`(subtransactions=False, nested=False)

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

  `begin_nested`()

    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.

  `bind_mapper`(mapper, bind)

    Bind operations for a mapper to a Connectable.

    mapper
      A mapper instance or mapped class
    bind
      Any Connectable: a `Engine` or `Connection`.

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

  `bind_table`(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.

  `close`()

    Close this Session.

    This clears all items and ends any transaction in progress.

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

  classmethod `close_all`()

    Close all sessions in memory.

  `commit`()

    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.

  `connection`(mapper=None, clause=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`
  `delete`(instance)

    Mark an instance as deleted.

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

  `deleted`

    The set of all instances marked as ‘deleted’ within this `Session`

  `dirty`

    The 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.

  `execute`(clause, params=None, mapper=None, **kw)

    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
    **kw
      Additional keyword arguments are sent to `get_bind()` which locates a connectable to use for the execution. Subclasses of `Session` may override this.
  `expire`(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.

  `expire_all`()

    Expires all persistent instances within this Session.

  `expunge`(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.

  `expunge_all`()

    Remove all object instances from this `Session`.

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

  `flush`(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. Deprecated - this flag prevents the session from properly maintaining accounting among inter-object relations and can cause invalid results.
  `get_bind`(mapper, clause=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.)
  `is_active`

    True if this Session has an active transaction.

  `is_modified`(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.

  `merge`(instance, load=True, **kw)

    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`

    The set of all instances marked as ‘new’ within this `Session`.

  classmethod `object_session`(instance)

    Return the `Session` to which an object belongs.

  `prepare`()

    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.

  `prune`()

    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.

  `query`(*entities, **kwargs)

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

  `refresh`(instance, attribute_names=None, lockmode=None)

    Expire and 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.

    Parameters: | attribute_names – optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed. lockmode – Passed to the `Query` as used by `with_lockmode()`.

  `rollback`()

    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 subtransactions up to the first real transaction are closed. Subtransactions occur when begin() is called multiple times.

  `scalar`(clause, params=None, mapper=None, **kw)

    Like execute() but return a scalar result.

class `sqlalchemy.orm.scoping.``ScopedSession`(session_factory, scopefunc=None)

  Provides thread-local management of Sessions.

  Usage:

      Session = scoped_session(sessionmaker(autoflush=True))

      ... use session normally.

  `__init__`(session_factory, scopefunc=None)
  `configure`(**kwargs)

    reconfigure the sessionmaker used by this ScopedSession.

  `mapper`(*args, **kwargs)

    return a mapper() function which associates this ScopedSession with the Mapper.

    Session.mapper is deprecated. Please see http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper for information on how to replicate its behavior.

    DEPRECATED.

  `query_property`(query_cls=None)

    return a class property which produces a Query object against the class when called.

    e.g.::

      Session = scoped_session(sessionmaker())

      class MyClass(object):
        query = Session.query_property()

      # after mappers are defined result = MyClass.query.filter(MyClass.name==’foo’).all()

    Produces instances of the session’s configured query class by default. To override and use a custom implementation, provide a `query_cls` callable. The callable will be invoked with the class’s mapper as a positional argument and a session keyword argument.

    There is no limit to the number of query properties placed on a class.

  `remove`()

    Dispose of the current contextual session.