Results

Result types for SQL operations. Every driver method returns one of these result wrappers, providing helpers like all(), one(), scalar(), to_pandas(), and to_arrow().

StatementResult

class sqlspec.core.result._base.StatementResult[source]

Bases: ABC, Iterable[Any]

Abstract base class for SQL statement execution results.

Provides a common interface for handling different types of SQL operation results. Subclasses implement specific behavior for SELECT, INSERT, UPDATE, DELETE, and script operations.

statement

The original SQL statement that was executed.

data

The result data from the operation.

rows_affected

Number of rows affected by the operation.

last_inserted_id

Last inserted ID from INSERT operations.

execution_time

Time taken to execute the statement in seconds.

metadata

Additional metadata about the operation.

__init__(statement, data=None, rows_affected=0, last_inserted_id=None, execution_time=None, metadata=None)[source]

Initialize statement result.

Parameters:
  • statement (SQL) – The original SQL statement that was executed.

  • data (Any) – The result data from the operation.

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id (int | str | None) – Last inserted ID from the operation.

  • execution_time (float | None) – Time taken to execute the statement in seconds.

  • metadata (dict[str, typing.Any] | None) – Additional metadata about the operation.

abstractmethod __iter__()[source]

Iterate over result rows.

Return type:

Iterator[typing.Any]

abstractmethod is_success()[source]

Check if the operation was successful.

Return type:

bool

Returns:

True if the operation completed successfully, False otherwise.

abstractmethod get_data()[source]

Get the processed data from the result.

Return type:

typing.Any

Returns:

The processed result data in an appropriate format.

get_metadata(key, default=None)[source]

Get metadata value by key.

Parameters:
  • key (str) – The metadata key to retrieve.

  • default (Any) – Default value if key is not found.

Return type:

Any

Returns:

The metadata value or default.

set_metadata(key, value)[source]

Set metadata value by key.

Parameters:
  • key (str) – The metadata key to set.

  • value (Any) – The value to set.

Return type:

None

property operation_type: Literal['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'COPY', 'COPY_FROM', 'COPY_TO', 'EXECUTE', 'SCRIPT', 'DDL', 'PRAGMA', 'MERGE', 'COMMAND', 'UNKNOWN']

Get operation type from the statement.

Returns:

The type of SQL operation that produced this result.

SQLResult

class sqlspec.core.result.SQLResult[source]

Bases: StatementResult

Result class for SQL operations that return rows or affect rows.

Handles SELECT, INSERT, UPDATE, DELETE operations. For DML operations with RETURNING clauses, the returned data is stored in the data attribute. The operation_type attribute indicates the nature of the operation.

For script execution, tracks multiple statement results and errors.

__init__(statement, data=None, rows_affected=0, last_inserted_id=None, execution_time=None, metadata=None, error=None, operation_type='SELECT', operation_index=None, parameters=None, column_names=None, total_count=None, has_more=False, inserted_ids=None, statement_results=None, errors=None, total_statements=0, successful_statements=0, row_format='dict')[source]

Initialize SQL result.

Parameters:
  • statement (SQL) – The original SQL statement that was executed.

  • data (Sequence[typing.Any] | None) – The result data from the operation (raw driver-native format).

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id (int | str | None) – Last inserted ID from the operation.

  • execution_time (float | None) – Time taken to execute the statement in seconds.

  • metadata (dict[str, typing.Any] | None) – Additional metadata about the operation.

  • error (Exception | None) – Exception that occurred during execution.

  • operation_type (Literal['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'COPY', 'COPY_FROM', 'COPY_TO', 'EXECUTE', 'SCRIPT', 'DDL', 'PRAGMA', 'MERGE', 'COMMAND', 'UNKNOWN']) – Type of SQL operation performed.

  • operation_index (int | None) – Index of operation in a script.

  • parameters (Any | None) – Parameters used for the query.

  • column_names (list[str] | None) – Names of columns in the result set.

  • total_count (int | None) – Total number of rows in the complete result set.

  • has_more (bool) – Whether there are additional result pages available.

  • inserted_ids (list[int | str] | None) – List of IDs from INSERT operations.

  • statement_results (list[SQLResult] | None) – Results from individual statements in a script.

  • errors (list[str] | None) – List of error messages for script execution.

  • total_statements (int) – Total number of statements in a script.

  • successful_statements (int) – Count of successful statements in a script.

  • row_format (str) – Format of raw rows - “tuple”, “dict”, or “record”.

property operation_type: Literal['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'COPY', 'COPY_FROM', 'COPY_TO', 'EXECUTE', 'SCRIPT', 'DDL', 'PRAGMA', 'MERGE', 'COMMAND', 'UNKNOWN']

Get operation type for this result.

Returns:

The type of SQL operation that produced this result.

property raw_data: tuple[list[TypeAliasForwardRef('typing.Any')], list[str]]

Zero-copy access to raw driver-native rows and column names.

Returns:

Tuple of (raw_rows, column_names).

get_metadata(key, default=None)[source]

Get metadata value by key.

Parameters:
  • key (str) – The metadata key to retrieve.

  • default (Any) – Default value if key is not found.

Return type:

Any

Returns:

The metadata value or default.

set_metadata(key, value)[source]

Set metadata value by key.

Parameters:
  • key (str) – The metadata key to set.

  • value (Any) – The value to set.

Return type:

None

is_success()[source]

Check if the operation was successful.

Return type:

bool

Returns:

True if operation was successful, False otherwise.

get_data(*, schema_type=None)[source]

Get the data from the result.

For regular operations, returns the list of rows. For script operations, returns a summary dictionary containing execution statistics and results.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

list[TypeVar(SchemaT)] | list[dict[str, typing.Any]]

Returns:

List of result rows (optionally transformed to schema_type) or script summary.

add_statement_result(result)[source]

Add a statement result to the script execution results.

Parameters:

result (SQLResult) – Statement result to add.

Return type:

None

get_total_rows_affected()[source]

Get the total number of rows affected across all statements.

Return type:

int

Returns:

Total rows affected.

property num_rows: int

Get the number of rows affected (alias for get_total_rows_affected).

Returns:

Total rows affected.

property num_columns: int

Get the number of columns in the result data.

Returns:

Number of columns.

get_first(*, schema_type=None)[source]

Get the first row from the result, if any.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

Union[TypeVar(SchemaT), dict[str, typing.Any], None]

Returns:

First row (optionally transformed to schema_type) or None if no data.

get_count()[source]

Get the number of rows in the current result set (e.g., a page of data).

Return type:

int

Returns:

Number of rows in current result set.

is_empty()[source]

Check if the result set (self.data) is empty.

Return type:

bool

Returns:

True if result set is empty.

get_affected_count()[source]

Get the number of rows affected by a DML operation.

Return type:

int

Returns:

Number of affected rows.

was_inserted()[source]

Check if this was an INSERT operation.

Return type:

bool

Returns:

True if INSERT operation.

was_updated()[source]

Check if this was an UPDATE operation.

Return type:

bool

Returns:

True if UPDATE operation.

was_deleted()[source]

Check if this was a DELETE operation.

Return type:

bool

Returns:

True if DELETE operation.

__len__()[source]

Get the number of rows in the result set.

Return type:

int

Returns:

Number of rows in the data.

__getitem__(index)[source]

Get a row by index.

Parameters:

index (int) – Row index

Return type:

dict[str, typing.Any]

Returns:

The row at the specified index

__iter__()[source]

Iterate over the rows in the result.

Return type:

Iterator[dict[str, typing.Any]]

Returns:

Iterator that yields each row as a dictionary

all(*, schema_type=None)[source]

Return all rows as a list.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

list[TypeVar(SchemaT)] | list[dict[str, typing.Any]]

Returns:

List of all rows (optionally transformed to schema_type)

one(*, schema_type=None)[source]

Return exactly one row.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

Union[TypeVar(SchemaT), dict[str, typing.Any]]

Returns:

The single row (optionally transformed to schema_type)

Raises:

ValueError – If no results or more than one result

one_or_none(*, schema_type=None)[source]

Return at most one row.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

Union[TypeVar(SchemaT), dict[str, typing.Any], None]

Returns:

The single row (optionally transformed to schema_type) or None if no results

Raises:

ValueError – If more than one result

scalar()[source]

Return the first column of the first row.

Return type:

Any

Returns:

The scalar value from first column of first row

scalar_or_none()[source]

Return the first column of the first row, or None if no results.

Return type:

Any

Returns:

The scalar value from first column of first row, or None

to_arrow()[source]

Convert result data to Apache Arrow Table.

Return type:

Table

Returns:

Arrow Table containing the result data.

Raises:

ValueError – If no data available.

Examples

>>> result = session.select("SELECT * FROM users")
>>> table = result.to_arrow()
>>> print(table.num_rows)
3
to_pandas()[source]

Convert result data to pandas DataFrame.

Return type:

DataFrame

Returns:

pandas DataFrame containing the result data.

Raises:

ValueError – If no data available.

Examples

>>> result = session.select("SELECT * FROM users")
>>> df = result.to_pandas()
>>> print(df.head())
to_polars()[source]

Convert result data to Polars DataFrame.

Return type:

DataFrame

Returns:

Polars DataFrame containing the result data.

Raises:

ValueError – If no data available.

Examples

>>> result = session.select("SELECT * FROM users")
>>> df = result.to_polars()
>>> print(df.head())

ArrowResult

class sqlspec.core.result.ArrowResult[source]

Bases: StatementResult

Result class for SQL operations that return Apache Arrow data.

Used when database drivers support returning results in Apache Arrow format for data interchange. Suitable for analytics workloads and data science applications.

schema

Arrow schema information for the result data.

__init__(statement, data, rows_affected=0, last_inserted_id=None, execution_time=None, metadata=None, schema=None)[source]

Initialize Arrow result.

Parameters:
  • statement (SQL) – The original SQL statement that was executed.

  • data (Any) – The Apache Arrow Table containing the result data.

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id (int | str | None) – Last inserted ID (if applicable).

  • execution_time (float | None) – Time taken to execute the statement in seconds.

  • metadata (dict[str, typing.Any] | None) – Additional metadata about the operation.

  • schema (dict[str, typing.Any] | None) – Optional Arrow schema information.

is_success()[source]

Check if the operation was successful.

Return type:

bool

Returns:

True if Arrow table data is available, False otherwise.

get_data()[source]

Get the Apache Arrow Table from the result.

Return type:

Table

Returns:

The Arrow table containing the result data.

Raises:
property column_names: list[str]

Get the column names from the Arrow table.

Returns:

List of column names.

Raises:
property num_rows: int

Get the number of rows in the Arrow table.

Returns:

Number of rows.

Raises:
property num_columns: int

Get the number of columns in the Arrow table.

Returns:

Number of columns.

Raises:
to_pandas()[source]

Convert Arrow data to pandas DataFrame.

Return type:

DataFrame

Returns:

pandas DataFrame containing the result data.

Raises:

ValueError – If no Arrow table is available.

Examples

>>> result = session.select_to_arrow("SELECT * FROM users")
>>> df = result.to_pandas()
>>> print(df.head())
to_polars()[source]

Convert Arrow data to Polars DataFrame.

Return type:

DataFrame

Returns:

Polars DataFrame containing the result data.

Raises:

ValueError – If no Arrow table is available.

Examples

>>> result = session.select_to_arrow("SELECT * FROM users")
>>> df = result.to_polars()
>>> print(df.head())
to_dict()[source]

Convert Arrow data to list of dictionaries.

Return type:

list[dict[str, typing.Any]]

Returns:

List of dictionaries, one per row.

Raises:

Examples

>>> result = session.select_to_arrow(
...     "SELECT id, name FROM users"
... )
>>> rows = result.to_dict()
>>> print(rows[0])
{'id': 1, 'name': 'Alice'}
__len__()[source]

Return number of rows in the Arrow table.

Return type:

int

Returns:

Number of rows.

Raises:

Examples

>>> result = session.select_to_arrow("SELECT * FROM users")
>>> print(len(result))
100
__iter__()[source]

Iterate over rows as dictionaries.

Yields:

Dictionary for each row.

Raises:

ValueError – If no Arrow table is available.

Examples

>>> result = session.select_to_arrow(
...     "SELECT id, name FROM users"
... )
>>> for row in result:
...     print(row["name"])
Return type:

Iterator[dict[str, typing.Any]]

DMLResult

class sqlspec.core.result._base.DMLResult[source]

Bases: SQLResult

Optimized result for simple DML operations (INSERT/UPDATE/DELETE).

Used by the ultra-fast execution path to bypass full SQLResult construction and pooling for non-SELECT operations.

__init__(op_type, rows_affected=0)[source]

Initialize SQL result.

Parameters:
  • statement – The original SQL statement that was executed.

  • data – The result data from the operation (raw driver-native format).

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id – Last inserted ID from the operation.

  • execution_time – Time taken to execute the statement in seconds.

  • metadata – Additional metadata about the operation.

  • error – Exception that occurred during execution.

  • operation_type – Type of SQL operation performed.

  • operation_index – Index of operation in a script.

  • parameters – Parameters used for the query.

  • column_names – Names of columns in the result set.

  • total_count – Total number of rows in the complete result set.

  • has_more – Whether there are additional result pages available.

  • inserted_ids – List of IDs from INSERT operations.

  • statement_results – Results from individual statements in a script.

  • errors – List of error messages for script execution.

  • total_statements – Total number of statements in a script.

  • successful_statements – Count of successful statements in a script.

  • row_format – Format of raw rows - “tuple”, “dict”, or “record”.

is_success()[source]

Check if the operation was successful.

Return type:

bool

Returns:

True if operation was successful, False otherwise.

get_data(*, schema_type=None)[source]

Get the data from the result.

For regular operations, returns the list of rows. For script operations, returns a summary dictionary containing execution statistics and results.

Parameters:

schema_type (type[TypeVar(SchemaT)] | None) – Optional schema type to transform the data into. Supports Pydantic models, dataclasses, msgspec structs, attrs classes, and TypedDict.

Return type:

list[typing.Any]

Returns:

List of result rows (optionally transformed to schema_type) or script summary.

set_metadata(key, value)[source]

Set metadata value by key.

Parameters:
  • key (str) – The metadata key to set.

  • value (Any) – The value to set.

Return type:

None

EmptyResult

class sqlspec.core.result._base.EmptyResult[source]

Bases: StatementResult

Sentinel result used when a stack operation has no driver result.

__init__()[source]

Initialize statement result.

Parameters:
  • statement – The original SQL statement that was executed.

  • data – The result data from the operation.

  • rows_affected – Number of rows affected by the operation.

  • last_inserted_id – Last inserted ID from the operation.

  • execution_time – Time taken to execute the statement in seconds.

  • metadata – Additional metadata about the operation.

is_success()[source]

Check if the operation was successful.

Return type:

bool

Returns:

True if the operation completed successfully, False otherwise.

get_data()[source]

Get the processed data from the result.

Return type:

list[typing.Any]

Returns:

The processed result data in an appropriate format.

StackResult

class sqlspec.core.result.StackResult[source]

Bases: object

Wrapper for per-operation stack results that surfaces driver results directly.

__init__(result=None, *, rows_affected=None, error=None, warning=None, metadata=None)[source]
get_result()[source]

Return the underlying driver result.

Return type:

StatementResult | ArrowResult

property result_type: str

Describe the underlying result type (SQL operation, Arrow, or custom).

is_sql_result()[source]

Return True when the underlying result is an SQLResult.

Return type:

bool

is_arrow_result()[source]

Return True when the underlying result is an ArrowResult.

Return type:

bool

is_error()[source]

Return True when the stack operation captured an error.

Return type:

bool

with_error(error)[source]

Return a copy of the result that records the provided error.

Return type:

StackResult

classmethod from_sql_result(result)[source]

Convert a standard SQLResult into a stack-friendly representation.

Return type:

StackResult

classmethod from_arrow_result(result)[source]

Create a stack result from an ArrowResult instance.

Return type:

StackResult

classmethod from_error(error)[source]

Create an error-only stack result.

Return type:

StackResult

Factory Functions

sqlspec.core.result.create_sql_result(statement, data=None, rows_affected=0, last_inserted_id=None, execution_time=None, metadata=None, **kwargs)[source]

Create SQLResult instance.

Parameters:
  • statement (SQL) – The SQL statement that produced this result.

  • data (list[typing.Any] | None) – Result data from query execution (raw driver-native format).

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id (int | str | None) – Last inserted ID (for INSERT operations).

  • execution_time (float | None) – Execution time in seconds.

  • metadata (dict[str, typing.Any] | None) – Additional metadata about the result.

  • **kwargs (Any) – Additional arguments for SQLResult initialization.

Return type:

SQLResult

Returns:

SQLResult instance.

sqlspec.core.result.create_arrow_result(statement, data, rows_affected=0, last_inserted_id=None, execution_time=None, metadata=None, schema=None)[source]

Create ArrowResult instance.

Parameters:
  • statement (SQL) – The SQL statement that produced this result.

  • data (Any) – Arrow-based result data.

  • rows_affected (int) – Number of rows affected by the operation.

  • last_inserted_id (int | str | None) – Last inserted ID (for INSERT operations).

  • execution_time (float | None) – Execution time in seconds.

  • metadata (dict[str, typing.Any] | None) – Additional metadata about the result.

  • schema (dict[str, typing.Any] | None) – Optional Arrow schema information.

Return type:

ArrowResult

Returns:

ArrowResult instance.

sqlspec.core.result.build_arrow_result_from_table(statement, table, *, return_format='table', batch_size=None, arrow_schema=None)[source]

Create ArrowResult from a pyarrow table with optional formatting.

Parameters:
  • statement (SQL) – SQL statement that produced the table.

  • table (Table) – Arrow table to wrap.

  • return_format (Literal['table', 'reader', 'batch', 'batches']) – Output format for the Arrow data.

  • batch_size (int | None) – Batch size hint for batch-based formats.

  • arrow_schema (Any) – Optional pyarrow.Schema for casting.

Return type:

ArrowResult

Returns:

ArrowResult instance.