Session API
Session and sessionmaker()
Object Name | Description |
---|---|
Represents a call to the | |
Manages persistence operations for ORM-mapped objects. | |
A configurable | |
A |
class sqlalchemy.orm.``sessionmaker
(bind=None, class_=<class ‘sqlalchemy.orm.session.Session’>, autoflush=True, autocommit=False, expire_on_commit=True, info=None, \*kw*)
A configurable Session
factory.
The sessionmaker
factory generates new Session
objects when called, creating them given the configurational arguments established here.
e.g.:
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
# an Engine, which the Session will use for connection
# resources
engine = create_engine('postgresql://scott:tiger@localhost/')
Session = sessionmaker(engine)
with Session() as session:
session.add(some_object)
session.add(some_other_object)
session.commit()
Context manager use is optional; otherwise, the returned Session
object may be closed explicitly via the Session.close()
method. Using a try:/finally:
block is optional, however will ensure that the close takes place even if there are database errors:
session = Session()
try:
session.add(some_object)
session.add(some_other_object)
session.commit()
finally:
session.close()
sessionmaker
acts as a factory for Session
objects in the same way as an Engine
acts as a factory for Connection
objects. In this way it also includes a sessionmaker.begin()
method, that provides a context manager which both begins and commits a transaction, as well as closes out the Session
when complete, rolling back the transaction if any errors occur:
Session = sessionmaker(engine)
with Session.begin() as session:
session.add(some_object)
session.add(some_other_object)
# commits transaction, closes session
New in version 1.4.
When calling upon sessionmaker
to construct a Session
, keyword arguments may also be passed to the method; these arguments will override that of the globally configured parameters. Below we use a sessionmaker
bound to a certain Engine
to produce a Session
that is instead bound to a specific Connection
procured from that engine:
Session = sessionmaker(engine)
# bind an individual session to a connection
with engine.connect() as connection:
with Session(bind=connection) as session:
# work with session
The class also includes a method sessionmaker.configure()
, which can be used to specify additional keyword arguments to the factory, which will take effect for subsequent Session
objects generated. This is usually used to associate one or more Engine
objects with an existing sessionmaker
factory before it is first used:
# application starts, sessionmaker does not have
# an engine bound yet
Session = sessionmaker()
# ... later, when an engine URL is read from a configuration
# file or other events allow the engine to be created
engine = create_engine('sqlite:///foo.db')
Session.configure(bind=engine)
sess = Session()
# work with session
See also
Opening and Closing a Session - introductory text on creating sessions using sessionmaker
.
Class signature
class sqlalchemy.orm.sessionmaker
(sqlalchemy.orm.session._SessionClassMethods
)
method
sqlalchemy.orm.sessionmaker.
__call__
(\*local_kw*)Produce a new
Session
object using the configuration established in thissessionmaker
.In Python, the
__call__
method is invoked on an object when it is “called” in the same way as a function:Session = sessionmaker()
session = Session() # invokes sessionmaker.__call__()
method
sqlalchemy.orm.sessionmaker.
__init__
(bind=None, class_=<class ‘sqlalchemy.orm.session.Session’>, autoflush=True, autocommit=False, expire_on_commit=True, info=None, \*kw*)Construct a new
sessionmaker
.All arguments here except for
class_
correspond to arguments accepted bySession
directly. See theSession.__init__()
docstring for more details on parameters.Parameters
bind – a
Engine
or otherConnectable
with which newly createdSession
objects will be associated.class_ – class to use in order to create new
Session
objects. Defaults toSession
.autoflush – The autoflush setting to use with newly created
Session
objects.autocommit – The autocommit setting to use with newly created
Session
objects.expire_on_commit=True – the
Session.expire_on_commit
setting to use with newly createdSession
objects.info – optional dictionary of information that will be available via
Session.info
. Note this dictionary is updated, not replaced, when theinfo
parameter is specified to the specificSession
construction operation.**kw – all other keyword arguments are passed to the constructor of newly created
Session
objects.
method
sqlalchemy.orm.sessionmaker.
begin
()Produce a context manager that both provides a new
Session
as well as a transaction that commits.e.g.:
Session = sessionmaker(some_engine)
with Session.begin() as session:
session.add(some_object)
# commits transaction, closes session
New in version 1.4.
method
sqlalchemy.orm.sessionmaker.
classmethodclose_all
()inherited from the
sqlalchemy.orm.session._SessionClassMethods.close_all
method ofsqlalchemy.orm.session._SessionClassMethods
Close all sessions in memory.
Deprecated since version 1.3: The
Session.close_all()
method is deprecated and will be removed in a future release. Please refer toclose_all_sessions()
.method
sqlalchemy.orm.sessionmaker.
configure
(\*new_kw*)(Re)configure the arguments for this sessionmaker.
e.g.:
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite://'))
method
sqlalchemy.orm.sessionmaker.
classmethodidentity_key
(\args, **kwargs*)inherited from the
sqlalchemy.orm.session._SessionClassMethods.identity_key
method ofsqlalchemy.orm.session._SessionClassMethods
Return an identity key.
This is an alias of
identity_key()
.method
sqlalchemy.orm.sessionmaker.
classmethodobject_session
(instance)inherited from the
sqlalchemy.orm.session._SessionClassMethods.object_session
method ofsqlalchemy.orm.session._SessionClassMethods
Return the
Session
to which an object belongs.This is an alias of
object_session()
.
class sqlalchemy.orm.``ORMExecuteState
(session, statement, parameters, execution_options, bind_arguments, compile_state_cls, events_todo)
Represents a call to the Session.execute()
method, as passed to the SessionEvents.do_orm_execute()
event hook.
New in version 1.4.
See also
Execute Events - top level documentation on how to use SessionEvents.do_orm_execute()
Class signature
class sqlalchemy.orm.ORMExecuteState
(sqlalchemy.util.langhelpers.MemoizedSlots
)
attribute
sqlalchemy.orm.ORMExecuteState.
session
The
Session
in use.attribute
sqlalchemy.orm.ORMExecuteState.
statement
The SQL statement being invoked. For an ORM selection as would be retrieved from
Query
, this is an instance ofselect
that was generated from the ORM query.attribute
sqlalchemy.orm.ORMExecuteState.
parameters
Dictionary of parameters that was passed to
Session.execute()
.attribute
sqlalchemy.orm.ORMExecuteState.
bind_arguments
The dictionary passed as the
Session.execute.bind_arguments
dictionary. This dictionary may be used by extensions toSession
to pass arguments that will assist in determining amongst a set of database connections which one should be used to invoke this statement.attribute
sqlalchemy.orm.ORMExecuteState.
local_execution_options
Dictionary view of the execution options passed to the
Session.execute()
method. This does not include options that may be associated with the statement being invoked.See also
attribute
sqlalchemy.orm.ORMExecuteState.
execution_options
The complete dictionary of current execution options.
This is a merge of the statement level options with the locally passed execution options.
attribute
sqlalchemy.orm.ORMExecuteState.
all_mappers
Return a sequence of all
Mapper
objects that are involved at the top level of this statement.By “top level” we mean those
Mapper
objects that would be represented in the result set rows for aselect()
query, or for aupdate()
ordelete()
query, the mapper that is the main subject of the UPDATE or DELETE.New in version 1.4.0b2.
See also
attribute
sqlalchemy.orm.ORMExecuteState.
bind_mapper
Return the
Mapper
that is the primary “bind” mapper.For an
ORMExecuteState
object invoking an ORM statement, that is, theORMExecuteState.is_orm_statement
attribute isTrue
, this attribute will return theMapper
that is considered to be the “primary” mapper of the statement. The term “bind mapper” refers to the fact that aSession
object may be “bound” to multipleEngine
objects keyed to mapped classes, and the “bind mapper” determines which of thoseEngine
objects would be selected.For a statement that is invoked against a single mapped class,
ORMExecuteState.bind_mapper
is intended to be a reliable way of getting this mapper.New in version 1.4.0b2.
See also
method
sqlalchemy.orm.ORMExecuteState.
invoke_statement
(statement=None, params=None, execution_options=None, bind_arguments=None)Execute the statement represented by this
ORMExecuteState
, without re-invoking events that have already proceeded.This method essentially performs a re-entrant execution of the current statement for which the
SessionEvents.do_orm_execute()
event is being currently invoked. The use case for this is for event handlers that want to override how the ultimateResult
object is returned, such as for schemes that retrieve results from an offline cache or which concatenate results from multiple executions.When the
Result
object is returned by the actual handler function withinSessionEvents.do_orm_execute()
and is propagated to the callingSession.execute()
method, the remainder of theSession.execute()
method is preempted and theResult
object is returned to the caller ofSession.execute()
immediately.Parameters
statement – optional statement to be invoked, in place of the statement currently represented by
ORMExecuteState.statement
.params – optional dictionary of parameters which will be merged into the existing
ORMExecuteState.parameters
of thisORMExecuteState
.execution_options – optional dictionary of execution options will be merged into the existing
ORMExecuteState.execution_options
of thisORMExecuteState
.bind_arguments – optional dictionary of bind_arguments which will be merged amongst the current
ORMExecuteState.bind_arguments
of thisORMExecuteState
.
Returns
a
Result
object with ORM-level results.
See also
Re-Executing Statements - background and examples on the appropriate usage of
ORMExecuteState.invoke_statement()
.attribute
sqlalchemy.orm.ORMExecuteState.
is_column_load
Return True if the operation is refreshing column-oriented attributes on an existing ORM object.
This occurs during operations such as
Session.refresh()
, as well as when an attribute deferred bydefer()
is being loaded, or an attribute that was expired either directly bySession.expire()
or via a commit operation is being loaded.Handlers will very likely not want to add any options to queries when such an operation is occurring as the query should be a straight primary key fetch which should not have any additional WHERE criteria, and loader options travelling with the instance will have already been added to the query.
New in version 1.4.0b2.
See also
attribute
sqlalchemy.orm.ORMExecuteState.
is_delete
return True if this is a DELETE operation.
attribute
sqlalchemy.orm.ORMExecuteState.
is_insert
return True if this is an INSERT operation.
attribute
sqlalchemy.orm.ORMExecuteState.
is_orm_statement
return True if the operation is an ORM statement.
This indicates that the select(), update(), or delete() being invoked contains ORM entities as subjects. For a statement that does not have ORM entities and instead refers only to
Table
metadata, it is invoked as a Core SQL statement and no ORM-level automation takes place.attribute
sqlalchemy.orm.ORMExecuteState.
is_relationship_load
Return True if this load is loading objects on behalf of a relationship.
This means, the loader in effect is either a LazyLoader, SelectInLoader, SubqueryLoader, or similar, and the entire SELECT statement being emitted is on behalf of a relationship load.
Handlers will very likely not want to add any options to queries when such an operation is occurring, as loader options are already capable of being propagated to relationship loaders and should be already present.
See also
attribute
sqlalchemy.orm.ORMExecuteState.
is_select
return True if this is a SELECT operation.
attribute
sqlalchemy.orm.ORMExecuteState.
is_update
return True if this is an UPDATE operation.
attribute
sqlalchemy.orm.ORMExecuteState.
lazy_loaded_from
An
InstanceState
that is using this statement execution for a lazy load operation.The primary rationale for this attribute is to support the horizontal sharding extension, where it is available within specific query execution time hooks created by this extension. To that end, the attribute is only intended to be meaningful at query execution time, and importantly not any time prior to that, including query compilation time.
attribute
sqlalchemy.orm.ORMExecuteState.
load_options
Return the load_options that will be used for this execution.
attribute
sqlalchemy.orm.ORMExecuteState.
loader_strategy_path
Return the
PathRegistry
for the current load path.This object represents the “path” in a query along relationships when a particular object or collection is being loaded.
attribute
sqlalchemy.orm.ORMExecuteState.
update_delete_options
Return the update_delete_options that will be used for this execution.
attribute
sqlalchemy.orm.ORMExecuteState.
user_defined_options
The sequence of
UserDefinedOptions
that have been associated with the statement being invoked.
class sqlalchemy.orm.``Session
(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)
Manages persistence operations for ORM-mapped objects.
The Session’s usage paradigm is described at Using the Session.
Class signature
class sqlalchemy.orm.Session
(sqlalchemy.orm.session._SessionClassMethods
)
method
sqlalchemy.orm.Session.
__init__
(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 aSession
-producing callable with a given set of arguments.Parameters
autocommit –
Defaults to
False
. WhenTrue
, theSession
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, theSession.begin()
method may be used to explicitly start transactions, but the usual “autobegin” behavior is not present.Deprecated since version 1.4: The
Session.autocommit
parameter is deprecated and will be removed in SQLAlchemy version 2.0. TheSession
now features “autobegin” behavior such that theSession.begin()
method may be called if a transaction has not yet been started yet. See the section Explicit Begin for background.autoflush – When
True
, all query operations will issue aSession.flush()
call to thisSession
before proceeding. This is a convenience feature so thatSession.flush()
need not be called repeatedly in order for database queries to retrieve results. It’s typical thatautoflush
is used in conjunction withautocommit=False
. In this scenario, explicit calls toSession.flush()
are rarely needed; you usually only need to callSession.commit()
(which flushes) to finalize changes.bind – An optional
Engine
orConnection
to which thisSession
should be bound. When specified, all SQL operations performed by this session will execute via this connectable.binds –
A dictionary which may specify any number of
Engine
orConnection
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,Table
objects andMapper
objects. The values of the dictionary are then instances ofEngine
or less commonlyConnection
objects. Operations which proceed relative to a particular mapped class will consult this dictionary for the closest matching entity in order to determine whichEngine
should be used for a particular SQL operation. The complete heuristics for resolution are described atSession.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
Partitioning Strategies (e.g. multiple database backends per Session)
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 thesessionmaker
function, and is not sent directly to the constructor forSession
.enable_baked_queries –
defaults to
True
. A flag consumed by thesqlalchemy.ext.baked
extension to determine if “baked queries” should be cached, as is the normal operation of this extension. When set toFalse
, all caching is disabled, including baked queries defined by the calling application as well as those used internally. Setting this flag toFalse
can significantly reduce memory use, however will also degrade performance for those areas that make use of baked queries (such as relationship loaders). Additionally, baked query logic in the calling application or potentially within the ORM that may be malfunctioning due to cache key collisions or similar can be flagged by observing if this flag resolves the issue.New in version 1.2.
expire_on_commit –
Defaults to
True
. WhenTrue
, all instances will be fully expired after eachcommit()
, so that all attribute/object access subsequent to a completed transaction will load from the most recent database state.See also
future –
if True, use 2.0 style transactional and engine behavior. Future mode includes the following behaviors:
The
Session
will not use “bound” metadata in order to locate anEngine
; the engine or engines in use must be specified to the constructor ofSession
or otherwise be configured against thesessionmaker
in useThe “subtransactions” feature of
Session.begin()
is removed in version 2.0 and is disabled when the future flag is set.The behavior of the
relationship.cascade_backrefs
flag on arelationship()
will always assume “False” behavior.
New in version 1.4.
See also
info – optional dictionary of arbitrary data to be associated with this
Session
. Is available via theSession.info
attribute. Note the dictionary is copied at construction time so that modifications to the per-Session
dictionary will be local to thatSession
.query_cls – Class which should be used to create new Query objects, as returned by the
Session.query()
method. Defaults toQuery
.twophase – When
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 acommit()
, afterflush()
has been issued for all attached databases, theTwoPhaseTransaction.prepare()
method on each database’sTwoPhaseTransaction
will be called. This allows each database to roll back the entire transaction, before each transaction is committed.
method
sqlalchemy.orm.Session.
add
(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 ofadd()
isexpunge()
.method
sqlalchemy.orm.Session.
add_all
(instances)Add the given collection of instances to this
Session
.method
sqlalchemy.orm.Session.
begin
(subtransactions=False, nested=False, _subtrans=False)Begin a transaction, or nested transaction, on this
Session
.When used to begin the outermost transaction, an error is raised if this
Session
is already inside of a transaction.Parameters
nested – if True, begins a SAVEPOINT transaction and is equivalent to calling
Session.begin_nested()
. For documentation on SAVEPOINT transactions, please see Using SAVEPOINT.subtransactions –
if True, indicates that this
Session.begin()
can create a “subtransaction”.Deprecated since version 1.4: The
Session.begin.subtransactions
flag is deprecated and will be removed in SQLAlchemy version 2.0. See the documentation at Migrating from the “subtransaction” pattern for background on a compatible alternative pattern.
Returns
the
SessionTransaction
object. Note thatSessionTransaction
acts as a Python context manager, allowingSession.begin()
to be used in a “with” block. See Explicit Begin for an example.
See also
method
sqlalchemy.orm.Session.
begin_nested
()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 Using SAVEPOINT.
Returns
the
SessionTransaction
object. Note thatSessionTransaction
acts as a context manager, allowingSession.begin_nested()
to be used in a “with” block. See Using SAVEPOINT for a usage example.
See also
Serializable isolation / Savepoints / Transactional DDL - special workarounds required with the SQLite driver in order for SAVEPOINT to work correctly.
method
sqlalchemy.orm.Session.
bind_mapper
(mapper, bind)Associate a
Mapper
or arbitrary Python class with a “bind”, e.g. anEngine
orConnection
.The given entity is added to a lookup used by the
Session.get_bind()
method.Parameters
mapper – a
Mapper
object, or an instance of a mapped class, or any Python class that is the base of a set of mapped classes.bind – an
Engine
orConnection
object.
See also
[Partitioning Strategies (e.g. multiple database backends per Session)]($40343ee29299c061.md#session-partitioning)
[`Session.binds`](#sqlalchemy.orm.Session.params.binds "sqlalchemy.orm.Session")
[`Session.bind_table()`](#sqlalchemy.orm.Session.bind_table "sqlalchemy.orm.Session.bind_table")
method
sqlalchemy.orm.Session.
bind_table
(table, bind)Associate a
Table
with a “bind”, e.g. anEngine
orConnection
.The given
Table
is added to a lookup used by theSession.get_bind()
method.Parameters
table – a
Table
object, which is typically the target of an ORM mapping, or is present within a selectable that is mapped.bind – an
Engine
orConnection
object.
See also
[Partitioning Strategies (e.g. multiple database backends per Session)]($40343ee29299c061.md#session-partitioning)
[`Session.binds`](#sqlalchemy.orm.Session.params.binds "sqlalchemy.orm.Session")
[`Session.bind_mapper()`](#sqlalchemy.orm.Session.bind_mapper "sqlalchemy.orm.Session.bind_mapper")
method
sqlalchemy.orm.Session.
bulk_insert_mappings
(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
sqlalchemy.sql.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 read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.
Parameters
mapper – a mapped class, or the actual
Mapper
object, representing the single kind of object represented within the mapping list.mappings – a 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_defaults – when 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,
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.
See also
[Bulk Operations]($40343ee29299c061.md#bulk-operations)
[`Session.bulk_save_objects()`](#sqlalchemy.orm.Session.bulk_save_objects "sqlalchemy.orm.Session.bulk_save_objects")
[`Session.bulk_update_mappings()`](#sqlalchemy.orm.Session.bulk_update_mappings "sqlalchemy.orm.Session.bulk_update_mappings")
method
sqlalchemy.orm.Session.
bulk_save_objects
(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, unless the
return_defaults
flag is also set, in which case primary key attributes and server-side default values will be populated.New in version 1.0.0.
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 read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.
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 theInstanceState.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_defaults – when 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,
Session.bulk_save_objects.return_defaults
greatly reduces the performance gains of the method overall.update_changed_only – when 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.
See also
[Bulk Operations]($40343ee29299c061.md#bulk-operations)
[`Session.bulk_insert_mappings()`](#sqlalchemy.orm.Session.bulk_insert_mappings "sqlalchemy.orm.Session.bulk_insert_mappings")
[`Session.bulk_update_mappings()`](#sqlalchemy.orm.Session.bulk_update_mappings "sqlalchemy.orm.Session.bulk_update_mappings")
method
sqlalchemy.orm.Session.
bulk_update_mappings
(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 read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.
Parameters
mapper – a mapped class, or the actual
Mapper
object, representing the single kind of object represented within the mapping list.mappings – a 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.
See also
[Bulk Operations]($40343ee29299c061.md#bulk-operations)
[`Session.bulk_insert_mappings()`](#sqlalchemy.orm.Session.bulk_insert_mappings "sqlalchemy.orm.Session.bulk_insert_mappings")
[`Session.bulk_save_objects()`](#sqlalchemy.orm.Session.bulk_save_objects "sqlalchemy.orm.Session.bulk_save_objects")
method
sqlalchemy.orm.Session.
close
()Close this Session.
This clears all items and ends any transaction in progress.
If this Session was created with
autocommit=False
, a new transaction will be begun when theSession
is next asked to procure a database connection.Changed in version 1.4: The
Session.close()
method does not immediately create a newSessionTransaction
object; instead, the newSessionTransaction
is created only if theSession
is used again for a database operation.method
sqlalchemy.orm.Session.
classmethodclose_all
()inherited from the
sqlalchemy.orm.session._SessionClassMethods.close_all
method ofsqlalchemy.orm.session._SessionClassMethods
Close all sessions in memory.
Deprecated since version 1.3: The
Session.close_all()
method is deprecated and will be removed in a future release. Please refer toclose_all_sessions()
.method
sqlalchemy.orm.Session.
commit
()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 1.x-style use is in effect and there are currently SAVEPOINTs in progress via
Session.begin_nested()
, the operation will release the current SAVEPOINT but not commit the outermost database transaction.If 2.0-style use is in effect via the
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.
See also
method
sqlalchemy.orm.Session.
connection
(bind_arguments=None, close_with_result=False, execution_options=None, \*kw*)Return a
Connection
object corresponding to thisSession
object’s transactional state.If this
Session
is configured withautocommit=False
, either theConnection
corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and theConnection
returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted).Alternatively, if this
Session
is configured withautocommit=True
, an ad-hocConnection
is returned usingEngine.connect()
on the underlyingEngine
.Ambiguity in multi-bind or unbound
Session
objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of theget_bind()
method for resolution.Parameters
bind_arguments – dictionary of bind arguments. May include “mapper”, “bind”, “clause”, other custom arguments that are passed to
Session.get_bind()
.bind – deprecated; use bind_arguments
mapper – deprecated; use bind_arguments
clause – deprecated; use bind_arguments
close_with_result – Passed to
Engine.connect()
, indicating theConnection
should be considered “single use”, automatically closing when the first result set is closed. This flag only has an effect if thisSession
is configured withautocommit=True
and does not already have a transaction in progress.execution_options –
a dictionary of execution options that will be passed to
Connection.execution_options()
, when the connection is first procured only. If the connection is already present within theSession
, a warning is emitted and the arguments are ignored.See also
**kw – deprecated; use bind_arguments
method
sqlalchemy.orm.Session.
delete
(instance)Mark an instance as deleted.
The database delete operation occurs upon
flush()
.attribute
sqlalchemy.orm.Session.
deleted
The set of all instances marked as ‘deleted’ within this
Session
attribute
sqlalchemy.orm.Session.
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.method
sqlalchemy.orm.Session.
enable_relationship_loading
(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
relationship()
will attempt to load a value from the database using thisSession
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 theload_on_pending
flag onrelationship()
. 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
viaSession.enable_relationship_loading()
pending, add it to theSession
usingSession.add()
normally. If the object instead represents an existing identity in the database, it should be merged usingSession.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
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 aSession
without SQL emitted, which then will unexpire attributes on access.method
sqlalchemy.orm.Session.
execute
(statement, params=None, execution_options={}, bind_arguments=None, _parent_execute_state=None, _add_event=None, \*kw*)Execute a SQL expression construct.
Returns a
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
Session.execute()
is similar to that ofConnection.execute()
, the 2.0 style version ofConnection
.Changed in version 1.4: the
Session.execute()
method is now the primary point of ORM statement execution when using 2.0 style ORM usage.Parameters
statement – An executable statement (i.e. an
Executable
expression such asselect()
).params – Optional 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_options – optional 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
Connection.execution_options()
, and may also provide additional options understood only in an ORM context.bind_arguments – dictionary 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.mapper – deprecated; use the bind_arguments dictionary
bind – deprecated; use the bind_arguments dictionary
**kw – deprecated; use the bind_arguments dictionary
Returns
a
Result
object.
method
sqlalchemy.orm.Session.
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, 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, useSession.expire_all()
.The
Session
object’s default behavior is to expire all state whenever theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire()
only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.Parameters
instance – The instance to be refreshed.
attribute_names – optional list of string attribute names indicating a subset of attributes to be expired.
See also
[Refreshing / Expiring]($ab781dd78600e308.md#session-expire) - introductory material
[`Session.expire()`](#sqlalchemy.orm.Session.expire "sqlalchemy.orm.Session.expire")
[`Session.refresh()`](#sqlalchemy.orm.Session.refresh "sqlalchemy.orm.Session.refresh")
[`Query.populate_existing()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.populate_existing "sqlalchemy.orm.Query.populate_existing")
method
sqlalchemy.orm.Session.
expire_all
()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 theSession.rollback()
orSession.commit()
methods are called, so that new state can be loaded for the new transaction. For this reason, callingSession.expire_all()
should not be needed when autocommit isFalse
, assuming the transaction is isolated.See also
Refreshing / Expiring - introductory material
method
sqlalchemy.orm.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.
method
sqlalchemy.orm.Session.
expunge_all
()Remove all object instances from this
Session
.This is equivalent to calling
expunge(obj)
on all objects in thisSession
.method
sqlalchemy.orm.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, 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.
method
sqlalchemy.orm.Session.
get
(entity, ident, options=None, populate_existing=False, with_for_update=None, identity_token=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
Session.get()
, which is moved from the now deprecatedQuery.get()
method.Session.get()
is special in that it provides direct access to the identity map of theSession
. 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.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,ObjectDeletedError
is raised.Parameters
entity – a 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
Table
object’s primary key columns, or if theMapper.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})
options – optional sequence of loader options which will be applied to the query, if one is emitted.
populate_existing – causes 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_update – optional 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 ofQuery.with_for_update()
. Supersedes theSession.refresh.lockmode
parameter.
Returns
The object instance, or
None
.
method
sqlalchemy.orm.Session.
get_bind
(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
, except in the case where theSession
has been explicitly bound directly to aConnection
.For a multiply-bound or unbound
Session
, themapper
orclause
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 aSession.query()
, each individual INSERT/UPDATE/DELETE operation within aSession.flush()
, call, etc.The order of resolution is:
if mapper given and
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.if clause given and
Session.binds
is present, locate a bind based onTable
objects found in the given clause present inSession.binds
.if
Session.binds
is present, return that.if clause given, attempt to return a bind linked to the
MetaData
ultimately associated with the clause.if mapper given, attempt to return a bind linked to the
MetaData
ultimately associated with theTable
or other selectable to which the mapper is mapped.No bind can be found,
UnboundExecutionError
is raised.
Note that the
Session.get_bind()
method can be overridden on a user-defined subclass ofSession
to provide any kind of bind resolution scheme. See the example at Custom Vertical Partitioning.Parameters
mapper – Optional
mapper()
mapped class or instance ofMapper
. The bind can be derived from aMapper
first by consulting the “binds” map associated with thisSession
, and secondly by consulting theMetaData
associated with theTable
to which theMapper
is mapped for a bind.clause – A
ClauseElement
(i.e.select()
,text()
, etc.). If themapper
argument is not present or could not produce a bind, the given expression construct will be searched for a bound element, typically aTable
associated with boundMetaData
.
See also
[Partitioning Strategies (e.g. multiple database backends per Session)]($40343ee29299c061.md#session-partitioning)
[`Session.binds`](#sqlalchemy.orm.Session.params.binds "sqlalchemy.orm.Session")
[`Session.bind_mapper()`](#sqlalchemy.orm.Session.bind_mapper "sqlalchemy.orm.Session.bind_mapper")
[`Session.bind_table()`](#sqlalchemy.orm.Session.bind_table "sqlalchemy.orm.Session.bind_table")
method
sqlalchemy.orm.Session.
get_nested_transaction
()Return the current nested transaction in progress, if any.
New in version 1.4.
method
sqlalchemy.orm.Session.
get_transaction
()Return the current root transaction in progress, if any.
New in version 1.4.
method
sqlalchemy.orm.Session.
classmethodidentity_key
(\args, **kwargs*)inherited from the
sqlalchemy.orm.session._SessionClassMethods.identity_key
method ofsqlalchemy.orm.session._SessionClassMethods
Return an identity key.
This is an alias of
identity_key()
.attribute
sqlalchemy.orm.Session.
identity_map
= NoneA 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.method
sqlalchemy.orm.Session.
in_nested_transaction
()Return True if this
Session
has begun a nested transaction, e.g. SAVEPOINT.New in version 1.4.
method
sqlalchemy.orm.Session.
in_transaction
()Return True if this
Session
has begun a transaction.New in version 1.4.
See also
attribute
sqlalchemy.orm.Session.
info
A user-modifiable dictionary.
The initial value of this dictionary can be populated using the
info
argument to theSession
constructor orsessionmaker
constructor or factory methods. The dictionary here is always local to thisSession
and can be modified independently of all otherSession
objects.method
sqlalchemy.orm.Session.
invalidate
()Close this Session, using connection invalidation.
This is a variant of
Session.close()
that will additionally ensure that theConnection.invalidate()
method will be called on eachConnection
object that is currently in use for a transaction (typically there is only one connection unless theSession
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
Session.close()
does, including that all ORM objects are expunged.attribute
sqlalchemy.orm.Session.
is_active
True if this
Session
not in “partial rollback” state.Changed in version 1.4: The
Session
no longer begins a new transaction immediately, so this attribute will be False when theSession
is first instantiated.“partial rollback” state typically indicates that the flush process of the
Session
has failed, and that theSession.rollback()
method must be emitted in order to fully roll back the transaction.If this
Session
is not in a transaction at all, theSession
will autobegin when it is first used, so in this caseSession.is_active
will return True.Otherwise, if this
Session
is within a transaction, and that transaction has not been rolled back internally, theSession.is_active
will also return True.See also
method
sqlalchemy.orm.Session.
is_modified
(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 reportFalse
when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it inSession.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 toTrue
. 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 theactive_history
argument withcolumn_property()
.Parameters
instance – mapped instance to be tested for pending changes.
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.
method
sqlalchemy.orm.Session.
merge
(instance, load=True)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 theSession
if not already.This operation cascades to associated instances if the association is mapped with
cascade="merge"
.See 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 Session.merge resolves pending conflicts the same as persistent for discussion.Parameters
instance – Instance 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 aSession
from a second level cache, or to transfer just-loaded objects into theSession
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 anySession
. 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 fromload=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.
See also
[`make_transient_to_detached()`](#sqlalchemy.orm.make_transient_to_detached "sqlalchemy.orm.make_transient_to_detached") - provides for an alternative means of “merging” a single object into the [`Session`](#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
attribute
sqlalchemy.orm.Session.
new
The set of all instances marked as ‘new’ within this
Session
.attribute
sqlalchemy.orm.Session.
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.method
sqlalchemy.orm.Session.
classmethodobject_session
(instance)inherited from the
sqlalchemy.orm.session._SessionClassMethods.object_session
method ofsqlalchemy.orm.session._SessionClassMethods
Return the
Session
to which an object belongs.This is an alias of
object_session()
.method
sqlalchemy.orm.Session.
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.method
sqlalchemy.orm.Session.
query
(\entities, **kwargs*)method
sqlalchemy.orm.Session.
refresh
(instance, attribute_names=None, with_for_update=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.
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 - usage of
Session.refresh()
usually only makes sense if non-ORM SQL statement were emitted in the ongoing transaction, or if autocommit mode is turned on.Parameters
attribute_names – optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.
with_for_update –
optional 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 ofQuery.with_for_update()
. Supersedes theSession.refresh.lockmode
parameter.New in version 1.2.
See also
[Refreshing / Expiring]($ab781dd78600e308.md#session-expire) - introductory material
[`Session.expire()`](#sqlalchemy.orm.Session.expire "sqlalchemy.orm.Session.expire")
[`Session.expire_all()`](#sqlalchemy.orm.Session.expire_all "sqlalchemy.orm.Session.expire_all")
[`Query.populate_existing()`]($3cf240505c8b4e45.md#sqlalchemy.orm.Query.populate_existing "sqlalchemy.orm.Query.populate_existing")
method
sqlalchemy.orm.Session.
rollback
()Rollback the current transaction in progress.
If no transaction is in progress, this method is a pass-through.
In 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 2.0-style use is in effect via the
Session.future
flag, the method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress.See also
method
sqlalchemy.orm.Session.
scalar
(statement, params=None, execution_options={}, bind_arguments=None, \*kw*)Execute a statement and return a scalar result.
Usage and parameters are the same as that of
Session.execute()
; the return result is a scalar Python value.attribute
sqlalchemy.orm.Session.
transaction
The current active or inactive
SessionTransaction
.Deprecated since version 1.4: The
Session.transaction
attribute is considered legacy as of the 1.x series of SQLAlchemy and will be removed in 2.0. For context manager use, useSession.begin()
. To access the current root transaction, useSession.get_transaction()
. (Background on SQLAlchemy 2.0 at: Migrating to SQLAlchemy 2.0)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.
class sqlalchemy.orm.``SessionTransaction
(session, parent=None, nested=False, autobegin=False)
A Session
-level transaction.
SessionTransaction
is produced from the Session.begin()
and Session.begin_nested()
methods. It’s largely an internal object that in modern use provides a context manager for session transactions.
Documentation on interacting with SessionTransaction
is at: Managing Transactions.
Changed in version 1.4: The scoping and API methods to work with the SessionTransaction
object directly have been simplified.
See also
Session.in_nested_transaction()
Session.get_nested_transaction()
attribute
sqlalchemy.orm.SessionTransaction.
nested
= FalseIndicates if this is a nested, or SAVEPOINT, transaction.
When
SessionTransaction.nested
is True, it is expected thatSessionTransaction.parent
will be True as well.attribute
sqlalchemy.orm.SessionTransaction.
parent
The parent
SessionTransaction
of thisSessionTransaction
.If this attribute is
None
, indicates thisSessionTransaction
is at the top of the stack, and corresponds to a real “COMMIT”/”ROLLBACK” block. If non-None
, then this is either a “subtransaction” or a “nested” / SAVEPOINT transaction. If theSessionTransaction.nested
attribute isTrue
, then this is a SAVEPOINT, and ifFalse
, indicates this a subtransaction.New in version 1.0.16: - use ._parent for previous versions
Session Utilities
Object Name | Description |
---|---|
Close all sessions in memory. | |
| Alter the state of the given instance so that it is transient. |
| Make the given transient instance detached. |
| Return the |
| Return True if the given object was deleted within a session flush. |
function sqlalchemy.orm.``close_all_sessions
()
Close all sessions in memory.
This function consults a global registry of all Session
objects and calls Session.close()
on them, which resets them to a clean state.
This function is not for general use but may be useful for test suites within the teardown scheme.
New in version 1.3.
function sqlalchemy.orm.``make_transient
(instance)
Alter the state of the given instance so that it is transient.
Note
make_transient()
is a special-case function for advanced use cases only.
The given mapped instance is assumed to be in the persistent or detached state. The function will remove its association with any Session
as well as its InstanceState.identity
. The effect is that the object will behave as though it were newly constructed, except retaining any attribute / collection values that were loaded at the time of the call. The InstanceState.deleted
flag is also reset if this object had been deleted as a result of using Session.delete()
.
Warning
make_transient()
does not “unexpire” or otherwise eagerly load ORM-mapped attributes that are not currently loaded at the time the function is called. This includes attributes which:
were expired via
Session.expire()
were expired as the natural effect of committing a session transaction, e.g.
Session.commit()
are normally lazy loaded but are not currently loaded
are “deferred” via Deferred Column Loading and are not yet loaded
were not present in the query which loaded this object, such as that which is common in joined table inheritance and other scenarios.
After make_transient()
is called, unloaded attributes such as those above will normally resolve to the value None
when accessed, or an empty collection for a collection-oriented attribute. As the object is transient and un-associated with any database identity, it will no longer retrieve these values.
See also
function sqlalchemy.orm.``make_transient_to_detached
(instance)
Make the given transient instance detached.
Note
make_transient_to_detached()
is a special-case function for advanced use cases only.
All attribute history on the given instance will be reset as though the instance were freshly loaded from a query. Missing attributes will be marked as expired. The primary key attributes of the object, which are required, will be made into the “key” of the instance.
The object can then be added to a session, or merged possibly with the load=False flag, at which point it will look as if it were loaded that way, without emitting SQL.
This is a special use case function that differs from a normal call to Session.merge()
in that a given persistent state can be manufactured without any SQL calls.
See also
Session.enable_relationship_loading()
function sqlalchemy.orm.``object_session
(instance)
Return the Session
to which the given instance belongs.
This is essentially the same as the InstanceState.session
accessor. See that attribute for details.
function sqlalchemy.orm.util.``was_deleted
(object_)
Return True if the given object was deleted within a session flush.
This is regardless of whether or not the object is persistent or detached.
See also
Attribute and State Management Utilities
These functions are provided by the SQLAlchemy attribute instrumentation API to provide a detailed interface for dealing with instances, attribute values, and history. Some of them are useful when constructing event listener functions, such as those described in ORM Events.
Object Name | Description |
---|---|
| Delete the value of an attribute, firing history events. |
| Mark an instance as ‘dirty’ without any specific attribute mentioned. |
| Mark an attribute on an instance as ‘modified’. |
| Get the value of an attribute, firing any callables required. |
| Return a |
A 3-tuple of added, unchanged and deleted values, representing the changes which have occurred on an instrumented attribute. | |
| Initialize a collection attribute and return the collection adapter. |
Return the | |
| Return True if the given attribute on the given instance is instrumented by the attributes package. |
| Given an object, return the |
| Set the value of an attribute, firing history events. |
| Set the value of an attribute with no history events. |
function sqlalchemy.orm.util.``object_state
(instance)
Given an object, return the InstanceState
associated with the object.
Raises sqlalchemy.orm.exc.UnmappedInstanceError
if no mapping is configured.
Equivalent functionality is available via the inspect()
function as:
inspect(instance)
Using the inspection system will raise sqlalchemy.exc.NoInspectionAvailable
if the instance is not part of a mapping.
function sqlalchemy.orm.attributes.``del_attribute
(instance, key)
Delete the value of an attribute, firing history events.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy.
function sqlalchemy.orm.attributes.``get_attribute
(instance, key)
Get the value of an attribute, firing any callables required.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to make usage of attribute state as understood by SQLAlchemy.
function sqlalchemy.orm.attributes.``get_history
(obj, key, passive=symbol(‘PASSIVE_OFF’))
Return a History
record for the given object and attribute key.
This is the pre-flush history for a given attribute, which is reset each time the Session
flushes changes to the current database transaction.
Note
Prefer to use the AttributeState.history
and AttributeState.load_history()
accessors to retrieve the History
for instance attributes.
Parameters
obj – an object whose class is instrumented by the attributes package.
key – string attribute name.
passive – indicates loading behavior for the attribute if the value is not already present. This is a bitflag attribute, which defaults to the symbol
PASSIVE_OFF
indicating all necessary SQL should be emitted.
See also
AttributeState.load_history()
- retrieve history using loader callables if the value is not locally present.
function sqlalchemy.orm.attributes.``init_collection
(obj, key)
Initialize a collection attribute and return the collection adapter.
This function is used to provide direct access to collection internals for a previously unloaded attribute. e.g.:
collection_adapter = init_collection(someobject, 'elements')
for elem in values:
collection_adapter.append_without_event(elem)
For an easier way to do the above, see set_committed_value()
.
Parameters
obj – a mapped object
key – string attribute name where the collection is located.
function sqlalchemy.orm.attributes.``flag_modified
(instance, key)
Mark an attribute on an instance as ‘modified’.
This sets the ‘modified’ flag on the instance and establishes an unconditional change event for the given attribute. The attribute must have a value present, else an InvalidRequestError
is raised.
To mark an object “dirty” without referring to any specific attribute so that it is considered within a flush, use the flag_dirty()
call.
See also
function sqlalchemy.orm.attributes.``flag_dirty
(instance)
Mark an instance as ‘dirty’ without any specific attribute mentioned.
This is a special operation that will allow the object to travel through the flush process for interception by events such as SessionEvents.before_flush()
. Note that no SQL will be emitted in the flush process for an object that has no changes, even if marked dirty via this method. However, a SessionEvents.before_flush()
handler will be able to see the object in the Session.dirty
collection and may establish changes on it, which will then be included in the SQL emitted.
New in version 1.2.
See also
function sqlalchemy.orm.attributes.``instance_state
()
Return the InstanceState
for a given mapped object.
This function is the internal version of object_state()
. The object_state()
and/or the inspect()
function is preferred here as they each emit an informative exception if the given object is not mapped.
function sqlalchemy.orm.instrumentation.``is_instrumented
(instance, key)
Return True if the given attribute on the given instance is instrumented by the attributes package.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required.
function sqlalchemy.orm.attributes.``set_attribute
(instance, key, value, initiator=None)
Set the value of an attribute, firing history events.
This function may be used regardless of instrumentation applied directly to the class, i.e. no descriptors are required. Custom attribute management schemes will need to make usage of this method to establish attribute state as understood by SQLAlchemy.
Parameters
instance – the object that will be modified
key – string name of the attribute
value – value to assign
initiator –
an instance of
Event
that would have been propagated from a previous event listener. This argument is used when theset_attribute()
function is being used within an existing event listening function where anEvent
object is being supplied; the object may be used to track the origin of the chain of events.New in version 1.2.3.
function sqlalchemy.orm.attributes.``set_committed_value
(instance, key, value)
Set the value of an attribute with no history events.
Cancels any previous history present. The value should be a scalar value for scalar-holding attributes, or an iterable for any collection-holding attribute.
This is the same underlying method used when a lazy loader fires off and loads additional data from the database. In particular, this method can be used by application code which has loaded additional attributes or collections through separate queries, which can then be attached to an instance as though it were part of its original loaded state.
class sqlalchemy.orm.attributes.``History
(added, unchanged, deleted)
A 3-tuple of added, unchanged and deleted values, representing the changes which have occurred on an instrumented attribute.
The easiest way to get a History
object for a particular attribute on an object is to use the inspect()
function:
from sqlalchemy import inspect
hist = inspect(myobject).attrs.myattribute.history
Each tuple member is an iterable sequence:
added
- the collection of items added to the attribute (the first tuple element).unchanged
- the collection of items that have not changed on the attribute (the second tuple element).deleted
- the collection of items that have been removed from the attribute (the third tuple element).
Class signature
class sqlalchemy.orm.History
(sqlalchemy.orm.History
)
method
sqlalchemy.orm.attributes.History.
empty
()Return True if this
History
has no changes and no existing, unchanged state.method
sqlalchemy.orm.attributes.History.
has_changes
()Return True if this
History
has changes.method
sqlalchemy.orm.attributes.History.
non_added
()Return a collection of unchanged + deleted.
method
sqlalchemy.orm.attributes.History.
non_deleted
()Return a collection of added + unchanged.
method
sqlalchemy.orm.attributes.History.
sum
()Return a collection of added + unchanged + deleted.