GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • litestar-org/sqlspec
  • Home
  • Learn
  • Databases
  • Integrations
  • Reference
  • Playground
  • Project
  • SQLSpec
  • Configuration
  • Exceptions
  • Protocols
  • Typing
  • Drivers

This view

  • Original page
  • New address

GeezerVison is showing sqlspec.dev — SQLFileLoader - SQLSpec

SQL File Loader¶

from sqlspec.core import (
    ParameterDeclaration,
    ParamTypeMatcher,
    matches_param_type,
    register_param_type,
    resolve_param_type,
)
from sqlspec.loader import (
    NamedStatement,
    SlotDeclaration,
    SQLFile,
    SQLFileCacheEntry,
    SQLFileLoader,
)

Load, cache, and compose named SQL queries (-- name:), declared parameters (-- param:), reusable fragments (-- fragment: / /* include: */), and dynamic slots (-- slot: / /* slot: */) from local files or remote object storage. See SQL Files — Fragments, Slots, and Composition Rules for directive syntax, slot validation rules, and the query composition decision matrix.

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.

__init__ ¶

__init__(
    *,
    encoding="utf-8",
    storage_registry=None,
    runtime=None,
    strict_parameter_annotations=False,
)

Initialize the SQL file loader.

Parameters:

Name Type Description Default
encoding str

Text encoding for reading SQL files.

'utf-8'
storage_registry StorageRegistry | None

Storage registry for handling file URIs.

None
runtime ObservabilityRuntime | None

Observability runtime for instrumentation.

None
strict_parameter_annotations bool

When True, a malformed -- param: directive raises instead of emitting a warning and skipping the line.

False

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.

set_observability_runtime ¶

set_observability_runtime(runtime)

Attach an observability runtime used for instrumentation.

SQLFile ¶

Represents a loaded SQL file with metadata.

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

Statement, Slot & Parameter 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.

ParameterDeclaration ¶

A single parameter declared in a SQL file header.

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.

ParamTypeMatcher ¶

ParamTypeMatcher = type | tuple[type, ...] | Callable[[object], bool]

register_param_type ¶

register_param_type(name, py_type)

Register or override a declared-type-string matcher.

Parameters:

Name Type Description Default
name str

The declared type string as written in -- param: (case-insensitive).

required
py_type ParamTypeMatcher

The Python type, tuple of types, or predicate used for validation.

required

resolve_param_type ¶

resolve_param_type(type_str)

Resolve a declared type string to a matcher, or None if 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).

Parameters:

Name Type Description Default
type_str str

The declared type string from a -- param: directive.

required

Returns:

Type Description
ParamTypeMatcher | None

The resolved matcher, or None when not in the registry.

matches_param_type ¶

matches_param_type(type_str, value)

Return whether a value satisfies a declared type string.

Unknown type strings are documentation-only and always match. None is handled by the driver as SQL NULL before this helper is called.

You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.