Asynchronous Driver Base¶
from sqlspec.driver import (
AsyncDataDictionaryBase,
AsyncDriverAdapterBase,
AsyncPoolConnectionContext,
AsyncPoolSessionFactory,
AsyncRowStream,
)
Base asynchronous driver adapter class inherited by all asynchronous SQLSpec database adapters (AsyncpgDriver, PsycopgAsyncDriver, PsqlpyDriver, AiosqliteDriver, AsyncmyDriver, AiomysqlDriver, OracleAsyncDriver, SpannerAsyncDriver, Db2AsyncDriver, MssqlAsyncDriver, CockroachAsyncpgDriver, CockroachPsycopgAsyncDriver). See Querying for usage examples.
Asynchronous Driver Adapter¶
AsyncDriverAdapterBase
¶
Bases: CommonDriverAttributesMixin
Base execution, transaction, Arrow, and storage adapter for asynchronous database drivers.
Provides uniform SQL compilation, parameter binding, statement caching, result mapping, Apache Arrow fetching, and storage pipeline execution over asynchronous driver connections.
execute
¶
Execute a statement with parameter handling.
execute_many
¶
Execute statement multiple times with different parameters.
Parameters passed will be used as the batch execution sequence.
execute_script
¶
Execute a multi-statement script.
By default, validates each statement and logs warnings for dangerous operations. Use suppress_warnings=True for migrations and admin scripts.
execute_stack
¶
Execute a StatementStack sequentially using the adapter's primitives.
select
¶
Execute a select statement and return all rows.
select_one
¶
Execute a select statement and return exactly one row.
Raises an exception if no rows or more than one row is returned.
select_one_or_none
¶
Execute a select statement and return at most one row.
Returns None if no rows are found. Raises
:class:~sqlspec.exceptions.MultipleResultsFoundError if more than one row
is returned. Any database or SQL execution errors raised by the driver are
propagated unchanged.
select_value
¶
Execute a select statement and return a single scalar value.
Expects exactly one row with one column. Raises an exception if no rows or more than one row/column is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement
|
Statement | QueryBuilder
|
SQL statement or query builder to execute. |
required |
*parameters
|
StatementParameters | StatementFilter
|
Positional parameters for the statement. |
()
|
value_type
|
type[ValueT] | None
|
Optional type to convert the result to. When provided, the return value is converted to this type and the return type is narrowed for type checkers. Supports int, float, str, bool, datetime, date, time, Decimal, UUID, Path, dict, and list. |
None
|
statement_config
|
StatementConfig | None
|
Optional statement configuration. |
None
|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
ValueT | Any
|
The scalar value, optionally converted to the specified type |
select_value_or_none
¶
Execute a select statement and return a single scalar value or None.
Returns None if no rows are found. Expects at most one row with one column. Raises an exception if more than one row is returned.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement
|
Statement | QueryBuilder
|
SQL statement or query builder to execute. |
required |
*parameters
|
StatementParameters | StatementFilter
|
Positional parameters for the statement. |
()
|
value_type
|
type[ValueT] | None
|
Optional type to convert the result to. When provided,
the return value is converted to this type and the return type
is narrowed to |
None
|
statement_config
|
StatementConfig | None
|
Optional statement configuration. |
None
|
**kwargs
|
Any
|
Additional keyword arguments. |
{}
|
Returns:
| Type | Description |
|---|---|
ValueT | Any | None
|
The scalar value (optionally converted), or None if no rows found. |
select_with_total
¶
select_with_total(
statement,
/,
*parameters,
schema_type=None,
statement_config=None,
count_with_window=False,
**kwargs,
)
Execute a select statement and return both the data and total count.
This method is designed for pagination scenarios where you need both the current page of data and the total number of rows that match the query.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement
|
Statement | QueryBuilder
|
The SQL statement, QueryBuilder, or raw SQL string |
required |
*parameters
|
StatementParameters | StatementFilter
|
Parameters for the SQL statement |
()
|
schema_type
|
type[SchemaT] | None
|
Optional schema type for data transformation |
None
|
statement_config
|
StatementConfig | None
|
Optional SQL configuration |
None
|
count_with_window
|
bool
|
If True, use a single query with COUNT(*) OVER() window function instead of two separate queries. This can be more efficient for some databases but adds a column to each row. Default False. |
False
|
**kwargs
|
Any
|
Additional keyword arguments |
{}
|
A tuple containing: - List of data rows (transformed by schema_type if provided) - Total count of rows matching the query (ignoring LIMIT/OFFSET)
select_to_arrow
¶
select_to_arrow(
statement,
/,
*parameters,
statement_config=None,
return_format="table",
native_only=False,
batch_size=None,
arrow_schema=None,
**kwargs,
)
Execute query and return results as Apache Arrow format (async).
This base implementation uses the conversion path: execute() → dict → Arrow. Adapters with native Arrow support (ADBC, DuckDB, BigQuery) override this method to use zero-copy native paths for 5-10x performance improvement.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
statement
|
Statement | QueryBuilder
|
SQL query string, Statement, or QueryBuilder |
required |
*parameters
|
StatementParameters | StatementFilter
|
Query parameters (same format as execute()/select()) |
()
|
statement_config
|
StatementConfig | None
|
Optional statement configuration override |
None
|
return_format
|
ArrowReturnFormat
|
"table" for pyarrow.Table (default), "batch" for single RecordBatch, "batches" for iterator of RecordBatches, "reader" for RecordBatchReader |
'table'
|
native_only
|
bool
|
If True, raise error if native Arrow unavailable (default: False) |
False
|
batch_size
|
int | None
|
Rows per batch for "batch"/"batches" format (default: None = all rows) |
None
|
arrow_schema
|
Any
|
Optional pyarrow.Schema for type casting |
None
|
**kwargs
|
Any
|
Additional keyword arguments |
{}
|
Returns:
| Type | Description |
|---|---|
ArrowResult
|
ArrowResult containing pyarrow.Table, RecordBatchReader, or RecordBatches |
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
If native_only=True and adapter doesn't support native Arrow |
load_from_arrow
¶
Load Arrow data into the target table.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
table
|
str
|
Target table name. |
required |
source
|
ArrowResult | Any
|
Arrow data source. |
required |
partitioner
|
dict[str, object] | None
|
Optional partitioner configuration. |
None
|
overwrite
|
bool
|
Whether to overwrite existing data. |
False
|
Returns:
| Type | Description |
|---|---|
StorageBridgeJob
|
StorageBridgeJob with execution telemetry. |
Raises:
| Type | Description |
|---|---|
NotImplementedError
|
If not implemented. |
transaction
¶
Return a context manager that wraps a block in a transaction.
Entering the block calls begin() and yields this driver. A normal exit
calls commit(); an exception calls rollback() and propagates. A
failed commit is followed by a rollback attempt before the commit error
propagates. When the connection already has an open transaction, the block
joins it instead of calling begin() and commits it on exit. Inside
another transaction() or service begin_transaction() block on this
driver, the block runs in a savepoint instead and leaves the outer
transaction open.
Isolation settings are applied with execute_script inside the block.
Example
.. code-block:: python
async with session.transaction():
await session.execute(
"INSERT INTO items (id) VALUES (:id)", id=1
)
Returns:
| Type | Description |
|---|---|
_AsyncDriverTransaction[Self]
|
A context manager yielding this driver. |
Asynchronous Data Dictionary & Streaming¶
AsyncDataDictionaryBase
¶
Bases: DataDictionaryDialectMixin, DataDictionaryMixin
Base class for asynchronous data dictionary implementations.
Uses Python-compatible class layouts for cross-module inheritance. Child classes define dialect as a class attribute.
AsyncRowStream
¶
Bases: Generic[RowT]
Async bounded-memory iterator backed by an async chunk source.
Pool Context Managers¶
AsyncPoolConnectionContext
¶
Base async connection context using pool acquire/release pattern.
Subclass per adapter and override __aenter__/__aexit__ for
adapter-specific pool acquisition and release logic.
AsyncPoolSessionFactory
¶
Base async session factory using pool acquire/release pattern.
Subclass per adapter and override acquire_connection/release_connection
for adapter-specific pool acquisition and release logic.