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:

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: 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)]

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.

  • allow_missing (bool) – Allow out-of-order migrations.

  • auto_sync (bool) – Auto-reconcile renamed migrations.

  • dry_run (bool) – Show what would be done without applying.

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

None

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.

  • dry_run (bool) – Show what would be done without applying.

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

None

get_current_migration(verbose=False)[source]

Get the current migration version.

Parameters:

verbose (bool) – Whether to show detailed migration history.

Return type:

str | None

Returns:

Current migration version or None if no migrations applied.

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

Return type:

None

init_migrations(directory=None, package=True)[source]

Initialize migration directory structure.

Parameters:
  • directory (str | None) – Directory to initialize migrations in.

  • package (bool) – Whether to create __init__.py file.

Return type:

None

stamp_migration(revision)[source]

Mark database as being at a specific revision without running migrations.

Parameters:

revision (str) – The revision to stamp.

Return type:

None

fix_migrations(dry_run=False, update_database=True, yes=False)[source]

Convert timestamp migrations to sequential format.

Parameters:
  • dry_run (bool) – Preview changes without applying.

  • update_database (bool) – Update migration records in database.

  • yes (bool) – Skip confirmation prompt.

Return type:

None

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.

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

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.

Parameters:
  • revision (str) – Target revision or “head” for latest.

  • allow_missing (bool) – Allow out-of-order migrations.

  • auto_sync (bool) – Auto-reconcile renamed migrations.

  • dry_run (bool) – Show what would be done without applying.

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

None

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.

  • dry_run (bool) – Show what would be done without applying.

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

None

async get_current_migration(verbose=False)[source]

Get the current migration version.

Parameters:

verbose (bool) – Whether to show detailed migration history.

Return type:

str | None

Returns:

Current migration version or None if no migrations applied.

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

Return type:

None

async init_migrations(directory=None, package=True)[source]

Initialize migration directory structure.

Parameters:
  • directory (str | None) – Directory to initialize migrations in.

  • package (bool) – Whether to create __init__.py file.

Return type:

None

async stamp_migration(revision)[source]

Mark database as being at a specific revision without running migrations.

Parameters:

revision (str) – The revision to stamp.

Return type:

None

async fix_migrations(dry_run=False, update_database=True, yes=False)[source]

Convert timestamp migrations to sequential format.

Parameters:
  • dry_run (bool) – Preview changes without applying.

  • update_database (bool) – Update migration records in database.

  • yes (bool) – Skip confirmation prompt.

Return type:

None

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

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.

  • allow_missing (bool) – Allow out-of-order migrations.

  • auto_sync (bool) – Auto-reconcile renamed migrations.

  • dry_run (bool) – Show what would be done without applying.

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

None

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.

  • dry_run (bool) – Show what would be done without applying.

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

None

get_current_migration(verbose=False)[source]

Get the current migration version.

Parameters:

verbose (bool) – Whether to show detailed migration history.

Return type:

str | None

Returns:

Current migration version or None if no migrations applied.

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

Return type:

None

init_migrations(directory=None, package=True)[source]

Initialize migration directory structure.

Parameters:
  • directory (str | None) – Directory to initialize migrations in.

  • package (bool) – Whether to create __init__.py file.

Return type:

None

stamp_migration(revision)[source]

Mark database as being at a specific revision without running migrations.

Parameters:

revision (str) – The revision to stamp.

Return type:

None

fix_migrations(dry_run=False, update_database=True, yes=False)[source]

Convert timestamp migrations to sequential format.

Parameters:
  • dry_run (bool) – Preview changes without applying.

  • update_database (bool) – Update migration records in database.

  • yes (bool) – Skip confirmation prompt.

Return type:

None

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

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.

Parameters:
  • revision (str) – Target revision or “head” for latest.

  • allow_missing (bool) – Allow out-of-order migrations.

  • auto_sync (bool) – Auto-reconcile renamed migrations.

  • dry_run (bool) – Show what would be done without applying.

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

None

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.

  • dry_run (bool) – Show what would be done without applying.

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

None

async get_current_migration(verbose=False)[source]

Get the current migration version.

Parameters:

verbose (bool) – Whether to show detailed migration history.

Return type:

str | None

Returns:

Current migration version or None if no migrations applied.

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

Return type:

None

async init_migrations(directory=None, package=True)[source]

Initialize migration directory structure.

Parameters:
  • directory (str | None) – Directory to initialize migrations in.

  • package (bool) – Whether to create __init__.py file.

Return type:

None

async stamp_migration(revision)[source]

Mark database as being at a specific revision without running migrations.

Parameters:

revision (str) – The revision to stamp.

Return type:

None

async fix_migrations(dry_run=False, update_database=True, yes=False)[source]

Convert timestamp migrations to sequential format.

Parameters:
  • dry_run (bool) – Preview changes without applying.

  • update_database (bool) – Update migration records in database.

  • yes (bool) – Skip confirmation prompt.

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

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:

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_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 (e.g., when using ephemeral ‘listen_notify’ backend), 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)

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.

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.