Configuration¶
from sqlspec.config import (
ADKConfig,
AsyncDatabaseConfig,
DatabaseConfigProtocol,
EventsConfig,
ExtensionConfigs,
FastAPIConfig,
FlaskConfig,
LifecycleConfig,
LitestarConfig,
MigrationConfig,
NoPoolAsyncConfig,
NoPoolSyncConfig,
OpenTelemetryConfig,
PrometheusConfig,
SanicConfig,
StarletteConfig,
SyncDatabaseConfig,
)
Base configuration protocols, pooled and non-pooled database config classes, lifecycle hooks, migration settings, and typed extension_config dictionaries. See the Databases and Integrations guides for concrete examples.
Base Configuration Classes¶
DatabaseConfigProtocol
¶
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.
provide_connection
¶
Provide a database connection context manager.
set_migration_config
¶
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:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
dict[str, Any] | MigrationConfig
|
Migration configuration dictionary. |
required |
attach_observability
¶
Attach merged observability runtime composed from registry and adapter overrides.
SyncDatabaseConfig
¶
Bases: _SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]
Base class for sync database configurations with connection pooling.
AsyncDatabaseConfig
¶
Bases: _AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, PoolT, DriverT]
Base class for async database configurations with connection pooling.
NoPoolSyncConfig
¶
Bases: _SyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]
Base class for sync database configurations that do not implement a pool.
NoPoolAsyncConfig
¶
Bases: _AsyncMigrationMixin, DatabaseConfigProtocol[ConnectionT, None, DriverT]
Base class for async database configurations that do not implement a pool.
Lifecycle & Migration Settings¶
LifecycleConfig
¶
Bases: TypedDict
Lifecycle callback hooks for database adapters.
Each hook accepts a list of callables to support multiple handlers.
Attributes:
| Name | Type | Description |
|---|---|---|
on_connection_create |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked immediately after a raw driver connection is established. |
on_connection_destroy |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked before closing or destroying a driver connection. |
on_pool_create |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked after the adapter connection pool is initialized. |
on_pool_destroying |
NotRequired[list[Callable[[Any], Any]]]
|
Callbacks invoked immediately before shutting down the connection pool. |
on_pool_destroy |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked after the connection pool has finished closing. |
on_session_start |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked when a driver session context begins. |
on_session_end |
NotRequired[list[Callable[[Any], None]]]
|
Callbacks invoked when a driver session context exits. |
on_query_start |
NotRequired[list[Callable[[str, dict[str, Any]], None]]]
|
Callbacks invoked before statement execution with a |
on_query_complete |
NotRequired[list[Callable[[str, dict[str, Any], Any], None]]]
|
Callbacks invoked on completion with a |
on_error |
NotRequired[list[Callable[[Exception, str, dict[str, Any]], None]]]
|
Callbacks invoked on query failure with a |
MigrationConfig
¶
Bases: TypedDict
Configuration options for database migrations.
All fields are optional with default values.
Attributes:
| Name | Type | Description |
|---|---|---|
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. |
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}_'. |
exclude_extensions |
NotRequired[list[str]]
|
List of extension names to exclude from automatic migration inclusion. |
transactional |
NotRequired[bool]
|
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: false' comment. |
use_logger |
NotRequired[bool]
|
Use Python logger instead of Rich console for migration output. |
echo |
NotRequired[bool]
|
Echo migration output to the console. |
summary_only |
NotRequired[bool]
|
Emit a single summary log entry for migration commands. |
default_format |
NotRequired[Literal['sql', 'py']]
|
File format used by |
title |
NotRequired[str]
|
Title rendered into generated migration files. Defaults to 'SQLSpec Migration'. |
templates |
NotRequired[MigrationTemplates]
|
Template fragment overrides applied when generating migration files. |
MigrationTemplates
¶
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.
Attributes:
| Name | Type | Description |
|---|---|---|
sql |
NotRequired[SQLTemplateOverride]
|
Overrides for generated |
py |
NotRequired[PythonTemplateOverride]
|
Overrides for generated |
title |
NotRequired[str]
|
Title used when |
PythonTemplateOverride
¶
Bases: TypedDict
Overrides for the Python migration template.
Attributes:
| Name | Type | Description |
|---|---|---|
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'. |
SQLTemplateOverride
¶
Bases: TypedDict
Overrides for the SQL migration template.
Attributes:
| Name | Type | Description |
|---|---|---|
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'. |
validate_migration_config_keys
¶
Reject migration configuration keys that SQLSpec does not read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
migration_config
|
Mapping[str, Any]
|
Migration configuration mapping to check. |
required |
Raises:
| Type | Description |
|---|---|
ImproperConfigurationError
|
If the mapping contains an unrecognized key. |
Extension Configuration Schemas¶
Top-level extension_config mapping passed to any database configuration class. LitestarConfig and ADKConfig are documented on their respective extension pages.
ExtensionConfigs: TypeAlias = dict[str, dict[str, Any] | LitestarConfig | FastAPIConfig | StarletteConfig | SanicConfig | FlaskConfig | ADKConfig | EventsConfig | OpenTelemetryConfig | PrometheusConfig]
¶
EventsConfig
¶
Bases: TypedDict
Configuration options for the events extension.
Use in extension_config["events"].
Attributes:
| Name | Type | Description |
|---|---|---|
migrations_path |
NotRequired[str | Path]
|
Directory containing this extension's migrations, or a |
manage_schema |
NotRequired[bool]
|
Apply additive target-schema reconciliation. Default: True. |
create_schema |
NotRequired[bool]
|
Create the queue table during managed reconciliation. Default: True. |
backend |
NotRequired[Literal['notify', 'notify_queue', 'poll_queue', 'aq', 'txeventq']]
|
Backend implementation. PostgreSQL adapters default to 'notify', others to 'poll_queue'. |
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. |
shard_count |
NotRequired[int]
|
Number of hash shards for queue table and index prefixing (e.g. Cloud Spanner). Defaults to 1. |
FastAPIConfig
¶
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".
StarletteConfig
¶
Bases: TypedDict
Configuration options for Starlette SQLSpec extension.
All fields are optional with sensible defaults. Use in extension_config["starlette"]:
Attributes:
| Name | Type | Description |
|---|---|---|
connection_key |
NotRequired[str]
|
Key for storing connection in request.state. Default: 'db_connection' |
pool_key |
NotRequired[str]
|
Key for storing connection pool in app.state. Default: 'db_pool' |
session_key |
NotRequired[str]
|
Key for storing session in request.state. Default: 'db_session' |
commit_mode |
NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]
|
Transaction commit mode. Default: 'manual' |
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. |
enable_sqlcommenter_middleware |
NotRequired[bool]
|
Control automatic SQLCommenter middleware registration. Default: True. |
sqlcommenter_framework |
NotRequired[str]
|
Framework name for SQLCommenter attributes. Default: 'starlette'. |
FlaskConfig
¶
Bases: TypedDict
Configuration options for Flask SQLSpec extension.
All fields are optional with sensible defaults. Use in extension_config["flask"]:
Attributes:
| Name | Type | Description |
|---|---|---|
connection_key |
NotRequired[str]
|
Key for storing connection in Flask g object. Default: auto-generated from session_key. |
session_key |
NotRequired[str]
|
Key for accessing session via plugin.get_session(). Default: 'db_session'. |
commit_mode |
NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]
|
Transaction commit mode. Default: 'manual'. |
extra_commit_statuses |
NotRequired[set[int]]
|
Additional HTTP status codes that trigger commit. Default: None. |
extra_rollback_statuses |
NotRequired[set[int]]
|
Additional HTTP status codes that trigger rollback. Default: None. |
disable_di |
NotRequired[bool]
|
Disable built-in dependency injection. Default: False. |
enable_sqlcommenter_middleware |
NotRequired[bool]
|
Control automatic SQLCommenter context population. Default: True. |
SanicConfig
¶
Bases: TypedDict
Configuration options for Sanic SQLSpec extension.
All fields are optional with sensible defaults. Use in extension_config["sanic"].
Attributes:
| Name | Type | Description |
|---|---|---|
connection_key |
NotRequired[str]
|
Key for storing connection in request.ctx. Default: 'db_connection' |
pool_key |
NotRequired[str]
|
Key for storing connection pool in app.ctx. Default: 'db_pool' |
session_key |
NotRequired[str]
|
Key for storing session in request.ctx. Default: 'db_session' |
commit_mode |
NotRequired[Literal['manual', 'autocommit', 'autocommit_include_redirect']]
|
Transaction commit mode. Default: 'manual' |
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. |
enable_correlation_middleware |
NotRequired[bool]
|
Enable request correlation ID middleware. Default: False. |
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. |
enable_sqlcommenter_middleware |
NotRequired[bool]
|
Control automatic SQLCommenter middleware registration. Default: True. |
sqlcommenter_framework |
NotRequired[str]
|
Framework name for SQLCommenter attributes. Default: 'sanic'. |
OpenTelemetryConfig
¶
Bases: TypedDict
Configuration options for OpenTelemetry integration.
Use in extension_config["otel"].
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
NotRequired[bool]
|
Enable the extension. Default: True. |
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 |
NotRequired[Callable[[], Any]]
|
Factory returning a tracer provider. Invoked lazily when spans are needed. |
PrometheusConfig
¶
Bases: TypedDict
Configuration options for Prometheus metrics.
Use in extension_config["prometheus"].
Attributes:
| Name | Type | Description |
|---|---|---|
enabled |
NotRequired[bool]
|
Enable the extension. Default: True. |
namespace |
NotRequired[str]
|
Prometheus metric namespace. Default: |
subsystem |
NotRequired[str]
|
Prometheus metric subsystem. Default: |
registry |
NotRequired[Any]
|
Custom Prometheus registry (defaults to the global registry). |
label_names |
NotRequired[tuple[str, ...]]
|
Labels applied to metrics. Default: ("driver", "operation"). |
duration_buckets |
NotRequired[tuple[float, ...]]
|
Histogram buckets for query duration (seconds). |