class documentation

class Session(_SessionClassMethods):

Known subclasses: sqlalchemy.ext.horizontal_shard.ShardedSession

View In Hierarchy

Manages persistence operations for ORM-mapped objects.

The Session's usage paradigm is described at :doc:`/orm/session`.

Method __contains__ Return True if the instance is associated with this session.
Method __enter__ Undocumented
Method __exit__ Undocumented
Method __init__ Construct a new Session.
Method __iter__ Iterate over all pending or persistent instances within this Session.
Method ​_add​_bind Undocumented
Method ​_after​_attach Undocumented
Method ​_autobegin Undocumented
Method ​_autoflush Undocumented
Method ​_before​_attach Undocumented
Method ​_bulk​_save​_mappings Undocumented
Method ​_close​_impl Undocumented
Method ​_conditional​_expire Expire a state if persistent, else expunge if pending
Method ​_connection​_for​_bind Undocumented
Method ​_contains​_state Undocumented
Method ​_delete​_impl Undocumented
Method ​_expire​_state Undocumented
Method ​_expunge​_states Undocumented
Method ​_flush Undocumented
Method ​_flush​_warning Undocumented
Method ​_get​_impl Undocumented
Method ​_identity​_lookup Locate an object in the identity map.
Method ​_is​_clean Undocumented
Method ​_legacy​_transaction Undocumented
Method ​_maker​_context​_manager Undocumented
Method ​_merge Undocumented
Method ​_register​_altered Undocumented
Method ​_register​_persistent Register all persistent objects from a flush.
Method ​_remove​_newly​_deleted Undocumented
Method ​_save​_impl Undocumented
Method ​_save​_or​_update​_impl Undocumented
Method ​_save​_or​_update​_state Undocumented
Method ​_update​_impl Undocumented
Method ​_validate​_persistent Undocumented
Method add Place an object in the Session.
Method add​_all Add the given collection of instances to this Session.
Method begin Begin a transaction, or nested transaction, on this .Session, if one is not already begun.
Method begin​_nested Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
Method bind​_mapper Associate a _orm.Mapper or arbitrary Python class with a "bind", e.g. an _engine.Engine or _engine.Connection.
Method bind​_table Associate a _schema.Table with a "bind", e.g. an _engine.Engine or _engine.Connection.
Method bulk​_insert​_mappings Perform a bulk insert of the given list of mapping dictionaries.
Method bulk​_save​_objects Perform a bulk save of the given list of objects.
Method bulk​_update​_mappings Perform a bulk update of the given list of mapping dictionaries.
Method close Close out the transactional resources and ORM objects used by this _orm.Session.
Method commit Flush pending changes and commit the current transaction.
Method connection Return a _engine.Connection object corresponding to this .Session object's transactional state.
Method delete Mark an instance as deleted.
Method enable​_relationship​_loading Associate an object with this .Session for related object loading.
Method execute Execute a SQL expression construct.
Method expire Expire the attributes on an instance.
Method expire​_all Expires all persistent instances within this Session.
Method expunge Remove the instance from this Session.
Method expunge​_all Remove all object instances from this Session.
Method flush Flush all the object changes to the database.
Method get Return an instance based on the given primary key identifier, or None if not found.
Method get​_bind Return a "bind" to which this .Session is bound.
Method get​_nested​_transaction Return the current nested transaction in progress, if any.
Method get​_transaction Return the current root transaction in progress, if any.
Method in​_nested​_transaction Return True if this _orm.Session has begun a nested transaction, e.g. SAVEPOINT.
Method in​_transaction Return True if this _orm.Session has begun a transaction.
Method invalidate Close this Session, using connection invalidation.
Method is​_modified Return True if the given instance has locally modified attributes.
Method merge Copy the state of a given instance into a corresponding instance within this .Session.
Method prepare Prepare the current transaction in progress for two phase commit.
Method query Return a new _query.Query object corresponding to this _orm.Session.
Method refresh Expire and refresh attributes on the given instance.
Method rollback Rollback the current transaction in progress.
Method scalar Execute a statement and return a scalar result.
Method scalars Execute a statement and return the results as scalars.
Class Variable ​_is​_asyncio Undocumented
Class Variable ​_trans​_context​_manager Undocumented
Class Variable connection​_callable Undocumented
Instance Variable __binds Undocumented
Instance Variable ​_deleted Undocumented
Instance Variable ​_flushing Undocumented
Instance Variable ​_nested​_transaction Undocumented
Instance Variable ​_new Undocumented
Instance Variable ​_query​_cls Undocumented
Instance Variable ​_transaction Undocumented
Instance Variable ​_warn​_on​_events Undocumented
Instance Variable autocommit Undocumented
Instance Variable autoflush Undocumented
Instance Variable bind Undocumented
Instance Variable enable​_baked​_queries Undocumented
Instance Variable expire​_on​_commit Undocumented
Instance Variable future Undocumented
Instance Variable hash​_key Undocumented
Instance Variable identity​_map A mapping of object identities to objects themselves.
Instance Variable twophase Undocumented
Property ​_dirty​_states The set of all persistent states considered dirty.
Property deleted The set of all instances marked as 'deleted' within this Session
Property dirty The set of all persistent instances considered dirty.
Property info A user-modifiable dictionary.
Property is​_active True if this .Session not in "partial rollback" state.
Property new The set of all instances marked as 'new' within this Session.
Property no​_autoflush Return a context manager that disables autoflush.
Property transaction The current active or inactive .SessionTransaction.

Inherited from _SessionClassMethods:

Class Method close​_all Close all sessions in memory.
Class Method identity​_key Return an identity key.
Class Method object​_session Return the .Session to which an object belongs.
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 __enter__(self):

Undocumented

def __exit__(self, type_, value, traceback):

Undocumented

@util.deprecated_params(autocommit=('2.0', 'The :paramref:`.Session.autocommit` parameter is deprecated and will be removed in SQLAlchemy version 2.0. The :class:`_orm.Session` now features "autobegin" behavior such that the :meth:`.Session.begin` method may be called if a transaction has not yet been started yet. See the section :ref:`session_explicit_begin` for background.'))
def __init__(self, bind=None, autoflush=True, future=False, expire_on_commit=True, autocommit=False, twophase=False, binds=None, enable_baked_queries=True, info=None, query_cls=None):

Construct a new Session.

See also the .sessionmaker function which is used to generate a .Session-producing callable with a given set of arguments.

Parameters
bindAn optional _engine.Engine or _engine.Connection to which this Session should be bound. When specified, all SQL operations performed by this session will execute via this connectable.
autoflushWhen True, all query operations will issue a ~.Session.flush call to this Session before proceeding. This is a convenience feature so that ~.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 ~.Session.flush are rarely needed; you usually only need to call ~.Session.commit (which flushes) to finalize changes.
future

if True, use 2.0 style transactional and engine behavior. Future mode includes the following behaviors:

  • The _orm.Session will not use "bound" metadata in order to locate an _engine.Engine; the engine or engines in use must be specified to the constructor of _orm.Session or otherwise be configured against the _orm.sessionmaker in use
  • The "subtransactions" feature of _orm.Session.begin is removed in version 2.0 and is disabled when the future flag is set.
  • The behavior of the :paramref:`_orm.relationship.cascade_backrefs` flag on a _orm.relationship will always assume "False" behavior.
New in version 1.4.
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.

autocommitDefaults to False. When True, the .Session does not automatically begin transactions for individual statement executions, will acquire connections from the engine on an as-needed basis, releasing to the connection pool after each statement. 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 explicitly start transactions, but the usual "autobegin" behavior is not present.
twophaseWhen 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 ~.commit, after ~.flush has been issued for all attached databases, the ~.TwoPhaseTransaction.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.
binds

A dictionary which may specify any number of _engine.Engine or _engine.Connection objects as the source of connectivity for SQL operations on a per-entity basis. The keys of the dictionary consist of any series of mapped classes, arbitrary Python classes that are bases for mapped classes, _schema.Table objects and _orm.Mapper objects. The values of the dictionary are then instances of _engine.Engine or less commonly _engine.Connection objects. Operations which proceed relative to a particular mapped class will consult this dictionary for the closest matching entity in order to determine which _engine.Engine should be used for a particular SQL operation. The complete heuristics for resolution are described at .Session.get_bind. Usage looks like:

Session = sessionmaker(binds={
    SomeMappedClass: create_engine('postgresql://engine1'),
    SomeDeclarativeBase: create_engine('postgresql://engine2'),
    some_mapper: create_engine('postgresql://engine3'),
    some_table: create_engine('postgresql://engine4'),
    })

See Also

:ref:`session_partitioning`

.Session.bind_mapper

.Session.bind_table

.Session.get_bind

enable​_baked​_queries

defaults to True. A flag consumed by the sqlalchemy.ext.baked extension to determine if "baked queries" should be cached, as is the normal operation of this extension. When set to False, caching as used by this particular extension is disabled.

Changed in version 1.4: The sqlalchemy.ext.baked extension is legacy and is not used by any of SQLAlchemy's internals. This flag therefore only affects applications that are making explicit use of this extension within their own code.
infooptional dictionary of arbitrary data to be associated with this .Session. Is available via the .Session.info attribute. Note the dictionary is copied at construction time so that modifications to the per- .Session dictionary will be local to that .Session.
query​_clsClass which should be used to create new Query objects, as returned by the ~.Session.query method. Defaults to _query.Query.
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.
def __iter__(self):
Iterate over all pending or persistent instances within this Session.
def _add_bind(self, key, bind):

Undocumented

def _after_attach(self, state, obj):

Undocumented

def _autobegin(self):

Undocumented

def _autoflush(self):

Undocumented

def _before_attach(self, state, obj):

Undocumented

def _bulk_save_mappings(self, mapper, mappings, isupdate, isstates, return_defaults, update_changed_only, render_nulls):

Undocumented

def _close_impl(self, invalidate):

Undocumented

def _conditional_expire(self, state, autoflush=None):
Expire a state if persistent, else expunge if pending
def _connection_for_bind(self, engine, execution_options=None, **kw):

Undocumented

def _contains_state(self, state):

Undocumented

def _delete_impl(self, state, obj, head):

Undocumented

def _expire_state(self, state, attribute_names):

Undocumented

def _expunge_states(self, states, to_transient=False):

Undocumented

def _flush(self, objects=None):

Undocumented

def _flush_warning(self, method):

Undocumented

def _get_impl(self, entity, primary_key_identity, db_load_fn, options=None, populate_existing=False, with_for_update=None, identity_token=None, execution_options=None):

Undocumented

def _identity_lookup(self, mapper, primary_key_identity, identity_token=None, passive=attributes.PASSIVE_OFF, lazy_loaded_from=None):

Locate an object in the identity map.

Given a primary key identity, constructs an identity key and then looks in the session's identity map. If present, the object may be run through unexpiration rules (e.g. load unloaded attributes, check if was deleted).

e.g.:

obj = session._identity_lookup(inspect(SomeClass), (1, ))
Changed in version 1.4.0: - the .Session._identity_lookup method was moved from _query.Query to .Session, to avoid having to instantiate the _query.Query object.
Parameters
mappermapper in use
primary​_key​_identitythe primary key we are searching for, as a tuple.
identity​_tokenidentity token that should be used to create the identity key. Used as is, however overriding subclasses can repurpose this in order to interpret the value in a special way, such as if None then look among multiple target tokens.
passivepassive load flag passed to .loading.get_from_identity, which impacts the behavior if the object is found; the object may be validated and/or unexpired if the flag allows for SQL to be emitted.
lazy​_loaded​_froman .InstanceState that is specifically asking for this identity as a related identity. Used for sharding schemes where there is a correspondence between an object and a related object being lazy-loaded (or otherwise relationship-loaded).
Returns
None if the object is not found in the identity map, or if the object was unexpired and found to have been deleted. if passive flags disallow SQL and the object is expired, returns PASSIVE_NO_RESULT. In all other cases the instance is returned.
def _is_clean(self):

Undocumented

def _legacy_transaction(self):

Undocumented

@util.contextmanager
def _maker_context_manager(self):

Undocumented

def _merge(self, state, state_dict, load=True, options=None, _recursive=None, _resolve_conflict_map=None):

Undocumented

def _register_altered(self, states):

Undocumented

def _register_persistent(self, states):

Register all persistent objects from a flush.

This is used both for pending objects moving to the persistent state as well as already persistent objects.

def _remove_newly_deleted(self, states):

Undocumented

def _save_impl(self, state):

Undocumented

def _save_or_update_impl(self, state):

Undocumented

def _save_or_update_state(self, state):

Undocumented

def _update_impl(self, state, revert_deletion=False):

Undocumented

def _validate_persistent(self, state):

Undocumented

def add(self, instance, _warn=True):

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

def add_all(self, instances):
Add the given collection of instances to this Session.
@util.deprecated_params(subtransactions=('2.0', 'The :paramref:`_orm.Session.begin.subtransactions` flag is deprecated and will be removed in SQLAlchemy version 2.0. See the documentation at :ref:`session_subtransactions` for background on a compatible alternative pattern.'))
def begin(self, subtransactions=False, nested=False, _subtrans=False):

Begin a transaction, or nested transaction, on this .Session, if one is not already begun.

The _orm.Session object features autobegin behavior, so that normally it is not necessary to call the _orm.Session.begin method explicitly. However, it may be used in order to control the scope of when the transactional state is begun.

When used to begin the outermost transaction, an error is raised if this .Session is already inside of a transaction.

Parameters
subtransactionsif True, indicates that this ~.Session.begin can create a "subtransaction".
nestedif True, begins a SAVEPOINT transaction and is equivalent to calling ~.Session.begin_nested. For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`.
​_subtransUndocumented
Returns
the .SessionTransaction object. Note that .SessionTransaction acts as a Python context manager, allowing .Session.begin to be used in a "with" block. See :ref:`session_autocommit` for an example.
def begin_nested(self):

Begin a "nested" transaction on this Session, e.g. SAVEPOINT.

The target database(s) and associated drivers must support SQL SAVEPOINT for this method to function correctly.

For documentation on SAVEPOINT transactions, please see :ref:`session_begin_nested`.

See Also

:ref:`session_begin_nested`

:ref:`pysqlite_serializable` - special workarounds required with the SQLite driver in order for SAVEPOINT to work correctly.

Returns
the .SessionTransaction object. Note that .SessionTransaction acts as a context manager, allowing .Session.begin_nested to be used in a "with" block. See :ref:`session_begin_nested` for a usage example.
def bind_mapper(self, mapper, bind):

Associate a _orm.Mapper or arbitrary Python class with a "bind", e.g. an _engine.Engine or _engine.Connection.

The given entity is added to a lookup used by the .Session.get_bind method.

Parameters
mappera _orm.Mapper object, or an instance of a mapped class, or any Python class that is the base of a set of mapped classes.
bindan _engine.Engine or _engine.Connection object.
def bind_table(self, table, bind):

Associate a _schema.Table with a "bind", e.g. an _engine.Engine or _engine.Connection.

The given _schema.Table is added to a lookup used by the .Session.get_bind method.

Parameters
tablea _schema.Table object, which is typically the target of an ORM mapping, or is present within a selectable that is mapped.
bindan _engine.Engine or _engine.Connection object.
def bulk_insert_mappings(self, mapper, mappings, return_defaults=False, render_nulls=False):

Perform a bulk insert of the given list of mapping dictionaries.

The bulk insert feature allows plain Python dictionaries to be used as the source of simple INSERT operations which can be more easily grouped together into higher performing "executemany" operations. Using dictionaries, there is no "history" or session state management features in use, reducing latency when inserting large numbers of simple rows.

The values within the dictionaries as given are typically passed without modification into Core _expression.Insert constructs, after organizing the values within them across the tables to which the given mapper is mapped.

New in version 1.0.0.

Warning

The bulk insert feature allows for a lower-latency INSERT of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw INSERT of records.

Please note that newer versions of SQLAlchemy are greatly improving the efficiency of the standard flush process. It is strongly recommended to not use the bulk methods as they represent a forking of SQLAlchemy's functionality and are slowly being moved into legacy status. New features such as :ref:`orm_dml_returning_objects` are both more efficient than the "bulk" methods and provide more predictable functionality.

Please read the list of caveats at :ref:`bulk_operations_caveats` before using this method, and fully test and confirm the functionality of all code developed using these systems.

See Also

:ref:`bulk_operations`

.Session.bulk_save_objects

.Session.bulk_update_mappings

Parameters
mappera mapped class, or the actual _orm.Mapper object, representing the single kind of object represented within the mapping list.
mappingsa sequence of dictionaries, each one containing the state of the mapped row to be inserted, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary must contain all keys to be populated into all tables.
return​_defaultswhen True, rows that are missing values which generate defaults, namely integer primary key defaults and sequences, will be inserted one at a time, so that the primary key value is available. In particular this will allow joined-inheritance and other multi-table mappings to insert correctly without the need to provide primary key values ahead of time; however, :paramref:`.Session.bulk_insert_mappings.return_defaults` greatly reduces the performance gains of the method overall. If the rows to be inserted only refer to a single table, then there is no reason this flag should be set as the returned default information is not used.
render​_nulls

When True, a value of None will result in a NULL value being included in the INSERT statement, rather than the column being omitted from the INSERT. This allows all the rows being INSERTed to have the identical set of columns which allows the full set of rows to be batched to the DBAPI. Normally, each column-set that contains a different combination of NULL values than the previous row must omit a different series of columns from the rendered INSERT statement, which means it must be emitted as a separate statement. By passing this flag, the full set of rows are guaranteed to be batchable into one batch; the cost however is that server-side defaults which are invoked by an omitted column will be skipped, so care must be taken to ensure that these are not necessary.

Warning

When this flag is set, server side default SQL values will not be invoked for those columns that are inserted as NULL; the NULL value will be sent explicitly. Care must be taken to ensure that no server-side default functions need to be invoked for the operation as a whole.

New in version 1.1.
def bulk_save_objects(self, objects, return_defaults=False, update_changed_only=True, preserve_order=True):

Perform a bulk save of the given list of objects.

The bulk save feature allows mapped objects to be used as the source of simple INSERT and UPDATE operations which can be more easily grouped together into higher performing "executemany" operations; the extraction of data from the objects is also performed using a lower-latency process that ignores whether or not attributes have actually been modified in the case of UPDATEs, and also ignores SQL expressions.

The objects as given are not added to the session and no additional state is established on them. If the :paramref:`_orm.Session.bulk_save_objects.return_defaults` flag is set, then server-generated primary key values will be assigned to the returned objects, but not server side defaults; this is a limitation in the implementation. If stateful objects are desired, please use the standard _orm.Session.add_all approach or as an alternative newer mass-insert features such as :ref:`orm_dml_returning_objects`.

Warning

The bulk save feature allows for a lower-latency INSERT/UPDATE of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw INSERT/UPDATES of records.

Please note that newer versions of SQLAlchemy are greatly improving the efficiency of the standard flush process. It is strongly recommended to not use the bulk methods as they represent a forking of SQLAlchemy's functionality and are slowly being moved into legacy status. New features such as :ref:`orm_dml_returning_objects` are both more efficient than the "bulk" methods and provide more predictable functionality.

Please read the list of caveats at :ref:`bulk_operations_caveats` before using this method, and fully test and confirm the functionality of all code developed using these systems.

See Also

:ref:`bulk_operations`

.Session.bulk_insert_mappings

.Session.bulk_update_mappings

Parameters
objects

a sequence of mapped object instances. The mapped objects are persisted as is, and are not associated with the .Session afterwards.

For each object, whether the object is sent as an INSERT or an UPDATE is dependent on the same rules used by the .Session in traditional operation; if the object has the .InstanceState.key attribute set, then the object is assumed to be "detached" and will result in an UPDATE. Otherwise, an INSERT is used.

In the case of an UPDATE, statements are grouped based on which attributes have changed, and are thus to be the subject of each SET clause. If update_changed_only is False, then all attributes present within each object are applied to the UPDATE statement, which may help in allowing the statements to be grouped together into a larger executemany(), and will also reduce the overhead of checking history on attributes.

return​_defaultswhen True, rows that are missing values which generate defaults, namely integer primary key defaults and sequences, will be inserted one at a time, so that the primary key value is available. In particular this will allow joined-inheritance and other multi-table mappings to insert correctly without the need to provide primary key values ahead of time; however, :paramref:`.Session.bulk_save_objects.return_defaults` greatly reduces the performance gains of the method overall. It is strongly advised to please use the standard _orm.Session.add_all approach.
update​_changed​_onlywhen True, UPDATE statements are rendered based on those attributes in each state that have logged changes. When False, all attributes present are rendered into the SET clause with the exception of primary key attributes.
preserve​_order

when True, the order of inserts and updates matches exactly the order in which the objects are given. When False, common types of objects are grouped into inserts and updates, to allow for more batching opportunities.

New in version 1.3.
def bulk_update_mappings(self, mapper, mappings):

Perform a bulk update of the given list of mapping dictionaries.

The bulk update feature allows plain Python dictionaries to be used as the source of simple UPDATE operations which can be more easily grouped together into higher performing "executemany" operations. Using dictionaries, there is no "history" or session state management features in use, reducing latency when updating large numbers of simple rows.

New in version 1.0.0.

Warning

The bulk update feature allows for a lower-latency UPDATE of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw UPDATES of records.

Please note that newer versions of SQLAlchemy are greatly improving the efficiency of the standard flush process. It is strongly recommended to not use the bulk methods as they represent a forking of SQLAlchemy's functionality and are slowly being moved into legacy status. New features such as :ref:`orm_dml_returning_objects` are both more efficient than the "bulk" methods and provide more predictable functionality.

Please read the list of caveats at :ref:`bulk_operations_caveats` before using this method, and fully test and confirm the functionality of all code developed using these systems.

See Also

:ref:`bulk_operations`

.Session.bulk_insert_mappings

.Session.bulk_save_objects

Parameters
mappera mapped class, or the actual _orm.Mapper object, representing the single kind of object represented within the mapping list.
mappingsa sequence of dictionaries, each one containing the state of the mapped row to be updated, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary may contain keys corresponding to all tables. All those keys which are present and are not part of the primary key are applied to the SET clause of the UPDATE statement; the primary key values, which are required, are applied to the WHERE clause.
def close(self):

Close out the transactional resources and ORM objects used by this _orm.Session.

This expunges all ORM objects associated with this _orm.Session, ends any transaction in progress and :term:`releases` any _engine.Connection objects which this _orm.Session itself has checked out from associated _engine.Engine objects. The operation then leaves the _orm.Session in a state which it may be used again.

Tip

The _orm.Session.close method does not prevent the Session from being used again. The _orm.Session itself does not actually have a distinct "closed" state; it merely means the _orm.Session will release all database connections and ORM objects.

Changed in version 1.4: The .Session.close method does not immediately create a new .SessionTransaction object; instead, the new .SessionTransaction is created only if the .Session is used again for a database operation.

See Also

:ref:`session_closing` - detail on the semantics of _orm.Session.close

def commit(self):

Flush pending changes and commit the current transaction.

If no transaction is in progress, the method will first "autobegin" a new transaction and commit.

If :term:`1.x-style` use is in effect and there are currently SAVEPOINTs in progress via _orm.Session.begin_nested, the operation will release the current SAVEPOINT but not commit the outermost database transaction.

If :term:`2.0-style` use is in effect via the :paramref:`_orm.Session.future` flag, the outermost database transaction is committed unconditionally, automatically releasing any SAVEPOINTs in effect.

When using legacy "autocommit" mode, this method is only valid to call if a transaction is actually in progress, else an error is raised. Similarly, when using legacy "subtransactions", the method will instead close out the current "subtransaction", rather than the actual database transaction, if a transaction is in progress.

def connection(self, bind_arguments=None, close_with_result=False, execution_options=None, **kw):

Return a _engine.Connection object corresponding to this .Session object's transactional state.

If this .Session is configured with autocommit=False, either the _engine.Connection corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the _engine.Connection returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted).

Alternatively, if this .Session is configured with autocommit=True, an ad-hoc _engine.Connection is returned using _engine.Engine.connect on the underlying _engine.Engine.

Ambiguity in multi-bind or unbound .Session objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of the .get_bind method for resolution.

Parameters
bind​_argumentsdictionary of bind arguments. May include "mapper", "bind", "clause", other custom arguments that are passed to .Session.get_bind.
close​_with​_result

Passed to _engine.Engine.connect, indicating the _engine.Connection should be considered "single use", automatically closing when the first result set is closed. This flag only has an effect if this .Session is configured with autocommit=True and does not already have a transaction in progress.

Deprecated since version 1.4: this parameter is deprecated and will be removed in SQLAlchemy 2.0
execution​_options

a dictionary of execution options that will be passed to _engine.Connection.execution_options, when the connection is first procured only. If the connection is already present within the .Session, a warning is emitted and the arguments are ignored.

**kwdeprecated; use bind_arguments
binddeprecated; use bind_arguments
mapperdeprecated; use bind_arguments
clausedeprecated; use bind_arguments
def delete(self, instance):

Mark an instance as deleted.

The database delete operation occurs upon flush().

def enable_relationship_loading(self, obj):

Associate an object with this .Session for related object loading.

Warning

.enable_relationship_loading exists to serve special use cases and is not recommended for general use.

Accesses of attributes mapped with _orm.relationship will attempt to load a value from the database using this .Session as the source of connectivity. The values will be loaded based on foreign key and primary key values present on this object - if not present, then those relationships will be unavailable.

The object will be attached to this session, but will not participate in any persistence operations; its state for almost all purposes will remain either "transient" or "detached", except for the case of relationship loading.

Also note that backrefs will often not work as expected. Altering a relationship-bound attribute on the target object may not fire off a backref event, if the effective value is what was already loaded from a foreign-key-holding value.

The .Session.enable_relationship_loading method is similar to the load_on_pending flag on _orm.relationship. Unlike that flag, .Session.enable_relationship_loading allows an object to remain transient while still being able to load related items.

To make a transient object associated with a .Session via .Session.enable_relationship_loading pending, add it to the .Session using .Session.add normally. If the object instead represents an existing identity in the database, it should be merged using .Session.merge.

.Session.enable_relationship_loading does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before flush() proceeds. This method is not intended for general use.

See Also

:paramref:`_orm.relationship.load_on_pending` - this flag allows per-relationship loading of many-to-ones on items that are pending.

.make_transient_to_detached - allows for an object to be added to a .Session without SQL emitted, which then will unexpire attributes on access.

def execute(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, _parent_execute_state=None, _add_event=None, **kw):

Execute a SQL expression construct.

Returns a _engine.Result object representing results of the statement execution.

E.g.:

from sqlalchemy import select
result = session.execute(
    select(User).where(User.id == 5)
)

The API contract of _orm.Session.execute is similar to that of _future.Connection.execute, the :term:`2.0 style` version of _future.Connection.

Changed in version 1.4: the _orm.Session.execute method is now the primary point of ORM statement execution when using :term:`2.0 style` ORM usage.
Parameters
statementAn executable statement (i.e. an .Executable expression such as _expression.select).
paramsOptional dictionary, or list of dictionaries, containing bound parameter values. If a single dictionary, single-row execution occurs; if a list of dictionaries, an "executemany" will be invoked. The keys in each dictionary must correspond to parameter names present in the statement.
execution​_optionsoptional dictionary of execution options, which will be associated with the statement execution. This dictionary can provide a subset of the options that are accepted by _engine.Connection.execution_options, and may also provide additional options understood only in an ORM context.
bind​_argumentsdictionary of additional arguments to determine the bind. May include "mapper", "bind", or other custom arguments. Contents of this dictionary are passed to the .Session.get_bind method.
​_parent​_execute​_stateUndocumented
​_add​_eventUndocumented
**kwdeprecated; use the bind_arguments dictionary
mapperdeprecated; use the bind_arguments dictionary
binddeprecated; use the bind_arguments dictionary
Returns
a _engine.Result object.
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, a query will be issued to the .Session object's current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.

To expire all objects in the .Session simultaneously, use Session.expire_all.

The .Session object's default behavior is to expire all state whenever the Session.rollback or Session.commit methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.

See Also

:ref:`session_expire` - introductory material

.Session.expire

.Session.refresh

_orm.Query.populate_existing

Parameters
instanceThe instance to be refreshed.
attribute​_namesoptional list of string attribute names indicating a subset of attributes to be expired.
def expire_all(self):

Expires all persistent instances within this Session.

When any attributes on a persistent instance is next accessed, a query will be issued using the .Session object's current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.

To expire individual objects and individual attributes on those objects, use Session.expire.

The .Session object's default behavior is to expire all state whenever the Session.rollback or Session.commit methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire_all should not be needed when autocommit is False, assuming the transaction is isolated.

See Also

:ref:`session_expire` - introductory material

.Session.expire

.Session.refresh

_orm.Query.populate_existing

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 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, unless an error occurs, in which case the entire transaction is rolled back. 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 into the flush.

Parameters
objects

Optional; restricts the flush operation to operate only on elements that are in the given collection.

This feature is for an extremely narrow set of use cases where particular objects may need to be operated upon before the full flush() occurs. It is not intended for general use.

def get(self, entity, ident, options=None, populate_existing=False, with_for_update=None, identity_token=None, execution_options=None):

Return an instance based on the given primary key identifier, or None if not found.

E.g.:

my_user = session.get(User, 5)

some_object = session.get(VersionedFoo, (5, 10))

some_object = session.get(
    VersionedFoo,
    {"id": 5, "version_id": 10}
)
New in version 1.4: Added _orm.Session.get, which is moved from the now deprecated _orm.Query.get method.

_orm.Session.get is special in that it provides direct access to the identity map of the .Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

_orm.Session.get also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, ~sqlalchemy.orm.exc.ObjectDeletedError is raised.

Parameters
entitya mapped class or .Mapper indicating the type of entity to be loaded.
ident

A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed.

For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value "5", the call looks like:

my_object = session.get(SomeClass, 5)

The tuple form contains primary key values typically in the order in which they correspond to the mapped _schema.Table object's primary key columns, or if the :paramref:`_orm.Mapper.primary_key` configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits "5, 10" the call would look like:

my_object = session.get(SomeClass, (5, 10))

The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes id, version_id as the attributes which store the object's primary key value, the call would look like:

my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
optionsoptional sequence of loader options which will be applied to the query, if one is emitted.
populate​_existingcauses the method to unconditionally emit a SQL query and refresh the object with the newly loaded data, regardless of whether or not the object is already present.
with​_for​_updateoptional boolean True indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of _query.Query.with_for_update. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
identity​_tokenUndocumented
execution​_options

optional dictionary of execution options, which will be associated with the query execution if one is emitted. This dictionary can provide a subset of the options that are accepted by _engine.Connection.execution_options, and may also provide additional options understood only in an ORM context.

New in version 1.4.29.

See Also

:ref:`orm_queryguide_execution_options` - ORM-specific execution options

Returns
The object instance, or None.
def get_bind(self, mapper=None, clause=None, bind=None, _sa_skip_events=None, _sa_skip_for_implicit_returning=False):

Return a "bind" to which this .Session is bound.

The "bind" is usually an instance of _engine.Engine, except in the case where the .Session has been explicitly bound directly to a _engine.Connection.

For a multiply-bound or unbound .Session, the mapper or clause arguments are used to determine the appropriate bind to return.

Note that the "mapper" argument is usually present when .Session.get_bind is called via an ORM operation such as a .Session.query, each individual INSERT/UPDATE/DELETE operation within a .Session.flush, call, etc.

The order of resolution is:

  1. if mapper given and :paramref:`.Session.binds` is present, locate a bind based first on the mapper in use, then on the mapped class in use, then on any base classes that are present in the __mro__ of the mapped class, from more specific superclasses to more general.
  2. if clause given and Session.binds is present, locate a bind based on _schema.Table objects found in the given clause present in Session.binds.
  3. if Session.binds is present, return that.
  4. if clause given, attempt to return a bind linked to the _schema.MetaData ultimately associated with the clause.
  5. if mapper given, attempt to return a bind linked to the _schema.MetaData ultimately associated with the _schema.Table or other selectable to which the mapper is mapped.
  6. No bind can be found, ~sqlalchemy.exc.UnboundExecutionError is raised.

Note that the .Session.get_bind method can be overridden on a user-defined subclass of .Session to provide any kind of bind resolution scheme. See the example at :ref:`session_custom_partitioning`.

See Also

:ref:`session_partitioning`

:paramref:`.Session.binds`

.Session.bind_mapper

.Session.bind_table

Parameters
mapperOptional .mapper mapped class or instance of _orm.Mapper. The bind can be derived from a _orm.Mapper first by consulting the "binds" map associated with this .Session, and secondly by consulting the _schema.MetaData associated with the _schema.Table to which the _orm.Mapper is mapped for a bind.
clauseA _expression.ClauseElement (i.e. _expression.select, _expression.text, etc.). If the mapper argument is not present or could not produce a bind, the given expression construct will be searched for a bound element, typically a _schema.Table associated with bound _schema.MetaData.
bindUndocumented
​_sa​_skip​_eventsUndocumented
​_sa​_skip​_for​_implicit​_returningUndocumented
def get_nested_transaction(self):

Return the current nested transaction in progress, if any.

New in version 1.4.
def get_transaction(self):

Return the current root transaction in progress, if any.

New in version 1.4.
def in_nested_transaction(self):

Return True if this _orm.Session has begun a nested transaction, e.g. SAVEPOINT.

New in version 1.4.
def in_transaction(self):

Return True if this _orm.Session has begun a transaction.

New in version 1.4.

See Also

_orm.Session.is_active

def invalidate(self):

Close this Session, using connection invalidation.

This is a variant of .Session.close that will additionally ensure that the _engine.Connection.invalidate method will be called on each _engine.Connection object that is currently in use for a transaction (typically there is only one connection unless the _orm.Session is used with multiple engines).

This can be called when the database is known to be in a state where the connections are no longer safe to be used.

Below illustrates a scenario when using gevent, which can produce Timeout exceptions that may mean the underlying connection should be discarded:

import gevent

try:
    sess = Session()
    sess.add(User())
    sess.commit()
except gevent.Timeout:
    sess.invalidate()
    raise
except:
    sess.rollback()
    raise

The method additionally does everything that _orm.Session.close does, including that all ORM objects are expunged.

def is_modified(self, instance, include_collections=True):

Return True if the given instance has locally modified attributes.

This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any.

It is in effect a more expensive and accurate version of checking for the given instance in the .Session.dirty collection; a full test for each attribute's net "dirty" status is performed.

E.g.:

return session.is_modified(someobject)

A few caveats to this method apply:

  • Instances present in the .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 .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 cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the "old" value when a set event occurs, so it skips the expense of a SQL call if the old value isn't present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn't, is less expensive on average than issuing a defensive SELECT.

    The "old" value is fetched unconditionally upon set only if the attribute container has the active_history flag set to True. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use the active_history argument with .column_property.

Parameters
instancemapped instance to be tested for pending changes.
include​_collectionsIndicates 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.
def merge(self, instance, load=True, options=None):

Copy the state of a given instance into a corresponding instance within this .Session.

.Session.merge examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the 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 .Session if not already.

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

See :ref:`unitofwork_merging` for a detailed discussion of merging.

Changed in version 1.1: - .Session.merge will now reconcile pending objects with overlapping primary keys in the same way as persistent. See :ref:`change_3601` for discussion.

See Also

.make_transient_to_detached - provides for an alternative means of "merging" a single object into the .Session

Parameters
instanceInstance to be merged.
load

Boolean, when False, .merge switches into a "high performance" mode which causes it to forego emitting history events as well as all database access. This flag is used for cases such as transferring graphs of objects into a .Session from a second level cache, or to transfer just-loaded objects into the .Session owned by a worker thread or process without re-querying the database.

The load=False use case adds the caveat that the given object has to be in a "clean" state, that is, has no pending changes to be flushed - even if the incoming object is detached from any .Session. This is so that when the merge operation populates local attributes and cascades to related objects and collections, the values can be "stamped" onto the target object as is, without generating any history or attribute events, and without the need to reconcile the incoming data with 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.

options

optional sequence of loader options which will be applied to the _orm.Session.get method when the merge operation loads the existing version of the object from the database.

New in version 1.4.24.
def prepare(self):

Prepare the current transaction in progress for two phase commit.

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

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

def query(self, *entities, **kwargs):
Return a new _query.Query object corresponding to this _orm.Session.
def refresh(self, instance, attribute_names=None, with_for_update=None):

Expire and refresh attributes on the given instance.

The selected attributes will first be expired as they would when using _orm.Session.expire; then a SELECT statement will be issued to the database to refresh column-oriented attributes with the current value available in the current transaction.

_orm.relationship oriented attributes will also be immediately loaded if they were already eagerly loaded on the object, using the same eager loading strategy that they were loaded with originally. Unloaded relationship attributes will remain unloaded, as will relationship attributes that were originally lazy loaded.

New in version 1.4: - the _orm.Session.refresh method can also refresh eagerly loaded attributes.

Tip

While the _orm.Session.refresh method is capable of refreshing both column and relationship oriented attributes, its primary focus is on refreshing of local column-oriented attributes on a single instance. For more open ended "refresh" functionality, including the ability to refresh the attributes on many objects at once while having explicit control over relationship loader strategies, use the :ref:`populate existing <orm_queryguide_populate_existing>` feature instead.

Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. Refreshing attributes usually only makes sense at the start of a transaction where database rows have not yet been accessed.

See Also

:ref:`session_expire` - introductory material

.Session.expire

.Session.expire_all

:ref:`orm_queryguide_populate_existing` - allows any ORM query to refresh objects as they would be loaded normally.

Parameters
instanceUndocumented
attribute​_namesoptional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.
with​_for​_updateoptional boolean True indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of _query.Query.with_for_update. Supersedes the :paramref:`.Session.refresh.lockmode` parameter.
def rollback(self):

Rollback the current transaction in progress.

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

In :term:`1.x-style` use, this method rolls back the topmost database transaction if no nested transactions are in effect, or to the current nested transaction if one is in effect.

When :term:`2.0-style` use is in effect via the :paramref:`_orm.Session.future` flag, the method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress.

def scalar(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return a scalar result.

Usage and parameters are the same as that of _orm.Session.execute; the return result is a scalar Python value.

def scalars(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return the results as scalars.

Usage and parameters are the same as that of _orm.Session.execute; the return result is a _result.ScalarResult filtering object which will return single elements rather than _row.Row objects.

New in version 1.4.24.
Returns
a _result.ScalarResult object
_is_asyncio: bool =

Undocumented

_trans_context_manager =

Undocumented

connection_callable =
__binds: dict =
_deleted: dict =

Undocumented

_flushing: bool =

Undocumented

_nested_transaction =

Undocumented

_new: dict =

Undocumented

_query_cls =

Undocumented

_transaction =

Undocumented

_warn_on_events: bool =

Undocumented

autocommit: bool =

Undocumented

autoflush =

Undocumented

bind =

Undocumented

enable_baked_queries =

Undocumented

expire_on_commit =

Undocumented

future =

Undocumented

hash_key =

Undocumented

identity_map =

A mapping of object identities to objects themselves.

Iterating through Session.identity_map.values() provides access to the full set of persistent objects (i.e., those that have row identity) currently in the session.

See Also

.identity_key - helper function to produce the keys used in this dictionary.

twophase =

Undocumented

@property
_dirty_states =

The set of all persistent states considered dirty.

This method returns all states that were modified including those that were possibly deleted.

@property
deleted =
The set of all instances marked as 'deleted' within this Session
@property
dirty =

The set of all persistent instances considered dirty.

E.g.:

some_mapped_object in session.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 .Session.is_modified method.

A user-modifiable dictionary.

The initial value of this dictionary can be populated using the info argument to the .Session constructor or .sessionmaker constructor or factory methods. The dictionary here is always local to this .Session and can be modified independently of all other .Session objects.

@property
is_active =

True if this .Session not in "partial rollback" state.

Changed in version 1.4: The _orm.Session no longer begins a new transaction immediately, so this attribute will be False when the _orm.Session is first instantiated.

"partial rollback" state typically indicates that the flush process of the _orm.Session has failed, and that the _orm.Session.rollback method must be emitted in order to fully roll back the transaction.

If this _orm.Session is not in a transaction at all, the _orm.Session will autobegin when it is first used, so in this case _orm.Session.is_active will return True.

Otherwise, if this _orm.Session is within a transaction, and that transaction has not been rolled back internally, the _orm.Session.is_active will also return True.

See Also

:ref:`faq_session_rollback`

_orm.Session.in_transaction

@property
new =
The set of all instances marked as 'new' within this Session.
@property
@util.contextmanager
no_autoflush =

Return a context manager that disables autoflush.

e.g.:

with session.no_autoflush:

    some_object = SomeClass()
    session.add(some_object)
    # won't autoflush
    some_object.related_thing = session.query(SomeRelated).first()

Operations that proceed within the with: block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed.

@property
@util.deprecated_20(':attr:`_orm.Session.transaction`', alternative='For context manager use, use :meth:`_orm.Session.begin`. To access the current root transaction, use :meth:`_orm.Session.get_transaction`.', warn_on_attribute_access=True)
transaction =

The current active or inactive .SessionTransaction.

May be None if no transaction has begun yet.

Changed in version 1.4: the .Session.transaction attribute is now a read-only descriptor that also may return None if no transaction has begun yet.