Skip to content

query_executor

QueryExecutor module - executes database queries natively on the driver when a native backend is available, otherwise through the SQLAlchemy async API.

QueryExecutor

Executes database queries. With a native backend, statements run directly on the driver connection underneath the SQLAlchemy connection; statements the backend cannot run (and every statement without a backend) go through the SQLAlchemy async API. Provides a databases-compatible interface.

Source code in ormar/databases/query_executor.py
Python
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
class QueryExecutor:
    """
    Executes database queries. With a native backend, statements run directly on
    the driver connection underneath the SQLAlchemy connection; statements the
    backend cannot run (and every statement without a backend) go through the
    SQLAlchemy async API. Provides a databases-compatible interface.
    """

    def __init__(
        self, connection: AsyncConnection, native: Optional[NativeBackend] = None
    ) -> None:
        """
        Initialize query executor.

        :param connection: SQLAlchemy async connection
        :param native: native backend of the database, if the driver has one
        """
        self._connection = connection
        self._native = native
        self._raw: Any = None

    async def fetch_all(
        self,
        query: Executable,
        params: Optional[Mapping[str, Any]] = None,
        as_tuples: bool = False,
    ) -> List[Any]:
        """
        Execute a query and fetch all rows.

        Rows are mappings keyed by result label (and by the selected column
        objects); with ``as_tuples`` they are tuples of values in select order
        instead::

            await executor.fetch_all(select(users.c.id, users.c.name))
            # -> [{"id": 1, "name": "a"}]
            await executor.fetch_all(select(users.c.id, users.c.name), as_tuples=True)
            # -> [(1, "a")]

        :param query: SQLAlchemy query expression
        :type query: Executable
        :param params: values for named bind parameters of the query, by name;
            a cached query template passes its slot values here
        :type params: Optional[Mapping[str, Any]]
        :param as_tuples: return tuples of values in select order
        :type as_tuples: bool
        :return: rows as mappings keyed by result label, or tuples
        :rtype: List[Any]
        """
        bound = self._bind(query=query, params=params)
        if bound is not None:
            return await self._fetch_native(bound=bound, as_tuples=as_tuples)
        result: CursorResult[Any] = await self._connection.execute(
            statement=query, parameters=params
        )
        if as_tuples:
            return [tuple(row) for row in result.all()]
        return list(result.mappings().all())

    async def fetch_one(
        self,
        query: Executable,
        params: Optional[Mapping[str, Any]] = None,
        as_tuples: bool = False,
    ) -> Optional[Any]:
        """
        Execute a query and fetch one row.

        :param query: SQLAlchemy query expression
        :type query: Executable
        :param params: values for named bind parameters of the query, by name;
            a cached query template passes its slot values here
        :type params: Optional[Mapping[str, Any]]
        :param as_tuples: return a tuple of values in select order instead of
            a mapping keyed by result label
        :type as_tuples: bool
        :return: single row (mapping or tuple) or None when there is no row
        :rtype: Optional[Any]
        """
        bound = self._bind(query=query, params=params)
        if bound is not None:
            rows = await self._fetch_native(bound=bound, as_tuples=as_tuples)
            return rows[0] if rows else None
        result: CursorResult[Any] = await self._connection.execute(
            statement=query, parameters=params
        )
        if as_tuples:
            row = result.first()
            return tuple(row) if row is not None else None
        return result.mappings().first()

    async def fetch_val(
        self,
        query: Executable,
        column: int = 0,
        params: Optional[Mapping[str, Any]] = None,
    ) -> Optional[Any]:
        """
        Execute a query and fetch a single scalar value.

        :param query: SQLAlchemy query expression
        :param column: position of the column in the select to fetch (default 0)
        :param params: values for named bind parameters of the query, by name;
            a cached query template passes its slot values here
        :return: value of the column in the first row, None when there are no rows
        """
        row = await self.fetch_one(query=query, params=params, as_tuples=True)
        return row[column] if row is not None else None

    async def execute(
        self, query: Executable, params: Optional[Mapping[str, Any]] = None
    ) -> Any:
        """
        Execute a query (INSERT, UPDATE, DELETE).

        :param query: SQLAlchemy query expression
        :param params: values for named bind parameters of the query
        :return: For INSERT, the inserted primary key or ``None`` if the backend
            cannot return one (e.g. Oracle MySQL inserting into a
            non-AUTO_INCREMENT pk with a server default — no RETURNING support).
            For UPDATE/DELETE, the row count.
        """
        bound = self._bind(query=query, params=params)
        if bound is not None:
            assert self._native is not None
            return await self._run(
                method=self._native.adapter.execute, payload=bound, args=bound.args
            )

        result: CursorResult[Any] = await self._connection.execute(
            statement=query, parameters=params
        )

        # For INSERT queries, try to get the inserted primary key via the
        # dialect's best-available mechanism (RETURNING on PostgreSQL / SQLite
        # 3.35+ / MariaDB 10.5+, LAST_INSERT_ID() on MySQL AUTO_INCREMENT).
        # Do NOT fall back to rowcount here: rowcount is not a pk, and
        # returning it would silently corrupt `Model.pk` in `save()`.
        if result.context and result.context.isinsert:
            # a primary key bound by name (insert templates bind it as
            # ``ormar_v{i}``) is returned as bound: SQLAlchemy only looks the
            # inserted key up under the column key, so it would miss it
            compiled = cast(SQLCompiler, result.context.compiled)
            key = pk_param_key(compiled=compiled) if params else None
            if key is not None and params and params.get(key) is not None:
                return params[key]
            if result.inserted_primary_key:
                pk_value = result.inserted_primary_key[0]
                if pk_value is not None:
                    return pk_value

            if hasattr(result, "lastrowid") and result.lastrowid:  # pragma: no cover
                return result.lastrowid

            return None  # pragma: no cover

        return result.rowcount if result.rowcount is not None else 0

    async def execute_many(
        self, query: Union[Executable, str], values: Sequence[Mapping[str, Any]]
    ) -> None:
        """
        Execute a query multiple times with different parameter sets.

        :param query: SQLAlchemy query expression or SQL string
        :param values: Sequence of parameter mappings
        """
        # SQLAlchemy runs a statement given no parameter sets once; leave
        # that case to it so both paths behave the same.
        if self._native is not None and values and is_plannable(stmt=query):
            batch = self._native.compiler.bind_many(stmt=query, rows=values)
            if not batch.plan.fallback:
                await self._run(
                    method=self._native.adapter.execute_many,
                    payload=batch,
                    args=batch.args_list,
                )
                return
        exec_query = text(text=query) if isinstance(query, str) else query
        # an empty list is deprecated in SQLAlchemy 2.1, None runs it once too
        await self._connection.execute(
            statement=exec_query, parameters=list(values) or None
        )

    async def iterate(
        self, query: Executable, params: Optional[Mapping[str, Any]] = None
    ) -> AsyncIterator[Any]:
        """
        Execute a query and iterate over results.

        :param query: SQLAlchemy query expression
        :param params: values for named bind parameters of the query, by name;
            a cached query template passes its slot values here
        :return: Async iterator of rows, accessible by result label
        """
        bound = self._bind(query=query, params=params)
        if bound is not None:
            assert self._native is not None
            raw = await self._raw_connection()
            rows = self._native.adapter.stream(
                raw=raw, bound=bound, batch_size=ITERATE_BATCH_SIZE
            )
            async with contextlib.aclosing(rows):
                try:
                    async for row in rows:
                        yield row
                except self._native.adapter.driver_errors as error:
                    await self._translate(error=error, sql=bound.sql, args=bound.args)
                except GeneratorExit:
                    raise
                except BaseException as error:
                    await self._reraise_interrupted(error=error)
            return
        async with self._connection.stream(
            statement=query, parameters=params
        ) as result:
            async for mapping in result.mappings():
                yield mapping

    async def _fetch_native(
        self, bound: BoundStatement, as_tuples: bool = False
    ) -> List[Any]:
        """
        Fetch all rows of a bound statement on the driver.

        :param bound: bound statement
        :type bound: BoundStatement
        :param as_tuples: return tuples of values in select order
        :type as_tuples: bool
        :return: rows keyed by result label, or tuples
        :rtype: List[Any]
        """
        assert self._native is not None
        method = self._native.adapter.fetch_all
        if as_tuples:
            method = functools.partial(method, as_tuples=True)
        return await self._run(method=method, payload=bound, args=bound.args)

    def _bind(
        self, query: Executable, params: Optional[Mapping[str, Any]] = None
    ) -> Optional[BoundStatement]:
        """
        Bind the query for native execution.

        :param query: SQLAlchemy query expression
        :param params: values for named bind parameters of the query, by name;
            a cached query template passes its slot values here
        :return: bound statement, or None when it must run through SQLAlchemy
        """
        if self._native is None or not is_plannable(stmt=query):
            return None
        bound = self._native.compiler.bind(stmt=query, params=params)
        return None if bound.plan.fallback else bound

    async def _raw_connection(self) -> Any:
        """
        Return the pooled raw connection under the SQLAlchemy connection.

        :return: pooled raw connection
        """
        if self._raw is None:
            # an established connection already holds its pooled connection;
            # only a lazy, not yet connected one needs SQLAlchemy's greenlet
            sync_connection = self._connection.sync_connection
            if sync_connection is not None and (
                sync_connection._dbapi_connection is not None
            ):
                self._raw = sync_connection._dbapi_connection
            else:
                self._raw = await self._connection.get_raw_connection()
        return self._raw

    async def _run(
        self,
        method: Callable[[Any, Payload], Awaitable[Result]],
        payload: Payload,
        args: Sequence[Any],
    ) -> Result:
        """
        Run an adapter method, translating driver errors to SQLAlchemy ones.

        :param method: adapter method to run
        :param payload: bound statement or batch
        :param args: driver arguments, reported in a translated error
        :return: result of the adapter method
        """
        assert self._native is not None
        raw = await self._raw_connection()
        try:
            return await method(raw, payload)
        except self._native.adapter.driver_errors as error:
            await self._translate(
                error=error,
                sql=payload.sql,
                args=args,
                ismulti=isinstance(payload, BoundBatch),
            )
        except BaseException as error:
            await self._reraise_interrupted(error=error)

    async def _reraise_interrupted(self, error: BaseException) -> NoReturn:
        """
        Re-raise an exception from a native call, first invalidating the
        connection when the call was interrupted (task cancellation,
        KeyboardInterrupt, ...), as SQLAlchemy does, so a connection left
        mid-statement never returns to the pool.

        :param error: exception raised during the call
        """
        if util.is_exit_exception(e=error):
            await self._connection.invalidate()
        raise error

    async def _translate(
        self,
        error: BaseException,
        sql: str,
        args: Sequence[Any],
        ismulti: bool = False,
    ) -> NoReturn:
        """
        Re-raise a driver error as the matching SQLAlchemy exception.

        :param error: exception raised by the driver
        :param sql: executed SQL
        :param args: driver arguments
        :param ismulti: whether the statement ran once per row of a batch
        """
        assert self._native is not None
        await raise_translated(
            error=error,
            backend=self._native,
            sa_connection=self._connection,
            sql=sql,
            args=args,
            ismulti=ismulti,
        )

__init__(connection, native=None)

Initialize query executor.

Parameters:

Name Type Description Default
connection AsyncConnection

SQLAlchemy async connection

required
native Optional[NativeBackend]

native backend of the database, if the driver has one

None
Source code in ormar/databases/query_executor.py
Python
51
52
53
54
55
56
57
58
59
60
61
62
def __init__(
    self, connection: AsyncConnection, native: Optional[NativeBackend] = None
) -> None:
    """
    Initialize query executor.

    :param connection: SQLAlchemy async connection
    :param native: native backend of the database, if the driver has one
    """
    self._connection = connection
    self._native = native
    self._raw: Any = None

execute(query, params=None) async

Execute a query (INSERT, UPDATE, DELETE).

Parameters:

Name Type Description Default
query Executable

SQLAlchemy query expression

required
params Optional[Mapping[str, Any]]

values for named bind parameters of the query

None

Returns:

Type Description
Any

For INSERT, the inserted primary key or None if the backend cannot return one (e.g. Oracle MySQL inserting into a non-AUTO_INCREMENT pk with a server default — no RETURNING support). For UPDATE/DELETE, the row count.

Source code in ormar/databases/query_executor.py
Python
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
async def execute(
    self, query: Executable, params: Optional[Mapping[str, Any]] = None
) -> Any:
    """
    Execute a query (INSERT, UPDATE, DELETE).

    :param query: SQLAlchemy query expression
    :param params: values for named bind parameters of the query
    :return: For INSERT, the inserted primary key or ``None`` if the backend
        cannot return one (e.g. Oracle MySQL inserting into a
        non-AUTO_INCREMENT pk with a server default — no RETURNING support).
        For UPDATE/DELETE, the row count.
    """
    bound = self._bind(query=query, params=params)
    if bound is not None:
        assert self._native is not None
        return await self._run(
            method=self._native.adapter.execute, payload=bound, args=bound.args
        )

    result: CursorResult[Any] = await self._connection.execute(
        statement=query, parameters=params
    )

    # For INSERT queries, try to get the inserted primary key via the
    # dialect's best-available mechanism (RETURNING on PostgreSQL / SQLite
    # 3.35+ / MariaDB 10.5+, LAST_INSERT_ID() on MySQL AUTO_INCREMENT).
    # Do NOT fall back to rowcount here: rowcount is not a pk, and
    # returning it would silently corrupt `Model.pk` in `save()`.
    if result.context and result.context.isinsert:
        # a primary key bound by name (insert templates bind it as
        # ``ormar_v{i}``) is returned as bound: SQLAlchemy only looks the
        # inserted key up under the column key, so it would miss it
        compiled = cast(SQLCompiler, result.context.compiled)
        key = pk_param_key(compiled=compiled) if params else None
        if key is not None and params and params.get(key) is not None:
            return params[key]
        if result.inserted_primary_key:
            pk_value = result.inserted_primary_key[0]
            if pk_value is not None:
                return pk_value

        if hasattr(result, "lastrowid") and result.lastrowid:  # pragma: no cover
            return result.lastrowid

        return None  # pragma: no cover

    return result.rowcount if result.rowcount is not None else 0

execute_many(query, values) async

Execute a query multiple times with different parameter sets.

Parameters:

Name Type Description Default
query Union[Executable, str]

SQLAlchemy query expression or SQL string

required
values Sequence[Mapping[str, Any]]

Sequence of parameter mappings

required
Source code in ormar/databases/query_executor.py
Python
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
async def execute_many(
    self, query: Union[Executable, str], values: Sequence[Mapping[str, Any]]
) -> None:
    """
    Execute a query multiple times with different parameter sets.

    :param query: SQLAlchemy query expression or SQL string
    :param values: Sequence of parameter mappings
    """
    # SQLAlchemy runs a statement given no parameter sets once; leave
    # that case to it so both paths behave the same.
    if self._native is not None and values and is_plannable(stmt=query):
        batch = self._native.compiler.bind_many(stmt=query, rows=values)
        if not batch.plan.fallback:
            await self._run(
                method=self._native.adapter.execute_many,
                payload=batch,
                args=batch.args_list,
            )
            return
    exec_query = text(text=query) if isinstance(query, str) else query
    # an empty list is deprecated in SQLAlchemy 2.1, None runs it once too
    await self._connection.execute(
        statement=exec_query, parameters=list(values) or None
    )

fetch_all(query, params=None, as_tuples=False) async

Execute a query and fetch all rows.

Rows are mappings keyed by result label (and by the selected column objects); with as_tuples they are tuples of values in select order instead::

Text Only
1
2
3
4
await executor.fetch_all(select(users.c.id, users.c.name))
# -> [{"id": 1, "name": "a"}]
await executor.fetch_all(select(users.c.id, users.c.name), as_tuples=True)
# -> [(1, "a")]

Parameters:

Name Type Description Default
query Executable

SQLAlchemy query expression

required
params Optional[Mapping[str, Any]]

values for named bind parameters of the query, by name; a cached query template passes its slot values here

None
as_tuples bool

return tuples of values in select order

False

Returns:

Type Description
List[Any]

rows as mappings keyed by result label, or tuples

Source code in ormar/databases/query_executor.py
Python
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
async def fetch_all(
    self,
    query: Executable,
    params: Optional[Mapping[str, Any]] = None,
    as_tuples: bool = False,
) -> List[Any]:
    """
    Execute a query and fetch all rows.

    Rows are mappings keyed by result label (and by the selected column
    objects); with ``as_tuples`` they are tuples of values in select order
    instead::

        await executor.fetch_all(select(users.c.id, users.c.name))
        # -> [{"id": 1, "name": "a"}]
        await executor.fetch_all(select(users.c.id, users.c.name), as_tuples=True)
        # -> [(1, "a")]

    :param query: SQLAlchemy query expression
    :type query: Executable
    :param params: values for named bind parameters of the query, by name;
        a cached query template passes its slot values here
    :type params: Optional[Mapping[str, Any]]
    :param as_tuples: return tuples of values in select order
    :type as_tuples: bool
    :return: rows as mappings keyed by result label, or tuples
    :rtype: List[Any]
    """
    bound = self._bind(query=query, params=params)
    if bound is not None:
        return await self._fetch_native(bound=bound, as_tuples=as_tuples)
    result: CursorResult[Any] = await self._connection.execute(
        statement=query, parameters=params
    )
    if as_tuples:
        return [tuple(row) for row in result.all()]
    return list(result.mappings().all())

fetch_one(query, params=None, as_tuples=False) async

Execute a query and fetch one row.

Parameters:

Name Type Description Default
query Executable

SQLAlchemy query expression

required
params Optional[Mapping[str, Any]]

values for named bind parameters of the query, by name; a cached query template passes its slot values here

None
as_tuples bool

return a tuple of values in select order instead of a mapping keyed by result label

False

Returns:

Type Description
Optional[Any]

single row (mapping or tuple) or None when there is no row

Source code in ormar/databases/query_executor.py
Python
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
async def fetch_one(
    self,
    query: Executable,
    params: Optional[Mapping[str, Any]] = None,
    as_tuples: bool = False,
) -> Optional[Any]:
    """
    Execute a query and fetch one row.

    :param query: SQLAlchemy query expression
    :type query: Executable
    :param params: values for named bind parameters of the query, by name;
        a cached query template passes its slot values here
    :type params: Optional[Mapping[str, Any]]
    :param as_tuples: return a tuple of values in select order instead of
        a mapping keyed by result label
    :type as_tuples: bool
    :return: single row (mapping or tuple) or None when there is no row
    :rtype: Optional[Any]
    """
    bound = self._bind(query=query, params=params)
    if bound is not None:
        rows = await self._fetch_native(bound=bound, as_tuples=as_tuples)
        return rows[0] if rows else None
    result: CursorResult[Any] = await self._connection.execute(
        statement=query, parameters=params
    )
    if as_tuples:
        row = result.first()
        return tuple(row) if row is not None else None
    return result.mappings().first()

fetch_val(query, column=0, params=None) async

Execute a query and fetch a single scalar value.

Parameters:

Name Type Description Default
query Executable

SQLAlchemy query expression

required
column int

position of the column in the select to fetch (default 0)

0
params Optional[Mapping[str, Any]]

values for named bind parameters of the query, by name; a cached query template passes its slot values here

None

Returns:

Type Description
Optional[Any]

value of the column in the first row, None when there are no rows

Source code in ormar/databases/query_executor.py
Python
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
async def fetch_val(
    self,
    query: Executable,
    column: int = 0,
    params: Optional[Mapping[str, Any]] = None,
) -> Optional[Any]:
    """
    Execute a query and fetch a single scalar value.

    :param query: SQLAlchemy query expression
    :param column: position of the column in the select to fetch (default 0)
    :param params: values for named bind parameters of the query, by name;
        a cached query template passes its slot values here
    :return: value of the column in the first row, None when there are no rows
    """
    row = await self.fetch_one(query=query, params=params, as_tuples=True)
    return row[column] if row is not None else None

iterate(query, params=None) async

Execute a query and iterate over results.

Parameters:

Name Type Description Default
query Executable

SQLAlchemy query expression

required
params Optional[Mapping[str, Any]]

values for named bind parameters of the query, by name; a cached query template passes its slot values here

None

Returns:

Type Description
AsyncIterator[Any]

Async iterator of rows, accessible by result label

Source code in ormar/databases/query_executor.py
Python
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
async def iterate(
    self, query: Executable, params: Optional[Mapping[str, Any]] = None
) -> AsyncIterator[Any]:
    """
    Execute a query and iterate over results.

    :param query: SQLAlchemy query expression
    :param params: values for named bind parameters of the query, by name;
        a cached query template passes its slot values here
    :return: Async iterator of rows, accessible by result label
    """
    bound = self._bind(query=query, params=params)
    if bound is not None:
        assert self._native is not None
        raw = await self._raw_connection()
        rows = self._native.adapter.stream(
            raw=raw, bound=bound, batch_size=ITERATE_BATCH_SIZE
        )
        async with contextlib.aclosing(rows):
            try:
                async for row in rows:
                    yield row
            except self._native.adapter.driver_errors as error:
                await self._translate(error=error, sql=bound.sql, args=bound.args)
            except GeneratorExit:
                raise
            except BaseException as error:
                await self._reraise_interrupted(error=error)
        return
    async with self._connection.stream(
        statement=query, parameters=params
    ) as result:
        async for mapping in result.mappings():
            yield mapping