Skip to content

SQL File Loader

from sqlspec.loader import NamedStatement, SlotDeclaration, SQLFile, SQLFileCacheEntry, SQLFileLoader

Load, cache, and compose named SQL queries (-- name:), reusable fragments (-- fragment: / /* include: */), and dynamic slots (-- slot: / /* slot: */) from local files or remote object storage. See the SQL Files Guide for syntax and usage examples.

File Loader & Containers

SQLFileLoader

Loads and parses SQL files with named SQL queries.

Loads SQL files containing named queries (using -- name: syntax) and retrieves them by name.

load_sql

load_sql(*paths)

Load SQL files and parse named queries.

Parameters:

Name Type Description Default
*paths str | Path

One or more file paths or directory paths to load.

()

add_named_sql

add_named_sql(name, sql, dialect=None, parameters=None)

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:

Name Type Description Default
name str

Name for the SQL query.

required
sql str

Raw SQL content.

required
dialect str | None

Optional dialect for the SQL statement.

None
parameters Sequence[ParameterDeclaration] | None

Optional declared parameter metadata for the query.

None

Raises:

Type Description
ValueError

If query name already exists.

add_fragment

add_fragment(name, sql)

Add a reusable SQL fragment directly without loading from a file.

Parameters:

Name Type Description Default
name str

Name for the fragment, referenced by /* include: name */ markers.

required
sql str

Fragment SQL text; may contain include and slot markers.

required

Raises:

Type Description
ValueError

If the fragment name already exists.

has_fragment

has_fragment(name)

Check if a fragment exists.

Parameters:

Name Type Description Default
name str

Fragment name to check.

required

Returns:

Type Description
bool

True if the fragment exists.

list_fragments

list_fragments()

List all available fragment names.

Returns:

Type Description
list[str]

Sorted list of fragment names.

get_fragment_text

get_fragment_text(name)

Get a fragment's SQL text with its includes resolved.

Slot markers are left in place.

Parameters:

Name Type Description Default
name str

Fragment name.

required

Returns:

Type Description
str

Fragment SQL text with /* include: */ markers replaced.

Raises:

Type Description
SQLFragmentNotFoundError

If the fragment or an included fragment does not exist.

SQLFileParseError

If the includes form a cycle.

get_query_slots

get_query_slots(name)

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 Type Description Default
name str

Query name (hyphens are converted to underscores).

required

Returns:

Type Description
tuple[SlotDeclaration, ...]

Tuple of slot declarations; empty if the query has none.

Raises:

Type Description
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

get_query_parameters(name)

Get declared parameter metadata for a query.

Parameters:

Name Type Description Default
name str

Query name (hyphens are converted to underscores).

required

Returns:

Type Description
tuple[ParameterDeclaration, ...]

Tuple of declared parameters; empty if the query declares none.

Raises:

Type Description
SQLStatementNotFoundError

If the query does not exist.

get_file

get_file(path)

Get a loaded SQLFile object by path.

Parameters:

Name Type Description Default
path str | Path

Path of the file.

required

Returns:

Type Description
SQLFile | None

SQLFile object if loaded, None otherwise.

get_file_for_query

get_file_for_query(name)

Get the SQLFile object containing a query.

Parameters:

Name Type Description Default
name str

Query name (hyphens are converted to underscores).

required

Returns:

Type Description
SQLFile | None

SQLFile object if query exists, None otherwise.

list_queries

list_queries()

List all available query names.

Returns:

Type Description
list[str]

Sorted list of query names.

list_files

list_files()

List all loaded file paths.

Returns:

Type Description
list[str]

Sorted list of file paths.

has_query

has_query(name)

Check if a query exists.

Parameters:

Name Type Description Default
name str

Query name to check.

required

Returns:

Type Description
bool

True if query exists.

clear_cache

clear_cache()

Clear all cached files and queries.

clear_file_cache

clear_file_cache()

Clear the file cache only, keeping loaded queries.

get_query_text

get_query_text(name)

Get raw SQL text for a query.

Includes are resolved; slot markers are left in place.

Parameters:

Name Type Description Default
name str

Query name.

required

Returns:

Type Description
str

Raw SQL text.

Raises:

Type Description
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

get_sql(name, **slots)

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 a str (spliced verbatim), a sqlglot expression (rendered with the statement's dialect), or a SQL object (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 a SQL value.

The statement is cached only when no slot values are given.

Parameters:

Name Type Description Default
name str

Name of the statement (from -- name: in SQL file). Hyphens in names are converted to underscores.

required
**slots Any

Values for the statement's slots, keyed by slot name.

{}

Returns:

Type Description
SQL

SQL object ready for execution.

Raises:

Type Description
SQLSlotError

If a required slot is missing, a slot name is unknown, a SQL value 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, or SQL.

SQLFileParseError

If declared parameters do not match the filled SQL or the SQL cannot be compiled.

SQLFile

Represents a loaded SQL file with metadata.

Contains SQL content and associated metadata including file location, timestamps, and content hash.

Statement & Slot Metadata

NamedStatement

Represents 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.

SlotDeclaration

A fill point declared by a /* slot: name */ marker.

A slot with a default comes from a -- slot: name = default directive; a slot whose default is None must be supplied by the caller.

SQLFileCacheEntry

Cached SQL file with parsed statements and fragments.

Stored in the file cache to avoid re-parsing SQL files when their content hasn't changed.