Database Configuration#

Base configuration classes for database adapters. All adapter-specific config classes inherit from one of these bases.

DatabaseConfigProtocol#

class sqlspec.config.DatabaseConfigProtocol[source]#

Bases: ABC, Generic[ConnectionT, PoolT, DriverT]

Protocol defining the stability-critical config contract.

Compiled callers rely on these attributes and methods remaining runtime-visible while sqlspec.config stays interpreted. Changes to migration setup, pool/session provider behavior, storage capabilities, or observability bootstrap must preserve this contract or move behind a separately verified compiled helper boundary.

property migration_config: dict[str, TypeAliasForwardRef('typing.Any')] | MigrationConfig#

Return the current migration configuration.

set_migration_config(config)[source]#

Attach migration configuration after initial config creation.

This is equivalent to setting migration_config directly but provides a discoverable method for post-construction configuration.

Parameters:

config (dict[str, typing.Any] | MigrationConfig) -- Migration configuration dictionary.

Return type:

None

storage_capabilities()[source]#

Return cached storage capabilities for this configuration.

Return type:

StorageCapabilities

reset_storage_capabilities_cache()[source]#

Clear the cached capability snapshot.

Return type:

None

get_event_runtime_hints()[source]#

Return default event runtime hints for this configuration.

Return type:

EventRuntimeHints

attach_observability(registry_config)[source]#

Attach merged observability runtime composed from registry and adapter overrides.

Return type:

None

get_observability_runtime()[source]#

Return the attached runtime, creating a disabled instance when missing.

Return type:

ObservabilityRuntime

abstractmethod create_connection()[source]#

Create and return a new database connection.

Return type:

Union[TypeVar(ConnectionT), Awaitable[TypeVar(ConnectionT)]]

abstractmethod provide_connection(*args, **kwargs)[source]#

Provide a database connection context manager.

Return type:

AbstractContextManager[TypeVar(ConnectionT)] | AbstractAsyncContextManager[TypeVar(ConnectionT)]

abstractmethod provide_session(*args, **kwargs)[source]#

Provide a database session context manager.

Return type:

AbstractContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)] | AbstractAsyncContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)]

abstractmethod create_pool()[source]#

Create and return connection pool.

Return type:

Union[TypeVar(PoolT), Awaitable[TypeVar(PoolT)]]

abstractmethod close_pool()[source]#

Terminate the connection pool.

Return type:

Awaitable[None] | None

abstractmethod provide_pool(*args, **kwargs)[source]#

Provide pool instance.

Return type:

Union[TypeVar(PoolT), Awaitable[TypeVar(PoolT)], AbstractContextManager[TypeVar(PoolT)], AbstractAsyncContextManager[TypeVar(PoolT)]]

get_signature_namespace()[source]#

Get the signature namespace for this database configuration.

Returns a dictionary of type names to objects (classes, functions, or other callables) that should be registered with Litestar's signature namespace to prevent serialization attempts on database-specific structures.

Return type:

dict[str, typing.Any]

Returns:

Dictionary mapping type names to objects.

get_migration_loader()[source]#

Get the SQL loader for migration files.

Provides access to migration SQL files loaded from the configured script_location directory. Files are loaded lazily on first access.

Return type:

SQLFileLoader

Returns:

SQLFileLoader instance with migration files loaded.

load_migration_sql_files(*paths)[source]#

Load additional migration SQL files from specified paths.

Parameters:

*paths (str | Path) -- One or more file paths or directory paths to load migration SQL files from.

Return type:

None

get_migration_commands()[source]#

Get migration commands for this configuration.

The first call constructs the tracker and discovers extension migrations. Call this during application startup to surface their initialization errors eagerly. Subsequent calls reuse the helper until configuration changes.

Returns:

MigrationCommands instance configured for this database.

add_extension_migrations(name, migrations_path, settings=None)[source]#

Register migrations shipped by a package outside the sqlspec.extensions namespace.

Records the extension under extension_config, opts it into migration_config["include_extensions"], and invalidates cached migration commands so the extension is discovered on their next access. Migrations are versioned under the ext_{name}_ prefix, so name must stay stable once migrations are applied.

Parameters:
  • name (str) -- Extension name, used as the ext_{name}_ version prefix.

  • migrations_path (str | Path) -- Directory containing the migrations, or a '<dotted.module>:<subdir>' specification.

  • settings (dict[str, typing.Any] | None) -- Extension settings passed to its migrations. Merged into any settings already registered under name.

Return type:

None

remove_extension_migrations(name)[source]#

Unregister migrations previously registered for an extension.

Removes the extension entry from extension_config and from migration_config["include_extensions"]. If anything was removed, cached migration commands are invalidated so the extension is no longer discovered on their next access.

Parameters:

name (str) -- Extension name to unregister.

Return type:

bool

Returns:

True if the extension was found and removed, False otherwise.

abstractmethod migrate_up(revision='head', allow_missing=False, auto_sync=True, dry_run=False, *, use_logger=False, echo=None, summary_only=None)[source]#

Apply database migrations up to specified revision.

Parameters:
  • revision (str) -- Target revision or "head" for latest. Defaults to "head".

  • allow_missing (bool) -- Allow out-of-order migrations. Defaults to False.

  • auto_sync (bool) -- Auto-reconcile renamed migrations. Defaults to True.

  • dry_run (bool) -- Show what would be done without applying. Defaults to False.

  • use_logger (bool) -- Use Python logger instead of Rich console for output. Defaults to False. Can be set via MigrationConfig for persistent default.

  • echo (bool | None) -- Echo output to the console. Defaults to True when unset.

  • summary_only (bool | None) -- Emit a single summary log entry when logger output is enabled.

Return type:

Awaitable[None] | None

abstractmethod migrate_down(revision='-1', *, dry_run=False, use_logger=False, echo=None, summary_only=None)[source]#

Apply database migrations down to specified revision.

Parameters:
  • revision (str) -- Target revision, "-1" for one step back, or "base" for all migrations. Defaults to "-1".

  • dry_run (bool) -- Show what would be done without applying. Defaults to False.

  • use_logger (bool) -- Use Python logger instead of Rich console for output. Defaults to False. Can be set via MigrationConfig for persistent default.

  • echo (bool | None) -- Echo output to the console. Defaults to True when unset.

  • summary_only (bool | None) -- Emit a single summary log entry when logger output is enabled.

Return type:

Awaitable[None] | None

abstractmethod get_current_migration(verbose=False)[source]#

Get the current migration version.

Parameters:

verbose (bool) -- Whether to show detailed migration history. Defaults to False.

Return type:

Awaitable[str | None] | str | None

Returns:

Current migration version or None if no migrations applied.

abstractmethod create_migration(message, file_type='sql')[source]#

Create a new migration file.

Parameters:
  • message (str) -- Description for the migration.

  • file_type (str) -- Type of migration file to create ('sql' or 'py'). Defaults to 'sql'.

Return type:

Awaitable[None] | None

abstractmethod init_migrations(directory=None, package=True)[source]#

Initialize migration directory structure.

Parameters:
  • directory (str | None) -- Directory to initialize migrations in. Uses script_location from migration_config if not provided.

  • package (bool) -- Whether to create __init__.py file. Defaults to True.

Return type:

Awaitable[None] | None

abstractmethod stamp_migration(revision)[source]#

Mark database as being at a specific revision without running migrations.

Parameters:

revision (str) -- The revision to stamp.

Return type:

Awaitable[None] | None

abstractmethod fix_migrations(dry_run=False, update_database=True, yes=False)[source]#

Convert timestamp migrations to sequential format.

Implements hybrid versioning workflow where development uses timestamps and production uses sequential numbers. Creates backup before changes and provides rollback on errors.

Parameters:
  • dry_run (bool) -- Preview changes without applying. Defaults to False.

  • update_database (bool) -- Update migration records in database. Defaults to True.

  • yes (bool) -- Skip confirmation prompt. Defaults to False.

Return type:

Awaitable[None] | None

SyncDatabaseConfig#

class sqlspec.config.SyncDatabaseConfig[source]#

Bases: _SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]

Base class for sync database configurations with connection pooling.

migration_tracker_type#

alias of SyncMigrationTracker

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]#
create_pool()[source]#

Create and return the connection pool.

Return type:

TypeVar(PoolT)

Returns:

The created pool.

close_pool()[source]#

Close the connection pool.

Return type:

None

provide_pool(*args, **kwargs)[source]#

Provide pool instance.

Return type:

TypeVar(PoolT)

create_connection()[source]#

Create a database connection.

Return type:

TypeVar(ConnectionT)

provide_connection(*args, **kwargs)[source]#

Provide a database connection context manager.

Return type:

AbstractContextManager[TypeVar(ConnectionT)]

provide_session(*args, statement_config=None, **kwargs)[source]#

Provide a database session context manager.

Return type:

AbstractContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)]

AsyncDatabaseConfig#

class sqlspec.config.AsyncDatabaseConfig[source]#

Bases: _AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]

Base class for async database configurations with connection pooling.

migration_tracker_type#

alias of AsyncMigrationTracker

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None, **kwargs)[source]#
async create_pool()[source]#

Create and return the connection pool.

Return type:

TypeVar(PoolT)

Returns:

The created pool.

async close_pool()[source]#

Close the connection pool.

Return type:

None

async provide_pool(*args, **kwargs)[source]#

Provide pool instance.

Return type:

TypeVar(PoolT)

async create_connection()[source]#

Create a database connection.

Return type:

TypeVar(ConnectionT)

provide_connection(*args, **kwargs)[source]#

Provide a database connection context manager.

Return type:

AbstractAsyncContextManager[TypeVar(ConnectionT)]

provide_session(*args, statement_config=None, **kwargs)[source]#

Provide a database session context manager.

Return type:

AbstractAsyncContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)]

NoPoolSyncConfig#

class sqlspec.config.NoPoolSyncConfig[source]#

Bases: _SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]

Base class for sync database configurations that do not implement a pool.

migration_tracker_type#

alias of SyncMigrationTracker

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None)[source]#
create_connection()[source]#

Create a database connection.

Return type:

TypeVar(ConnectionT)

provide_connection(*args, **kwargs)[source]#

Provide a database connection context manager.

Return type:

AbstractContextManager[TypeVar(ConnectionT)]

provide_session(*args, statement_config=None, **kwargs)[source]#

Provide a database session context manager.

Return type:

AbstractContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)]

create_pool()[source]#

Create and return connection pool.

Return type:

None

close_pool()[source]#

Terminate the connection pool.

Return type:

None

provide_pool(*args, **kwargs)[source]#

Provide pool instance.

Return type:

None

NoPoolAsyncConfig#

class sqlspec.config.NoPoolAsyncConfig[source]#

Bases: _AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]

Base class for async database configurations that do not implement a pool.

migration_tracker_type#

alias of AsyncMigrationTracker

__init__(*, connection_config=None, connection_instance=None, migration_config=None, statement_config=None, driver_features=None, bind_key=None, extension_config=None, observability_config=None)[source]#
async create_connection()[source]#

Create a database connection.

Return type:

TypeVar(ConnectionT)

provide_connection(*args, **kwargs)[source]#

Provide a database connection context manager.

Return type:

AbstractAsyncContextManager[TypeVar(ConnectionT)]

provide_session(*args, statement_config=None, **kwargs)[source]#

Provide a database session context manager.

Return type:

AbstractAsyncContextManager[TypeVar(DriverT, bound= SyncDriverAdapterBase | AsyncDriverAdapterBase)]

async create_pool()[source]#

Create and return connection pool.

Return type:

None

async close_pool()[source]#

Terminate the connection pool.

Return type:

None

provide_pool(*args, **kwargs)[source]#

Provide pool instance.

Return type:

None

Extension Configuration Types#

class sqlspec.config.LifecycleConfig[source]#

Bases: TypedDict

Lifecycle hooks for database adapters.

Each hook accepts a list of callables to support multiple handlers.

class sqlspec.config.MigrationConfig[source]#

Bases: TypedDict

Configuration options for database migrations.

All fields are optional with default values.

script_location: NotRequired[str | Path]#

Path to the migrations directory. Accepts string or Path object. Defaults to 'migrations'.

version_table_name: NotRequired[str]#

Name of the table used to track applied migrations. Defaults to 'ddl_migrations'.

default_schema: NotRequired[str]#

Schema applied to migration sessions before user migration SQL runs, when supported by the adapter. Can be overridden on individual migration files via the -- schema: <name> directive.

version_table_schema: NotRequired[str]#

Schema that stores the migration tracking table. Defaults to default_schema when omitted.

project_root: NotRequired[str]#

Path to the project root directory. Used for relative path resolution.

author: NotRequired[str]#

Author recorded on generated migration files. Defaults to the detected git user.

enabled: NotRequired[bool]#

Whether this configuration should be included in CLI operations. Defaults to True.

auto_sync: NotRequired[bool]#

Enable automatic version reconciliation during upgrade. When enabled (default), SQLSpec automatically updates database tracking when migrations are renamed from timestamp to sequential format. Defaults to True.

strict_ordering: NotRequired[bool]#

Enforce strict migration ordering. When enabled, prevents out-of-order migrations from being applied. Defaults to False.

include_extensions: NotRequired[list[str]]#

List of extension names whose migrations should be included. Extension migrations maintain separate versioning and are prefixed with 'ext_{name}_'.

Note: Extensions with migration support (litestar, adk, events) are auto-included when their settings are present in extension_config, as is any extension whose settings declare migrations_path. Use exclude_extensions to opt out.

exclude_extensions: NotRequired[list[str]]#

List of extension names to exclude from automatic migration inclusion.

When an extension is configured in extension_config, its migrations are automatically included. Use this to prevent that for specific extensions:

transactional: NotRequired[bool]#

false' comment.

Type:

Wrap migrations in transactions when supported. When enabled (default for adapters that support it), each migration runs in a transaction that is committed on success or rolled back on failure. This prevents partial migrations from leaving the database in an inconsistent state. Requires adapter support for transactional DDL. Defaults to True for PostgreSQL, SQLite, and DuckDB; False for MySQL, Oracle, and BigQuery. Individual migrations can override this with a '-- transactional

use_logger: NotRequired[bool]#

Use Python logger instead of Rich console for migration output.

When True, migration progress is logged via structlog/logging instead of being printed to the console with Rich formatting. This is useful for programmatic usage where console output is not desired.

Can be overridden per-call via the use_logger parameter on migrate_up() and migrate_down() methods.

Defaults to False (Rich console output).

echo: NotRequired[bool]#

Echo migration output to the console.

When False, console output is suppressed. This is useful for script or CI environments that need quiet stdout.

Defaults to True.

summary_only: NotRequired[bool]#

Emit a single summary log entry for migration commands.

When True and use_logger is enabled, per-migration output is suppressed in favor of a single structured summary log event.

Defaults to False.

default_format: NotRequired[Literal['sql', 'py']]#

File format used by create-migration when none is requested. Defaults to 'sql'.

title: NotRequired[str]#

Title rendered into generated migration files. Defaults to 'SQLSpec Migration'.

templates: NotRequired[MigrationTemplates]#

Template fragment overrides applied when generating migration files.

class sqlspec.config.MigrationTemplates[source]#

Bases: TypedDict

Template overrides applied when generating migration files.

Placeholders available to every fragment: title, version, message, description, created_at, author, adapter, and project_slug.

sql: NotRequired[SQLTemplateOverride]#

Overrides for generated .sql migrations.

py: NotRequired[PythonTemplateOverride]#

Overrides for generated .py migrations.

title: NotRequired[str]#

Title used when MigrationConfig.title is omitted.

class sqlspec.config.SQLTemplateOverride[source]#

Bases: TypedDict

Overrides for the SQL migration template.

header: NotRequired[str]#

First line of the generated file. Supports the migration template placeholders.

metadata: NotRequired[list[str]]#

Comment lines rendered beneath the header.

body: NotRequired[str]#

Migration body containing the up and down named statements.

description_key: NotRequired[str | list[str]]#

Metadata label(s) the description is read back from. Defaults to 'Description'.

class sqlspec.config.PythonTemplateOverride[source]#

Bases: TypedDict

Overrides for the Python migration template.

docstring: NotRequired[str]#

Module docstring contents. Supports the migration template placeholders.

body: NotRequired[str]#

Module body defining the up and down functions.

imports: NotRequired[list[str]]#

Import lines rendered between the docstring and the body.

description_key: NotRequired[str | list[str]]#

Docstring label(s) the description is read back from. Defaults to 'Description'.

class sqlspec.config.EventsConfig[source]#

Bases: TypedDict

Configuration options for the events extension.

Use in extension_config["events"].

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 in migration_config["include_extensions"].

manage_schema: NotRequired[bool]#

True.

Type:

Apply additive target-schema reconciliation. Default

create_schema: NotRequired[bool]#

True.

Type:

Create the queue table during managed reconciliation. Default

backend: NotRequired[Literal['notify', 'notify_queue', 'poll_queue', 'aq', 'txeventq']]#

Backend implementation. PostgreSQL adapters default to 'notify', others to 'poll_queue'.

  • notify: Transient PostgreSQL LISTEN/NOTIFY wakeup; not a durable event ledger

  • notify_queue: Durable table queue with PostgreSQL LISTEN/NOTIFY wakeups

  • poll_queue: Durable table queue discovered by polling

  • aq: Oracle Advanced Queuing

  • txeventq: Oracle Transactional Event Queues

queue_table: NotRequired[str]#

Name of the fallback queue table. Defaults to 'sqlspec_event_queue'.

lease_seconds: NotRequired[int]#

Lease duration for claimed events before they can be retried. Defaults to 30 seconds.

retention_seconds: NotRequired[int]#

Retention window for acknowledged events before cleanup. Defaults to 86400 (24 hours).

poll_interval: NotRequired[float]#

Compatibility alias for event_poll_interval. Defaults to 1.0.

event_poll_interval: NotRequired[float]#

Durable event reconciliation interval in seconds. Takes precedence over poll_interval.

select_for_update: NotRequired[bool]#

Use SELECT FOR UPDATE locking when claiming events. Defaults to False.

skip_locked: NotRequired[bool]#

Use SKIP LOCKED for non-blocking event claims. Defaults to False.

class sqlspec.config.OpenTelemetryConfig[source]#

Bases: TypedDict

Configuration options for OpenTelemetry integration.

Use in extension_config["otel"].

enabled: NotRequired[bool]#

True.

Type:

Enable the extension. Default

enable_spans: NotRequired[bool]#

Enable span emission (set False to disable while keeping other settings).

resource_attributes: NotRequired[dict[str, Any]]#

Additional resource attributes passed to the tracer provider factory.

tracer_provider: NotRequired[Any]#

Tracer provider instance to reuse. Mutually exclusive with tracer_provider_factory.

tracer_provider_factory: NotRequired[Callable[[], Any]]#

Factory returning a tracer provider. Invoked lazily when spans are needed.

class sqlspec.config.PrometheusConfig[source]#

Bases: TypedDict

Configuration options for Prometheus metrics.

Use in extension_config["prometheus"].

enabled: NotRequired[bool]#

True.

Type:

Enable the extension. Default

namespace: NotRequired[str]#

"sqlspec".

Type:

Prometheus metric namespace. Default

subsystem: NotRequired[str]#

"driver".

Type:

Prometheus metric subsystem. Default

registry: NotRequired[Any]#

Custom Prometheus registry (defaults to the global registry).

label_names: NotRequired[tuple[str, ...]]#

("driver", "operation").

Type:

Labels applied to metrics. Default

duration_buckets: NotRequired[tuple[float, ...]]#

Histogram buckets for query duration (seconds).

class sqlspec.config.ADKConfig[source]#

Bases: TypedDict

Configuration options for ADK session and memory store extension.

All fields are optional with sensible defaults. Use in extension_config["adk"]:

Configuration supports three deployment scenarios:
  1. SQLSpec manages everything (runtime + migrations)

  2. SQLSpec runtime only (external migration tools like Alembic/Flyway)

  3. Selective features (sessions OR memory, not both)

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 in migration_config["include_extensions"].

manage_schema: NotRequired[bool]#

True.

Type:

Apply additive target-schema reconciliation. Default

create_schema: NotRequired[bool]#

True.

Type:

Create missing ADK tables during managed reconciliation. Default

enable_sessions: NotRequired[bool]#

True.

When False the session service is unavailable, session store operations are disabled, and packaged ADK migrations emit no session, event, state, or metadata DDL.

Type:

Enable the session store at runtime and in packaged migrations. Default

enable_memory: NotRequired[bool]#

True.

When False the memory service is unavailable, memory store operations are disabled, and packaged ADK migrations emit no memory table DDL or PostgreSQL vector extension statement.

Type:

Enable the memory store at runtime and in packaged migrations. Default

session_table: NotRequired[str]#

'adk_session'

Type:

Name of the sessions table. Default

events_table: NotRequired[str]#

'adk_event'

Type:

Name of the events table. Default

app_state_table: NotRequired[str]#

'adk_app_state'

Type:

Name of the app-scoped state table. Default

user_state_table: NotRequired[str]#

'adk_user_state'

Type:

Name of the user-scoped state table. Default

metadata_table: NotRequired[str]#

'adk_internal_metadata'

Type:

Name of the internal metadata table. Default

memory_table: NotRequired[str]#

'adk_memory'

Type:

Name of the memory entries table. Default

artifact_table: NotRequired[str]#

'adk_artifact'

Type:

Name of the artifact metadata table. Default

artifact_storage_uri: NotRequired[str]#

Base URI for artifact content storage.

Points to a sqlspec/storage/ backend where artifact binary content is stored. Can be a direct URI (s3://bucket/path, file:///path) or a registered alias in the storage registry.

memory_use_fts: NotRequired[bool]#

False.

When True, adapters will use their native FTS capabilities where available: - PostgreSQL: to_tsvector/to_tsquery with GIN index - SQLite: FTS5 virtual table - DuckDB: FTS extension with match_bm25 - Oracle: CONTAINS() with CTXSYS.CONTEXT index - Spanner: TOKENIZE_FULLTEXT with search index - MySQL: MATCH...AGAINST with FULLTEXT index

When False, adapters use simple LIKE/ILIKE queries (works without indexes).

Type:

Enable full-text search when supported. Default

memory_max_results: NotRequired[int]#

Limits the number of memory entries returned by search_memory(). Can be overridden per-query via the limit parameter.

Type:

Maximum number of results for memory search queries. Default

owner_id_column: NotRequired[str]#

Optional owner ID column definition to link sessions/memories to a user, tenant, team, or other entity.

Format: "column_name TYPE [NOT NULL] REFERENCES table(column) [options...]"

The entire definition is passed through to DDL verbatim. We only parse the column name (first word) for use in INSERT/SELECT statements.

This column is added to both session and memory tables for consistent multi-tenant isolation.

Supports:
  • Foreign key constraints: REFERENCES table(column)

  • Nullable or NOT NULL

  • CASCADE options: ON DELETE CASCADE, ON UPDATE CASCADE

  • Dialect-specific options (DEFERRABLE, ENABLE VALIDATE, etc.)

  • Plain columns without FK (just extra column storage)

Framework Configuration Types#

class sqlspec.config.LitestarConfig[source]#

Bases: TypedDict

Configuration 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 in migration_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 database connections, pools, and sessions, or the per-request handler that commits and closes request connections. Pool startup and shutdown follow manage_lifespan, which defaults to False when disable_di is True.

Type:

Disable built-in dependency injection. Default

manage_lifespan: NotRequired[bool]#

the inverse of disable_di. When True, the Litestar plugin creates the configuration's pool on application startup, stores it in application state under pool_key, and closes it on shutdown, whether or not disable_di is set. Set to True alongside disable_di=True to keep pool lifecycle management while another DI solution provides connections and sessions. When False, the application creates and closes the pool itself; with dependency injection enabled, the plugin's providers still read the pool from application state under pool_key.

Type:

Register the plugin's pool lifespan handler. Default

enable_sqlcommenter_middleware: NotRequired[bool]#

True. When the driver's StatementConfig has enable_sqlcommenter=True, the middleware is registered automatically. Set to False to 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

class sqlspec.config.FastAPIConfig[source]#

Bases: StarletteConfig

Configuration options for FastAPI SQLSpec extension.

All fields are optional with sensible defaults. Use in extension_config["fastapi"]. SQLCommenter defaults the framework attribute to "fastapi".

class sqlspec.config.StarletteConfig[source]#

Bases: TypedDict

Configuration options for Starlette SQLSpec extension.

All fields are optional with sensible defaults. Use in extension_config["starlette"]:

connection_key: NotRequired[str]#

'db_connection'

Type:

Key for storing connection in request.state. Default

pool_key: NotRequired[str]#

'db_pool'

Type:

Key for storing connection pool in app.state. Default

session_key: NotRequired[str]#

'db_session'

Type:

Key for storing session in request.state. Default

commit_mode: NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]#

'manual'

  • manual: No automatic commit/rollback

  • autocommit: Commit on 2xx, rollback otherwise

  • autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise

Type:

Transaction commit mode. 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 Starlette/FastAPI extension will not add middleware for managing database connections 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 StatementConfig has enable_sqlcommenter=True, the middleware is registered automatically. Set to False to explicitly disable middleware registration.

Type:

Control automatic SQLCommenter middleware registration. Default

sqlcommenter_framework: NotRequired[str]#

'starlette'. Set to 'fastapi' when using FastAPI.

Type:

Framework name for SQLCommenter attributes. Default

class sqlspec.config.SanicConfig[source]#

Bases: TypedDict

Configuration options for Sanic SQLSpec extension.

All fields are optional with sensible defaults. Use in extension_config["sanic"].

connection_key: NotRequired[str]#

'db_connection'

Type:

Key for storing connection in request.ctx. Default

pool_key: NotRequired[str]#

'db_pool'

Type:

Key for storing connection pool in app.ctx. Default

session_key: NotRequired[str]#

'db_session'

Type:

Key for storing session in request.ctx. Default

commit_mode: NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]#

'manual'

  • manual: No automatic commit/rollback

  • autocommit: Commit on 2xx, rollback otherwise

  • autocommit_include_redirect: Commit on 2xx-3xx, rollback otherwise

Type:

Transaction commit mode. 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 Sanic extension will not register request middleware for managing database connections and sessions. Users are responsible for managing the database lifecycle manually via their own DI solution.

Type:

Disable built-in dependency injection. Default

enable_correlation_middleware: NotRequired[bool]#

False.

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

enable_sqlcommenter_middleware: NotRequired[bool]#

True. When the driver's StatementConfig has enable_sqlcommenter=True, the middleware is registered automatically. Set to False to explicitly disable middleware registration.

Type:

Control automatic SQLCommenter middleware registration. Default

sqlcommenter_framework: NotRequired[str]#

'sanic'.

Type:

Framework name for SQLCommenter attributes. Default

class sqlspec.config.FlaskConfig[source]#

Bases: TypedDict

Configuration options for Flask SQLSpec extension.

All fields are optional with sensible defaults. Use in extension_config["flask"]:

connection_key: NotRequired[str]#

auto-generated from session_key.

Type:

Key for storing connection in Flask g object. Default

session_key: NotRequired[str]#

'db_session'.

Type:

Key for accessing session via plugin.get_session(). Default

commit_mode: NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]#

'manual'. - manual: No automatic commits, user handles explicitly - autocommit: Commits on 2xx status, rollback otherwise - autocommit_include_redirect: Commits on 2xx-3xx status, rollback otherwise

Type:

Transaction commit mode. Default

extra_commit_statuses: NotRequired[set[int]]#

None.

Type:

Additional HTTP status codes that trigger commit. Default

extra_rollback_statuses: NotRequired[set[int]]#

None.

Type:

Additional HTTP status codes that trigger rollback. Default

disable_di: NotRequired[bool]#

False. When True, the Flask extension will not register request hooks for managing database connections 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 StatementConfig has enable_sqlcommenter=True, request attributes are populated automatically. Set to False to explicitly disable this behavior.

Type:

Control automatic SQLCommenter context population. Default

Extension Configuration Map#

Validation Utilities#

sqlspec.config.validate_migration_config_keys(migration_config)[source]#

Reject migration configuration keys that SQLSpec does not read.

Parameters:

migration_config (Mapping[str, typing.Any]) -- Migration configuration mapping to check.

Raises:

ImproperConfigurationError -- If the mapping contains an unrecognized key.

Return type:

None

Type Variables#

sqlspec.config.SyncConfigT = ~SyncConfigT#

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

sqlspec.config.AsyncConfigT = ~AsyncConfigT#

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

sqlspec.config.ConfigT = ~ConfigT#

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

sqlspec.config.DriverT = ~DriverT#

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, classes, and type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bound and constrained type variables:

# S is a TypeVar bound to str
class StrSequence[S: str]:
    ...

# A is a TypeVar constrained to str or bytes
class StrOrBytesSequence[A: (str, bytes)]:
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax and when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.