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 interface for database configurations.
- storage_capabilities()[source]¶
Return cached storage capabilities for this configuration.
- Return type:
- get_event_runtime_hints()[source]¶
Return default event runtime hints for this configuration.
- Return type:
- attach_observability(registry_config)[source]¶
Attach merged observability runtime composed from registry and adapter overrides.
- Return type:
- get_observability_runtime()[source]¶
Return the attached runtime, creating a disabled instance when missing.
- Return type:
- 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 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.
- 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:
- Returns:
SQLFileLoader instance with migration files loaded.
- 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:
- 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:
- abstractmethod init_migrations(directory=None, package=True)[source]¶
Initialize migration directory structure.
- abstractmethod stamp_migration(revision)[source]¶
Mark database as being at a specific revision without running migrations.
- 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.
SyncDatabaseConfig¶
- class sqlspec.config.SyncDatabaseConfig[source]¶
Bases:
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.
- 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)]
- 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.
- 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.use_logger¶ (
bool) – Use Python logger instead of Rich console for output.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:
- stamp_migration(revision)[source]¶
Mark database as being at a specific revision without running migrations.
AsyncDatabaseConfig¶
- class sqlspec.config.AsyncDatabaseConfig[source]¶
Bases:
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.
- 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 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.
- async 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.use_logger¶ (
bool) – Use Python logger instead of Rich console for output.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:
- async init_migrations(directory=None, package=True)[source]¶
Initialize migration directory structure.
- async stamp_migration(revision)[source]¶
Mark database as being at a specific revision without running migrations.
NoPoolSyncConfig¶
- class sqlspec.config.NoPoolSyncConfig[source]¶
Bases:
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]¶
- 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)]
- 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.
- 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.use_logger¶ (
bool) – Use Python logger instead of Rich console for output.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:
- stamp_migration(revision)[source]¶
Mark database as being at a specific revision without running migrations.
NoPoolAsyncConfig¶
- class sqlspec.config.NoPoolAsyncConfig[source]¶
Bases:
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]¶
- 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 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.
- async 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.use_logger¶ (
bool) – Use Python logger instead of Rich console for output.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:
- async init_migrations(directory=None, package=True)[source]¶
Initialize migration directory structure.
- async stamp_migration(revision)[source]¶
Mark database as being at a specific revision without running migrations.
Extension Configuration Types¶
- class sqlspec.config.LifecycleConfig[source]¶
Bases:
TypedDictLifecycle hooks for database adapters.
Each hook accepts a list of callables to support multiple handlers.
- class sqlspec.config.MigrationConfig[source]¶
Bases:
TypedDictConfiguration 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’.
-
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. Useexclude_extensionsto 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:Example
- migration_config={
“exclude_extensions”: [“events”] # Use ephemeral listen_notify, skip queue table
}
-
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 (e.g., in tests, automated scripts, or production deployments with structured logging).
Can be overridden per-call via the
use_loggerparameter onmigrate_up()andmigrate_down()methods.Defaults to False (Rich console output).
-
script_location:
- class sqlspec.config.EventsConfig[source]¶
Bases:
TypedDictConfiguration 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
-
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.
-
backend:
- class sqlspec.config.OpenTelemetryConfig[source]¶
Bases:
TypedDictConfiguration options for OpenTelemetry integration.
Use in
extension_config["otel"].-
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.
-
enable_spans:
- class sqlspec.config.PrometheusConfig[source]¶
Bases:
TypedDictConfiguration options for Prometheus metrics.
Use in
extension_config["prometheus"].
- class sqlspec.config.ADKConfig[source]¶
Bases:
TypedDictConfiguration 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)
Example
from sqlspec.adapters.asyncpg import AsyncpgConfig
- config = AsyncpgConfig(
connection_config={“dsn”: “postgresql://localhost/mydb”}, extension_config={
- “adk”: {
“session_table”: “my_sessions”, “events_table”: “my_events”, “memory_table”: “my_memories”, “memory_use_fts”: True, “owner_id_column”: “tenant_id INTEGER REFERENCES tenants(id)”
}
}
)
Notes
This TypedDict provides type safety for extension config but is not required. You can use plain dicts as well.
-
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’
Examples
“agent_sessions” “my_app_sessions” “tenant_acme_sessions”
- Type:
Name of the sessions table. Default
-
events_table:
NotRequired[str]¶ ‘adk_events’
Examples
“agent_events” “my_app_events” “tenant_acme_events”
- Type:
Name of the events table. Default
-
memory_table:
NotRequired[str]¶ ‘adk_memory_entries’
Examples
“agent_memories” “my_app_memories” “tenant_acme_memories”
- Type:
Name of the memory entries table. Default
-
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 - BigQuery: SEARCH() function (requires search 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)
Examples
- PostgreSQL with UUID FK:
“account_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE”
- MySQL with BIGINT FK:
“user_id BIGINT NOT NULL REFERENCES users(id) ON DELETE RESTRICT”
- Oracle with NUMBER FK:
“user_id NUMBER(10) REFERENCES users(id) ENABLE VALIDATE”
- SQLite with INTEGER FK:
“tenant_id INTEGER NOT NULL REFERENCES tenants(id)”
- Nullable FK (optional relationship):
“workspace_id UUID REFERENCES workspaces(id) ON DELETE SET NULL”
- No FK (just extra column):
“organization_name VARCHAR(128) NOT NULL”
- Deferred constraint (PostgreSQL):
“user_id UUID REFERENCES users(id) DEFERRABLE INITIALLY DEFERRED”
Notes
Column name (first word) is extracted for INSERT/SELECT queries
Rest of definition is passed through to CREATE TABLE DDL
Database validates the DDL syntax (fail-fast on errors)
Works with all database dialects (PostgreSQL, MySQL, SQLite, Oracle, etc.)
-
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.
Examples
- Oracle with in-memory enabled:
- config = OracleAsyncConfig(
connection_config={“dsn”: “oracle://…”}, extension_config={
- “adk”: {
“in_memory”: True
}
}
)
Notes
Improves query performance for analytics (10-100x faster)
Tables created with INMEMORY clause
Requires Oracle Database In-Memory option license
Ignored by non-Oracle adapters
- 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 (e.g., Spanner columnar/tiered storage). Ignored by adapters without table OPTIONS support.
-
events_table_options:
NotRequired[str]¶ Adapter-specific table OPTIONS/clauses for the events table.