Sessions
plateforme.core.database.sessions
This module provides utilities for managing database sessions within the Plateforme framework using SQLAlchemy features.
Async
This module provides utilities for managing database sessions within the Plateforme framework using SQLAlchemy features.
AsyncSessionFactory
module-attribute
AsyncSessionFactory = (
async_sessionmaker["AsyncSession"]
| async_scoped_session["AsyncSession"]
)
A type alias for an async session factory for async session objects.
AsyncSession
AsyncSession(
bind: AsyncConnection | AsyncEngine | None = None,
routing: DatabaseManager | None = None,
*args: Any,
**kwargs: Any,
)
Bases: AsyncSession
Manages persistence operations asynchronously for ORM-mapped objects.
Asyncio version of the Session
. It is a proxy for a traditional class
Session
instance.
Initialize the async session.
See also the async_session_factory
function which is used to generate
an AsyncSession
-producing callable with a given set of arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bind
|
AsyncConnection | AsyncEngine | None
|
An optional |
None
|
routing
|
DatabaseManager | None
|
An optional |
None
|
Note
All other keyword arguments are passed to the constructor of the SQLAlchemy parent session class.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
sync_session_class
class-attribute
instance-attribute
The class or callable that provides the
underlying :class:_orm.Session
instance for a particular
:class:_asyncio.AsyncSession
.
At the class level, this attribute is the default value for the
:paramref:_asyncio.AsyncSession.sync_session_class
parameter. Custom
subclasses of :class:_asyncio.AsyncSession
can override this.
At the instance level, this attribute indicates the current class or
callable that was used to provide the :class:_orm.Session
instance for
this :class:_asyncio.AsyncSession
instance.
.. versionadded:: 1.4.24
sync_session
instance-attribute
sync_session: Session
Reference to the underlying :class:_orm.Session
this
:class:_asyncio.AsyncSession
proxies requests towards.
This instance can be used as an event target.
.. seealso::
:ref:`asyncio_events`
dirty
property
dirty: Any
The set of all persistent instances considered dirty.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
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 :meth:.Session.is_modified
method.
deleted
property
deleted: Any
The set of all instances marked as 'deleted' within this Session
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
new
property
new: Any
The set of all instances marked as 'new' within this Session
.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
identity_map
property
writable
identity_map: IdentityMap
Proxy for the :attr:_orm.Session.identity_map
attribute
on behalf of the :class:_asyncio.AsyncSession
class.
is_active
property
is_active: Any
True if this :class:.Session
not in "partial rollback" state.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
.. versionchanged:: 1.4 The :class:_orm.Session
no longer begins
a new transaction immediately, so this attribute will be False
when the :class:_orm.Session
is first instantiated.
"partial rollback" state typically indicates that the flush process
of the :class:_orm.Session
has failed, and that the
:meth:_orm.Session.rollback
method must be emitted in order to
fully roll back the transaction.
If this :class:_orm.Session
is not in a transaction at all, the
:class:_orm.Session
will autobegin when it is first used, so in this
case :attr:_orm.Session.is_active
will return True.
Otherwise, if this :class:_orm.Session
is within a transaction,
and that transaction has not been rolled back internally, the
:attr:_orm.Session.is_active
will also return True.
.. seealso::
:ref:`faq_session_rollback`
:meth:`_orm.Session.in_transaction`
autoflush
property
writable
autoflush: bool
Proxy for the :attr:_orm.Session.autoflush
attribute
on behalf of the :class:_asyncio.AsyncSession
class.
no_autoflush
property
no_autoflush: Any
Return a context manager that disables autoflush.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
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.
info
property
info: Any
A user-modifiable dictionary.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class
on behalf of the :class:`_asyncio.AsyncSession` class.
The initial value of this dictionary can be populated using the
info
argument to the :class:.Session
constructor or
:class:.sessionmaker
constructor or factory methods. The dictionary
here is always local to this :class:.Session
and can be modified
independently of all other :class:.Session
objects.
refresh
async
refresh(
instance: object,
attribute_names: Optional[Iterable[str]] = None,
with_for_update: ForUpdateParameter = None,
) -> 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.
This is the async version of the :meth:_orm.Session.refresh
method.
See that method for a complete description of all options.
.. seealso::
:meth:`_orm.Session.refresh` - main documentation for refresh
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
run_sync
async
Invoke the given synchronous (i.e. not async) callable,
passing a synchronous-style :class:_orm.Session
as the first
argument.
This method allows traditional synchronous SQLAlchemy functions to run within the context of an asyncio application.
E.g.::
def some_business_method(session: Session, param: str) -> str:
'''A synchronous function that does not require awaiting
:param session: a SQLAlchemy Session, used synchronously
:return: an optional return value is supported
'''
session.add(MyObject(param=param))
session.flush()
return "success"
async def do_something_async(async_engine: AsyncEngine) -> None:
'''an async function that uses awaiting'''
with AsyncSession(async_engine) as async_session:
# run some_business_method() with a sync-style
# Session, proxied into an awaitable
return_code = await async_session.run_sync(some_business_method, param="param1")
print(return_code)
This method maintains the asyncio event loop all the way through to the database connection by running the given callable in a specially instrumented greenlet.
.. tip::
The provided callable is invoked inline within the asyncio event
loop, and will block on traditional IO calls. IO within this
callable should only call into SQLAlchemy's asyncio database
APIs which will be properly adapted to the greenlet context.
.. seealso::
:class:`.AsyncAttrs` - a mixin for ORM mapped classes that provides
a similar feature more succinctly on a per-attribute basis
:meth:`.AsyncConnection.run_sync`
:ref:`session_run_sync`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
execute
async
execute(
statement: TypedReturnsRows[_T],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
_parent_execute_state: Optional[Any] = None,
_add_event: Optional[Any] = None,
) -> Result[_T]
execute(
statement: UpdateBase,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
_parent_execute_state: Optional[Any] = None,
_add_event: Optional[Any] = None,
) -> CursorResult[Any]
execute(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Result[Any]
Execute a statement and return a buffered
:class:_engine.Result
object.
.. seealso::
:meth:`_orm.Session.execute` - main documentation for execute
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
scalar
async
scalar(
statement: TypedReturnsRows[Tuple[_T]],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Optional[_T]
scalar(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Any
scalar(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Any
Execute a statement and return a scalar result.
.. seealso::
:meth:`_orm.Session.scalar` - main documentation for scalar
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
scalars
async
scalars(
statement: TypedReturnsRows[Tuple[_T]],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[_T]
scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[Any]
scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[Any]
Execute a statement and return scalar results.
:return: a :class:_result.ScalarResult
object
.. versionadded:: 1.4.24 Added :meth:_asyncio.AsyncSession.scalars
.. versionadded:: 1.4.26 Added
:meth:_asyncio.async_scoped_session.scalars
.. seealso::
:meth:`_orm.Session.scalars` - main documentation for scalars
:meth:`_asyncio.AsyncSession.stream_scalars` - streaming version
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
get
async
get(
entity: _EntityBindKey[_O],
ident: _PKIdentityArgument,
*,
options: Optional[Sequence[ORMOption]] = None,
populate_existing: bool = False,
with_for_update: ForUpdateParameter = None,
identity_token: Optional[Any] = None,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
) -> Union[_O, None]
Return an instance based on the given primary key identifier,
or None
if not found.
.. seealso::
:meth:`_orm.Session.get` - main documentation for get
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
get_one
async
get_one(
entity: _EntityBindKey[_O],
ident: _PKIdentityArgument,
*,
options: Optional[Sequence[ORMOption]] = None,
populate_existing: bool = False,
with_for_update: ForUpdateParameter = None,
identity_token: Optional[Any] = None,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
) -> _O
Return an instance based on the given primary key identifier, or raise an exception if not found.
Raises sqlalchemy.orm.exc.NoResultFound
if the query selects
no rows.
..versionadded: 2.0.22
.. seealso::
:meth:`_orm.Session.get_one` - main documentation for get_one
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
stream
async
stream(
statement: TypedReturnsRows[_T],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncResult[_T]
stream(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncResult[Any]
stream(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncResult[Any]
Execute a statement and return a streaming
:class:_asyncio.AsyncResult
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
stream_scalars
async
stream_scalars(
statement: TypedReturnsRows[Tuple[_T]],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncScalarResult[_T]
stream_scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncScalarResult[Any]
stream_scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> AsyncScalarResult[Any]
Execute a statement and return a stream of scalar results.
:return: an :class:_asyncio.AsyncScalarResult
object
.. versionadded:: 1.4.24
.. seealso::
:meth:`_orm.Session.scalars` - main documentation for scalars
:meth:`_asyncio.AsyncSession.scalars` - non streaming version
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
delete
async
delete(instance: object) -> None
Mark an instance as deleted.
The database delete operation occurs upon flush()
.
As this operation may need to cascade along unloaded relationships, it is awaitable to allow for those queries to take place.
.. seealso::
:meth:`_orm.Session.delete` - main documentation for delete
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
merge
async
Copy the state of a given instance into a corresponding instance
within this :class:_asyncio.AsyncSession
.
.. seealso::
:meth:`_orm.Session.merge` - main documentation for merge
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
flush
async
Flush all the object changes to the database.
.. seealso::
:meth:`_orm.Session.flush` - main documentation for flush
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
get_transaction
get_transaction() -> Optional[AsyncSessionTransaction]
Return the current root transaction in progress, if any.
:return: an :class:_asyncio.AsyncSessionTransaction
object, or
None
.
.. versionadded:: 1.4.18
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
get_nested_transaction
get_nested_transaction() -> Optional[
AsyncSessionTransaction
]
Return the current nested transaction in progress, if any.
:return: an :class:_asyncio.AsyncSessionTransaction
object, or
None
.
.. versionadded:: 1.4.18
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
get_bind
get_bind(
mapper: Optional[_EntityBindKey[_O]] = None,
clause: Optional[ClauseElement] = None,
bind: Optional[_SessionBind] = None,
**kw: Any,
) -> Union[Engine, Connection]
Return a "bind" to which the synchronous proxied :class:_orm.Session
is bound.
Unlike the :meth:_orm.Session.get_bind
method, this method is
currently not used by this :class:.AsyncSession
in any way
in order to resolve engines for requests.
.. note::
This method proxies directly to the :meth:`_orm.Session.get_bind`
method, however is currently **not** useful as an override target,
in contrast to that of the :meth:`_orm.Session.get_bind` method.
The example below illustrates how to implement custom
:meth:`_orm.Session.get_bind` schemes that work with
:class:`.AsyncSession` and :class:`.AsyncEngine`.
The pattern introduced at :ref:session_custom_partitioning
illustrates how to apply a custom bind-lookup scheme to a
:class:_orm.Session
given a set of :class:_engine.Engine
objects.
To apply a corresponding :meth:_orm.Session.get_bind
implementation
for use with a :class:.AsyncSession
and :class:.AsyncEngine
objects, continue to subclass :class:_orm.Session
and apply it to
:class:.AsyncSession
using
:paramref:.AsyncSession.sync_session_class
. The inner method must
continue to return :class:_engine.Engine
instances, which can be
acquired from a :class:_asyncio.AsyncEngine
using the
:attr:_asyncio.AsyncEngine.sync_engine
attribute::
# using example from "Custom Vertical Partitioning"
import random
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import async_sessionmaker
from sqlalchemy.orm import Session
# construct async engines w/ async drivers
engines = {
'leader':create_async_engine("sqlite+aiosqlite:///leader.db"),
'other':create_async_engine("sqlite+aiosqlite:///other.db"),
'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"),
'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"),
}
class RoutingSession(Session):
def get_bind(self, mapper=None, clause=None, **kw):
# within get_bind(), return sync engines
if mapper and issubclass(mapper.class_, MyOtherClass):
return engines['other'].sync_engine
elif self._flushing or isinstance(clause, (Update, Delete)):
return engines['leader'].sync_engine
else:
return engines[
random.choice(['follower1','follower2'])
].sync_engine
# apply to AsyncSession using sync_session_class
AsyncSessionMaker = async_sessionmaker(
sync_session_class=RoutingSession
)
The :meth:_orm.Session.get_bind
method is called in a non-asyncio,
implicitly non-blocking context in the same manner as ORM event hooks
and functions that are invoked via :meth:.AsyncSession.run_sync
, so
routines that wish to run SQL commands inside of
:meth:_orm.Session.get_bind
can continue to do so using
blocking-style code, which will be translated to implicitly async calls
at the point of invoking IO on the database drivers.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 |
|
connection
async
connection(
bind_arguments: Optional[_BindArguments] = None,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
**kw: Any,
) -> AsyncConnection
Return a :class:_asyncio.AsyncConnection
object corresponding to
this :class:.Session
object's transactional state.
This method may also be used to establish execution options for the database connection used by the current transaction.
.. versionadded:: 1.4.24 Added **kw arguments which are passed
through to the underlying :meth:_orm.Session.connection
method.
.. seealso::
:meth:`_orm.Session.connection` - main documentation for
"connection"
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
begin
begin() -> AsyncSessionTransaction
Return an :class:_asyncio.AsyncSessionTransaction
object.
The underlying :class:_orm.Session
will perform the
"begin" action when the :class:_asyncio.AsyncSessionTransaction
object is entered::
async with async_session.begin():
# .. ORM transaction is begun
Note that database IO will not normally occur when the session-level
transaction is begun, as database transactions begin on an
on-demand basis. However, the begin block is async to accommodate
for a :meth:_orm.SessionEvents.after_transaction_create
event hook that may perform IO.
For a general description of ORM begin, see
:meth:_orm.Session.begin
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
begin_nested
begin_nested() -> AsyncSessionTransaction
Return an :class:_asyncio.AsyncSessionTransaction
object
which will begin a "nested" transaction, e.g. SAVEPOINT.
Behavior is the same as that of :meth:_asyncio.AsyncSession.begin
.
For a general description of ORM begin nested, see
:meth:_orm.Session.begin_nested
.
.. seealso::
:ref:`aiosqlite_serializable` - special workarounds required
with the SQLite asyncio driver in order for SAVEPOINT to work
correctly.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
rollback
async
Rollback the current transaction in progress.
.. seealso::
:meth:`_orm.Session.rollback` - main documentation for
"rollback"
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
commit
async
Commit the current transaction in progress.
.. seealso::
:meth:`_orm.Session.commit` - main documentation for
"commit"
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
close
async
Close out the transactional resources and ORM objects used by this
:class:_asyncio.AsyncSession
.
.. seealso::
:meth:`_orm.Session.close` - main documentation for
"close"
:ref:`session_closing` - detail on the semantics of
:meth:`_asyncio.AsyncSession.close` and
:meth:`_asyncio.AsyncSession.reset`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
reset
async
Close out the transactional resources and ORM objects used by this
:class:_orm.Session
, resetting the session to its initial state.
.. versionadded:: 2.0.22
.. seealso::
:meth:`_orm.Session.reset` - main documentation for
"reset"
:ref:`session_closing` - detail on the semantics of
:meth:`_asyncio.AsyncSession.close` and
:meth:`_asyncio.AsyncSession.reset`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
aclose
async
A synonym for :meth:_asyncio.AsyncSession.close
.
The :meth:_asyncio.AsyncSession.aclose
name is specifically
to support the Python standard library @contextlib.aclosing
context manager function.
.. versionadded:: 2.0.20
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
invalidate
async
Close this Session, using connection invalidation.
For a complete description, see :meth:_orm.Session.invalidate
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
close_all
async
classmethod
Close all :class:_asyncio.AsyncSession
sessions.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
add
Place an object into this :class:_orm.Session
.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
Objects that are in the :term:transient
state when passed to the
:meth:_orm.Session.add
method will move to the
:term:pending
state, until the next flush, at which point they
will move to the :term:persistent
state.
Objects that are in the :term:detached
state when passed to the
:meth:_orm.Session.add
method will move to the :term:persistent
state directly.
If the transaction used by the :class:_orm.Session
is rolled back,
objects which were transient when they were passed to
:meth:_orm.Session.add
will be moved back to the
:term:transient
state, and will no longer be present within this
:class:_orm.Session
.
.. seealso::
:meth:`_orm.Session.add_all`
:ref:`session_adding` - at :ref:`session_basics`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
add_all
Add the given collection of instances to this :class:_orm.Session
.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
See the documentation for :meth:_orm.Session.add
for a general
behavioral description.
.. seealso::
:meth:`_orm.Session.add`
:ref:`session_adding` - at :ref:`session_basics`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
expire
Expire the attributes on an instance.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
Marks the attributes of an instance as out of date. When an expired
attribute is next accessed, a query will be issued to the
:class:.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 :class:.Session
simultaneously,
use :meth:Session.expire_all
.
The :class:.Session
object's default behavior is to
expire all state whenever the :meth:Session.rollback
or :meth:Session.commit
methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling :meth:Session.expire
only makes sense for the specific
case that a non-ORM SQL statement was emitted in the current
transaction.
:param instance: The instance to be refreshed. :param attribute_names: optional list of string attribute names indicating a subset of attributes to be expired.
.. seealso::
:ref:`session_expire` - introductory material
:meth:`.Session.expire`
:meth:`.Session.refresh`
:meth:`_orm.Query.populate_existing`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
expire_all
Expires all persistent instances within this Session.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
When any attributes on a persistent instance is next accessed,
a query will be issued using the
:class:.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 :meth:Session.expire
.
The :class:.Session
object's default behavior is to
expire all state whenever the :meth:Session.rollback
or :meth:Session.commit
methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling :meth:Session.expire_all
is not usually needed,
assuming the transaction is isolated.
.. seealso::
:ref:`session_expire` - introductory material
:meth:`.Session.expire`
:meth:`.Session.refresh`
:meth:`_orm.Query.populate_existing`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
expunge
expunge(instance: object) -> None
Remove the instance
from this Session
.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
expunge_all
Remove all object instances from this Session
.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
This is equivalent to calling expunge(obj)
on all objects in this
Session
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
is_modified
Return True
if the given instance has locally
modified attributes.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
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
:attr:.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 :attr:
.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 in :attr:.Session.dirty
, but ultimately the state is the same as that loaded from the database, resulting in no net change here. - Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the "old" value when a set event occurs, so it skips the expense of a SQL call if the old value isn't present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn't, is less expensive on average than issuing a defensive SELECT.
The "old" value is fetched unconditionally upon set only if the
attribute container has the active_history
flag set to True
.
This flag is set typically for primary key attributes and scalar
object references that are not a simple many-to-one. To set this
flag for any arbitrary mapped column, use the active_history
argument with :func:.column_property
.
:param instance: mapped instance to be tested for pending changes.
:param 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 |
|
in_transaction
in_transaction() -> bool
Return True if this :class:_orm.Session
has begun a transaction.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
.. versionadded:: 1.4
.. seealso::
:attr:`_orm.Session.is_active`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
in_nested_transaction
in_nested_transaction() -> bool
Return True if this :class:_orm.Session
has begun a nested
transaction, e.g. SAVEPOINT.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
object_session
classmethod
Return the :class:.Session
to which an object belongs.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
This is an alias of :func:.object_session
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
identity_key
classmethod
identity_key(
class_: Optional[Type[Any]] = None,
ident: Union[Any, Tuple[Any, ...]] = None,
*,
instance: Optional[Any] = None,
row: Optional[Union[Row[Any], RowMapping]] = None,
identity_token: Optional[Any] = None,
) -> _IdentityKeyType[Any]
Return an identity key.
.. container:: class_bases
Proxied for the :class:`_orm.Session` class on
behalf of the :class:`_asyncio.AsyncSession` class.
This is an alias of :func:.util.identity_key
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/ext/asyncio/session.py
bulk
async
bulk(
*, proxy_reference: bool = True
) -> AsyncGenerator[AsyncSessionBulk, None]
An async session bulk context manager for AsyncSession
objects.
The proxy option indicates that the provided resource references should be encapsulated with a proxy, this is done when validating the resource using the Pydantic core schema. This can be useful to resolve the references that target the same resource into a single instance. Thus, modifying a resolved instance will affect all references that target the same resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proxy_reference
|
bool
|
Whether the registered resource references should
be encapsulated with a proxy or not. Defaults to |
True
|
Returns:
Type | Description |
---|---|
AsyncGenerator[AsyncSessionBulk, None]
|
An |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
AsyncSessionBulk
AsyncSessionBulk(
session: _T, *, proxy_reference: bool = True
)
Bases: Bulk[AsyncSession]
An async bulk operation manager for resources.
It is used to register resources for bulk operations and commit or rollback them in a single operation within an async session.
Initialize the session bulk manager.
The proxy option indicates that the provided resource references should be encapsulated with a proxy, this is done when validating the resource using the Pydantic core schema. This can be useful to resolve the references that target the same resource into a single instance. Thus, modifying a resolved instance will affect all references that target the same resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
_T
|
The session to use for the bulk operations. |
required |
proxy_reference
|
bool
|
Whether the registered resource references should
be encapsulated with a proxy or not. Defaults to |
True
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
add
add(
instance: BaseResource | BaseSpec,
*,
is_reference: bool = False,
) -> None
Add a resource instance to the bulk manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instance
|
BaseResource | BaseSpec
|
The resource instance to add to the bulk manager. |
required |
is_reference
|
bool
|
Whether the provided resource instance is a reference
or not. Defaults to |
False
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
get
get(
entity: ResourceType | SpecType,
*,
resolved: bool | None = None,
scope: Literal["all", "references", "values"] = "all",
) -> list[BaseResource]
Get the resource instances registered in the bulk manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
entity
|
ResourceType | SpecType
|
The resource type to get the resource instances for. |
required |
resolved
|
bool | None
|
Whether to get only the resolved resources or not:
- |
None
|
scope
|
Literal['all', 'references', 'values']
|
The scope of the resource instances to get:
- |
'all'
|
Returns:
Type | Description |
---|---|
list[BaseResource]
|
The list of resource instances registered in the bulk manager for |
list[BaseResource]
|
the specified resource type and options. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
resolve
async
resolve(
*,
raise_errors: bool = True,
scope: Literal["all", "references", "values"] = "all",
strategy: Literal["bind", "hydrate"] = "bind",
) -> None
Resolve the specified scope of resource entries in the bulk.
For resource references, if the proxy_reference
option is enabled,
the resolved instances replace the reference proxy targets. Otherwise,
the resolved instances are used to update the reference proxy target.
For resource values, the resolved instances are used to update the resource instances with the fetched data, no proxy is used.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
raise_errors
|
bool
|
Whether to raise errors when failing to resolve
resource references or values. Defaults to |
True
|
scope
|
Literal['all', 'references', 'values']
|
The scope of the resources to resolve, it can be either:
- |
'all'
|
strategy
|
Literal['bind', 'hydrate']
|
The resolution strategy to use, it can be either:
- |
'bind'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
async_session_factory
async_session_factory(
bind: AsyncConnection | AsyncEngine | None = None,
routing: DatabaseManager | None = None,
scoped: bool = False,
scopefunc: Callable[[], Any] = current_task,
*args: Any,
**kwargs: Any,
) -> AsyncSessionFactory
Create an async session factory for Session
objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bind
|
AsyncConnection | AsyncEngine | None
|
An optional |
None
|
routing
|
DatabaseManager | None
|
An optional |
None
|
scoped
|
bool
|
Whether to use a scoped session or not. The scoped session
factory ensures that the session is thread-safe.
Defaults to |
False
|
scopefunc
|
Callable[[], Any]
|
An optional callable that returns a hashable token that
identifies the current scope. Defaults to |
current_task
|
Returns:
Type | Description |
---|---|
AsyncSessionFactory
|
An |
All other keyword arguments are passed to the constructor of the
parent SQLAlchemy async_sessionmaker
class.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
async_session_manager
async
async_session_manager(
*,
using: AsyncSessionFactory | None = None,
auto_commit: bool = False,
new: bool = False,
on_missing: Literal["create", "raise"] = "create",
) -> AsyncGenerator[AsyncSession, None]
An async session context manager for AsyncSession
objects.
Provide a transactional async session context around a series of operations. It manages the async session lifecycle and commits or rollbacks the async session automatically based on the context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
using
|
AsyncSessionFactory | None
|
An optional |
None
|
auto_commit
|
bool
|
Whether to automatically commit on success or rollback on
failure after the operation completes. Defaults to |
False
|
new
|
bool
|
Whether to create a new session or not. If set to |
False
|
on_missing
|
Literal['create', 'raise']
|
The behavior to follow when no current session is
available, either to create a new session or raise an error.
Defaults to |
'create'
|
Returns:
Type | Description |
---|---|
AsyncGenerator[AsyncSession, None]
|
An |
Note
If neither an application nor a factory are provided and no current session is available, the manager will look for a session factory in the current context.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 |
|
Sync
This module provides utilities for managing database sessions within the Plateforme framework using SQLAlchemy features.
SessionFactory
module-attribute
SessionFactory = (
sessionmaker["Session"] | scoped_session["Session"]
)
A type alias for a sync session factory for sync session objects.
Session
Session(
bind: Connection | Engine | None = None,
routing: DatabaseManager | None = None,
proxy: AsyncSession | None = None,
*args: Any,
**kwargs: Any,
)
Bases: Session
Manages persistence operations synchronously for ORM-mapped objects.
Initialize the session.
See also the session_factory
function which is used to generate a
Session
-producing callable with a given set of arguments.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bind
|
Connection | Engine | None
|
An optional |
None
|
routing
|
DatabaseManager | None
|
An optional |
None
|
proxy
|
AsyncSession | None
|
An optional |
None
|
Note
All other keyword arguments are passed to the constructor of the SQLAlchemy parent session class.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
identity_map
instance-attribute
identity_map: IdentityMap = WeakInstanceDict()
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.
.. seealso::
:func:`.identity_key` - helper function to produce the keys used
in this dictionary.
is_active
property
is_active: bool
True if this :class:.Session
not in "partial rollback" state.
.. versionchanged:: 1.4 The :class:_orm.Session
no longer begins
a new transaction immediately, so this attribute will be False
when the :class:_orm.Session
is first instantiated.
"partial rollback" state typically indicates that the flush process
of the :class:_orm.Session
has failed, and that the
:meth:_orm.Session.rollback
method must be emitted in order to
fully roll back the transaction.
If this :class:_orm.Session
is not in a transaction at all, the
:class:_orm.Session
will autobegin when it is first used, so in this
case :attr:_orm.Session.is_active
will return True.
Otherwise, if this :class:_orm.Session
is within a transaction,
and that transaction has not been rolled back internally, the
:attr:_orm.Session.is_active
will also return True.
.. seealso::
:ref:`faq_session_rollback`
:meth:`_orm.Session.in_transaction`
dirty
property
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 :meth:.Session.is_modified
method.
deleted
property
The set of all instances marked as 'deleted' within this Session
close_all
classmethod
Close all sessions in memory.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
identity_key
classmethod
identity_key(
class_: Optional[Type[Any]] = None,
ident: Union[Any, Tuple[Any, ...]] = None,
*,
instance: Optional[Any] = None,
row: Optional[Union[Row[Any], RowMapping]] = None,
identity_token: Optional[Any] = None,
) -> _IdentityKeyType[Any]
Return an identity key.
This is an alias of :func:.util.identity_key
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
object_session
classmethod
Return the :class:.Session
to which an object belongs.
This is an alias of :func:.object_session
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
in_transaction
in_transaction() -> bool
Return True if this :class:_orm.Session
has begun a transaction.
.. versionadded:: 1.4
.. seealso::
:attr:`_orm.Session.is_active`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
in_nested_transaction
in_nested_transaction() -> bool
Return True if this :class:_orm.Session
has begun a nested
transaction, e.g. SAVEPOINT.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
get_transaction
get_transaction() -> Optional[SessionTransaction]
Return the current root transaction in progress, if any.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
get_nested_transaction
get_nested_transaction() -> Optional[SessionTransaction]
Return the current nested transaction in progress, if any.
.. versionadded:: 1.4
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
info
A user-modifiable dictionary.
The initial value of this dictionary can be populated using the
info
argument to the :class:.Session
constructor or
:class:.sessionmaker
constructor or factory methods. The dictionary
here is always local to this :class:.Session
and can be modified
independently of all other :class:.Session
objects.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
begin
begin(nested: bool = False) -> SessionTransaction
Begin a transaction, or nested transaction,
on this :class:.Session
, if one is not already begun.
The :class:_orm.Session
object features autobegin behavior,
so that normally it is not necessary to call the
:meth:_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 :class:.Session
is already inside of a transaction.
:param nested: if True, begins a SAVEPOINT transaction and is
equivalent to calling :meth:~.Session.begin_nested
. For
documentation on SAVEPOINT transactions, please see
:ref:session_begin_nested
.
:return: the :class:.SessionTransaction
object. Note that
:class:.SessionTransaction
acts as a Python context manager, allowing :meth:.Session.begin
to be used in a "with" block. See :ref:session_explicit_begin
for
an example.
.. seealso::
:ref:`session_autobegin`
:ref:`unitofwork_transaction`
:meth:`.Session.begin_nested`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
begin_nested
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 :ref:session_begin_nested
.
:return: the :class:.SessionTransaction
object. Note that
:class:.SessionTransaction
acts as a context manager, allowing
:meth:.Session.begin_nested
to be used in a "with" block.
See :ref:session_begin_nested
for a usage example.
.. seealso::
:ref:`session_begin_nested`
:ref:`pysqlite_serializable` - special workarounds required
with the SQLite driver in order for SAVEPOINT to work
correctly. For asyncio use cases, see the section
:ref:`aiosqlite_serializable`.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
rollback
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.
.. seealso::
:ref:`session_rollback`
:ref:`unitofwork_transaction`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
commit
Flush pending changes and commit the current transaction.
When the COMMIT operation is complete, all objects are fully
:term: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 :term:detached
from the :class:.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 :class:.Session
,
indicating that no operations were invoked on this :class:.Session
since the previous call to :meth:.Session.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.
.. seealso::
:ref:`session_committing`
:ref:`unitofwork_transaction`
:ref:`asyncio_orm_avoid_lazyloads`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
prepare
Prepare the current transaction in progress for two phase commit.
If no transaction is in progress, this method raises an
:exc:~sqlalchemy.exc.InvalidRequestError
.
Only root transactions of two phase sessions can be prepared. If the
current transaction is not such, an
:exc:~sqlalchemy.exc.InvalidRequestError
is raised.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
connection
connection(
bind_arguments: Optional[_BindArguments] = None,
execution_options: Optional[
CoreExecuteOptionsParameter
] = None,
) -> Connection
Return a :class:_engine.Connection
object corresponding to this
:class:.Session
object's transactional state.
Either the :class:_engine.Connection
corresponding to the current
transaction is returned, or if no transaction is in progress, a new
one is begun and the :class:_engine.Connection
returned (note that no
transactional state is established with the DBAPI until the first
SQL statement is emitted).
Ambiguity in multi-bind or unbound :class:.Session
objects can be
resolved through any of the optional keyword arguments. This
ultimately makes usage of the :meth:.get_bind
method for resolution.
:param bind_arguments: dictionary of bind arguments. May include
"mapper", "bind", "clause", other custom arguments that are passed
to :meth:.Session.get_bind
.
:param execution_options: a dictionary of execution options that will
be passed to :meth:_engine.Connection.execution_options
, when the
connection is first procured only. If the connection is already
present within the :class:.Session
, a warning is emitted and
the arguments are ignored.
.. seealso::
:ref:`session_transaction_isolation`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
execute
execute(
statement: TypedReturnsRows[_T],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
_parent_execute_state: Optional[Any] = None,
_add_event: Optional[Any] = None,
) -> Result[_T]
execute(
statement: UpdateBase,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
_parent_execute_state: Optional[Any] = None,
_add_event: Optional[Any] = None,
) -> CursorResult[Any]
execute(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
_parent_execute_state: Optional[Any] = None,
_add_event: Optional[Any] = None,
) -> Result[Any]
Execute a SQL expression construct.
Returns a :class:_engine.Result
object representing
results of the statement execution.
E.g.::
from sqlalchemy import select
result = session.execute(
select(User).where(User.id == 5)
)
The API contract of :meth:_orm.Session.execute
is similar to that
of :meth:_engine.Connection.execute
, the :term:2.0 style
version
of :class:_engine.Connection
.
.. versionchanged:: 1.4 the :meth:_orm.Session.execute
method is
now the primary point of ORM statement execution when using
:term:2.0 style
ORM usage.
:param statement:
An executable statement (i.e. an :class:.Executable
expression
such as :func:_expression.select
).
:param 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.
:param 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 :meth:_engine.Connection.execution_options
, and may also
provide additional options understood only in an ORM context.
.. seealso::
:ref:`orm_queryguide_execution_options` - ORM-specific execution
options
:param 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
:meth:.Session.get_bind
method.
:return: a :class:_engine.Result
object.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 |
|
scalar
scalar(
statement: TypedReturnsRows[Tuple[_T]],
params: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Optional[_T]
scalar(
statement: Executable,
params: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Any
scalar(
statement: Executable,
params: Optional[_CoreSingleExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> Any
Execute a statement and return a scalar result.
Usage and parameters are the same as that of
:meth:_orm.Session.execute
; the return result is a scalar Python
value.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
scalars
scalars(
statement: TypedReturnsRows[Tuple[_T]],
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[_T]
scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[Any]
scalars(
statement: Executable,
params: Optional[_CoreAnyExecuteParams] = None,
*,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
**kw: Any,
) -> ScalarResult[Any]
Execute a statement and return the results as scalars.
Usage and parameters are the same as that of
:meth:_orm.Session.execute
; the return result is a
:class:_result.ScalarResult
filtering object which
will return single elements rather than :class:_row.Row
objects.
:return: a :class:_result.ScalarResult
object
.. versionadded:: 1.4.24 Added :meth:_orm.Session.scalars
.. versionadded:: 1.4.26 Added :meth:_orm.scoped_session.scalars
.. seealso::
:ref:`orm_queryguide_select_orm_entities` - contrasts the behavior
of :meth:`_orm.Session.execute` to :meth:`_orm.Session.scalars`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
close
Close out the transactional resources and ORM objects used by this
:class:_orm.Session
.
This expunges all ORM objects associated with this
:class:_orm.Session
, ends any transaction in progress and
:term:releases
any :class:_engine.Connection
objects which this
:class:_orm.Session
itself has checked out from associated
:class:_engine.Engine
objects. The operation then leaves the
:class:_orm.Session
in a state which it may be used again.
.. tip::
In the default running mode the :meth:`_orm.Session.close`
method **does not prevent the Session from being used again**.
The :class:`_orm.Session` itself does not actually have a
distinct "closed" state; it merely means
the :class:`_orm.Session` will release all database connections
and ORM objects.
Setting the parameter :paramref:`_orm.Session.close_resets_only`
to ``False`` will instead make the ``close`` final, meaning that
any further action on the session will be forbidden.
.. versionchanged:: 1.4 The :meth:.Session.close
method does not
immediately create a new :class:.SessionTransaction
object;
instead, the new :class:.SessionTransaction
is created only if
the :class:.Session
is used again for a database operation.
.. seealso::
:ref:`session_closing` - detail on the semantics of
:meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
:meth:`_orm.Session.reset` - a similar method that behaves like
``close()`` with the parameter
:paramref:`_orm.Session.close_resets_only` set to ``True``.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
reset
Close out the transactional resources and ORM objects used by this
:class:_orm.Session
, resetting the session to its initial state.
This method provides for same "reset-only" behavior that the
:meth:_orm.Session.close
method has provided historically, where the
state of the :class:_orm.Session
is reset as though the object were
brand new, and ready to be used again.
This method may then be useful for :class:_orm.Session
objects
which set :paramref:_orm.Session.close_resets_only
to False
,
so that "reset only" behavior is still available.
.. versionadded:: 2.0.22
.. seealso::
:ref:`session_closing` - detail on the semantics of
:meth:`_orm.Session.close` and :meth:`_orm.Session.reset`.
:meth:`_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 to ``False``.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
invalidate
Close this Session, using connection invalidation.
This is a variant of :meth:.Session.close
that will additionally
ensure that the :meth:_engine.Connection.invalidate
method will be called on each :class:_engine.Connection
object
that is currently in use for a transaction (typically there is only
one connection unless the :class:_orm.Session
is used with
multiple engines).
This can be called when the database is known to be in a state where the connections are no longer safe to be used.
Below illustrates a scenario when using gevent
<https://www.gevent.org/>
_, 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 :meth:_orm.Session.close
does, including that all ORM objects are expunged.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
expunge_all
Remove all object instances from this Session
.
This is equivalent to calling expunge(obj)
on all objects in this
Session
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
bind_mapper
Associate a :class:_orm.Mapper
or arbitrary Python class with a
"bind", e.g. an :class:_engine.Engine
or
:class:_engine.Connection
.
The given entity is added to a lookup used by the
:meth:.Session.get_bind
method.
:param mapper: a :class:_orm.Mapper
object,
or an instance of a mapped
class, or any Python class that is the base of a set of mapped
classes.
:param bind: an :class:_engine.Engine
or :class:_engine.Connection
object.
.. seealso::
:ref:`session_partitioning`
:paramref:`.Session.binds`
:meth:`.Session.bind_table`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
bind_table
bind_table(table: TableClause, bind: _SessionBind) -> None
Associate a :class:_schema.Table
with a "bind", e.g. an
:class:_engine.Engine
or :class:_engine.Connection
.
The given :class:_schema.Table
is added to a lookup used by the
:meth:.Session.get_bind
method.
:param table: a :class:_schema.Table
object,
which is typically the target
of an ORM mapping, or is present within a selectable that is
mapped.
:param bind: an :class:_engine.Engine
or :class:_engine.Connection
object.
.. seealso::
:ref:`session_partitioning`
:paramref:`.Session.binds`
:meth:`.Session.bind_mapper`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
query
query(_entity: _EntityType[_O]) -> Query[_O]
query(
_colexpr: TypedColumnsClauseRole[_T],
) -> RowReturningQuery[Tuple[_T]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
) -> RowReturningQuery[Tuple[_T0, _T1]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
) -> RowReturningQuery[Tuple[_T0, _T1, _T2, _T3, _T4, _T5]]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
) -> RowReturningQuery[
Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6]
]
query(
__ent0: _TypedColumnClauseArgument[_T0],
__ent1: _TypedColumnClauseArgument[_T1],
__ent2: _TypedColumnClauseArgument[_T2],
__ent3: _TypedColumnClauseArgument[_T3],
__ent4: _TypedColumnClauseArgument[_T4],
__ent5: _TypedColumnClauseArgument[_T5],
__ent6: _TypedColumnClauseArgument[_T6],
__ent7: _TypedColumnClauseArgument[_T7],
) -> RowReturningQuery[
Tuple[_T0, _T1, _T2, _T3, _T4, _T5, _T6, _T7]
]
Return a new :class:_query.Query
object corresponding to this
:class:_orm.Session
.
Note that the :class:_query.Query
object is legacy as of
SQLAlchemy 2.0; the :func:_sql.select
construct is now used
to construct ORM queries.
.. seealso::
:ref:`unified_tutorial`
:ref:`queryguide_toplevel`
:ref:`query_api_toplevel` - legacy API doc
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
refresh
refresh(
instance: object,
attribute_names: Optional[Iterable[str]] = 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
:meth:_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.
:func:_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.
.. versionadded:: 1.4 - the :meth:_orm.Session.refresh
method
can also refresh eagerly loaded attributes.
:func:_orm.relationship
oriented attributes that would normally
load using the select
(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 the
immediate
loader 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.
.. versionchanged:: 2.0.4 The :meth:_orm.Session.refresh
method
will now refresh lazy-loaded :func:_orm.relationship
oriented
attributes for those which are named explicitly in the
:paramref:_orm.Session.refresh.attribute_names
collection.
.. tip::
While the :meth:`_orm.Session.refresh` method is capable of
refreshing both column and relationship oriented attributes, its
primary focus is on refreshing of local column-oriented attributes
on a single instance. For more open ended "refresh" functionality,
including the ability to refresh the attributes on many objects at
once while having explicit control over relationship loader
strategies, use the
:ref:`populate existing <orm_queryguide_populate_existing>` feature
instead.
Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. Refreshing attributes usually only makes sense at the start of a transaction where database rows have not yet been accessed.
:param attribute_names: optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.
:param 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 of
:meth:_query.Query.with_for_update
.
Supersedes the :paramref:.Session.refresh.lockmode
parameter.
.. seealso::
:ref:`session_expire` - introductory material
:meth:`.Session.expire`
:meth:`.Session.expire_all`
:ref:`orm_queryguide_populate_existing` - allows any ORM query
to refresh objects as they would be loaded normally.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 |
|
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
:class:.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 :meth:Session.expire
.
The :class:.Session
object's default behavior is to
expire all state whenever the :meth:Session.rollback
or :meth:Session.commit
methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling :meth:Session.expire_all
is not usually needed,
assuming the transaction is isolated.
.. seealso::
:ref:`session_expire` - introductory material
:meth:`.Session.expire`
:meth:`.Session.refresh`
:meth:`_orm.Query.populate_existing`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
expire
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
:class:.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 :class:.Session
simultaneously,
use :meth:Session.expire_all
.
The :class:.Session
object's default behavior is to
expire all state whenever the :meth:Session.rollback
or :meth:Session.commit
methods are called, so that new
state can be loaded for the new transaction. For this reason,
calling :meth:Session.expire
only makes sense for the specific
case that a non-ORM SQL statement was emitted in the current
transaction.
:param instance: The instance to be refreshed. :param attribute_names: optional list of string attribute names indicating a subset of attributes to be expired.
.. seealso::
:ref:`session_expire` - introductory material
:meth:`.Session.expire`
:meth:`.Session.refresh`
:meth:`_orm.Query.populate_existing`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
expunge
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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
add
Place an object into this :class:_orm.Session
.
Objects that are in the :term:transient
state when passed to the
:meth:_orm.Session.add
method will move to the
:term:pending
state, until the next flush, at which point they
will move to the :term:persistent
state.
Objects that are in the :term:detached
state when passed to the
:meth:_orm.Session.add
method will move to the :term:persistent
state directly.
If the transaction used by the :class:_orm.Session
is rolled back,
objects which were transient when they were passed to
:meth:_orm.Session.add
will be moved back to the
:term:transient
state, and will no longer be present within this
:class:_orm.Session
.
.. seealso::
:meth:`_orm.Session.add_all`
:ref:`session_adding` - at :ref:`session_basics`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
add_all
Add the given collection of instances to this :class:_orm.Session
.
See the documentation for :meth:_orm.Session.add
for a general
behavioral description.
.. seealso::
:meth:`_orm.Session.add`
:ref:`session_adding` - at :ref:`session_basics`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
delete
delete(instance: object) -> None
Mark an instance as deleted.
The object is assumed to be either :term:persistent
or
:term:detached
when passed; after the method is called, the
object will remain in the :term:persistent
state until the next
flush proceeds. During this time, the object will also be a member
of the :attr:_orm.Session.deleted
collection.
When the next flush proceeds, the object will move to the
:term:deleted
state, indicating a DELETE
statement was emitted
for its row within the current transaction. When the transaction
is successfully committed,
the deleted object is moved to the :term:detached
state and is
no longer present within this :class:_orm.Session
.
.. seealso::
:ref:`session_deleting` - at :ref:`session_basics`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
get
get(
entity: _EntityBindKey[_O],
ident: _PKIdentityArgument,
*,
options: Optional[Sequence[ORMOption]] = None,
populate_existing: bool = False,
with_for_update: ForUpdateParameter = None,
identity_token: Optional[Any] = None,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
) -> Optional[_O]
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}
)
.. versionadded:: 1.4 Added :meth:_orm.Session.get
, which is moved
from the now legacy :meth:_orm.Query.get
method.
:meth:_orm.Session.get
is special in that it provides direct
access to the identity map of the :class:.Session
.
If the given primary key identifier is present
in the local identity map, the object is returned
directly from this collection and no SQL is emitted,
unless the object has been marked fully expired.
If not present,
a SELECT is performed in order to locate the object.
:meth:_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, :class:~sqlalchemy.orm.exc.ObjectDeletedError
is raised.
:param entity: a mapped class or :class:.Mapper
indicating the
type of entity to be loaded.
:param 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
:class:_schema.Table
object's primary key columns, or if the
:paramref:_orm.Mapper.primary_key
configuration parameter were
used, in
the order used for that parameter. For example, if the primary key
of a row is represented by the integer
digits "5, 10" the call would look like::
my_object = session.get(SomeClass, (5, 10))
The dictionary form should include as keys the mapped attribute names
corresponding to each element of the primary key. If the mapped class
has the attributes id
, version_id
as the attributes which
store the object's primary key value, the call would look like::
my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
:param options: optional sequence of loader options which will be applied to the query, if one is emitted.
:param 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.
:param 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 of
:meth:_query.Query.with_for_update
.
Supersedes the :paramref:.Session.refresh.lockmode
parameter.
:param 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 :meth:_engine.Connection.execution_options
, and may
also provide additional options understood only in an ORM context.
.. versionadded:: 1.4.29
.. seealso::
:ref:`orm_queryguide_execution_options` - ORM-specific execution
options
:param 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
:meth:.Session.get_bind
method.
.. versionadded: 2.0.0rc1
:return: The object instance, or None
.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 |
|
get_one
get_one(
entity: _EntityBindKey[_O],
ident: _PKIdentityArgument,
*,
options: Optional[Sequence[ORMOption]] = None,
populate_existing: bool = False,
with_for_update: ForUpdateParameter = None,
identity_token: Optional[Any] = None,
execution_options: OrmExecuteOptionsParameter = EMPTY_DICT,
bind_arguments: Optional[_BindArguments] = None,
) -> _O
Return exactly one instance based on the given primary key identifier, or raise an exception if not found.
Raises sqlalchemy.orm.exc.NoResultFound
if the query
selects no rows.
For a detailed documentation of the arguments see the
method :meth:.Session.get
.
.. versionadded:: 2.0.22
:return: The object instance.
.. seealso::
:meth:`.Session.get` - equivalent method that instead
returns ``None`` if no row was found with the provided primary
key
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
merge
Copy the state of a given instance into a corresponding instance
within this :class:.Session
.
:meth:.Session.merge
examines the primary key attributes of the
source instance, and attempts to reconcile it with an instance of the
same primary key in the session. If not found locally, it attempts
to load the object from the database based on primary key, and if
none can be located, creates a new instance. The state of each
attribute on the source instance is then copied to the target
instance. The resulting target instance is then returned by the
method; the original source instance is left unmodified, and
un-associated with the :class:.Session
if not already.
This operation cascades to associated instances if the association is
mapped with cascade="merge"
.
See :ref:unitofwork_merging
for a detailed discussion of merging.
:param instance: Instance to be merged.
:param load: Boolean, when False, :meth:.merge
switches into
a "high performance" mode which causes it to forego emitting history
events as well as all database access. This flag is used for
cases such as transferring graphs of objects into a :class:.Session
from a second level cache, or to transfer just-loaded objects
into the :class:.Session
owned by a worker thread or process
without re-querying the database.
The load=False
use case adds the caveat that the given
object has to be in a "clean" state, that is, has no pending changes
to be flushed - even if the incoming object is detached from any
:class:.Session
. This is so that when
the merge operation populates local attributes and
cascades to related objects and
collections, the values can be "stamped" onto the
target object as is, without generating any history or attribute
events, and without the need to reconcile the incoming data with
any existing related objects or collections that might not
be loaded. The resulting objects from load=False
are always
produced as "clean", so it is only appropriate that the given objects
should be "clean" as well, else this suggests a mis-use of the
method.
:param options: optional sequence of loader options which will be
applied to the :meth:_orm.Session.get
method when the merge
operation loads the existing version of the object from the database.
.. versionadded:: 1.4.24
.. seealso::
:func:`.make_transient_to_detached` - provides for an alternative
means of "merging" a single object into the :class:`.Session`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 |
|
enable_relationship_loading
enable_relationship_loading(obj: object) -> None
Associate an object with this :class:.Session
for related
object loading.
.. warning::
:meth:`.enable_relationship_loading` exists to serve special
use cases and is not recommended for general use.
Accesses of attributes mapped with :func:_orm.relationship
will attempt to load a value from the database using this
:class:.Session
as the source of connectivity. The values
will be loaded based on foreign key and primary key values
present on this object - if not present, then those relationships
will be unavailable.
The object will be attached to this session, but will not participate in any persistence operations; its state for almost all purposes will remain either "transient" or "detached", except for the case of relationship loading.
Also note that backrefs will often not work as expected. Altering a relationship-bound attribute on the target object may not fire off a backref event, if the effective value is what was already loaded from a foreign-key-holding value.
The :meth:.Session.enable_relationship_loading
method is
similar to the load_on_pending
flag on :func:_orm.relationship
.
Unlike that flag, :meth:.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 :class:.Session
via :meth:.Session.enable_relationship_loading
pending, add
it to the :class:.Session
using :meth:.Session.add
normally.
If the object instead represents an existing identity in the database,
it should be merged using :meth:.Session.merge
.
:meth:.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.
.. seealso::
:paramref:`_orm.relationship.load_on_pending` - this flag
allows per-relationship loading of many-to-ones on items that
are pending.
:func:`.make_transient_to_detached` - allows for an object to
be added to a :class:`.Session` without SQL emitted, which then
will unexpire attributes on access.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 |
|
flush
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.
:param 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
bulk_save_objects
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.
.. legacy::
This method is a legacy feature as of the 2.0 series of
SQLAlchemy. For modern bulk INSERT and UPDATE, see
the sections :ref:`orm_queryguide_bulk_insert` and
:ref:`orm_queryguide_bulk_update`.
For general INSERT and UPDATE of existing ORM mapped objects,
prefer standard :term:`unit of work` data management patterns,
introduced in the :ref:`unified_tutorial` at
:ref:`tutorial_orm_data_manipulation`. SQLAlchemy 2.0
now uses :ref:`engine_insertmanyvalues` with modern dialects
which solves previous issues of bulk INSERT slowness.
:param objects: a sequence of mapped object instances. The mapped
objects are persisted as is, and are not associated with the
:class:.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 :class:.Session
in traditional operation; if the object has the
:attr:.InstanceState.key
attribute set, then the object is assumed to be "detached" and
will result in an UPDATE. Otherwise, an INSERT is used.
In the case of an UPDATE, statements are grouped based on which
attributes have changed, and are thus to be the subject of each
SET clause. If update_changed_only
is False, then all
attributes present within each object are applied to the UPDATE
statement, which may help in allowing the statements to be grouped
together into a larger executemany(), and will also reduce the
overhead of checking history on attributes.
:param 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 :meth:_orm.Session.add_all
approach.
:param 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.
:param 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.
.. seealso::
:doc:`queryguide/dml`
:meth:`.Session.bulk_insert_mappings`
:meth:`.Session.bulk_update_mappings`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 |
|
bulk_insert_mappings
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.
.. legacy::
This method is a legacy feature as of the 2.0 series of
SQLAlchemy. For modern bulk INSERT and UPDATE, see
the sections :ref:`orm_queryguide_bulk_insert` and
:ref:`orm_queryguide_bulk_update`. The 2.0 API shares
implementation details with this method and adds new features
as well.
:param mapper: a mapped class, or the actual :class:_orm.Mapper
object,
representing the single kind of object represented within the mapping
list.
:param 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.
:param 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
:ref:Joined Table Inheritance <joined_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
:ref:engine_insertmanyvalues
for background on which backends are affected.
:param 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.
.. seealso::
:doc:`queryguide/dml`
:meth:`.Session.bulk_save_objects`
:meth:`.Session.bulk_update_mappings`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 |
|
bulk_update_mappings
Perform a bulk update of the given list of mapping dictionaries.
.. legacy::
This method is a legacy feature as of the 2.0 series of
SQLAlchemy. For modern bulk INSERT and UPDATE, see
the sections :ref:`orm_queryguide_bulk_insert` and
:ref:`orm_queryguide_bulk_update`. The 2.0 API shares
implementation details with this method and adds new features
as well.
:param mapper: a mapped class, or the actual :class:_orm.Mapper
object,
representing the single kind of object represented within the mapping
list.
:param 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.
.. seealso::
:doc:`queryguide/dml`
:meth:`.Session.bulk_insert_mappings`
:meth:`.Session.bulk_save_objects`
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
is_modified
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
:attr:.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 :attr:
.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 in :attr:.Session.dirty
, but ultimately the state is the same as that loaded from the database, resulting in no net change here. - Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the "old" value when a set event occurs, so it skips the expense of a SQL call if the old value isn't present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn't, is less expensive on average than issuing a defensive SELECT.
The "old" value is fetched unconditionally upon set only if the
attribute container has the active_history
flag set to True
.
This flag is set typically for primary key attributes and scalar
object references that are not a simple many-to-one. To set this
flag for any arbitrary mapped column, use the active_history
argument with :func:.column_property
.
:param instance: mapped instance to be tested for pending changes.
:param 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.
Source code in .venv/lib/python3.12/site-packages/sqlalchemy/orm/session.py
4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 |
|
get_bind
get_bind(
mapper: Mapper[_T] | type[_T] | None = None,
*args: Any,
**kwargs: Any,
) -> Connection | Engine
Return a bind
to which this Session
is bound.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
mapper
|
Mapper[_T] | type[_T] | None
|
Optional mapped class or corresponding |
None
|
Returns:
Type | Description |
---|---|
Connection | Engine
|
The |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
bulk
bulk(
*, proxy_reference: bool = True
) -> Generator[SessionBulk, None, None]
A session bulk context manager for Session
objects.
The proxy option indicates that the provided resource references should be encapsulated with a proxy, this is done when validating the resource using the Pydantic core schema. This can be useful to resolve the references that target the same resource into a single instance. Thus, modifying a resolved instance will affect all references that target the same resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
proxy_reference
|
bool
|
Whether the registered resource references should
be encapsulated with a proxy or not. Defaults to |
True
|
Returns:
Type | Description |
---|---|
None
|
A |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
SessionBulk
SessionBulk(session: _T, *, proxy_reference: bool = True)
A bulk operation manager for resources.
It is used to register resources for bulk operations and commit or rollback them in a single operation within a session.
Initialize the session bulk manager.
The proxy option indicates that the provided resource references should be encapsulated with a proxy, this is done when validating the resource using the Pydantic core schema. This can be useful to resolve the references that target the same resource into a single instance. Thus, modifying a resolved instance will affect all references that target the same resource.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
session
|
_T
|
The session to use for the bulk operations. |
required |
proxy_reference
|
bool
|
Whether the registered resource references should
be encapsulated with a proxy or not. Defaults to |
True
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
add
add(
instance: BaseResource | BaseSpec,
*,
is_reference: bool = False,
) -> None
Add a resource instance to the bulk manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
instance
|
BaseResource | BaseSpec
|
The resource instance to add to the bulk manager. |
required |
is_reference
|
bool
|
Whether the provided resource instance is a reference
or not. Defaults to |
False
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
get
get(
entity: ResourceType | SpecType,
*,
resolved: bool | None = None,
scope: Literal["all", "references", "values"] = "all",
) -> list[BaseResource]
Get the resource instances registered in the bulk manager.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
entity
|
ResourceType | SpecType
|
The resource type to get the resource instances for. |
required |
resolved
|
bool | None
|
Whether to get only the resolved resources or not:
- |
None
|
scope
|
Literal['all', 'references', 'values']
|
The scope of the resource instances to get:
- |
'all'
|
Returns:
Type | Description |
---|---|
list[BaseResource]
|
The list of resource instances registered in the bulk manager for |
list[BaseResource]
|
the specified resource type and options. |
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/bulk.py
resolve
resolve(
*,
raise_errors: bool = True,
scope: Literal["all", "references", "values"] = "all",
strategy: Literal["bind", "hydrate"] = "bind",
) -> None
Resolve the specified scope of resource entries in the bulk.
For resource references, if the proxy_reference
option is enabled,
the resolved instances replace the reference proxy targets. Otherwise,
the resolved instances are used to update the reference proxy target.
For resource values, the resolved instances are used to update the resource instances with the fetched data, no proxy is used.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
raise_errors
|
bool
|
Whether to raise errors when failing to resolve
resource references or values. Defaults to |
True
|
scope
|
Literal['all', 'references', 'values']
|
The scope of the resources to resolve, it can be either:
- |
'all'
|
strategy
|
Literal['bind', 'hydrate']
|
The resolution strategy to use, it can be either:
- |
'bind'
|
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
session_factory
session_factory(
bind: Connection | Engine | None = None,
routing: DatabaseManager | None = None,
scoped: bool = False,
*args: Any,
**kwargs: Any,
) -> SessionFactory
Create a sync session factory for Session
objects.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
bind
|
Connection | Engine | None
|
An optional |
None
|
routing
|
DatabaseManager | None
|
An optional |
None
|
scoped
|
bool
|
Whether to use a scoped session or not. The scoped session
factory ensures that the session is thread-safe.
Defaults to |
False
|
Returns:
Type | Description |
---|---|
SessionFactory
|
A |
Note
All other keyword arguments are passed to the constructor of the parent
SQLAlchemy sessionmaker
class.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
session_manager
session_manager(
*,
using: SessionFactory | None = None,
auto_commit: bool = False,
new: bool = False,
on_missing: Literal["create", "raise"] = "create",
) -> Generator[Session, None, None]
A sync session context manager for Session
objects.
Provide a transactional session context around a series of operations. It manages the session lifecycle and commits or rollbacks the session automatically based on the context.
Parameters:
Name | Type | Description | Default |
---|---|---|---|
using
|
SessionFactory | None
|
An optional |
None
|
auto_commit
|
bool
|
Whether to automatically commit on success or rollback on
failure after the operation completes. Defaults to |
False
|
new
|
bool
|
Whether to create a new session or not. If set to |
False
|
on_missing
|
Literal['create', 'raise']
|
The behavior to follow when no current session is
available, either to create a new session or raise an error.
Defaults to |
'create'
|
Returns:
Type | Description |
---|---|
None
|
A |
Note
If neither an application nor a factory are provided and no current session is available, the manager will look for a session factory in the current context.
Source code in .venv/lib/python3.12/site-packages/plateforme/core/database/sessions.py
539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 |
|