SQL File Loader#
Load and cache SQL files with named statement support. SQL files can contain
multiple named statements separated by -- name: comments.
SQLFileLoader#
- class sqlspec.loader.SQLFileLoader[source]#
Bases:
objectLoads and parses SQL files with named SQL queries.
Loads SQL files containing named queries (using -- name: syntax) and retrieves them by name.
- __init__(*, encoding='utf-8', storage_registry=None, runtime=None, strict_parameter_annotations=False)[source]#
Initialize the SQL file loader.
- Parameters:
storage_registry¶ (
StorageRegistry|None) -- Storage registry for handling file URIs.runtime¶ (
ObservabilityRuntime|None) -- Observability runtime for instrumentation.strict_parameter_annotations¶ (
bool) -- When True, a malformed-- param:directive raises instead of emitting a warning and skipping the line.
- set_observability_runtime(runtime)[source]#
Attach an observability runtime used for instrumentation.
- Return type:
- add_named_sql(name, sql, dialect=None, parameters=None)[source]#
Add a named SQL query directly without loading from a file.
The SQL may contain
/* include: name */and/* slot: name */markers; slots added this way have no defaults.- Parameters:
- Raises:
ValueError -- If query name already exists.
- Return type:
- get_fragment_text(name)[source]#
Get a fragment's SQL text with its includes resolved.
Slot markers are left in place.
- Parameters:
- Return type:
- Returns:
Fragment SQL text with
/* include: */markers replaced.- Raises:
SQLFragmentNotFoundError -- If the fragment or an included fragment does not exist.
SQLFileParseError -- If the includes form a cycle.
- get_query_slots(name)[source]#
Get the slots of a query, including slots contributed by included fragments.
Slots declared with
-- slot:come first in declaration order, then undeclared (required) markers in the query's own text, then markers contributed by included fragments; markers keep their order of appearance.- Parameters:
name¶ (
str) -- Query name (hyphens are converted to underscores).- Return type:
- Returns:
Tuple of slot declarations; empty if the query has none.
- Raises:
SQLStatementNotFoundError -- If the query or an included fragment does not exist.
SQLFileParseError -- If a declared slot has no marker or the includes form a cycle.
- get_query_parameters(name)[source]#
Get declared parameter metadata for a query.
- Parameters:
name¶ (
str) -- Query name (hyphens are converted to underscores).- Return type:
- Returns:
Tuple of declared parameters; empty if the query declares none.
- Raises:
SQLStatementNotFoundError -- If the query does not exist.
- get_query_text(name)[source]#
Get raw SQL text for a query.
Includes are resolved; slot markers are left in place.
- Parameters:
- Return type:
- Returns:
Raw SQL text.
- Raises:
SQLStatementNotFoundError -- If the query or an included fragment does not exist.
SQLFileParseError -- If a declared slot has no marker or the includes form a cycle.
- get_sql(name, **slots)[source]#
Get a SQL object by statement name, filling its slots.
Each
/* slot: name */marker is replaced by the matching keyword value, or by the slot's-- slot:default when no value is given. A value may be astr(spliced verbatim), a sqlglot expression (rendered with the statement's dialect), or aSQLobject (its text is spliced and its named parameters are bound on the returned statement). Slot values are SQL, not data: pass user input as parameters of aSQLvalue.The statement is cached only when no slot values are given.
- Parameters:
- Return type:
- Returns:
SQL object ready for execution.
- Raises:
SQLSlotError -- If a required slot is missing, a slot name is unknown, a
SQLvalue uses positional parameters, or slot parameter names collide with each other or with the statement's placeholders.TypeError -- If a slot value is not a
str, sqlglot expression, orSQL.SQLFileParseError -- If declared parameters do not match the filled SQL or the SQL cannot be compiled.
SQLFile#
NamedStatement#
- class sqlspec.loader.NamedStatement[source]#
Bases:
objectRepresents a parsed SQL statement with metadata.
Contains individual SQL statements extracted from files with their normalized names, SQL content, optional dialect specifications, line position for error reporting, slot declarations from the statement's own text, and whether the text contains include markers.
Fragments and Slots#
SQL files can declare reusable -- fragment: sections, splice them into queries
with /* include: name */, and mark fill points with /* slot: name */. See
Fragments and Slots for the syntax and the
get_sql(name, **slots) call.
- class sqlspec.loader.SlotDeclaration[source]#
Bases:
objectA fill point declared by a
/* slot: name */marker.A slot with a
defaultcomes from a-- slot: name = defaultdirective; a slot whosedefaultis None must be supplied by the caller.
- class sqlspec.exceptions.SQLSlotError[source]#
Bases:
SQLSpecErrorRaised when a SQL statement slot is missing, unknown, or conflicts.
- class sqlspec.exceptions.SQLFragmentNotFoundError[source]#
Bases:
SQLStatementNotFoundErrorRaised when a SQL fragment named by an include or lookup is not loaded.
SQLFileCacheEntry#
- class sqlspec.loader.SQLFileCacheEntry[source]#
Bases:
objectCached SQL file with parsed statements and fragments.
Stored in the file cache to avoid re-parsing SQL files when their content hasn't changed.
Declared Parameters#
Parameters declared in SQL files via -- param: directives are exposed as
ParameterDeclaration objects. See Declared Parameters
for the grammar and validation behavior.
- class sqlspec.ParameterDeclaration[source]
Bases:
objectA single parameter declared in a SQL file header.
- __init__(name, type_str, description=None, *, required=True)[source]
- sqlspec.register_param_type(name, py_type)[source]#
Register or override a declared-type-string matcher.
- sqlspec.resolve_param_type(type_str)[source]#
Resolve a declared type string to a matcher, or
Noneif unknown.Unknown type strings are documentation-only and skipped during validation. The declared string is looked up, never evaluated. Parameterized containers (
list[int]) resolve to their origin type (list).