simplelogincmd.database.session.SimpleLoginSession¶
- class SimpleLoginSession(bind: _SessionBind | None = None, *, autoflush: bool = True, future: Literal[True] = True, expire_on_commit: bool = True, autobegin: bool = True, twophase: bool = False, binds: Dict[_SessionBindKey, _SessionBind] | None = None, enable_baked_queries: bool = True, info: _InfoType | None = None, query_cls: Type[Query[Any]] | None = None, autocommit: Literal[False] = False, join_transaction_mode: JoinTransactionMode = 'conditional_savepoint', close_resets_only: bool | _NoArg = _NoArg.NO_ARG)¶
Bases:
SessionAn extended database session
Construct a new
_orm.Session.See also the
sessionmakerfunction which is used to generate aSession-producing callable with a given set of arguments.- Parameters:
autoflush –
When
True, all query operations will issue aflush()call to thisSessionbefore proceeding. This is a convenience feature so thatflush()need not be called repeatedly in order for database queries to retrieve results.See also
Flushing - additional background on autoflush
autobegin –
Automatically start transactions (i.e. equivalent to invoking
_orm.Session.begin()) when database access is requested by an operation. Defaults toTrue. Set toFalseto prevent a_orm.Sessionfrom implicitly beginning transactions after construction, as well as after any of the_orm.Session.rollback(),_orm.Session.commit(), or_orm.Session.close()methods are called.Added in version 2.0.
bind – An optional
_engine.Engineor_engine.Connectionto which thisSessionshould 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.Engineor_engine.Connectionobjects 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.Tableobjects and_orm.Mapperobjects. The values of the dictionary are then instances of_engine.Engineor less commonly_engine.Connectionobjects. Operations which proceed relative to a particular mapped class will consult this dictionary for the closest matching entity in order to determine which_engine.Engineshould 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+psycopg2://engine1'), SomeDeclarativeBase: create_engine('postgresql+psycopg2://engine2'), some_mapper: create_engine('postgresql+psycopg2://engine3'), some_table: create_engine('postgresql+psycopg2://engine4'), })
See also
Partitioning Strategies (e.g. multiple database backends per Session)
Session.bind_mapper()Session.bind_table()Session.get_bind()class_ – Specify an alternate class other than
sqlalchemy.orm.session.Sessionwhich should be used by the returned class. This is the only argument that is local to thesessionmakerfunction, and is not sent directly to the constructor forSession.enable_baked_queries –
legacy; defaults to
True. A parameter consumed by thesqlalchemy.ext.bakedextension to determine if “baked queries” should be cached, as is the normal operation of this extension. When set toFalse, caching as used by this particular extension is disabled.Changed in version 1.4: The
sqlalchemy.ext.bakedextension 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.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 –
Deprecated; this flag is always True.
info – optional dictionary of arbitrary data to be associated with this
Session. Is available via theSession.infoattribute. Note the dictionary is copied at construction time so that modifications to the per-Sessiondictionary will be local to thatSession.query_cls – Class which should be used to create new Query objects, as returned by the
query()method. Defaults to_query.Query.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, theprepare()method on each database’sTwoPhaseTransactionwill be called. This allows each database to roll back the entire transaction, before each transaction is committed.autocommit – the “autocommit” keyword is present for backwards compatibility but must remain at its default value of
False.join_transaction_mode –
Describes the transactional behavior to take when a given bind is a
_engine.Connectionthat has already begun a transaction outside the scope of this_orm.Session; in other words the_engine.Connection.in_transaction()method returns True.The following behaviors only take effect when the
_orm.Sessionactually makes use of the connection given; that is, a method such as_orm.Session.execute(),_orm.Session.connection(), etc. are actually invoked:"conditional_savepoint"- this is the default. if the given_engine.Connectionis begun within a transaction but does not have a SAVEPOINT, then"rollback_only"is used. If the_engine.Connectionis additionally within a SAVEPOINT, in other words_engine.Connection.in_nested_transaction()method returns True, then"create_savepoint"is used."conditional_savepoint"behavior attempts to make use of savepoints in order to keep the state of the existing transaction unchanged, but only if there is already a savepoint in progress; otherwise, it is not assumed that the backend in use has adequate support for SAVEPOINT, as availability of this feature varies."conditional_savepoint"also seeks to establish approximate backwards compatibility with previous_orm.Sessionbehavior, for applications that are not setting a specific mode. It is recommended that one of the explicit settings be used."create_savepoint"- the_orm.Sessionwill use_engine.Connection.begin_nested()in all cases to create its own transaction. This transaction by its nature rides “on top” of any existing transaction that’s opened on the given_engine.Connection; if the underlying database and the driver in use has full, non-broken support for SAVEPOINT, the external transaction will remain unaffected throughout the lifespan of the_orm.Session.The
"create_savepoint"mode is the most useful for integrating a_orm.Sessioninto a test suite where an externally initiated transaction should remain unaffected; however, it relies on proper SAVEPOINT support from the underlying driver and database.Tip
When using SQLite, the SQLite driver included through Python 3.11 does not handle SAVEPOINTs correctly in all cases without workarounds. See the sections Serializable isolation / Savepoints / Transactional DDL and Serializable isolation / Savepoints / Transactional DDL (asyncio version) for details on current workarounds.
"control_fully"- the_orm.Sessionwill take control of the given transaction as its own;_orm.Session.commit()will call.commit()on the transaction,_orm.Session.rollback()will call.rollback()on the transaction,_orm.Session.close()will call.rollbackon the transaction.Tip
This mode of use is equivalent to how SQLAlchemy 1.4 would handle a
_engine.Connectiongiven with an existing SAVEPOINT (i.e._engine.Connection.begin_nested()); the_orm.Sessionwould take full control of the existing SAVEPOINT."rollback_only"- the_orm.Sessionwill take control of the given transaction for.rollback()calls only;.commit()calls will not be propagated to the given transaction..close()calls will have no effect on the given transaction.Tip
This mode of use is equivalent to how SQLAlchemy 1.4 would handle a
_engine.Connectiongiven with an existing regular database transaction (i.e._engine.Connection.begin()); the_orm.Sessionwould propagate_orm.Session.rollback()calls to the underlying transaction, but not_orm.Session.commit()or_orm.Session.close()calls.
Added in version 2.0.0rc1.
close_resets_only –
Defaults to
True. Determines if the session should reset itself after calling.close()or should pass in a no longer usable state, disabling re-use.Added in version 2.0.22: added flag
close_resets_only. A future SQLAlchemy version may change the default value of this flag toFalse.See also
Closing - Detail on the semantics of
_orm.Session.close()and_orm.Session.reset().
Methods
Place an object into this
_orm.Session.Add the given collection of instances to this
_orm.Session.Begin a transaction, or nested transaction, on this
Session, if one is not already begun.Begin a "nested" transaction on this Session, e.g. SAVEPOINT.
Associate a
_orm.Mapperor arbitrary Python class with a "bind", e.g. an_engine.Engineor_engine.Connection.Associate a
_schema.Tablewith a "bind", e.g. an_engine.Engineor_engine.Connection.Perform a bulk insert of the given list of mapping dictionaries.
Perform a bulk save of the given list of objects.
Perform a bulk update of the given list of mapping dictionaries.
Close out the transactional resources and ORM objects used by this
_orm.Session.Close all sessions in memory.
Flush pending changes and commit the current transaction.
Return a
_engine.Connectionobject corresponding to thisSessionobject's transactional state.Mark an instance as deleted.
Associate an object with this
Sessionfor related object loading.Execute a SQL expression construct.
Expire the attributes on an instance.
Expires all persistent instances within this Session.
Remove the instance from this
Session.Remove all object instances from this
Session.Flush all the object changes to the database.
Return an instance based on the given primary key identifier, or
Noneif not found.Return a "bind" to which this
Sessionis bound.Return the current nested transaction in progress, if any.
Return exactly one instance based on the given primary key identifier, or raise an exception if not found.
Return the current root transaction in progress, if any.
Return an identity key.
Return True if this
_orm.Sessionhas begun a nested transaction, e.g. SAVEPOINT.Return True if this
_orm.Sessionhas begun a transaction.Close this Session, using connection invalidation.
Return
Trueif the given instance has locally modified attributes.Copy the state of a given instance into a corresponding instance within this
Session.Return the
Sessionto which an object belongs.Prepare the current transaction in progress for two phase commit.
Return a new
_query.Queryobject corresponding to this_orm.Session.Expire and refresh attributes on the given instance.
Close out the transactional resources and ORM objects used by this
_orm.Session, resetting the session to its initial state.Rollback the current transaction in progress.
Execute a statement and return a scalar result.
Execute a statement and return the results as scalars.
Approximate insert-or-update functionality
Attributes
connection_callableThe set of all instances marked as 'deleted' within this
SessionThe set of all persistent instances considered dirty.
dispatchA user-modifiable dictionary.
True if this
Sessionnot in "partial rollback" state.The set of all instances marked as 'new' within this
Session.Return a context manager that disables autoflush.
A mapping of object identities to objects themselves.
bindhash_keyautoflushexpire_on_commitenable_baked_queriestwophasejoin_transaction_mode- add(instance: object, _warn: bool = True) None¶
Place an object into this
_orm.Session.Objects that are in the transient state when passed to the
_orm.Session.add()method will move to the pending state, until the next flush, at which point they will move to the persistent state.Objects that are in the detached state when passed to the
_orm.Session.add()method will move to the persistent state directly.If the transaction used by the
_orm.Sessionis rolled back, objects which were transient when they were passed to_orm.Session.add()will be moved back to the transient state, and will no longer be present within this_orm.Session.
- add_all(instances: Iterable[object]) None¶
Add the given collection of instances to this
_orm.Session.See the documentation for
_orm.Session.add()for a general behavioral description.
- begin(nested: bool = False) SessionTransaction¶
Begin a transaction, or nested transaction, on this
Session, if one is not already begun.The
_orm.Sessionobject 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
Sessionis already inside of a transaction.- Parameters:
nested – if True, begins a SAVEPOINT transaction and is equivalent to calling
begin_nested(). For documentation on SAVEPOINT transactions, please see Using SAVEPOINT.- Returns:
the
SessionTransactionobject. Note thatSessionTransactionacts as a Python context manager, allowingSession.begin()to be used in a “with” block. See Explicit Begin for an example.
- begin_nested() SessionTransaction¶
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
SessionTransactionobject. Note thatSessionTransactionacts 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. For asyncio use cases, see the section Serializable isolation / Savepoints / Transactional DDL (asyncio version).
- bind_mapper(mapper: _EntityBindKey[_O], bind: _SessionBind) None¶
Associate a
_orm.Mapperor arbitrary Python class with a “bind”, e.g. an_engine.Engineor_engine.Connection.The given entity is added to a lookup used by the
Session.get_bind()method.- Parameters:
mapper – a
_orm.Mapperobject, or an instance of a mapped class, or any Python class that is the base of a set of mapped classes.bind – an
_engine.Engineor_engine.Connectionobject.
- bind_table(table: TableClause, bind: Engine | Connection) None¶
Associate a
_schema.Tablewith a “bind”, e.g. an_engine.Engineor_engine.Connection.The given
_schema.Tableis added to a lookup used by theSession.get_bind()method.- Parameters:
table – a
_schema.Tableobject, which is typically the target of an ORM mapping, or is present within a selectable that is mapped.bind – an
_engine.Engineor_engine.Connectionobject.
See also
Partitioning Strategies (e.g. multiple database backends per Session)
Session.bind_mapper()
- bulk_insert_mappings(mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]], return_defaults: bool = False, render_nulls: bool = False) None¶
Perform a bulk insert of the given list of mapping dictionaries.
- Parameters:
mapper – a mapped class, or the actual
_orm.Mapperobject, 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, the INSERT process will be altered to ensure that newly generated primary key values will be fetched. The rationale for this parameter is typically to enable Joined Table Inheritance mappings to be bulk inserted.
Note
for backends that don’t support RETURNING, the :paramref:`_orm.Session.bulk_insert_mappings.return_defaults` parameter can significantly decrease performance as INSERT statements can no longer be batched. See “Insert Many Values” Behavior for INSERT statements for background on which backends are affected.
render_nulls –
When True, a value of
Nonewill 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.
See also
queryguide/dml
Session.bulk_save_objects()Session.bulk_update_mappings()
- bulk_save_objects(objects: Iterable[object], return_defaults: bool = False, update_changed_only: bool = True, preserve_order: bool = True) None¶
Perform a bulk save of the given list of objects.
- Parameters:
objects –
a sequence of mapped object instances. The mapped objects are persisted as is, and are not associated with the
Sessionafterwards.For each object, whether the object is sent as an INSERT or an UPDATE is dependent on the same rules used by the
Sessionin traditional operation; if the object has theInstanceState.keyattribute 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_onlyis 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, :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_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.
See also
queryguide/dml
Session.bulk_insert_mappings()Session.bulk_update_mappings()
- bulk_update_mappings(mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]]) None¶
Perform a bulk update of the given list of mapping dictionaries.
- Parameters:
mapper – a mapped class, or the actual
_orm.Mapperobject, 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
queryguide/dml
Session.bulk_insert_mappings()Session.bulk_save_objects()
- close() None¶
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 releases any_engine.Connectionobjects which this_orm.Sessionitself has checked out from associated_engine.Engineobjects. The operation then leaves the_orm.Sessionin a state which it may be used again.Tip
In the default running mode the
_orm.Session.close()method does not prevent the Session from being used again. The_orm.Sessionitself does not actually have a distinct “closed” state; it merely means the_orm.Sessionwill release all database connections and ORM objects.Setting the parameter :paramref:`_orm.Session.close_resets_only` to
Falsewill instead make theclosefinal, meaning that any further action on the session will be forbidden.Changed in version 1.4: The
Session.close()method does not immediately create a newSessionTransactionobject; instead, the newSessionTransactionis created only if theSessionis used again for a database operation.See also
Closing - detail on the semantics of
_orm.Session.close()and_orm.Session.reset()._orm.Session.reset()- a similar method that behaves likeclose()with the parameter :paramref:`_orm.Session.close_resets_only` set toTrue.
- classmethod close_all() None¶
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 tosession.close_all_sessions().
- commit() None¶
Flush pending changes and commit the current transaction.
When the COMMIT operation is complete, all objects are fully expired, erasing their internal contents, which will be automatically re-loaded when the objects are next accessed. In the interim, these objects are in an expired state and will not function if they are detached from the
Session. Additionally, this re-load operation is not supported when using asyncio-oriented APIs. The :paramref:`.Session.expire_on_commit` parameter may be used to disable this behavior.When there is no transaction in place for the
Session, indicating that no operations were invoked on thisSessionsince the previous call toSession.commit(), the method will begin and commit an internal-only “logical” transaction, that does not normally affect the database unless pending flush changes were detected, but will still invoke event handlers and object expiration rules.The outermost database transaction is committed unconditionally, automatically releasing any SAVEPOINTs in effect.
- connection(bind_arguments: _BindArguments | None = None, execution_options: CoreExecuteOptionsParameter | None = None) Connection¶
Return a
_engine.Connectionobject corresponding to thisSessionobject’s transactional state.Either the
_engine.Connectioncorresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the_engine.Connectionreturned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted).Ambiguity in multi-bind or unbound
Sessionobjects 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().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 theSession, a warning is emitted and the arguments are ignored.
- delete(instance: object) None¶
Mark an instance as deleted.
The object is assumed to be either persistent or detached when passed; after the method is called, the object will remain in the persistent state until the next flush proceeds. During this time, the object will also be a member of the
_orm.Session.deletedcollection.When the next flush proceeds, the object will move to the deleted state, indicating a
DELETEstatement was emitted for its row within the current transaction. When the transaction is successfully committed, the deleted object is moved to the detached state and is no longer present within this_orm.Session.See also
- property deleted: IdentitySet¶
The set of all instances marked as ‘deleted’ within this
Session
- property dirty: IdentitySet¶
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.
- enable_relationship_loading(obj: object) None¶
Associate an object with this
Sessionfor 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 thisSessionas 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_pendingflag 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
SessionviaSession.enable_relationship_loading()pending, add it to theSessionusingSession.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
: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 aSessionwithout SQL emitted, which then will unexpire attributes on access.
- execute(statement: Executable, params: _CoreAnyExecuteParams | None = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: _BindArguments | None = None, _parent_execute_state: Any | None = None, _add_event: Any | None = None) Result[Any]¶
Execute a SQL expression construct.
Returns a
_engine.Resultobject 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_engine.Connection.execute(), the 2.0 style version of_engine.Connection.Changed in version 1.4: the
_orm.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
Executableexpression such as_expression.select()).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
_engine.Connection.execution_options(), and may also provide additional options understood only in an ORM context.See also
ORM Execution Options - ORM-specific execution options
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.
- Returns:
a
_engine.Resultobject.
- expire(instance: object, attribute_names: Iterable[str] | None = None) 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
Sessionobject’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
Sessionsimultaneously, useSession.expire_all().The
Sessionobject’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 - introductory material
Session.expire()Session.refresh()_orm.Query.populate_existing()
- expire_all() None¶
Expires all persistent instances within this Session.
When any attributes on a persistent instance is next accessed, a query will be issued using the
Sessionobject’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
Sessionobject’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()is not usually needed, assuming the transaction is isolated.See also
Refreshing / Expiring - introductory material
Session.expire()Session.refresh()_orm.Query.populate_existing()
- expunge(instance: object) None¶
Remove the instance from this
Session.This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.
- expunge_all() None¶
Remove all object instances from this
Session.This is equivalent to calling
expunge(obj)on all objects in thisSession.
- flush(objects: Sequence[Any] | None = None) 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.
- 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.
- get(entity: _EntityBindKey[_O], ident: _PKIdentityArgument, *, options: Sequence[ORMOption] | None = None, populate_existing: bool = False, with_for_update: ForUpdateParameter = None, identity_token: Any | None = None, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: _BindArguments | None = None) _O | None¶
Return an instance based on the given primary key identifier, or
Noneif 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} )
Added in version 1.4: Added
_orm.Session.get(), which is moved from the now legacy_orm.Query.get()method._orm.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._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,ObjectDeletedErroris raised.- Parameters:
entity – a mapped class or
Mapperindicating 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.Tableobject’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_idas 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
Trueindicating 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.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.Added in version 1.4.29.
See also
ORM Execution Options - ORM-specific execution options
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.
- Returns:
The object instance, or
None.
- get_bind(mapper: _EntityBindKey[_O] | None = None, *, clause: ClauseElement | None = None, bind: _SessionBind | None = None, _sa_skip_events: bool | None = None, _sa_skip_for_implicit_returning: bool = False, **kw: Any) Engine | Connection¶
Return a “bind” to which this
Sessionis bound.The “bind” is usually an instance of
_engine.Engine, except in the case where theSessionhas been explicitly bound directly to a_engine.Connection.For a multiply-bound or unbound
Session, themapperorclausearguments 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 :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.if clause given and
Session.bindsis present, locate a bind based on_schema.Tableobjects found in the given clause present inSession.binds.if
Session.bindsis present, return that.if clause given, attempt to return a bind linked to the
_schema.MetaDataultimately associated with the clause.if mapper given, attempt to return a bind linked to the
_schema.MetaDataultimately associated with the_schema.Tableor other selectable to which the mapper is mapped.No bind can be found,
UnboundExecutionErroris raised.
Note that the
Session.get_bind()method can be overridden on a user-defined subclass ofSessionto provide any kind of bind resolution scheme. See the example at Custom Vertical Partitioning.- Parameters:
mapper – Optional mapped class or corresponding
_orm.Mapperinstance. The bind can be derived from a_orm.Mapperfirst by consulting the “binds” map associated with thisSession, and secondly by consulting the_schema.MetaDataassociated with the_schema.Tableto which the_orm.Mapperis mapped for a bind.clause – A
_expression.ClauseElement(i.e._expression.select(),_expression.text(), etc.). If themapperargument is not present or could not produce a bind, the given expression construct will be searched for a bound element, typically a_schema.Tableassociated with bound_schema.MetaData.
See also
Partitioning Strategies (e.g. multiple database backends per Session)
Session.bind_mapper()Session.bind_table()
- get_nested_transaction() SessionTransaction | None¶
Return the current nested transaction in progress, if any.
Added in version 1.4.
- get_one(entity: _EntityBindKey[_O], ident: _PKIdentityArgument, *, options: Sequence[ORMOption] | None = None, populate_existing: bool = False, with_for_update: ForUpdateParameter = None, identity_token: Any | None = None, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: _BindArguments | None = None) _O¶
Return exactly one instance based on the given primary key identifier, or raise an exception if not found.
Raises
sqlalchemy.orm.exc.NoResultFoundif the query selects no rows.For a detailed documentation of the arguments see the method
Session.get().Added in version 2.0.22.
- Returns:
The object instance.
See also
Session.get()- equivalent method that insteadreturns
Noneif no row was found with the provided primary key
- get_transaction() SessionTransaction | None¶
Return the current root transaction in progress, if any.
Added in version 1.4.
- classmethod identity_key(class_: Type[Any] | None = None, ident: Any | Tuple[Any, ...] = None, *, instance: Any | None = None, row: Row[Any] | RowMapping | None = None, identity_token: Any | None = None) _IdentityKeyType[Any]¶
Return an identity key.
This is an alias of
util.identity_key().
- identity_map: IdentityMap¶
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.
- in_nested_transaction() bool¶
Return True if this
_orm.Sessionhas begun a nested transaction, e.g. SAVEPOINT.Added in version 1.4.
- in_transaction() bool¶
Return True if this
_orm.Sessionhas begun a transaction.Added in version 1.4.
See also
_orm.Session.is_active
- info¶
A user-modifiable dictionary.
The initial value of this dictionary can be populated using the
infoargument to theSessionconstructor orsessionmakerconstructor or factory methods. The dictionary here is always local to thisSessionand can be modified independently of all otherSessionobjects.
- invalidate() None¶
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.Connectionobject that is currently in use for a transaction (typically there is only one connection unless the_orm.Sessionis 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
Timeoutexceptions 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.
- property is_active: bool¶
True if this
Sessionnot in “partial rollback” state.Changed in version 1.4: The
_orm.Sessionno longer begins a new transaction immediately, so this attribute will be False when the_orm.Sessionis first instantiated.“partial rollback” state typically indicates that the flush process of the
_orm.Sessionhas failed, and that the_orm.Session.rollback()method must be emitted in order to fully roll back the transaction.If this
_orm.Sessionis not in a transaction at all, the_orm.Sessionwill autobegin when it is first used, so in this case_orm.Session.is_activewill return True.Otherwise, if this
_orm.Sessionis within a transaction, and that transaction has not been rolled back internally, the_orm.Session.is_activewill also return True.See also
_orm.Session.in_transaction()
- is_modified(instance: object, include_collections: bool = True) bool¶
Return
Trueif 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.dirtycollection; 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.dirtycollection may reportFalsewhen 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_historyflag 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_historyargument 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
Falseis 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.
- merge(instance: _O, *, load: bool = True, options: Sequence[ORMOption] | None = None) _O¶
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 theSessionif not already.This operation cascades to associated instances if the association is mapped with
cascade="merge".See Merging for a detailed discussion of merging.
- 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 aSessionfrom a second level cache, or to transfer just-loaded objects into theSessionowned by a worker thread or process without re-querying the database.The
load=Falseuse 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=Falseare 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.Added in version 1.4.24.
See also
make_transient_to_detached()- provides for an alternative means of “merging” a single object into theSession
- property new: IdentitySet¶
The set of all instances marked as ‘new’ within this
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.
- classmethod object_session(instance: object) Session | None¶
Return the
Sessionto which an object belongs.This is an alias of
object_session().
- prepare() None¶
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
InvalidRequestErroris raised.
- query(*entities: _ColumnsClauseArgument[Any], **kwargs: Any) Query[Any]¶
Return a new
_query.Queryobject corresponding to this_orm.Session.Note that the
_query.Queryobject is legacy as of SQLAlchemy 2.0; the_sql.select()construct is now used to construct ORM queries.
- refresh(instance: object, attribute_names: Iterable[str] | None = None, with_for_update: ForUpdateParameter = None) 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.Added in version 1.4: - the
_orm.Session.refresh()method can also refresh eagerly loaded attributes._orm.relationship()oriented attributes that would normally load using theselect(or “lazy”) loader strategy will also load if they are named explicitly in the attribute_names collection, emitting a SELECT statement for the attribute using theimmediateloader strategy. If lazy-loaded relationships are not named in :paramref:`_orm.Session.refresh.attribute_names`, then they remain as “lazy loaded” attributes and are not implicitly refreshed.Changed in version 2.0.4: The
_orm.Session.refresh()method will now refresh lazy-loaded_orm.relationship()oriented attributes for those which are named explicitly in the :paramref:`_orm.Session.refresh.attribute_names` collection.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 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.
- Parameters:
attribute_names – optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.
with_for_update – optional boolean
Trueindicating 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.
See also
Refreshing / Expiring - introductory material
Session.expire()Session.expire_all()Populate Existing - allows any ORM query to refresh objects as they would be loaded normally.
- reset() None¶
Close out the transactional resources and ORM objects used by this
_orm.Session, resetting the session to its initial state.This method provides for same “reset-only” behavior that the
_orm.Session.close()method has provided historically, where the state of the_orm.Sessionis reset as though the object were brand new, and ready to be used again. This method may then be useful for_orm.Sessionobjects which set :paramref:`_orm.Session.close_resets_only` toFalse, so that “reset only” behavior is still available.Added in version 2.0.22.
See also
Closing - detail on the semantics of
_orm.Session.close()and_orm.Session.reset()._orm.Session.close()- a similar method will additionally prevent re-use of the Session when the parameter :paramref:`_orm.Session.close_resets_only` is set toFalse.
- rollback() None¶
Rollback the current transaction in progress.
If no transaction is in progress, this method is a pass-through.
The method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress.
- scalar(statement: Executable, params: _CoreSingleExecuteParams | None = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: _BindArguments | None = None, **kw: Any) Any¶
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.
- scalars(statement: Executable, params: _CoreAnyExecuteParams | None = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: _BindArguments | None = None, **kw: Any) ScalarResult[Any]¶
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.ScalarResultfiltering object which will return single elements rather than_row.Rowobjects.- Returns:
a
_result.ScalarResultobject
Added in version 1.4.24: Added
_orm.Session.scalars()Added in version 1.4.26: Added
_orm.scoped_session.scalars()See also
Selecting ORM Entities - contrasts the behavior of
_orm.Session.execute()to_orm.Session.scalars()
- upsert(obj: Object) Object¶
Approximate insert-or-update functionality
If the given object is not in the session, it is merged in, loading and updating the object that shares its type and primary key if any, or creating a completely new object if one of its type with its primary key did not already exist. Objects passed in that were already in the session are not touched,, as modifications to those objects will be persisted on next commit regardless.