Skip to content

Litestar Extension

from sqlspec.extensions.litestar import (
    BaseSQLSpecStore,
    CommitMode,
    CorrelationMiddleware,
    LitestarConfig,
    SQLSpecChannelsBackend,
    SQLSpecPlugin,
    TenantResolutionSettings,
    get_sqlspec_scope_state,
    is_scope_authenticated,
    require_tenant,
    resolve_litestar_tenant,
    set_request_tenant,
    tenant_bypass,
    set_sqlspec_scope_state,
)
from sqlspec.extensions.litestar.plugin import (
    integrity_error_handler,
    not_found_error_handler,
)

Litestar plugin, ASGI transaction and correlation middlewares, automatic HTTP 404/409 exception handlers, server-side session store base class, and Litestar Channels backend (SQLSpecSyncService and SQLSpecAsyncService are documented in Service Layer; TenantResolutionSettings, require_tenant, set_request_tenant, resolve_litestar_tenant, is_scope_authenticated, and tenant_bypass are documented in Tenant APIs). Adapter-specific LitestarConfig TypedDicts and BaseSQLSpecStore subclasses are documented on each Database Adapter page. 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.

sqlspec

sqlspec

Return the underlying SQLSpec registry.

config

config

Return the plugin configurations.

Returns:

Type Description
list[AnyDatabaseConfig]

List of database configurations.

on_app_init

on_app_init(app_config)

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

on_cli_init(cli)

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_config(name=None)

Get a configuration instance by name, or the sole configuration when omitted.

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

Optional configuration identifier. Defaults to the sole registered configuration when None.

None

Raises:

Type Description
KeyError

If no configuration is found for name, if name is None when zero or multiple configurations are registered, or if several configurations share the requested concrete type.

Returns:

Type Description
DatabaseConfigProtocol[Any, Any, Any]

The configuration instance for the specified identifier.

resolve_tenant_settings

resolve_tenant_settings(key=None)

Resolve tenant extraction settings for a registered Litestar configuration.

Parameters:

Name Type Description Default
key str | AnyDatabaseConfig | type[AnyDatabaseConfig] | None

Optional configuration key, concrete type, or instance. When omitted, prefers the sole tenant-enforced configuration, then the sole configuration, or raises when multiple tenant databases define distinct settings.

None

Returns:

Type Description
TenantResolutionSettings

The active TenantResolutionSettings for key.

Raises:

Type Description
KeyError

key does not match any registered configuration.

ImproperConfigurationError

key is omitted and multiple tenant databases configure distinct TenantResolutionSettings.

get_annotations

get_annotations()

Return the list of annotations.

Returns:

Type Description
list[type[AnyDatabaseConfig]]

List of annotations.

provide_db_session

provide_db_session(key, state, scope)

Provide a database session for the specified configuration key from request scope.

For a synchronous configuration the connection must already exist in scope; use provide_db_session_sync to check one out on demand. For an asynchronous configuration whose connection is not open yet, the session opens it on the first awaited call, with the same tenant resolution and commit or rollback handling as provide_db_session_async.

Parameters:

Name Type Description Default
key str | AnyDatabaseConfig | type[AnyDatabaseConfig]

The configuration identifier (same as get_config).

required
state State

The Litestar application State object.

required
scope Scope

The ASGI scope containing the request context.

required

Returns:

Type Description
SyncDriverAdapterBase | AsyncDriverAdapterBase

A driver session instance for the specified database configuration.

provide_db_session_sync

provide_db_session_sync(key, state, scope)

Provide a sync database session for the specified configuration key from request scope.

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. An asynchronous configuration returns the same deferred session as provide_db_session.

Parameters:

Name Type Description Default
key str | SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any] | type[SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]]

The configuration identifier (same as get_config).

required
state State

The Litestar application State object.

required
scope Scope

The ASGI scope containing the request context.

required

Returns:

Type Description
SyncDriverAdapterBase | Any

A sync driver session instance for the specified database configuration.

provide_db_session_async

provide_db_session_async(key, state, scope)

Provide an async database session for the specified configuration key from request scope.

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_db_session instead.

Parameters:

Name Type Description Default
key str | AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any] | type[AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]]

The configuration identifier (same as get_config).

required
state State

The Litestar application State object.

required
scope Scope

The ASGI scope containing the request context.

required

Returns:

Type Description
AsyncDriverAdapterBase | Any

An async driver session instance for the specified database configuration.

CommitMode

CommitMode = Literal['manual', 'autocommit', 'autocommit_include_redirect']

LitestarConfig

Bases: TypedDict

Configuration options for Litestar SQLSpec plugin.

All fields are optional with sensible defaults.

Attributes:

Name Type Description
tenant_extractor NotRequired[Callable[[MutableMapping[str, Any]], Any]]

Trusted scope callable returning a tenant identity, payload, None (no tenant from this source), or an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start.

tenant_user_attr NotRequired[str]

Verified direct tenant attribute or mapping key. Default: 'tenant_id'.

tenant_memberships_attr NotRequired[str]

Verified membership attribute or mapping key. Default: 'tenant_ids'.

tenant_variables_attr NotRequired[str]

Extra session variables attribute or mapping key. Default: 'tenant_variables'.

tenant_jwt_claim NotRequired[str]

Direct tenant key in verified auth claims or extras. Default: 'tenant_id'.

tenant_path_parameter NotRequired[str | None]

Route parameter checked against verified memberships. Default: 'tenant_id'.

tenant_session_key NotRequired[str | None]

Session selector checked against verified memberships. Default: 'tenant_id'.

tenant_header NotRequired[str | None]

Optional header selector checked against verified memberships. Default: None.

migrations_path NotRequired[str | Path]

Directory containing this extension's migrations, or a '<dotted.module>:<subdir>' specification.

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: 'autocommit'

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: X-Request-ID

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

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.

migration_mode NotRequired[ExtensionMigrationMode]

Extension migration strategy ('versioned' or 'reconcile'). Default: 'reconcile'.

replica_session_key NotRequired[str]

Request key for a replica session.

replica_connection_key NotRequired[str]

Request key for a replica connection.

routing_session_key NotRequired[str]

Request key for a routing session.

default_routing_mode NotRequired[Literal['primary', 'auto']]

Default request routing mode. Default: 'auto'.

enable_routing_middleware NotRequired[bool]

Install request-scoped routing middleware. Default: True.

routing_header NotRequired[str | None]

Trusted application routing header name when explicitly enabled behind a gateway. Default: None.

primary_pin_cookie NotRequired[str | None]

Optional application primary pin cookie name. Default: None.

primary_pin_secret NotRequired[str | bytes | None]

Optional HMAC secret verifying signed primary pin cookies. Default: None.

replica_pool_key NotRequired[str]

Request key for the selected replica pool.

pagination_cursor_secret NotRequired[str | bytes]

Application-wide secret enabling HMAC-SHA256 signed pagination cursors.

pagination_cursor_ttl NotRequired[int | float | timedelta]

Default cursor expiration window in seconds or timedelta.

pagination_cursor_encrypted NotRequired[bool]

Encrypt cursor payloads at rest when a cursor secret is configured.

Middleware, Stores & Channels

CorrelationMiddleware

ASGI middleware that binds a correlation ID to each HTTP request.

Only headers matching the configured headers allowlist are decoded from the ASGI header list (using latin-1 over precomputed lowercase bytes names). Checked in priority order, the first header whose bounded, single-line ASCII trace value passes validation becomes the correlation ID; invalid values fall through to subsequent headers, or to a newly generated ID when none qualify. 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

Inside a Litestar request that holds an open session for the store's config, store operations started by the request task run on that session inside the request transaction. In autocommit modes the request commits or rolls back the write. In manual mode the write joins uncommitted handler work when a transaction is open; otherwise the store begins its own transaction on the request session and commits it. After a request fails and releases its session, later store writes from the request task are rolled back. Outside a request, from other tasks, and after a successful release the store opens its own short session and commits itself.

Subclasses must implement dialect-specific SQL queries.

Parameters:

Name Type Description Default
config ConfigT

SQLSpec database configuration with extension_config["litestar"] settings.

required

create_table

create_table()

Create the session table if it doesn't exist.

delete_expired

delete_expired()

Delete all expired sessions.

Returns:

Type Description
int

Number of sessions deleted.

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.

on_startup

on_startup()

on_shutdown

on_shutdown()

publish

publish(data, channels)

subscribe

subscribe(channels)

unsubscribe

unsubscribe(channels)

stream_events

stream_events()

Exception Handlers & Scope State Helpers

not_found_error_handler

not_found_error_handler(request, exc)

Return a 404 response with the static detail "Not Found".

A handler for status 404 or for the HTTP exception type renders it, otherwise Litestar's default exception response. Handlers for :class:~sqlspec.exceptions.NotFoundError or a subclass take precedence; handlers for its base classes or status 500 do not.

integrity_error_handler

integrity_error_handler(request, exc)

Return a 409 response with the generic detail "Conflict".

A handler for status 409 or for the HTTP exception type renders it, otherwise Litestar's default exception response. Handlers for :class:~sqlspec.exceptions.IntegrityError or a subclass take precedence, and handlers for a later class in the error's MRO or for status 500 receive the original exception.

get_sqlspec_scope_state

get_sqlspec_scope_state(scope, key, default=None, pop=False)

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 key in internal connection scope namespace.

set_sqlspec_scope_state

set_sqlspec_scope_state(scope, key, value)

Set an internal value in connection scope state.

Parameters:

Name Type Description Default
scope Scope

The connection scope.

required
key str

Key to set under internal namespace in scope state.

required
value Any

Value for key.

required