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.

Returns:

MigrationCommands instance configured for this database.

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

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

class sqlspec.config.EventsConfig[source]

Bases: TypedDict

Configuration options for the events extension.

Use in extension_config["events"].

backend: NotRequired[Literal['listen_notify', 'table_queue', 'listen_notify_durable', 'advanced_queue']]

Backend implementation. PostgreSQL adapters default to 'listen_notify', others to 'table_queue'.

  • listen_notify: Real-time PostgreSQL LISTEN/NOTIFY (ephemeral)

  • table_queue: Durable table-backed queue with retries (all adapters)

  • listen_notify_durable: Hybrid combining both (PostgreSQL only)

  • advanced_queue: Oracle Advanced Queueing

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]

Default poll interval in seconds for event consumers. Defaults to 1.0.

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.

json_passthrough: NotRequired[bool]

Skip JSON encoding/decoding for payloads. Defaults to False.

in_memory: NotRequired[bool]

Enable Oracle INMEMORY clause for the queue table. Ignored by other adapters. Defaults to False.

Note: To skip events migrations, use migration_config={"exclude_extensions": ["events"]}.

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)

enable_sessions: NotRequired[bool]

True.

When False: session service unavailable, session store operations disabled. Independent of migration control - can use externally-managed tables.

Type:

Enable session store at runtime. Default

enable_memory: NotRequired[bool]

True.

When False: memory service unavailable, memory store operations disabled. Independent of migration control - can use externally-managed tables.

Type:

Enable memory store at runtime. Default

include_sessions_migration: NotRequired[bool]

True.

When False: session migration DDL skipped (use external migration tools). Decoupled from enable_sessions - allows external table management with SQLSpec runtime.

Type:

Include session tables in SQLSpec migrations. Default

include_memory_migration: NotRequired[bool]

True.

When False: memory migration DDL skipped (use external migration tools). Decoupled from enable_memory - allows external table management with SQLSpec runtime.

Type:

Include memory tables in SQLSpec migrations. Default

session_table: NotRequired[str]

'adk_sessions'

Type:

Name of the sessions table. Default

events_table: NotRequired[str]

'adk_events'

Type:

Name of the events table. Default

memory_table: NotRequired[str]

'adk_memory_entries'

Type:

Name of the memory entries table. Default

artifact_table: NotRequired[str]

'adk_artifact_versions'

Type:

Name of the artifact versions 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)

in_memory: NotRequired[bool]

False.

When enabled, tables are created with the INMEMORY clause for Oracle Database, which stores table data in columnar format in memory for faster query performance.

This is an Oracle-specific feature that requires:
  • Oracle Database 12.1.0.2 or higher

  • Database In-Memory option license (Enterprise Edition)

  • Sufficient INMEMORY_SIZE configured in the database instance

Other database adapters ignore this setting.

Type:

Enable in-memory table storage (Oracle-specific). Default

shard_count: NotRequired[int]

Optional hash shard count for session/event tables to reduce hotspotting.

When set (>1), adapters that support computed shard columns will create a generated shard_id using MOD(FARM_FINGERPRINT(primary_key), shard_count) and include it in the primary key and filters. Ignored by adapters that do not support computed shards.

session_table_options: NotRequired[str]

Adapter-specific table OPTIONS/clauses for the sessions table.

Passed verbatim when supported. Ignored by adapters without table OPTIONS support.

events_table_options: NotRequired[str]

Adapter-specific table OPTIONS/clauses for the events table.

memory_table_options: NotRequired[str]

Adapter-specific table OPTIONS/clauses for the memory table.

expires_index_options: NotRequired[str]

Adapter-specific options for the expires/index used in ADK stores.

fts_language: NotRequired[str]

'english'.

Controls the language dictionary/stemmer for FTS implementations:
  • PostgreSQL: to_tsvector/to_tsquery language parameter

  • SQLite FTS5: tokenizer language for unicode61/porter

  • MySQL: FULLTEXT parser language (with ngram for CJK on 5.7.6+)

  • Oracle: CTXSYS.CONTEXT lexer language

  • Spanner: TOKENIZE_FULLTEXT language parameter

  • DuckDB: FTS stemmer language

Only takes effect when memory_use_fts is True.

Common values: 'english', 'simple', 'german', 'french', 'spanish', 'portuguese', 'italian', 'dutch', 'russian', 'chinese', 'japanese', 'korean'.

Type:

Language configuration for full-text search indexing. Default

schema_version: NotRequired[int]

None (auto-detect).

When set, locks the ADK schema to a specific version. This is useful for: - Preventing automatic schema upgrades in production - Pinning to a known-good schema during testing - Coordinating schema changes across multiple application instances

When None, the ADK extension auto-detects the current schema version and applies any pending upgrades during initialization.

Type:

Explicit schema version for ADK tables. Default

partitioning: NotRequired[ADKPartitionConfig]

None (no partitioning).

Controls how ADK tables are partitioned for improved query performance and data management at scale. See ADKPartitionConfig for options.

Supported by: PostgreSQL, MySQL 8+, Oracle, Spanner. Ignored by: SQLite, DuckDB.

Type:

Table partitioning configuration. Default

retention: NotRequired[ADKRetentionConfig]

None (no automatic cleanup).

Controls automatic expiry and cleanup of old session, event, and memory data. See ADKRetentionConfig for options.

Backends with native TTL (CockroachDB, Spanner) use database-level enforcement. Others fall back to application-level sweep queries.

Type:

Data retention and TTL configuration. Default

compression: NotRequired[ADKCompressionConfig]

None (no compression).

Controls table-level compression for ADK tables. See ADKCompressionConfig for options.

Type:

Table compression configuration. Default

sqlite_optimization: NotRequired[ADKSqliteOptimizationConfig]

None (SQLite defaults).

Controls SQLite performance tuning parameters. Ignored by non-SQLite adapters. See ADKSqliteOptimizationConfig for options.

Type:

SQLite-specific PRAGMA optimization settings. Default