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.configstays 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_configdirectly but provides a discoverable method for post-construction configuration.- Parameters:
config¶ (
dict[str, typing.Any] |MigrationConfig) -- Migration configuration dictionary.- Return type:
- 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.
- add_extension_migrations(name, migrations_path, settings=None)[source]#
Register migrations shipped by a package outside the
sqlspec.extensionsnamespace.Records the extension under
extension_config, opts it intomigration_config["include_extensions"], and rebuilds the cached migration commands so the extension is discovered. Migrations are versioned under theext_{name}_prefix, sonamemust stay stable once migrations are applied.- Parameters:
name¶ (
str) -- Extension name, used as theext_{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 undername.
- Return type:
- 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:
_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.
- 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.
- 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]#
- 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)]
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]#
- 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)]
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'.
- 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, as is any extension whose settings declaremigrations_path. 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:
- 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_loggerparameter onmigrate_up()andmigrate_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_loggeris enabled, per-migration output is suppressed in favor of a single structured summary log event.Defaults to False.
- class sqlspec.config.EventsConfig[source]#
Bases:
TypedDictConfiguration 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 inmigration_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
- run_migrations: NotRequired[bool]#
False.
- Type:
Run packaged versioned migrations when an integration supplies a runner. 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.
- in_memory: NotRequired[bool]#
Enable Oracle INMEMORY storage for the queue table when available.
Note: To skip events migrations, use
migration_config={"exclude_extensions": ["events"]}.
- partitioning: NotRequired[dict[str, Any]]#
Configure adapter-specific queue-table partitioning where supported.
- partition_expiration_days: NotRequired[int]#
Set BigQuery queue partition expiration in days.
- require_partition_filter: NotRequired[bool]#
Require partition filters for BigQuery queue queries.
- fillfactor: NotRequired[int]#
Set PostgreSQL-family queue-table fillfactor.
- autovacuum_vacuum_scale_factor: NotRequired[float]#
Set the PostgreSQL-family queue-table autovacuum vacuum scale factor.
- autovacuum_analyze_scale_factor: NotRequired[float]#
Set the PostgreSQL-family queue-table autovacuum analyze scale factor.
- pragma_profile: NotRequired[bool]#
False.
- Type:
Apply the SQLite extension-store PRAGMA profile. Default
- class sqlspec.config.OpenTelemetryConfig[source]#
Bases:
TypedDictConfiguration 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:
TypedDictConfiguration 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:
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:
SQLSpec manages everything (runtime + migrations)
SQLSpec runtime only (external migration tools like Alembic/Flyway)
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 inmigration_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
- run_migrations: NotRequired[bool]#
False.
- Type:
Run packaged versioned migrations when an integration supplies a runner. Default
- 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_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)