Litestar Extension¶
from sqlspec.extensions.litestar import (
BaseSQLSpecStore,
CommitMode,
CorrelationMiddleware,
LitestarConfig,
SQLSpecAsyncService,
SQLSpecChannelsBackend,
SQLSpecPlugin,
SQLSpecSyncService,
database_group,
get_sqlspec_scope_state,
set_sqlspec_scope_state,
)
Litestar plugin, ASGI transaction and correlation middlewares, server-side session store base class, and Litestar Channels backend. See the Litestar Integration Guide for usage examples.
Plugin & Configuration¶
SQLSpecPlugin
¶
Bases: InitPluginProtocol, CLIPlugin
Litestar plugin for SQLSpec database integration.
Automatically configures NumPy array serialization when NumPy is installed, enabling seamless bidirectional conversion between NumPy arrays and JSON for vector embedding workflows.
Session Table Migrations
The Litestar extension includes migrations for creating session storage tables. To include these migrations in your database migration workflow, add 'litestar' to the include_extensions list in your migration configuration.
config
¶
Return the plugin configurations.
Returns:
| Type | Description |
|---|---|
list[AnyDatabaseConfig]
|
List of database configurations. |
on_app_init
¶
Configure Litestar application with SQLSpec database integration.
Automatically registers NumPy array serialization when NumPy is installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app_config
|
AppConfig
|
The Litestar application configuration instance. |
required |
Returns:
| Type | Description |
|---|---|
AppConfig
|
The updated application configuration instance. |
on_cli_init
¶
Configure CLI commands for SQLSpec database operations.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cli
|
Group
|
The Click command group to add commands to. |
required |
get_config
¶
Get a configuration instance by name.
Registry identifiers are available as soon as the plugin is constructed: a
config instance, its concrete config type when exactly one configuration has
that type, or a non-null bind_key. A bind_key wins over a dependency
key of the same value. The generated Litestar dependency keys
(session_key, connection_key, pool_key) resolve only after the
plugin is registered with a Litestar application.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
type[DatabaseConfigProtocol[Any, Any, Any]] | str | Any
|
The configuration identifier. |
required |
Raises:
| Type | Description |
|---|---|
KeyError
|
If no configuration is found for the given name, or if several configurations share the requested concrete type. |
Returns:
| Type | Description |
|---|---|
DatabaseConfigProtocol[Any, Any, Any]
|
The configuration instance for the specified name. |
get_annotations
¶
Return the list of annotations.
Returns:
| Type | Description |
|---|---|
list[type[AnyDatabaseConfig]]
|
List of annotations. |
LitestarConfig
¶
Bases: TypedDict
Configuration options for Litestar SQLSpec plugin.
All fields are optional with sensible defaults.
Attributes:
| Name | Type | Description |
|---|---|---|
migrations_path |
NotRequired[str | Path]
|
Directory containing this extension's migrations, or a |
session_table |
NotRequired[bool | str]
|
Enable session table for server-side session storage. |
connection_key |
NotRequired[str]
|
Key for storing connection in ASGI scope. Default: 'db_connection' |
pool_key |
NotRequired[str]
|
Key for storing connection pool in application state. Default: 'db_pool' |
session_key |
NotRequired[str]
|
Key for storing session in ASGI scope. Default: 'db_session' |
commit_mode |
NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]
|
Transaction commit mode. Default: 'manual' |
enable_correlation_middleware |
NotRequired[bool]
|
Enable request correlation ID middleware. Default: True |
correlation_header |
NotRequired[str]
|
HTTP header to read the request correlation ID from when middleware is enabled. Default: |
correlation_headers |
NotRequired[tuple[str, ...] | list[str]]
|
Additional HTTP headers to read as correlation ID fallbacks. |
auto_trace_headers |
NotRequired[bool]
|
Read standard trace context headers as correlation ID fallbacks. Default: True. |
extra_commit_statuses |
NotRequired[set[int]]
|
Additional HTTP status codes that trigger commit. Default: set() |
extra_rollback_statuses |
NotRequired[set[int]]
|
Additional HTTP status codes that trigger rollback. Default: set() |
disable_di |
NotRequired[bool]
|
Disable built-in dependency injection. Default: False. |
manage_lifespan |
NotRequired[bool]
|
Register the plugin's pool lifespan handler. Default: the inverse of |
enable_sqlcommenter_middleware |
NotRequired[bool]
|
Control automatic SQLCommenter middleware registration. Default: True. |
manage_schema |
NotRequired[bool]
|
Apply additive session-table reconciliation. Default: True. |
create_schema |
NotRequired[bool]
|
Create a missing session table during managed reconciliation. Default: True. |
Middleware, Stores & Channels¶
CorrelationMiddleware
¶
ASGI middleware that binds a correlation ID to each HTTP request.
The first non-empty value among headers, checked in order, becomes the
correlation ID after surrounding whitespace is trimmed and the value is
truncated to 128 characters; when no header has a value, or the trimmed
value is empty, a new ID is generated. The ID is set on
:class:~sqlspec.utils.correlation.CorrelationContext and in the request scope
for the duration of the request, then the previous ID is restored. Non-HTTP
scopes, and instances created with an empty headers tuple, pass through
unchanged.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
app
|
ASGIApp
|
The downstream ASGI application. |
required |
headers
|
tuple[str, ...]
|
Request header names to check, in priority order. |
required |
BaseSQLSpecStore
¶
Bases: Store, Generic[ConfigT]
Base class for SQLSpec-backed Litestar session stores.
Inherits Litestar's Store abstract base class for server-side session
storage backed by SQLSpec database adapters.
This abstract base class provides common functionality for all database-specific store implementations including: - Connection management via SQLSpec configs - Session expiration calculation - Table creation utilities
Subclasses must implement dialect-specific SQL queries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ConfigT
|
SQLSpec database configuration with extension_config["litestar"] settings. |
required |
SQLSpecChannelsBackend
¶
Bases: ChannelsBackend
A Litestar Channels backend implemented on top of SQLSpec's EventChannel.
This backend allows Litestar's ChannelsPlugin to use a SQLSpec database as the broker. Under the hood it relies on SQLSpec's events extension, which can be configured to use a durable table queue or native adapter backends.
Scope State Helpers¶
get_sqlspec_scope_state
¶
Get an internal value from connection scope state.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scope
|
Scope
|
The connection scope. |
required |
key
|
str
|
Key to get from internal namespace in scope state. |
required |
default
|
Any
|
Default value to return. |
None
|
pop
|
bool
|
Boolean flag dictating whether the value should be deleted from the state. |
False
|
Returns:
| Type | Description |
|---|---|
Any
|
Value mapped to |