Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 15 additions & 4 deletions agentex/src/adapters/crud_store/adapter_postgres.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
select,
update,
)
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm.interfaces import LoaderOption
from sqlalchemy.sql import Select
Expand Down Expand Up @@ -167,15 +168,25 @@ async def start_async_db_session(
yield session

async def create(self, item: T) -> T:
"""Create an item using INSERT ... RETURNING for single query efficiency.

Uses RETURNING with explicit columns to avoid lazy-loading relationship
attributes on the returned ORM object, which would fail outside async context.
"""
async with (
self.start_async_db_session(True) as session,
async_sql_exception_handler(),
):
orm = self.orm(**item.to_dict())
session.add(orm)
# Exclude None values to allow server defaults (e.g., created_at) to apply
values = {k: v for k, v in item.to_dict().items() if v is not None}
# Return only columns (not full ORM) to avoid lazy-loading relationships
stmt = (
insert(self.orm).values(**values).returning(*self.orm.__table__.columns)
)
result = await session.execute(stmt)
row = result.one()
await session.commit()
await session.refresh(orm)
return self.entity.model_validate(orm)
return self.entity.model_validate(dict(row._mapping))

async def batch_create(self, items: list[T]) -> list[T]:
async with (
Expand Down
23 changes: 14 additions & 9 deletions agentex/src/domain/repositories/event_repository.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

from fastapi import Depends
from sqlalchemy import and_
from sqlalchemy.dialects.postgresql import insert
from sqlalchemy.future import select
from src.adapters.crud_store.adapter_postgres import (
PostgresCRUDRepository,
Expand Down Expand Up @@ -32,28 +33,32 @@ def __init__(
EventEntity,
)

# Have to do this because the sequence_id is automatically generated by the ORM
async def create(
self,
id: str,
task_id: str,
agent_id: str,
content: TaskMessageContentEntity | None = None,
) -> EventEntity:
"""Create an event using INSERT ... RETURNING to get sequence_id in one query."""
async with (
self.start_async_db_session(True) as session,
async_sql_exception_handler(),
):
orm = EventORM(
id=id,
task_id=task_id,
agent_id=agent_id,
content=content.model_dump(mode="json") if content else None,
stmt = (
insert(EventORM)
.values(
id=id,
task_id=task_id,
agent_id=agent_id,
content=content.model_dump(mode="json") if content else None,
)
.returning(EventORM)
)
session.add(orm)

result = await session.execute(stmt)
orm = result.scalar_one()
await session.commit()
# Refresh the ORM object to get the auto-generated sequence_id
await session.refresh(orm)
return self.entity.model_validate(orm)

async def list_events_after_last_processed(
Expand Down
Loading