Skip to content

SQLAlchemyBackend

Bases: TransactionalBackend

SQLAlchemy integration backend for Event Sourcery.

Source code in event_sourcery_sqlalchemy/__init__.py
class SQLAlchemyBackend(TransactionalBackend):
    """
    SQLAlchemy integration backend for Event Sourcery.
    """

    UNCONFIGURED_MESSAGE = "Configure backend with `.configure(session, config)`"

    def __init__(self) -> None:
        super().__init__()
        self[Models] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[Session] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[SQLAlchemyConfig] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[StorageStrategy] = lambda c: SqlAlchemyStorageStrategy(
            c[Session],
            c[Dispatcher],
            c.get(SqlAlchemyOutboxStorageStrategy, None),
            c[Models].event_model,
            c[Models].snapshot_model,
            c[Models].stream_model,
        ).scoped_for_tenant(c[TenantId])
        self[SubscriptionStrategy] = lambda c: SqlAlchemySubscriptionStrategy(
            c[Session],
            c[SQLAlchemyConfig].gap_retry_interval,
            c[Models].event_model,
            c[Models].stream_model,
        )

    def configure(
        self,
        session: Session,
        config: SQLAlchemyConfig | None = None,
        custom_models: Models | None = None,
    ) -> Self:
        """
        Sets the backend configuration for SQLAlchemy session, outbox, and models.

        Allows you to provide a SQLAlchemy Session instance, an optional Config
        instance, and optional custom ORM models.
        If no config or models are provided, the default configuration and models are
        used.
        This method must be called before using the backend in production to ensure
        correct event publishing and subscription reliability.

        Args:
            session (Session): The SQLAlchemy session instance to use for backend operations.
            config (SQLAlchemyConfig | None): Optional custom configuration. If None, uses default Config().
            custom_models (Models | None): Optional custom ORM models. If None, uses default models.

        Returns:
            Self: The configured backend instance (for chaining).
        """

        if custom_models is None:
            custom_models = Models(
                event_model=DefaultEvent,
                stream_model=DefaultStream,
                snapshot_model=DefaultSnapshot,
                outbox_entry_model=DefaultOutboxEntry,
            )

        self[Session] = session
        self[SQLAlchemyConfig] = config or SQLAlchemyConfig()
        self[Models] = custom_models
        return self

    def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
        self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
        self[SqlAlchemyOutboxStorageStrategy] = (
            lambda c: SqlAlchemyOutboxStorageStrategy(
                c[Session],
                c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
                c[SQLAlchemyConfig].outbox_attempts,
                c[Models].outbox_entry_model,
            )
        )
        self[OutboxStorageStrategy] = lambda c: c[SqlAlchemyOutboxStorageStrategy]
        return self

configure(session, config=None, custom_models=None)

Sets the backend configuration for SQLAlchemy session, outbox, and models.

Allows you to provide a SQLAlchemy Session instance, an optional Config instance, and optional custom ORM models. If no config or models are provided, the default configuration and models are used. This method must be called before using the backend in production to ensure correct event publishing and subscription reliability.

Parameters:

Name Type Description Default
session Session

The SQLAlchemy session instance to use for backend operations.

required
config SQLAlchemyConfig | None

Optional custom configuration. If None, uses default Config().

None
custom_models Models | None

Optional custom ORM models. If None, uses default models.

None

Returns:

Name Type Description
Self Self

The configured backend instance (for chaining).

Source code in event_sourcery_sqlalchemy/__init__.py
def configure(
    self,
    session: Session,
    config: SQLAlchemyConfig | None = None,
    custom_models: Models | None = None,
) -> Self:
    """
    Sets the backend configuration for SQLAlchemy session, outbox, and models.

    Allows you to provide a SQLAlchemy Session instance, an optional Config
    instance, and optional custom ORM models.
    If no config or models are provided, the default configuration and models are
    used.
    This method must be called before using the backend in production to ensure
    correct event publishing and subscription reliability.

    Args:
        session (Session): The SQLAlchemy session instance to use for backend operations.
        config (SQLAlchemyConfig | None): Optional custom configuration. If None, uses default Config().
        custom_models (Models | None): Optional custom ORM models. If None, uses default models.

    Returns:
        Self: The configured backend instance (for chaining).
    """

    if custom_models is None:
        custom_models = Models(
            event_model=DefaultEvent,
            stream_model=DefaultStream,
            snapshot_model=DefaultSnapshot,
            outbox_entry_model=DefaultOutboxEntry,
        )

    self[Session] = session
    self[SQLAlchemyConfig] = config or SQLAlchemyConfig()
    self[Models] = custom_models
    return self

AsyncSQLAlchemyBackend

Bases: AsyncTransactionalBackend

Async SQLAlchemy integration backend for Event Sourcery.

Async counterpart of SQLAlchemyBackend. Uses an AsyncSession for all event store operations, exposed via AsyncEventStore, AsyncOutbox and AsyncSubscriptionBuilder resolved from this container.

In-transaction listeners remain synchronous callables, as they are dispatched within the append transaction.

Source code in event_sourcery_sqlalchemy/async_/__init__.py
class AsyncSQLAlchemyBackend(AsyncTransactionalBackend):
    """
    Async SQLAlchemy integration backend for Event Sourcery.

    Async counterpart of `SQLAlchemyBackend`. Uses an `AsyncSession` for all
    event store operations, exposed via `AsyncEventStore`, `AsyncOutbox` and
    `AsyncSubscriptionBuilder` resolved from this container.

    In-transaction listeners remain synchronous callables, as they are
    dispatched within the append transaction.
    """

    UNCONFIGURED_MESSAGE = "Configure backend with `.configure(session, config)`"

    def __init__(self) -> None:
        super().__init__()
        self[Models] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[AsyncSession] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[SQLAlchemyConfig] = not_configured(self.UNCONFIGURED_MESSAGE)
        self[AsyncStorageStrategy] = lambda c: AsyncSqlAlchemyStorageStrategy(
            c[AsyncSession],
            c[AsyncDispatcher],
            c.get(AsyncSqlAlchemyOutboxStorageStrategy, None),
            c[Models].event_model,
            c[Models].snapshot_model,
            c[Models].stream_model,
        ).scoped_for_tenant(c[TenantId])
        self[AsyncSubscriptionStrategy] = lambda c: (
            AsyncSqlAlchemySubscriptionStrategy(
                c[AsyncSession],
                c[SQLAlchemyConfig].gap_retry_interval,
                c[Models].event_model,
                c[Models].stream_model,
            )
        )

    def configure(
        self,
        session: AsyncSession,
        config: SQLAlchemyConfig | None = None,
        custom_models: Models | None = None,
    ) -> Self:
        """
        Sets the backend configuration for the async SQLAlchemy session.

        Mirrors `SQLAlchemyBackend.configure`, but accepts an `AsyncSession`.

        Args:
            session (AsyncSession):
                The async SQLAlchemy session instance to use for backend operations.
            config (SQLAlchemyConfig | None):
                Optional custom configuration. If None, uses default Config().
            custom_models (Models | None):
                Optional custom ORM models. If None, uses default models.

        Returns:
            Self: The configured backend instance (for chaining).
        """

        if custom_models is None:
            custom_models = Models(
                event_model=DefaultEvent,
                stream_model=DefaultStream,
                snapshot_model=DefaultSnapshot,
                outbox_entry_model=DefaultOutboxEntry,
            )

        self[AsyncSession] = session
        self[SQLAlchemyConfig] = config or SQLAlchemyConfig()
        self[Models] = custom_models
        return self

    def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
        """
        Enables the outbox for the backend.

        Mirrors `SQLAlchemyBackend.with_outbox`.
        """
        self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
        self[AsyncSqlAlchemyOutboxStorageStrategy] = (
            lambda c: AsyncSqlAlchemyOutboxStorageStrategy(
                c[AsyncSession],
                c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
                c[SQLAlchemyConfig].outbox_attempts,
                c[Models].outbox_entry_model,
            )
        )
        self[AsyncOutboxStorageStrategy] = lambda c: c[
            AsyncSqlAlchemyOutboxStorageStrategy
        ]
        return self

configure(session, config=None, custom_models=None)

Sets the backend configuration for the async SQLAlchemy session.

Mirrors SQLAlchemyBackend.configure, but accepts an AsyncSession.

Parameters:

Name Type Description Default
session AsyncSession

The async SQLAlchemy session instance to use for backend operations.

required
config SQLAlchemyConfig | None

Optional custom configuration. If None, uses default Config().

None
custom_models Models | None

Optional custom ORM models. If None, uses default models.

None

Returns:

Name Type Description
Self Self

The configured backend instance (for chaining).

Source code in event_sourcery_sqlalchemy/async_/__init__.py
def configure(
    self,
    session: AsyncSession,
    config: SQLAlchemyConfig | None = None,
    custom_models: Models | None = None,
) -> Self:
    """
    Sets the backend configuration for the async SQLAlchemy session.

    Mirrors `SQLAlchemyBackend.configure`, but accepts an `AsyncSession`.

    Args:
        session (AsyncSession):
            The async SQLAlchemy session instance to use for backend operations.
        config (SQLAlchemyConfig | None):
            Optional custom configuration. If None, uses default Config().
        custom_models (Models | None):
            Optional custom ORM models. If None, uses default models.

    Returns:
        Self: The configured backend instance (for chaining).
    """

    if custom_models is None:
        custom_models = Models(
            event_model=DefaultEvent,
            stream_model=DefaultStream,
            snapshot_model=DefaultSnapshot,
            outbox_entry_model=DefaultOutboxEntry,
        )

    self[AsyncSession] = session
    self[SQLAlchemyConfig] = config or SQLAlchemyConfig()
    self[Models] = custom_models
    return self

with_outbox(filterer=no_filter)

Enables the outbox for the backend.

Mirrors SQLAlchemyBackend.with_outbox.

Source code in event_sourcery_sqlalchemy/async_/__init__.py
def with_outbox(self, filterer: OutboxFiltererStrategy = no_filter) -> Self:
    """
    Enables the outbox for the backend.

    Mirrors `SQLAlchemyBackend.with_outbox`.
    """
    self[OutboxFiltererStrategy] = filterer  # type: ignore[type-abstract]
    self[AsyncSqlAlchemyOutboxStorageStrategy] = (
        lambda c: AsyncSqlAlchemyOutboxStorageStrategy(
            c[AsyncSession],
            c[OutboxFiltererStrategy],  # type: ignore[type-abstract]
            c[SQLAlchemyConfig].outbox_attempts,
            c[Models].outbox_entry_model,
        )
    )
    self[AsyncOutboxStorageStrategy] = lambda c: c[
        AsyncSqlAlchemyOutboxStorageStrategy
    ]
    return self

SQLAlchemyConfig

Bases: BaseModel

Configuration for SQLAlchemyBackend event store integration.

Attributes:

Name Type Description
outbox_attempts PositiveInt

Maximum number of outbox delivery attempts per event before giving up.

gap_retry_interval timedelta

Time to wait before retrying a subscription gap. If the subscription detects a gap in event identifiers (e.g., missing event IDs), it assumes there may be an open transaction and the database has already assigned IDs for new events that are not yet committed. This interval determines how long the subscription waits before retrying to fetch events, preventing loss of events that are in the process of being written to the database.

Source code in event_sourcery_sqlalchemy/__init__.py
class SQLAlchemyConfig(BaseModel):
    """
    Configuration for SQLAlchemyBackend event store integration.

    Attributes:
        outbox_attempts (PositiveInt):
            Maximum number of outbox delivery attempts per event before giving up.
        gap_retry_interval (timedelta):
            Time to wait before retrying a subscription gap. If the subscription detects a gap in event identifiers (e.g., missing event IDs),
            it assumes there may be an open transaction and the database has already assigned IDs for new events that are not yet committed.
            This interval determines how long the subscription waits before retrying to fetch events, preventing loss of events that are in the process of being written to the database.
    """

    model_config = ConfigDict(extra="forbid", frozen=True)

    outbox_attempts: PositiveInt = 3
    gap_retry_interval: timedelta = timedelta(seconds=0.5)

Models

Container for SQLAlchemy ORM models used by the backend.

Allows customization of the event, stream, snapshot, and outbox entry models used by the backend. It allows to have different event store models for different modules in modular monolith applications still having in transactional event dispatching between them.

By default, uses the standard models provided by Event Sourcery.

Attributes:

Name Type Description
event_model type[BaseEvent]

SQLAlchemy model for events.

stream_model type[BaseStream]

SQLAlchemy model for streams.

snapshot_model type[BaseSnapshot]

SQLAlchemy model for snapshots.

outbox_entry_model type[BaseOutboxEntry]

SQLAlchemy model for outbox entries (default: DefaultOutboxEntry).

Source code in event_sourcery_sqlalchemy/__init__.py
@dataclass(frozen=True)
class Models:
    """
    Container for SQLAlchemy ORM models used by the backend.

    Allows customization of the event, stream, snapshot, and outbox entry models used by
    the backend. It allows to have different event store models for different modules in
    modular monolith applications still having in transactional event dispatching
    between them.

    By default, uses the standard models provided by Event Sourcery.

    Attributes:
        event_model (type[BaseEvent]): SQLAlchemy model for events.
        stream_model (type[BaseStream]): SQLAlchemy model for streams.
        snapshot_model (type[BaseSnapshot]): SQLAlchemy model for snapshots.
        outbox_entry_model (type[BaseOutboxEntry]):
            SQLAlchemy model for outbox entries (default: DefaultOutboxEntry).
    """

    event_model: type[BaseEvent]
    stream_model: type[BaseStream]
    snapshot_model: type[BaseSnapshot]
    outbox_entry_model: type[BaseOutboxEntry] = DefaultOutboxEntry

configure_models

Configures SQLAlchemy ORM models for Event Sourcery backend.

Sets up mapping information and registers the provided (or default) models with SQLAlchemy's registry. This function allows customization of event, stream, snapshot, outbox entry, and projector cursor models for advanced scenarios, or uses the default models for standard usage. Ensures all models are mapped declaratively and share the same metadata and class registry, enabling flexible schema management and migrations.

Parameters:

Name Type Description Default
base type[BaseProto]

Base class providing SQLAlchemy MetaData for model registration.

required
event_model type[BaseEvent]

Event model class to use. Defaults to DefaultEvent.

DefaultEvent
stream_model type[BaseStream]

Stream model class to use. Defaults to DefaultStream.

DefaultStream
snapshot_model type[BaseSnapshot]

Snapshot model class to use. Defaults to DefaultSnapshot.

DefaultSnapshot
outbox_entry_model type[BaseOutboxEntry]

Outbox entry model class to use. Defaults to DefaultOutboxEntry.

DefaultOutboxEntry
projector_cursor_model type[BaseProjectorCursor]

Projector cursor model class to use. Defaults to DefaultProjectorCursor.

DefaultProjectorCursor
Source code in event_sourcery_sqlalchemy/models/__init__.py
def configure_models(
    base: type[BaseProto | DeclarativeBase],
    event_model: type[BaseEvent] = DefaultEvent,
    stream_model: type[BaseStream] = DefaultStream,
    snapshot_model: type[BaseSnapshot] = DefaultSnapshot,
    outbox_entry_model: type[BaseOutboxEntry] = DefaultOutboxEntry,
    projector_cursor_model: type[BaseProjectorCursor] = DefaultProjectorCursor,
) -> None:
    """
    Configures SQLAlchemy ORM models for Event Sourcery backend.

    Sets up mapping information and registers the provided (or default) models with
    SQLAlchemy's registry.
    This function allows customization of event, stream, snapshot, outbox entry, and
    projector cursor models for advanced scenarios, or uses the default models for
    standard usage.
    Ensures all models are mapped declaratively and share the same metadata and class
    registry, enabling flexible schema management and migrations.

    Args:
        base (type[BaseProto]):
            Base class providing SQLAlchemy MetaData for model registration.
        event_model (type[BaseEvent], optional):
            Event model class to use. Defaults to DefaultEvent.
        stream_model (type[BaseStream], optional):
            Stream model class to use. Defaults to DefaultStream.
        snapshot_model (type[BaseSnapshot], optional):
            Snapshot model class to use. Defaults to DefaultSnapshot.
        outbox_entry_model (type[BaseOutboxEntry], optional):
            Outbox entry model class to use. Defaults to DefaultOutboxEntry.
        projector_cursor_model (type[BaseProjectorCursor], optional):
            Projector cursor model class to use. Defaults to DefaultProjectorCursor.
    """
    event_model.__set_mapping_information__(stream_model)
    snapshot_model.__set_mapping_information__(stream_model)
    stream_model.__set_mapping_information__(event_model, snapshot_model)

    mapping_registry = registry(metadata=base.metadata, class_registry=_class_registry)
    for model_cls in (
        stream_model,
        event_model,
        snapshot_model,
        outbox_entry_model,
        projector_cursor_model,
    ):
        if model_cls in _class_registry.values():
            continue

        mapping_registry.map_declaratively(model_cls)

BaseEvent

Source code in event_sourcery_sqlalchemy/models/base.py
class BaseEvent:
    __stream_model__: type["BaseStream"]
    __tablename__: str

    @declared_attr  # type: ignore[arg-type]
    @classmethod
    def __table_args__(cls) -> tuple[Index | UniqueConstraint, ...]:
        return (
            Index(
                f"ix_events_stream_id_version_{cls.__tablename__}",
                "db_stream_id",
                "version",
                unique=True,
            ),
        )

    def __init__(
        self,
        uuid: UUID,
        created_at: datetime,
        name: str,
        data: dict,
        event_context: dict,
        version: int | None,
    ) -> None:
        self.uuid = uuid
        self.created_at = created_at
        self.name = name
        self.data = data
        self.event_context = event_context
        self.version = version

    @classmethod
    def __set_mapping_information__(cls, stream_model: type[BaseStream]) -> None:
        cls.__stream_model__ = stream_model

    @declared_attr
    @classmethod
    def _db_stream_id(cls) -> MappedColumn[Any]:
        return mapped_column(
            "db_stream_id",
            BigInteger().with_variant(Integer(), "sqlite"),
            ForeignKey(cls.__stream_model__.id),
            nullable=False,
            index=True,
        )

    @declared_attr
    @classmethod
    def stream(cls) -> Mapped[BaseStream]:
        return relationship(cls.__stream_model__, back_populates="events")

    id = mapped_column(BigInteger().with_variant(Integer(), "sqlite"), primary_key=True)
    version = mapped_column(Integer(), nullable=True)
    uuid = mapped_column(GUID(), index=True, unique=True)
    stream_id: AssociationProxy[StreamId] = association_proxy("stream", "stream_id")
    tenant_id: AssociationProxy[TenantId] = association_proxy("stream", "tenant_id")
    name = mapped_column(String(200), nullable=False)
    data = mapped_column(JSONB(), nullable=False)
    event_context = mapped_column(JSONB(), nullable=False)
    created_at = mapped_column(DateTime(), nullable=False, index=True)

BaseStream

Source code in event_sourcery_sqlalchemy/models/base.py
class BaseStream:
    __event_model__: type["BaseEvent"]
    __snapshot_model__: type["BaseSnapshot"]

    @declared_attr  # type: ignore[arg-type]
    @classmethod
    def __table_args__(cls) -> tuple[Index | UniqueConstraint, ...]:
        return (
            UniqueConstraint("uuid", "category", "tenant_id"),
            UniqueConstraint("name", "category", "tenant_id"),
        )

    id = mapped_column(BigInteger().with_variant(Integer(), "sqlite"), primary_key=True)
    uuid = mapped_column(GUID(), nullable=False)
    name = mapped_column(String(255), nullable=True, default=None)
    category = mapped_column(String(255), nullable=False, default="")
    tenant_id = mapped_column(String(255), nullable=False)
    version = mapped_column(BigInteger(), nullable=True)

    @classmethod
    def __set_mapping_information__(
        cls, event_model: type["BaseEvent"], snapshot_model: type["BaseSnapshot"]
    ) -> None:
        cls.__event_model__ = event_model
        cls.__snapshot_model__ = snapshot_model

    @declared_attr
    @classmethod
    def events(cls) -> Mapped[list["BaseEvent"]]:
        return relationship(cls.__event_model__, back_populates="stream")

    @declared_attr
    @classmethod
    def snapshots(cls) -> Mapped[list["BaseSnapshot"]]:
        return relationship(cls.__snapshot_model__, back_populates="stream")

    @hybrid_property
    def stream_id(self) -> StreamId:
        return StreamId(self.uuid, self.name, category=self.category or None)

    @stream_id.inplace.comparator
    @classmethod
    def _stream_id_comparator(cls) -> StreamIdComparator:
        return StreamIdComparator(cls.uuid, cls.name, cls.category)

BaseOutboxEntry

Source code in event_sourcery_sqlalchemy/models/base.py
class BaseOutboxEntry:
    id = mapped_column(BigInteger().with_variant(Integer(), "sqlite"), primary_key=True)
    created_at = mapped_column(DateTime(), nullable=False, index=True)
    data = mapped_column(JSONB(), nullable=False)
    stream_name = mapped_column(String(255), nullable=True)
    position = mapped_column(BigInteger().with_variant(Integer(), "sqlite"))
    tries_left = mapped_column(Integer(), nullable=False)

BaseProjectorCursor

Source code in event_sourcery_sqlalchemy/models/base.py
class BaseProjectorCursor:
    __tablename__: str

    @declared_attr  # type: ignore[arg-type]
    @classmethod
    def __table_args__(cls) -> tuple[Index | UniqueConstraint, ...]:
        return (
            Index(
                f"ix_name_stream_id_{cls.__tablename__}",
                "name",
                "stream_id",
                "category",
                unique=True,
            ),
        )

    id = mapped_column(BigInteger().with_variant(Integer(), "sqlite"), primary_key=True)
    name = mapped_column(String(255), nullable=False)
    stream_id = mapped_column(GUID(), nullable=False, index=True)
    category = mapped_column(String(255), nullable=True)
    version = mapped_column(BigInteger(), nullable=False)

BaseSnapshot

Source code in event_sourcery_sqlalchemy/models/base.py
class BaseSnapshot:
    __stream_model__: type["BaseStream"]

    def __init__(
        self,
        uuid: UUID,
        created_at: datetime,
        name: str,
        data: dict,
        event_context: dict,
        version: int | None,
    ) -> None:
        self.uuid = uuid
        self.created_at = created_at
        self.name = name
        self.data = data
        self.event_context = event_context
        self.version = version

    @classmethod
    def __set_mapping_information__(cls, stream_model: type[BaseStream]) -> None:
        cls.__stream_model__ = stream_model

    @declared_attr
    @classmethod
    def _db_stream_id(cls) -> MappedColumn[Any]:
        return mapped_column(
            "db_stream_id",
            BigInteger().with_variant(Integer(), "sqlite"),
            ForeignKey(cls.__stream_model__.id),
            nullable=False,
            index=True,
        )

    @declared_attr
    @classmethod
    def stream(cls) -> Mapped[BaseStream]:
        return relationship(cls.__stream_model__, back_populates="snapshots")

    uuid = mapped_column(GUID, primary_key=True)
    version = mapped_column(Integer(), nullable=False)
    stream_id: AssociationProxy[StreamId] = association_proxy("stream", "stream_id")
    name = mapped_column(String(50), nullable=False)
    data = mapped_column(JSONB(), nullable=False)
    event_context = mapped_column(JSONB(), nullable=False)
    created_at = mapped_column(DateTime(), nullable=False)

AsyncSqlAlchemyStorageStrategy

Bases: AsyncStorageStrategy

Async counterpart of SqlAlchemyStorageStrategy.

Stores events using an AsyncSession. Unlike the sync variant, it does not use ORM relationship arms (stream.events.extend(...), stream.snapshots.append(...)) to associate rows — those lazy-load collections, which is not available in an asyncio context. It assigns foreign keys (entry._db_stream_id) directly instead, producing identical INSERT statements.

Source code in event_sourcery_sqlalchemy/async_/event_store.py
@dataclass(repr=False)
class AsyncSqlAlchemyStorageStrategy(AsyncStorageStrategy):
    """
    Async counterpart of `SqlAlchemyStorageStrategy`.

    Stores events using an `AsyncSession`. Unlike the sync variant, it does not
    use ORM relationship arms (`stream.events.extend(...)`, `stream.snapshots.append(...)`)
    to associate rows — those lazy-load collections, which is not available in an
    asyncio context. It assigns foreign keys (`entry._db_stream_id`) directly instead,
    producing identical INSERT statements.
    """

    _session: AsyncSession
    _dispatcher: AsyncDispatcher
    _outbox: AsyncSqlAlchemyOutboxStorageStrategy | None
    _event_model: type[BaseEvent]
    _snapshot_model: type[BaseSnapshot]
    _stream_model: type[BaseStream]
    _tenant_id: TenantId = DEFAULT_TENANT

    async def fetch_events(
        self,
        stream_id: StreamId,
        start: int | None = None,
        stop: int | None = None,
    ) -> list[RawEvent]:
        events_stmt = (
            select(self._event_model)
            .options(selectinload(self._event_model.stream))
            .filter_by(stream_id=stream_id, tenant_id=self._tenant_id)
            .order_by(self._event_model.version)
        )

        if start is not None:
            events_stmt = events_stmt.filter(self._event_model.version >= start)

        if stop is not None:
            events_stmt = events_stmt.filter(self._event_model.version < stop)

        events: Sequence[BaseEvent | BaseSnapshot]
        try:
            snapshot_stmt = (
                select(self._snapshot_model)
                .options(selectinload(self._snapshot_model.stream))
                .join(self._stream_model)
                .filter(
                    self._stream_model.stream_id == stream_id,
                    self._stream_model.tenant_id == self._tenant_id,
                )
                .order_by(self._snapshot_model.created_at.desc())
                .limit(1)
            )
            if start is not None:
                snapshot_stmt = snapshot_stmt.filter(
                    self._snapshot_model.version >= start
                )

            if stop is not None:
                snapshot_stmt = snapshot_stmt.filter(
                    self._snapshot_model.version < stop
                )

            latest_snapshot = (
                (await self._session.execute(snapshot_stmt)).scalars().one()
            )
        except NoResultFound:
            events = (await self._session.execute(events_stmt)).scalars().all()
        else:
            events_stmt = events_stmt.filter(
                self._event_model.version > latest_snapshot.version
            )
            newer_events = list(
                (await self._session.execute(events_stmt)).scalars().all()
            )
            events = [latest_snapshot, *newer_events]

        if not events:
            return []

        raw_dict_events = [
            RawEvent(
                uuid=event.uuid,
                stream_id=event.stream_id,
                created_at=event.created_at,
                version=event.version,
                name=event.name,
                data=event.data,
                context=event.event_context,
            )
            for event in events
        ]
        return raw_dict_events

    async def _ensure_stream(
        self, stream_id: StreamId, versioning: Versioning
    ) -> BaseStream:
        initial_version = versioning.initial_version

        condition = (
            (self._stream_model.uuid == stream_id)
            & (self._stream_model.category == (stream_id.category or ""))
            & (self._stream_model.tenant_id == self._tenant_id)
        )
        if stream_id.name:
            condition = condition | (
                (self._stream_model.name == stream_id.name)
                & (self._stream_model.category == (stream_id.category or ""))
                & (self._stream_model.tenant_id == self._tenant_id)
            )
        matching_streams_stmt = select(self._stream_model).where(condition)
        matching_streams = (
            (await self._session.execute(matching_streams_stmt)).scalars().all()
        )
        inserted_stream_id = None
        if not matching_streams:
            ensure_stream_stmt = (
                postgresql_insert(self._stream_model)
                .values(
                    uuid=stream_id,
                    name=stream_id.name,
                    category=stream_id.category or "",
                    version=initial_version,
                    tenant_id=self._tenant_id,
                )
                .on_conflict_do_nothing()
                .returning(self._stream_model.id)
            )
            inserted_stream_id = (
                await self._session.execute(ensure_stream_stmt)
            ).scalar_one_or_none()
            matching_streams = (
                (await self._session.execute(matching_streams_stmt)).scalars().all()
            )

        if stream_id.name is not None:
            matching_stream_with_same_name: BaseStream = [
                stream
                for stream in matching_streams
                if stream.name == stream_id.name
                and stream.category == (stream_id.category or "")
            ].pop()
            if matching_stream_with_same_name.stream_id != stream_id:
                raise AnotherStreamWithThisNameButOtherIdExists()

        stream = cast(
            BaseStream,
            first_true(
                matching_streams, pred=lambda stream: stream.stream_id == stream_id
            ),
        )
        self._session.info.setdefault("strong_set", set())
        self._session.info["strong_set"].add(stream)

        versioning.validate_if_compatible(stream.version)

        if (
            inserted_stream_id is not None
            and versioning is not NO_VERSIONING
            and versioning.expected_version != 0
        ):
            await self._session.execute(
                delete(self._stream_model).filter(
                    self._stream_model.id == inserted_stream_id
                )
            )
            raise ConcurrentStreamWriteError

        if (
            inserted_stream_id is None
            and versioning.expected_version is not None
            and versioning is not NO_VERSIONING
        ):
            bump_version_stmt = (
                update(self._stream_model)
                .where(
                    self._stream_model.stream_id == stream_id,
                    self._stream_model.tenant_id == self._tenant_id,
                    self._stream_model.version == versioning.expected_version,
                )
                .values(version=versioning.initial_version)
            )
            result = cast(
                CursorResult[Any], await self._session.execute(bump_version_stmt)
            )

            if result.rowcount != 1:
                # optimistic lock failed
                raise ConcurrentStreamWriteError

        return stream

    async def insert_events(
        self, stream_id: StreamId, versioning: Versioning, events: list[RawEvent]
    ) -> None:
        # Unlike the sync variant, the stream is returned from `_ensure_stream`
        # instead of being looked up in `session.info["strong_set"]`: after a
        # commit the session expires ORM objects, and reading attributes of an
        # expired instance triggers a lazy refresh — synchronous I/O, which is
        # not available in an asyncio context (MissingGreenlet).
        stream = await self._ensure_stream(stream_id=stream_id, versioning=versioning)

        entries = []
        for event in events:
            entry = self._event_model(
                uuid=event.uuid,
                created_at=event.created_at,
                name=event.name,
                data=event.data,
                event_context=event.context,
                version=event.version,
            )
            # Unlike the sync variant, the foreign key is assigned directly.
            # Relationship-arm usage (`stream.events.extend(entries)`) would
            # lazy-load the collection, which is unavailable under asyncio.
            entry._db_stream_id = stream.id
            entries.append(entry)
        self._session.add_all(entries)
        await self._session.flush()
        records = [
            RecordedRaw(entry=raw, position=db.id, tenant_id=self._tenant_id)
            for raw, db in zip(events, entries, strict=False)
        ]
        if self._outbox:
            await self._outbox.put_into_outbox(records)
        await self._session.flush()
        await self._dispatcher.dispatch(*records)

    async def save_snapshot(self, snapshot: RawEvent) -> None:
        stream = (
            (
                await self._session.execute(
                    select(self._stream_model).filter_by(
                        stream_id=snapshot.stream_id, tenant_id=self._tenant_id
                    )
                )
            )
            .scalars()
            .one()
        )
        entry = self._snapshot_model(
            uuid=snapshot.uuid,
            created_at=snapshot.created_at,
            version=snapshot.version,
            name=snapshot.name,
            data=snapshot.data,
            event_context=snapshot.context,
        )
        # Same reason as in `insert_events`: avoid relationship lazy loads.
        entry._db_stream_id = stream.id
        self._session.add(entry)
        await self._session.flush()

    async def delete_stream(self, stream_id: StreamId) -> None:
        delete_events_stmt = delete(self._event_model).where(
            self._event_model.stream_id == stream_id,
            self._event_model.tenant_id == self._tenant_id,
        )
        await self._session.execute(delete_events_stmt)
        delete_stream_stmt = delete(self._stream_model).where(
            self._stream_model.stream_id == stream_id,
            self._stream_model.tenant_id == self._tenant_id,
        )
        await self._session.execute(delete_stream_stmt)

    async def current_position(self) -> Position | None:
        stmt = select(func.max(self._event_model.id))
        last_event = await self._session.scalar(stmt)
        return last_event or Position(0)

    def scoped_for_tenant(self, tenant_id: TenantId) -> Self:
        return replace(self, _tenant_id=tenant_id)

AsyncSqlAlchemySubscriptionStrategy

Bases: AsyncSubscriptionStrategy

Async counterpart of SqlAlchemySubscriptionStrategy.

Polls the events table with gap detection using an AsyncSession, yielding batches of recorded events as an async iterator.

Source code in event_sourcery_sqlalchemy/async_/subscription.py
class AsyncSqlAlchemySubscriptionStrategy(AsyncSubscriptionStrategy):
    """
    Async counterpart of `SqlAlchemySubscriptionStrategy`.

    Polls the events table with gap detection using an `AsyncSession`,
    yielding batches of recorded events as an async iterator.
    """

    def __init__(
        self,
        session: AsyncSession,
        gap_retry_interval: timedelta,
        event_model: type[BaseEvent],
        stream_model: type[BaseStream],
    ) -> None:
        self._session = session
        self._gap_retry_interval = gap_retry_interval
        self._event_model = event_model
        self._stream_model = stream_model

    def subscribe_to_all(
        self,
        start_from: Position,
        batch_size: int,
        timelimit: timedelta,
    ) -> AsyncIterator[list[RecordedRaw]]:
        return AsyncGapDetectingIterator(
            get_batch=AsyncGetBatchToAll(
                self._session, batch_size, self._event_model, self._stream_model
            ),
            gap_retry_interval=self._gap_retry_interval,
            start_from=start_from,
            batch_size=batch_size,
            timelimit=timelimit,
        )

    def subscribe_to_category(
        self,
        start_from: Position,
        batch_size: int,
        timelimit: timedelta,
        category: str,
    ) -> AsyncIterator[list[RecordedRaw]]:
        return AsyncGapDetectingIterator(
            get_batch=AsyncGetBatchToCategory(
                self._session,
                batch_size,
                category,
                self._event_model,
                self._stream_model,
            ),
            gap_retry_interval=self._gap_retry_interval,
            start_from=start_from,
            batch_size=batch_size,
            timelimit=timelimit,
        )

    def subscribe_to_events(
        self,
        start_from: Position,
        batch_size: int,
        timelimit: timedelta,
        events: list[str],
    ) -> AsyncIterator[list[RecordedRaw]]:
        return AsyncGapDetectingIterator(
            get_batch=AsyncGetBatchToEvents(
                self._session, batch_size, events, self._event_model, self._stream_model
            ),
            gap_retry_interval=self._gap_retry_interval,
            start_from=start_from,
            batch_size=batch_size,
            timelimit=timelimit,
        )

AsyncSqlAlchemyOutboxStorageStrategy

Bases: AsyncOutboxStorageStrategy

Async counterpart of SqlAlchemyOutboxStorageStrategy.

Stores outbox entries in a relational table using an AsyncSession.

Source code in event_sourcery_sqlalchemy/async_/outbox.py
@dataclass(repr=False)
class AsyncSqlAlchemyOutboxStorageStrategy(AsyncOutboxStorageStrategy):
    """
    Async counterpart of `SqlAlchemyOutboxStorageStrategy`.

    Stores outbox entries in a relational table using an `AsyncSession`.
    """

    _session: AsyncSession
    _filterer: OutboxFiltererStrategy
    _max_publish_attempts: int
    _outbox_entry_model: type[BaseOutboxEntry]

    async def put_into_outbox(self, records: list[RecordedRaw]) -> None:
        rows = []
        for record in records:
            if not self._filterer(record.entry):
                continue

            stream_id = record.entry.stream_id
            as_dict = dataclasses.asdict(record.entry)
            as_dict.pop("stream_id")
            created_at = cast(datetime, as_dict["created_at"])
            as_dict["created_at"] = created_at.isoformat()
            as_dict["uuid"] = str(as_dict["uuid"])
            as_dict["stream_id"] = str(stream_id)
            as_dict["stream_category"] = stream_id.category
            as_dict["tenant_id"] = str(record.tenant_id)
            rows.append(
                {
                    "created_at": datetime.now(timezone.utc).replace(tzinfo=None),
                    "data": as_dict,
                    "stream_name": record.entry.stream_id.name,
                    "position": record.position,
                    "tries_left": self._max_publish_attempts,
                }
            )

        if len(rows) == 0:
            return

        await self._session.execute(insert(self._outbox_entry_model), rows)

    async def outbox_entries(
        self, limit: int
    ) -> AsyncIterator[AbstractAsyncContextManager[RecordedRaw]]:
        stmt = (
            select(self._outbox_entry_model)
            .filter(self._outbox_entry_model.tries_left > 0)
            .order_by(self._outbox_entry_model.id)
            .limit(limit)
            .with_for_update(skip_locked=True)
        )
        entries = (await self._session.execute(stmt)).scalars().all()
        for entry in entries:
            yield self._publish_context(entry)

    @asynccontextmanager
    async def _publish_context(
        self, entry: BaseOutboxEntry
    ) -> AsyncGenerator[RecordedRaw, None]:
        raw = RawEvent(
            uuid=UUID(entry.data["uuid"]),
            stream_id=StreamId(
                from_hex=entry.data["stream_id"],
                name=entry.stream_name,
                category=entry.data.get("stream_category"),
            ),
            created_at=datetime.fromisoformat(entry.data["created_at"]),
            version=entry.data["version"],
            name=entry.data["name"],
            data=entry.data["data"],
            context=entry.data["context"],
        )
        try:
            yield RecordedRaw(
                entry=raw,
                position=entry.position,
                tenant_id=entry.data["tenant_id"],
            )
        except Exception:
            logger.exception("Failed to publish message #%d", entry.id)
            entry.tries_left -= 1
        else:
            await self._session.delete(entry)

AsyncSqlAlchemyCursorsDao

Bases: AsyncCursorsDao

Async counterpart of SqlAlchemyCursorsDao: cursor persistence for AsyncProjector, powered by an AsyncSession.

Source code in event_sourcery_sqlalchemy/async_/cursors_dao.py
class AsyncSqlAlchemyCursorsDao(AsyncCursorsDao):
    """
    Async counterpart of `SqlAlchemyCursorsDao`: cursor persistence for
    `AsyncProjector`, powered by an `AsyncSession`.
    """

    def __init__(
        self,
        session: AsyncSession,
        projector_cursor_model: type[BaseProjectorCursor],
    ) -> None:
        self._session = session
        self._projector_cursor_model = projector_cursor_model

    async def increment(self, name: str, stream_id: StreamId, version: int) -> None:
        if version == 1:
            current_version = await self._current_version(name, stream_id)
            if current_version is not None:
                raise self.AheadOfStream(current_version=current_version)

            stmt = insert(self._projector_cursor_model).values(
                name=name,
                stream_id=stream_id,
                category=stream_id.category,
                version=version,
            )
            await self._session.execute(stmt)
            return

        update_stmt = (
            update(self._projector_cursor_model)
            .where(
                self._projector_cursor_model.name == name,
                self._projector_cursor_model.stream_id == stream_id,
                self._projector_cursor_model.category == stream_id.category,
                self._projector_cursor_model.version == version - 1,
            )
            .values({self._projector_cursor_model.version: version})
        )
        result = cast(
            CursorResult[Any],
            await self._session.execute(update_stmt),
        )
        if result.rowcount == 1:
            return
        else:
            current_version = await self._current_version(name, stream_id)

            if current_version is None:
                raise self.StreamNotTracked
            elif current_version < version:
                raise self.BehindStream(current_version=current_version)
            else:
                raise self.AheadOfStream(current_version=current_version)

    async def _current_version(self, name: str, stream_id: StreamId) -> int | None:
        stmt = select(self._projector_cursor_model.version).filter(
            self._projector_cursor_model.name == name,
            self._projector_cursor_model.stream_id == stream_id,
            self._projector_cursor_model.category == stream_id.category,
        )
        return cast(int | None, (await self._session.execute(stmt)).scalar())

    async def put_at(self, name: str, stream_id: StreamId, version: int) -> None:
        stmt = insert(self._projector_cursor_model).values(
            name=name,
            stream_id=stream_id,
            category=stream_id.category,
            version=version,
        )
        await self._session.execute(stmt)

    async def move_to(self, name: str, stream_id: StreamId, version: int) -> None:
        stmt = (
            update(self._projector_cursor_model)
            .where(
                self._projector_cursor_model.name == name,
                self._projector_cursor_model.stream_id == stream_id,
                self._projector_cursor_model.category == stream_id.category,
            )
            .values({self._projector_cursor_model.version: version})
        )
        await self._session.execute(stmt)