Skip to content

Configuration

from sqlspec.config import (
    AsyncDatabaseConfig,
    DatabaseConfigProtocol,
    EventsConfig,
    ExtensionConfigs,
    FastAPIConfig,
    FlaskConfig,
    LifecycleConfig,
    MigrationConfig,
    MigrationTemplates,
    NoPoolAsyncConfig,
    NoPoolSyncConfig,
    OpenTelemetryConfig,
    PrometheusConfig,
    ReplicaGroup,
    PythonTemplateOverride,
    SanicConfig,
    SQLTemplateOverride,
    StarletteConfig,
    SyncDatabaseConfig,
    validate_migration_config_keys,
)

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.

create_connection

create_connection()

Create and return a new database connection.

provide_connection

provide_connection(*args, **kwargs)

Provide a database connection context manager.

provide_session

provide_session(*args, **kwargs)

Provide a database session context manager.

provide_replica_connection

provide_replica_connection(*args, replica_group=None, **kwargs)

Provide a replica connection, honoring scoped primary pins.

provide_replica_session

provide_replica_session(
    *args,
    replica_group=None,
    statement_config=None,
    tenant=None,
    bypass_tenant=False,
    **kwargs,
)

Provide a replica session while retaining the selected config's tenant lease.

provide_routing_session

provide_routing_session(
    *,
    replica_group=None,
    statement_config=None,
    tenant=None,
    bypass_tenant=False,
)

Construct a lazy routing facade for this configuration.

Parameters:

Name Type Description Default
replica_group str | None

Replica group used for eligible reads.

None
statement_config StatementConfig | None

Statement configuration override.

None
tenant str | UUID | TenantContextPayload | None

Tenant identity or payload for physical checkouts.

None
bypass_tenant bool

Explicitly bypass tenant setup.

False

Returns:

Type Description
SyncRoutingSession[Any] | AsyncRoutingSession[Any]

A facade matching this configuration's execution mode.

derive_pool

derive_pool(
    *,
    connection_config_overrides=None,
    driver_features_overrides=None,
    statement_config=None,
    migration_config=None,
    extension_config=None,
    observability_config=None,
    bind_key=None,
    is_replica=False,
    **overrides,
)

Clone this configuration with overridden connection/pool or feature settings and connection_instance=None.

create_pool

create_pool()

Create and return connection pool.

close_pool

close_pool()

Terminate the connection pool.

provide_pool

provide_pool(*args, **kwargs)

Provide pool instance.

set_migration_config

set_migration_config(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_observability(registry_config)

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 receiving a single :data:~sqlspec.observability.LifecycleContext (dict[str, Any]) mapping containing the config key (plus bind_key and correlation_id when set) and event-specific payload keys.

Attributes:

Name Type Description
on_connection_create NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked after a raw driver connection is created (connection key).

on_connection_destroy NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked before closing or destroying a driver connection (connection key).

on_pool_create NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked after the adapter connection pool is initialized (pool key).

on_pool_destroying NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked immediately before shutting down the connection pool (pool key).

on_pool_destroy NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked after the connection pool has finished closing (pool key).

on_session_start NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked when a driver session context begins (session key).

on_session_end NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked when a driver session context exits (session key).

on_query_start NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked before statement execution with LifecycleContext keys sql, parameters, driver, operation, is_many, and is_script.

on_query_complete NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked on completion with LifecycleContext keys sql, parameters, driver, operation, is_many, is_script, and rows_affected.

on_error NotRequired[list[Callable[[dict[str, Any]], Any]]]

Callbacks invoked on query failure with LifecycleContext keys exception, sql, parameters, driver, operation, is_many, and is_script.

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.

verify_checksums NotRequired[bool]

Refuse upgrade and downgrade when an applied migration file no longer matches its recorded checksum. Defaults to True.

lock_lease_seconds NotRequired[int]

Lease length in seconds for migration locks on backends without a native session lock. Renewed before each migration, so it must exceed the longest single migration. Defaults to 900.

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

schema_dump_path NotRequired[str | Path | None]

Default file path written by dump_schema() when output_path is omitted.

auto_dump_schema NotRequired[bool | str | Path | None]

Automatically dump the current database schema after upgrade() applies migrations.

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 .sql migrations.

py NotRequired[PythonTemplateOverride]

Overrides for generated .py migrations.

title NotRequired[str]

Title used when MigrationConfig.title is omitted.

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

validate_migration_config_keys(migration_config)

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 '<dotted.module>:<subdir>' specification.

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

max_attempts NotRequired[int]

Maximum claims per event before nack marks it failed. Defaults to 5.

retry_backoff_seconds NotRequired[float]

Base delay for exponential redelivery backoff after nack. Defaults to 1.0.

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.

migration_mode NotRequired[ExtensionMigrationMode]

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

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
tenant_extractor NotRequired[Callable[[Any], Any]]

Trusted scope extractor returning a tenant payload, string, UUID, 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.

connection_key NotRequired[str]

Key for storing the connection in request.state once it is checked out on first access. 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: 'autocommit'

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

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.

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.

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
tenant_extractor NotRequired[Callable[..., TenantExtractorValue]]

Return the authorized tenant payload, string, UUID, or None (no tenant from this source) for the request. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start. Accepts zero arguments or the Flask request.

connection_key NotRequired[str]

Key for storing the connection in Flask g once it is checked out on first access. 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: 'autocommit'.

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.

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.

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.

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
tenant_extractor NotRequired[Callable[[Any], TenantExtractorValue | Awaitable[TenantExtractorValue]]]

Return the authorized tenant payload, string, UUID, or None (no tenant from this source), optionally as an awaitable. Requires tenant_strategy on the same configuration; called on first tenant use, never at request start.

connection_key NotRequired[str]

Key for storing the connection in request.ctx once it is checked out on first access. 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: 'autocommit'

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

enable_sqlcommenter_middleware NotRequired[bool]

Control automatic SQLCommenter middleware registration. Default: True.

sqlcommenter_framework NotRequired[str]

Framework name for SQLCommenter attributes. Default: 'sanic'.

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.

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.

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: "sqlspec".

subsystem NotRequired[str]

Prometheus metric subsystem. Default: "driver".

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

Read Replica Topology

ReplicaGroup

Bases: Generic[ConfigT]

Managed homogeneous replica pools with checkout-only failover.