Executes database queries using SQLAlchemy async API. Provides a databases-compatible interface.
| 11 | |
| 12 | |
| 13 | class QueryExecutor: |
| 14 | """ |
| 15 | Executes database queries using SQLAlchemy async API. |
| 16 | Provides a databases-compatible interface. |
| 17 | """ |
| 18 | |
| 19 | def __init__(self, connection: AsyncConnection) -> None: |
| 20 | """ |
| 21 | Initialize query executor. |
| 22 | |
| 23 | :param connection: SQLAlchemy async connection |
| 24 | """ |
| 25 | self._connection = connection |
| 26 | |
| 27 | async def fetch_all(self, query: Executable) -> List[Any]: |
| 28 | """ |
| 29 | Execute a query and fetch all rows. |
| 30 | |
| 31 | :param query: SQLAlchemy query expression |
| 32 | :return: List of Row objects |
| 33 | """ |
| 34 | result: CursorResult[Any] = await self._connection.execute(query) |
| 35 | return list(result.mappings().all()) |
| 36 | |
| 37 | async def fetch_one(self, query: Executable) -> Optional[RowMapping]: |
| 38 | """ |
| 39 | Execute a query and fetch one row. |
| 40 | |
| 41 | :param query: SQLAlchemy query expression |
| 42 | :return: Single Row object or None |
| 43 | """ |
| 44 | result: CursorResult[Any] = await self._connection.execute(query) |
| 45 | row = result.mappings().first() |
| 46 | return row |
| 47 | |
| 48 | async def fetch_val(self, query: Executable, column: int = 0) -> Optional[Any]: |
| 49 | """ |
| 50 | Execute a query and fetch a single scalar value. |
| 51 | |
| 52 | :param query: SQLAlchemy query expression |
| 53 | :param column: Column index to fetch (default 0) |
| 54 | :return: Scalar value or None |
| 55 | """ |
| 56 | result: CursorResult[Any] = await self._connection.execute(query) |
| 57 | return result.scalar() |
| 58 | |
| 59 | async def execute(self, query: Executable) -> Any: |
| 60 | """ |
| 61 | Execute a query (INSERT, UPDATE, DELETE). |
| 62 | |
| 63 | :param query: SQLAlchemy query expression |
| 64 | :return: For INSERT, the inserted primary key or ``None`` if the backend |
| 65 | cannot return one (e.g. Oracle MySQL inserting into a |
| 66 | non-AUTO_INCREMENT pk with a server default — no RETURNING support). |
| 67 | For UPDATE/DELETE, the row count. |
| 68 | """ |
| 69 | result: CursorResult[Any] = await self._connection.execute(query) |
| 70 |