Statement & Compiler¶
SQL statement representation, configuration, and compilation.
SQL¶
- class sqlspec.core.statement.SQL[source]¶
Bases:
objectSQL statement with parameter and filter support.
Represents a SQL statement that can be compiled with parameters and filters. Supports both positional and named parameters, statement filtering, and various execution modes including batch operations.
- __init__(statement, *parameters, statement_config=None, is_many=None, **kwargs)[source]¶
Initialize SQL statement.
- property positional_parameters: list[TypeAliasForwardRef('typing.Any')]¶
Get positional parameters (public API).
- property named_parameters: dict[str, TypeAliasForwardRef('typing.Any')]¶
Get named parameters (public API).
- property operation_type: Literal['SELECT', 'INSERT', 'UPDATE', 'DELETE', 'COPY', 'COPY_FROM', 'COPY_TO', 'EXECUTE', 'SCRIPT', 'DDL', 'PRAGMA', 'MERGE', 'COMMAND', 'UNKNOWN']¶
SQL operation type.
- property statement_config: StatementConfig¶
Statement configuration.
- property raw_expression: Expression | None¶
Original expression supplied at construction, if available.
- property filters: list[StatementFilter]¶
Applied filters.
- get_filters_view()[source]¶
Get zero-copy filters view (public API).
- Return type:
- Returns:
Read-only view of filters without copying
- property statement_expression: Expression | None¶
Get parsed statement expression (public API).
- Returns:
Parsed SQLGlot expression or None if not parsed
- returns_rows()[source]¶
Check if statement returns rows.
- Return type:
- Returns:
True if the SQL statement returns result rows
- is_modifying_operation()[source]¶
Check if the SQL statement is a modifying operation.
- Return type:
- Returns:
True if the operation modifies data (INSERT/UPDATE/DELETE)
- as_script()[source]¶
Create copy marked for script execution.
- Return type:
- Returns:
New SQL instance configured for script execution
- limit(value)[source]¶
Add LIMIT clause to the SQL statement.
- Parameters:
- Return type:
- Returns:
New SQL instance with LIMIT applied
- Raises:
SQLSpecError – If statement is not a SELECT
- offset(value)[source]¶
Add OFFSET clause to the SQL statement.
- Parameters:
- Return type:
- Returns:
New SQL instance with OFFSET applied
- Raises:
SQLSpecError – If statement is not a SELECT
- paginate(page, page_size)[source]¶
Add LIMIT and OFFSET for pagination.
- Parameters:
- Return type:
- Returns:
New SQL instance with LIMIT and OFFSET applied
Example
# Get page 3 with 20 items per page stmt = SQL(“SELECT * FROM users”).paginate(3, 20) # Results in: SELECT * FROM users LIMIT 20 OFFSET 40
- select_only(*columns, prune_columns=None)[source]¶
Replace SELECT columns with only the specified columns.
This is useful for narrowing down the columns returned by a query without modifying the FROM clause or WHERE conditions.
- Parameters:
- Return type:
- Returns:
New SQL instance with only the specified columns
Example
stmt = SQL(“SELECT * FROM users WHERE active = 1”) narrow = stmt.select_only(“id”, “name”, “email”) # Results in: SELECT id, name, email FROM users WHERE active = 1
# With column pruning on a subquery: stmt = SQL(“SELECT * FROM (SELECT id, name, email, created_at FROM users) AS u”) narrow = stmt.select_only(“id”, “name”, prune_columns=True) # Results in: SELECT id, name FROM (SELECT id, name FROM users) AS u
- explain(analyze=False, verbose=False, format=None)[source]¶
Create an EXPLAIN statement for this SQL.
Wraps the current SQL statement in an EXPLAIN clause with dialect-aware syntax generation.
- Parameters:
- Return type:
- Returns:
New SQL instance containing the EXPLAIN statement
Examples
- Basic EXPLAIN:
stmt = SQL(“SELECT * FROM users”) explain_stmt = stmt.explain()
- With options:
explain_stmt = stmt.explain(analyze=True, format=”json”)
- builder(dialect=None)[source]¶
Create a query builder seeded from this SQL statement.
- Parameters:
dialect¶ (
Union[str,Dialect,Type[Dialect],None]) – Optional SQL dialect override for parsing and rendering.- Return type:
- Returns:
QueryBuilder instance initialized with the parsed statement.
- Raises:
SQLBuilderError – If the statement cannot be parsed.
Notes
Statements outside the DML set return an ExpressionBuilder without DML-specific helper methods.
StatementConfig¶
- class sqlspec.core.statement.StatementConfig[source]¶
Bases:
objectConfiguration for SQL statement processing.
Controls SQL parsing, validation, transformations, parameter handling, and other processing options for SQL statements.
- __init__(parameter_config=None, enable_parsing=True, enable_validation=True, enable_transformations=True, enable_analysis=False, enable_expression_simplification=False, enable_column_pruning=False, enable_parameter_type_wrapping=True, enable_caching=True, parameter_converter=None, parameter_validator=None, dialect=None, execution_mode=None, execution_args=None, output_transformer=None, statement_transformers=None)[source]¶
Initialize StatementConfig.
- Parameters:
parameter_config¶ – Parameter style configuration
enable_parsing¶ – Enable SQL parsing
enable_validation¶ – Run SQL validators
enable_transformations¶ – Apply SQL transformers
enable_analysis¶ – Run SQL analyzers
enable_expression_simplification¶ – Apply expression simplification
enable_column_pruning¶ – Remove unused columns from subqueries during select_only
enable_parameter_type_wrapping¶ – Wrap parameters with type information
enable_caching¶ – Cache processed SQL statements
parameter_converter¶ – Handles parameter style conversions
parameter_validator¶ – Validates parameter usage and styles
dialect¶ – SQL dialect
execution_mode¶ – Special execution mode
execution_args¶ – Arguments for special execution modes
output_transformer¶ – Optional output transformation function
statement_transformers¶ – Optional AST transformers executed during compilation
ProcessedState¶
- class sqlspec.core.statement.ProcessedState[source]¶
Bases:
objectProcessing results for SQL statements.
Contains the compiled SQL, execution parameters, parsed expression, operation type, and validation errors for a processed SQL statement.
- __init__(compiled_sql, execution_parameters, parsed_expression=None, operation_type='COMMAND', input_named_parameters=None, applied_wrap_types=False, filter_hash=0, parameter_fingerprint=None, parameter_casts=None, validation_errors=None, parameter_profile=None, operation_profile=None, is_many=False)[source]¶
Helper Functions¶
- sqlspec.core.statement.get_default_config()[source]¶
Get default statement configuration.
- Return type:
- Returns:
Cached StatementConfig singleton with default settings.
Compiler¶
- class sqlspec.core.compiler.SQLProcessor[source]¶
Bases:
objectSQL processor with compilation and caching.
Processes SQL statements by compiling them into executable format with parameter substitution. Includes LRU-style caching for compilation results to avoid re-processing identical statements.
- __init__(config, max_cache_size=1000, parse_cache_size=None, parameter_cache_size=None, validator_cache_size=None, cache_enabled=True)[source]¶
Initialize processor.
- Parameters:
config¶ (
StatementConfig) – Statement configurationmax_cache_size¶ (
int) – Maximum number of compilation results to cacheparse_cache_size¶ (
int|None) – Maximum number of parsed expressions to cacheparameter_cache_size¶ (
int|None) – Maximum parameter conversion cache entriesvalidator_cache_size¶ (
int|None) – Maximum cached parameter metadata entriescache_enabled¶ (
bool) – Toggle compiled SQL caching (parse/parameter caches remain size-driven)
- class sqlspec.core.compiler.CompiledSQL[source]¶
Bases:
objectCompiled SQL result.
Contains the result of SQL compilation with information needed for execution. Immutable container holding compiled SQL text, processed parameters, operation type, and execution metadata.
- __init__(compiled_sql, execution_parameters, operation_type, expression=None, parameter_style=None, supports_many=False, parameter_casts=None, parameter_profile=None, operation_profile=None, input_named_parameters=(), applied_wrap_types=False)[source]¶
Initialize compiled result.
- Parameters:
execution_parameters¶ (
Any) – Parameters in driver-specific formatoperation_type¶ (
Literal['SELECT','INSERT','UPDATE','DELETE','COPY','COPY_FROM','COPY_TO','EXECUTE','SCRIPT','DDL','PRAGMA','MERGE','COMMAND','UNKNOWN']) – SQL operation type (SELECT, INSERT, etc.)parameter_style¶ (
str|None) – Parameter style used in compilationsupports_many¶ (
bool) – Whether this supports execute_many operationsparameter_casts¶ (
dict[int,str] |None) – Mapping of parameter positions to cast typesparameter_profile¶ (
ParameterProfile|None) – Profile describing detected placeholdersoperation_profile¶ (
OperationProfile|None) – Profile describing semantic characteristicsinput_named_parameters¶ (
tuple[str,...]) – Original input named parameter orderapplied_wrap_types¶ (
bool) – Whether type wrapping was applied
- class sqlspec.core.compiler.OperationProfile[source]¶
Bases:
objectSemantic characteristics derived from the parsed SQL expression.
- sqlspec.core.compiler.is_copy_operation(operation_type)[source]¶
Determine if the operation corresponds to any PostgreSQL COPY variant.
- Parameters:
operation_type¶ (
Literal['SELECT','INSERT','UPDATE','DELETE','COPY','COPY_FROM','COPY_TO','EXECUTE','SCRIPT','DDL','PRAGMA','MERGE','COMMAND','UNKNOWN']) – Operation type detected by the compiler.- Return type:
- Returns:
True when the operation type represents COPY, COPY FROM, or COPY TO.
- sqlspec.core.compiler.is_copy_from_operation(operation_type)[source]¶
Check if the operation streams data into the database using COPY.
- Parameters:
operation_type¶ (
Literal['SELECT','INSERT','UPDATE','DELETE','COPY','COPY_FROM','COPY_TO','EXECUTE','SCRIPT','DDL','PRAGMA','MERGE','COMMAND','UNKNOWN']) – Operation type detected by the compiler.- Return type:
- Returns:
True for COPY operations that read from client input (COPY FROM).
- sqlspec.core.compiler.is_copy_to_operation(operation_type)[source]¶
Check if the operation streams data out from the database using COPY.
- Parameters:
operation_type¶ (
Literal['SELECT','INSERT','UPDATE','DELETE','COPY','COPY_FROM','COPY_TO','EXECUTE','SCRIPT','DDL','PRAGMA','MERGE','COMMAND','UNKNOWN']) – Operation type detected by the compiler.- Return type:
- Returns:
True for COPY operations that write to client output (COPY TO).