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]¶
-
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.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 is_success()[source]¶
Check if the operation was successful.
- Return type:
- 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.
SQLResult¶
- class sqlspec.core.result.SQLResult[source]¶
Bases:
StatementResultResult 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.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).
- is_success()[source]¶
Check if the operation was successful.
- Return type:
- 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.
- get_total_rows_affected()[source]¶
Get the total number of rows affected across all statements.
- Return type:
- 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.
- get_count()[source]¶
Get the number of rows in the current result set (e.g., a page of data).
- Return type:
- Returns:
Number of rows in current result set.
- is_empty()[source]¶
Check if the result set (self.data) is empty.
- Return type:
- Returns:
True if result set is empty.
- get_affected_count()[source]¶
Get the number of rows affected by a DML operation.
- Return type:
- Returns:
Number of affected rows.
- was_inserted()[source]¶
Check if this was an INSERT operation.
- Return type:
- Returns:
True if INSERT operation.
- was_updated()[source]¶
Check if this was an UPDATE operation.
- Return type:
- Returns:
True if UPDATE operation.
- was_deleted()[source]¶
Check if this was a DELETE operation.
- Return type:
- Returns:
True if DELETE operation.
- __len__()[source]¶
Get the number of rows in the result set.
- Return type:
- Returns:
Number of rows in the data.
- all(*, schema_type=None)[source]¶
Return all rows as a list.
- 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:
- 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:
- 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:
- 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:
- 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:
StatementResultResult 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:
- 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:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
- property column_names: list[str]¶
Get the column names from the Arrow table.
- Returns:
List of column names.
- Raises:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
- property num_rows: int¶
Get the number of rows in the Arrow table.
- Returns:
Number of rows.
- Raises:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
- property num_columns: int¶
Get the number of columns in the Arrow table.
- Returns:
Number of columns.
- Raises:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
- 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:
- Returns:
List of dictionaries, one per row.
- Raises:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
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:
- Returns:
Number of rows.
- Raises:
ValueError – If no Arrow table is available.
TypeError – If data is not an Arrow Table.
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"])
DMLResult¶
- class sqlspec.core.result._base.DMLResult[source]¶
Bases:
SQLResultOptimized 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:
- 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.
EmptyResult¶
- class sqlspec.core.result._base.EmptyResult[source]¶
Bases:
StatementResultSentinel 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.
StackResult¶
- class sqlspec.core.result.StackResult[source]¶
Bases:
objectWrapper for per-operation stack results that surfaces driver results directly.
- with_error(error)[source]¶
Return a copy of the result that records the provided error.
- Return type:
- classmethod from_sql_result(result)[source]¶
Convert a standard SQLResult into a stack-friendly representation.
- Return type:
- classmethod from_arrow_result(result)[source]¶
Create a stack result from an ArrowResult instance.
- Return type:
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).metadata¶ (
dict[str, typing.Any] |None) – Additional metadata about the result.**kwargs¶ (
Any) – Additional arguments for SQLResult initialization.
- Return type:
- 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.rows_affected¶ (
int) – Number of rows affected by the operation.last_inserted_id¶ (
int|str|None) – Last inserted ID (for INSERT operations).metadata¶ (
dict[str, typing.Any] |None) – Additional metadata about the result.schema¶ (
dict[str, typing.Any] |None) – Optional Arrow schema information.
- Return type:
- 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.