Litestar#
Full Litestar integration with plugin lifecycle, dependency injection, CLI commands, channels backend, and key-value store.
Plugin#
- class sqlspec.extensions.litestar.SQLSpecPlugin[source]#
Bases:
InitPluginProtocol,CLIPluginLitestar 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.
- __init__(sqlspec, *, loader=None)[source]#
Initialize SQLSpec plugin.
- Parameters:
sqlspec¶ (
SQLSpec) -- Pre-configured SQLSpec instance with registered database configs.loader¶ (
SQLFileLoader|None) -- Optional SQL file loader instance (SQLSpec may already have one).
- property config: list[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]#
Return the plugin configurations.
- Returns:
List of database configurations.
- on_app_init(app_config)[source]#
Configure Litestar application with SQLSpec database integration.
Automatically registers NumPy array serialization when NumPy is installed.
- get_annotations()[source]#
Return the list of annotations.
- Return type:
list[type[Union[SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any]]]]- Returns:
List of annotations.
- get_annotation(key)[source]#
Return the annotation for the given configuration.
- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any],type[Union[SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any]]]]) -- The configuration instance or key to lookup.- Raises:
KeyError -- If no configuration is found for the given key.
- Return type:
type[Union[SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any]]]- Returns:
The annotation for the configuration.
- get_config(name)[source]#
Get a configuration instance by name.
- Overloads:
self, name (type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]) → SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]
self, name (type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]) → AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]
self, name (SyncConfigT) → SyncConfigT
self, name (AsyncConfigT) → AsyncConfigT
self, name (str) → AnyDatabaseConfig
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. Abind_keywins 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¶ (
Union[type[DatabaseConfigProtocol[typing.Any, typing.Any, typing.Any]],str, typing.Any]) -- The configuration identifier.- Raises:
KeyError -- If no configuration is found for the given name, or if several configurations share the requested concrete type.
- Returns:
The configuration instance for the specified name.
- provide_request_session(key, state, scope)[source]#
Provide a database session for the specified configuration key from request scope.
- Overloads:
self, key (SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT] | type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]), state (State), scope (Scope) → DriverT
self, key (AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT] | type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]), state (State), scope (Scope) → DriverT
self, key (str), state (State), scope (Scope) → SyncDriverAdapterBase | AsyncDriverAdapterBase
This method requires the connection to already exist in scope. For on-demand connection creation, use
provide_request_session_syncorprovide_request_session_asyncinstead.- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any],type[Union[SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
A driver session instance for the specified database configuration.
- provide_request_session_sync(key, state, scope)[source]#
Provide a sync database session for the specified configuration key from request scope.
- Overloads:
self, key (SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]), state (State), scope (Scope) → DriverT
self, key (type[SyncDatabaseConfig[Any, Any, DriverT] | NoPoolSyncConfig[Any, DriverT]]), state (State), scope (Scope) → DriverT
self, key (str), state (State), scope (Scope) → SyncDriverAdapterBase
If no connection exists in scope, one will be created from the pool and stored in scope for reuse. The connection will be cleaned up by the before_send handler.
For async configurations, use
provide_request_session_asyncinstead.- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any],type[Union[SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
A sync driver session instance for the specified database configuration.
- async provide_request_session_async(key, state, scope)[source]#
Provide an async database session for the specified configuration key from request scope.
- Overloads:
self, key (AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]), state (State), scope (Scope) → DriverT
self, key (type[AsyncDatabaseConfig[Any, Any, DriverT] | NoPoolAsyncConfig[Any, DriverT]]), state (State), scope (Scope) → DriverT
self, key (str), state (State), scope (Scope) → AsyncDriverAdapterBase
If no connection exists in scope, one will be created from the pool and stored in scope for reuse. The connection will be cleaned up by the before_send handler.
For sync configurations, use
provide_request_sessioninstead.- Parameters:
key¶ (
Union[str,AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any],type[Union[AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
An async driver session instance for the specified database configuration.
- provide_request_connection(key, state, scope)[source]#
Provide a database connection for the specified configuration key from request scope.
- Overloads:
self, key (SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]), state (State), scope (Scope) → ConnectionT
self, key (type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any] | AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]), state (State), scope (Scope) → ConnectionT
self, key (str), state (State), scope (Scope) → Any
This method requires the connection to already exist in scope. For on-demand connection creation, use
provide_request_connection_syncorprovide_request_connection_asyncinstead.- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any],type[Union[SyncDatabaseConfig[Any,Any,Any],NoPoolSyncConfig[Any,Any],AsyncDatabaseConfig[Any,Any,Any],NoPoolAsyncConfig[Any,Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
A database connection instance for the specified database configuration.
- provide_request_connection_sync(key, state, scope)[source]#
Provide a sync database connection for the specified configuration key from request scope.
- Overloads:
self, key (SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]), state (State), scope (Scope) → ConnectionT
self, key (type[SyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolSyncConfig[ConnectionT, Any]]), state (State), scope (Scope) → ConnectionT
self, key (str), state (State), scope (Scope) → Any
If no connection exists in scope, one will be created from the pool and stored in scope for reuse. The connection will be cleaned up by the before_send handler.
For async configurations, use
provide_request_connection_asyncinstead.- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any],type[Union[SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
A database connection instance for the specified database configuration.
- async provide_request_connection_async(key, state, scope)[source]#
Provide an async database connection for the specified configuration key from request scope.
- Overloads:
self, key (AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]), state (State), scope (Scope) → ConnectionT
self, key (type[AsyncDatabaseConfig[ConnectionT, Any, Any] | NoPoolAsyncConfig[ConnectionT, Any]]), state (State), scope (Scope) → ConnectionT
self, key (str), state (State), scope (Scope) → Any
If no connection exists in scope, one will be created from the pool and stored in scope for reuse. The connection will be cleaned up by the before_send handler.
For sync configurations, use
provide_request_connectioninstead.- Parameters:
key¶ (
Union[str,AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any],type[Union[AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any]]]]) -- The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) -- The ASGI scope containing the request context.
- Returns:
A database connection instance for the specified database configuration.
Configuration#
- class sqlspec.extensions.litestar.LitestarConfig[source]#
Bases:
TypedDictConfiguration options for Litestar SQLSpec plugin.
All fields are optional with sensible defaults.
- migrations_path: NotRequired[str | Path]#
Directory containing this extension's migrations, or a
'<dotted.module>:<subdir>'specification.Overrides the default
sqlspec.extensions.<name>lookup. Setting this auto-includes the extension inmigration_config["include_extensions"].
- session_table: NotRequired[bool | str]#
Enable session table for server-side session storage.
True: Use default table name ('litestar_session')"custom_name": Use custom table name
When set, litestar extension migrations are auto-included to create the session table. If you're only using litestar for DI/connection management (not session storage), leave this unset to skip the migrations.
- connection_key: NotRequired[str]#
'db_connection'
- Type:
Key for storing connection in ASGI scope. Default
- pool_key: NotRequired[str]#
'db_pool'
- Type:
Key for storing connection pool in application state. Default
- session_key: NotRequired[str]#
'db_session'
- Type:
Key for storing session in ASGI scope. Default
- commit_mode: NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]#
'manual'
- Type:
Transaction commit mode. Default
- enable_correlation_middleware: NotRequired[bool]#
True
- Type:
Enable request correlation ID middleware. Default
- correlation_header: NotRequired[str]#
X-Request-ID- Type:
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]#
True.
- Type:
Read standard trace context headers as correlation ID fallbacks. Default
- extra_commit_statuses: NotRequired[set[int]]#
- Type:
Additional HTTP status codes that trigger commit. Default
- extra_rollback_statuses: NotRequired[set[int]]#
- Type:
Additional HTTP status codes that trigger rollback. Default
- disable_di: NotRequired[bool]#
False. When True, the Litestar plugin will not register dependency providers for managing database connections, pools, and sessions. Users are responsible for managing the database lifecycle manually via their own DI solution.
- Type:
Disable built-in dependency injection. Default
- enable_sqlcommenter_middleware: NotRequired[bool]#
True. When the driver's
StatementConfighasenable_sqlcommenter=True, the middleware is registered automatically. Set toFalseto explicitly disable middleware registration even when SQLCommenter is enabled on the driver config.- Type:
Control automatic SQLCommenter middleware registration. Default
- manage_schema: NotRequired[bool]#
True.
- Type:
Apply additive session-table reconciliation. Default
- create_schema: NotRequired[bool]#
True.
- Type:
Create a missing session table during managed reconciliation. Default
- run_migrations: NotRequired[bool]#
False.
- Type:
Run packaged versioned migrations when an integration supplies a runner. Default
- in_memory: NotRequired[bool]#
Enable Oracle Database In-Memory storage when licensed and available.
- shard_count: NotRequired[int]#
Set the Spanner session-table hash shard count.
- table_options: NotRequired[str]#
Set adapter-specific session-table options where supported.
- index_options: NotRequired[str]#
Set adapter-specific session expiry-index options where supported.
- partitioning: NotRequired[dict[str, Any]]#
Configure adapter-specific session-table partitioning where supported.
- partition_expiration_days: NotRequired[int]#
Set BigQuery partition expiration in days.
- require_partition_filter: NotRequired[bool]#
Require partition filters for BigQuery session queries.
- enable_hash_sharded_indexes: NotRequired[bool]#
Enable CockroachDB hash-sharded session indexes.
- hash_shard_bucket_count: NotRequired[int]#
Set the CockroachDB hash-shard bucket count.
- ttl_expiration_expression: NotRequired[Literal[False, 'expires_at']]#
Enable CockroachDB row-level TTL using the session
expires_atcolumn.
- fillfactor: NotRequired[int]#
- Type:
Set PostgreSQL-family session-table fillfactor. Default
- autovacuum_vacuum_scale_factor: NotRequired[float]#
Set the PostgreSQL-family autovacuum vacuum scale factor.
- autovacuum_analyze_scale_factor: NotRequired[float]#
Set the PostgreSQL-family autovacuum analyze scale factor.
- pragma_profile: NotRequired[bool]#
False.
- Type:
Apply the SQLite extension-store PRAGMA profile. Default
Channels Backend#
SQLSpecChannelsBackend buffers decoded output from every asynchronous
EventChannel transport. Pass output_queue_capacity to bound that buffer;
the default None remains unbounded. When full, the backend discards the
oldest decoded message before acknowledging and retaining the newest one.
output_queue_depth reports the current pending count and
dropped_message_count reports cumulative overflow drops for the backend
instance. Malformed payloads are acknowledged and logged without increasing the
overflow count. Shutdown clears pending output while preserving the cumulative
drop diagnostic for lifecycle reuse.
- class sqlspec.extensions.litestar.SQLSpecChannelsBackend[source]#
Bases:
ChannelsBackendA 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.
- __init__(event_channel, *, channel_prefix='litestar', poll_interval=0.2, output_queue_capacity=None)[source]#
- property dropped_message_count: int#
Return the cumulative number of messages dropped due to overflow.
- async publish_many(data, channels)[source]#
Publish independent payloads through one event-channel batch.
Store#
- class sqlspec.extensions.litestar.BaseSQLSpecStore[source]#
Bases:
Store,Generic[ConfigT]Base class for SQLSpec-backed Litestar session stores.
Inherits Litestar's
Storeabstract 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:
config¶ (
TypeVar(ConfigT)) -- SQLSpec database configuration with extension_config["litestar"] settings.
- property config: ConfigT#
Return the database configuration.
- abstractmethod async delete_expired()[source]#
Delete all expired sessions.
- Return type:
- Returns:
Number of sessions deleted.
- abstractmethod async create_table()[source]#
Create the session table if it doesn't exist.
- Return type:
- prepare_schema_sync(driver)[source]#
Prepare adapter-specific schema decisions with a synchronous driver.
- Return type:
Providers#
create_filter_dependencies() accepts camel-case aliases for configured
orderBy fields by default. Use sort_field_aliases to map explicit API
names to configured SQL-facing fields, or set sort_field_camelize=False when
an endpoint must accept only raw configured values. Alias values are normalized
before OrderByFilter is created, and unknown aliases cannot bypass the
sort_field allowlist.
- class sqlspec.extensions.litestar.providers.FilterConfig[source]#
Bases:
TypedDictConfiguration for generated Litestar filter dependencies.
All keys are optional. A filter dependency is created only for each enabled key. Field names are SQL-facing allowlist values; generated query parameter names and order-by aliases remain API-facing.
- id_filter: NotRequired[type[UUID | int | str]]#
Type of ID filter to enable. When set, creates an
idscollection filter.
- id_field: NotRequired[str]#
SQL-facing field name for ID filtering. Defaults to
"id".
- sort_field: NotRequired[str | set[str] | list[str]]#
Allowed SQL-facing field or fields for
orderBysorting.
- sort_field_aliases: NotRequired[dict[str, str]]#
Additional API-facing
orderByaliases mapped to configuredsort_fieldvalues.
- sort_field_camelize: NotRequired[bool]#
Whether to accept camel-case aliases for configured sort fields. Defaults to
True.
- sort_order: NotRequired[Literal['asc', 'desc']]#
Default sort order. Defaults to
"desc".
- pagination_type: NotRequired[Literal['limit_offset']]#
Pagination strategy to enable. Currently supports
"limit_offset".
- pagination_size: NotRequired[int]#
Default page size for limit/offset pagination.
- search: NotRequired[str | set[str] | list[str]]#
SQL-facing field or fields to search. Strings may be comma-separated.
- search_ignore_case: NotRequired[bool]#
Whether search filtering is case-insensitive. Defaults to
False.
- created_at: NotRequired[bool]#
Whether to enable
created_atbefore/after range filtering.
- updated_at: NotRequired[bool]#
Whether to enable
updated_atbefore/after range filtering.
- not_in_fields: NotRequired[FieldNameType | set[FieldNameType] | list[str | FieldNameType]]#
Field or fields that support
NOT INcollection filtering.
- in_fields: NotRequired[FieldNameType | set[FieldNameType] | list[str | FieldNameType]]#
Field or fields that support
INcollection filtering.
- null_fields: NotRequired[str | set[str] | list[str]]#
Field or fields that support
IS NULLfiltering.
- not_null_fields: NotRequired[str | set[str] | list[str]]#
Field or fields that support
IS NOT NULLfiltering.
- boolean_fields: NotRequired[str | set[str] | list[str]]#
Field or fields that support boolean filtering.
- choice_fields: NotRequired[ChoiceField | set[ChoiceField] | list[str | ChoiceField]]#
Field or fields that support choices filtering.
CLI#
- sqlspec.extensions.litestar.database_group#
Click command group for managing SQLSpec database components (migrations, etc.).
- Type: