Skip to content

Shared Driver Types

from sqlspec.driver import (
    AsyncExceptionHandler,
    BaseAsyncExceptionHandler,
    BaseSyncExceptionHandler,
    CachedQuery,
    CommonDriverAttributesMixin,
    DataDictionaryDialectMixin,
    DataDictionaryMixin,
    ExecutionResult,
    StackExecutionObserver,
    SyncExceptionHandler,
    convert_to_dialect,
    rows_to_dicts,
    validate_savepoint_name,
)

Shared driver execution results, exception handler protocols and base classes, mixins, and low-level driver utilities.

Execution Metadata & Caching

ExecutionResult

Bases: NamedTuple

Execution result containing all data needed for SQLResult building.

CachedQuery

Cached query metadata for fast-path execution.

StackExecutionObserver

Context manager that aggregates telemetry for stack execution.

Exception Handlers

SyncExceptionHandler

Bases: Protocol

Protocol for synchronous context managers that map driver errors to SQLSpec exceptions.

Implementations suppress recognized driver exceptions in __exit__ and expose the mapped SQLSpec exception on pending_exception for the caller to raise.

AsyncExceptionHandler

Bases: Protocol

Protocol for asynchronous context managers that map driver errors to SQLSpec exceptions.

Implementations suppress recognized driver exceptions in __aexit__ and expose the mapped SQLSpec exception on pending_exception for the caller to raise.

BaseSyncExceptionHandler

Base sync exception handler using the deferred exception pattern.

BaseAsyncExceptionHandler

Base async exception handler using the deferred exception pattern.

Driver Mixins & Helper Functions

CommonDriverAttributesMixin

Common attributes and methods for driver adapters.

prepare_statement

prepare_statement(
    statement, parameters=(), *, statement_config=None, kwargs=None
)

Build SQL statement from various input types.

Ensures dialect is set and preserves existing state when rebuilding SQL objects.

Parameters:

Name Type Description Default
statement Statement | QueryBuilder

SQL statement or QueryBuilder to prepare

required
parameters tuple[StatementParameters | StatementFilter, ...]

Parameters for the SQL statement

()
statement_config StatementConfig | None

Optional statement configuration override.

None
kwargs dict[str, Any] | None

Additional keyword arguments

None

Returns:

Type Description
SQL

Prepared SQL statement

build_statement_result

build_statement_result(statement, execution_result)

Build and return the SQLResult from ExecutionResult data.

Parameters:

Name Type Description Default
statement SQL

SQL statement that was executed

required
execution_result ExecutionResult

ExecutionResult containing all necessary data

required

Returns:

Type Description
SQLResult

SQLResult with complete execution data

create_execution_result

create_execution_result(
    cursor_result,
    *,
    rowcount_override=None,
    special_data=None,
    selected_data=None,
    column_names=None,
    data_row_count=None,
    statement_count=None,
    successful_statements=None,
    is_script_result=False,
    is_select_result=False,
    is_many_result=False,
    row_format="dict",
    last_inserted_id=None,
    column_types=None,
)

Create ExecutionResult with all necessary data for any operation type.

Parameters:

Name Type Description Default
cursor_result Any

The raw result returned by the database cursor/driver

required
rowcount_override int | None

Optional override for the number of affected rows

None
special_data Any

Any special metadata or additional information

None
selected_data list[Any] | None

For SELECT operations, the extracted row data (raw driver-native format)

None
column_names list[str] | None

For SELECT operations, the column names

None
data_row_count int | None

For SELECT operations, the number of rows returned

None
statement_count int | None

For script operations, total number of statements

None
successful_statements int | None

For script operations, number of successful statements

None
is_script_result bool

Whether this result is from script execution

False
is_select_result bool

Whether this result is from a SELECT operation

False
is_many_result bool

Whether this result is from an execute_many operation

False
row_format RowFormat

Format of raw rows - "tuple", "dict", or "record"

'dict'
last_inserted_id int | str | None

The ID of the last inserted row (if applicable)

None
column_types dict[str, str] | None

For SELECT operations, a column name to neutral type-token map describing declared column types, used to type all-NULL Arrow columns

None

Returns:

Type Description
ExecutionResult

ExecutionResult configured for the specified operation type

DataDictionaryMixin

Mixin providing common data dictionary functionality.

Includes version caching to avoid repeated database queries when checking feature flags or optimal types.

DataDictionaryDialectMixin

Mixin providing dialect SQL helpers for data dictionaries.

convert_to_dialect

convert_to_dialect(
    statement, source_dialect, to_dialect=None, pretty=DEFAULT_PRETTY
)

Convert a statement to a target SQL dialect.

Parameters:

Name Type Description Default
statement Statement

SQL statement to convert.

required
source_dialect DialectType | None

Source dialect for parsing.

required
to_dialect DialectType | None

Target dialect (defaults to source_dialect).

None
pretty bool

Whether to format the output SQL.

DEFAULT_PRETTY

Returns:

Type Description
str

SQL string in target dialect.

rows_to_dicts

rows_to_dicts(rows, column_names)

Return dict rows unchanged and zip positional rows with column names.

Parameters:

Name Type Description Default
rows list[Any]

Rows fetched from the cursor.

required
column_names list[str]

Column names from the cursor description.

required

Returns:

Type Description
list[dict[str, Any]]

Rows as dictionaries.

Raises:

Type Description
SQLSpecError

If positional rows arrive without column metadata, which would otherwise be indistinguishable from the end of the stream.

validate_savepoint_name

validate_savepoint_name(name)

Return the savepoint name when it is a safe SQL identifier.