Extensions¶
SQLSpec provides integration modules for popular web frameworks and external services, enabling seamless database connectivity with dependency injection, lifecycle management, and framework-specific utilities.
Overview¶
Available integrations:
AI & ML:
Google ADK - Session and event storage for Google Agent Development Kit
Web Frameworks:
Litestar - Modern async Python web framework
FastAPI - High-performance async web framework
Flask - Traditional Python web framework
Sanic - Async Python web framework
Starlette - Lightweight ASGI framework
Data Tools:
aiosql - SQL file loading integration
Each extension provides:
Configuration integration
Dependency injection (where applicable)
Lifecycle hooks (startup/shutdown)
Session management
Framework/service-specific utilities
Google ADK Integration¶
The ADK extension provides persistent session and event storage for the Google Agent Development Kit (ADK), enabling stateful AI agent applications with database-backed conversation history.
Features:
Session state persistence across multiple database backends
Event history storage with full ADK event model support
Multi-tenant support with customizable table names
Type-safe storage with TypedDicts
Production-ready for PostgreSQL, MySQL, SQLite, Oracle
Complete Documentation:
See Google ADK Extension for comprehensive documentation including:
Installation and quickstart guides
Complete API reference
Database adapter details
Schema reference
Migration strategies
Production examples
Quick Example:
from sqlspec.adapters.asyncpg import AsyncpgConfig
from sqlspec.adapters.asyncpg.adk import AsyncpgADKStore
from sqlspec.extensions.adk import SQLSpecSessionService
config = AsyncpgConfig(pool_config={"dsn": "postgresql://..."})
store = AsyncpgADKStore(config)
await store.create_tables()
service = SQLSpecSessionService(store)
session = await service.create_session(
app_name="my_agent",
user_id="user123",
state={"context": "initial"}
)
Base Store Classes¶
- class sqlspec.extensions.adk.BaseAsyncADKStore[source]
-
Base class for async SQLSpec-backed ADK session stores.
Implements storage operations for Google ADK sessions and events using SQLSpec database adapters with async/await.
This abstract base class provides common functionality for all database-specific store implementations including: - Connection management via SQLSpec configs - Table name validation - Session and event CRUD operations
Subclasses must implement dialect-specific SQL queries and will be created in each adapter directory (e.g., sqlspec/adapters/asyncpg/adk/store.py).
- Parameters:
config¶ (
TypeVar(ConfigT)) – SQLSpec database configuration with extension_config[“adk”] settings.
Notes
Configuration is read from config.extension_config[“adk”]: - session_table: Sessions table name (default: “adk_sessions”) - events_table: Events table name (default: “adk_events”) - owner_id_column: Optional owner FK column DDL (default: None)
Abstract base class for async ADK session stores. See API Reference for details.
- __init__(config)[source]
Initialize the ADK store.
Notes
Reads configuration from config.extension_config[“adk”]: - session_table: Sessions table name (default: “adk_sessions”) - events_table: Events table name (default: “adk_events”) - owner_id_column: Optional owner FK column DDL (default: None)
- property config: ConfigT
Return the database configuration.
- property session_table: str
Return the sessions table name.
- property events_table: str
Return the events table name.
- property owner_id_column_ddl: str | None
Return the full owner ID column DDL (or None if not configured).
- property owner_id_column_name: str | None
Return the owner ID column name only (or None if not configured).
- abstractmethod async create_session(session_id, app_name, user_id, state, owner_id=None)[source]
Create a new session.
- Parameters:
- Return type:
- Returns:
The created session record.
- abstractmethod async get_session(session_id)[source]
Get a session by ID.
- Parameters:
- Return type:
- Returns:
Session record if found, None otherwise.
- abstractmethod async update_session_state(session_id, state)[source]
Update session state.
- abstractmethod async list_sessions(app_name, user_id=None)[source]
List all sessions for an app, optionally filtered by user.
- abstractmethod async delete_session(session_id)[source]
Delete a session and its events.
- abstractmethod async append_event(event_record)[source]
Append an event to a session.
- Parameters:
event_record¶ (
EventRecord) – Event record to store.- Return type:
- abstractmethod async get_events(session_id, after_timestamp=None, limit=None)[source]
Get events for a session.
- class sqlspec.extensions.adk.BaseSyncADKStore[source]
-
Base class for sync SQLSpec-backed ADK session stores.
Implements storage operations for Google ADK sessions and events using SQLSpec database adapters with synchronous execution.
This abstract base class provides common functionality for sync database-specific store implementations including: - Connection management via SQLSpec configs - Table name validation - Session and event CRUD operations
Subclasses must implement dialect-specific SQL queries and will be created in each adapter directory (e.g., sqlspec/adapters/sqlite/adk/store.py).
- Parameters:
config¶ (
TypeVar(ConfigT)) – SQLSpec database configuration with extension_config[“adk”] settings.
Notes
Configuration is read from config.extension_config[“adk”]: - session_table: Sessions table name (default: “adk_sessions”) - events_table: Events table name (default: “adk_events”) - owner_id_column: Optional owner FK column DDL (default: None)
Abstract base class for sync ADK session stores. See API Reference for details.
- __init__(config)[source]
Initialize the sync ADK store.
Notes
Reads configuration from config.extension_config[“adk”]: - session_table: Sessions table name (default: “adk_sessions”) - events_table: Events table name (default: “adk_events”) - owner_id_column: Optional owner FK column DDL (default: None)
- property config: ConfigT
Return the database configuration.
- property session_table: str
Return the sessions table name.
- property events_table: str
Return the events table name.
- property owner_id_column_ddl: str | None
Return the full owner ID column DDL (or None if not configured).
- property owner_id_column_name: str | None
Return the owner ID column name only (or None if not configured).
- abstractmethod create_session(session_id, app_name, user_id, state, owner_id=None)[source]
Create a new session.
- Parameters:
- Return type:
- Returns:
The created session record.
- abstractmethod get_session(session_id)[source]
Get a session by ID.
- Parameters:
- Return type:
- Returns:
Session record if found, None otherwise.
- abstractmethod update_session_state(session_id, state)[source]
Update session state.
- abstractmethod list_sessions(app_name, user_id=None)[source]
List all sessions for an app, optionally filtered by user.
- abstractmethod delete_session(session_id)[source]
Delete a session and its events.
- abstractmethod create_event(event_id, session_id, app_name, user_id, author=None, actions=None, content=None, **kwargs)[source]
Create a new event.
- abstractmethod list_events(session_id)[source]
List events for a session ordered by timestamp.
- Parameters:
- Return type:
- Returns:
List of event records ordered by timestamp ASC.
Session Service¶
- class sqlspec.extensions.adk.SQLSpecSessionService[source]
Bases:
BaseSessionServiceSQLSpec-backed implementation of BaseSessionService.
Provides session and event storage using SQLSpec database adapters. Delegates all database operations to a store implementation.
- Parameters:
store¶ (
BaseAsyncADKStore) – Database store implementation (e.g., AsyncpgADKStore).
Example
from sqlspec.adapters.asyncpg import AsyncpgConfig from sqlspec.adapters.asyncpg.adk.store import AsyncpgADKStore from sqlspec.extensions.adk.service import SQLSpecSessionService
config = AsyncpgConfig(pool_config={“dsn”: “postgresql://…”}) store = AsyncpgADKStore(config) await store.create_tables()
service = SQLSpecSessionService(store) session = await service.create_session(
app_name=”my_app”, user_id=”user123”, state={“key”: “value”}
)
SQLSpec-backed implementation of Google ADK’s BaseSessionService. See API Reference for details.
- __init__(store)[source]
Initialize the session service.
- Parameters:
store¶ (
BaseAsyncADKStore) – Database store implementation.
- property store: BaseAsyncADKStore
Return the database store.
- async create_session(*, app_name, user_id, state=None, session_id=None)[source]
Create a new session.
- async get_session(*, app_name, user_id, session_id, config=None)[source]
Get a session by ID.
- async list_sessions(*, app_name, user_id=None)[source]
List all sessions for an app, optionally filtered by user.
- async delete_session(*, app_name, user_id, session_id)[source]
Delete a session and all its events.
Litestar Integration¶
The Litestar extension provides a plugin for SQLSpec integration with automatic dependency injection.
Plugin¶
- class sqlspec.extensions.litestar.SQLSpecPlugin[source]¶
Bases:
InitPluginProtocol,CLIPluginLitestar plugin for SQLSpec database integration.
Automatically configures NumPy array serialization when NumPy is installed, enabling seamless bidirectional conversion between NumPy arrays and JSON for vector embedding workflows.
- Session Table Migrations:
The Litestar extension includes migrations for creating session storage tables. To include these migrations in your database migration workflow, add ‘litestar’ to the include_extensions list in your migration configuration.
Example
- config = AsyncpgConfig(
pool_config={“dsn”: “postgresql://localhost/db”}, extension_config={
- “litestar”: {
“session_table”: “custom_sessions” # Optional custom table name
}
}, migration_config={
“script_location”: “migrations”, “include_extensions”: [“litestar”], # Simple string list only
}
)
The session table migration will automatically use the appropriate column types for your database dialect (JSONB for PostgreSQL, JSON for MySQL, TEXT for SQLite).
Extension migrations use the ext_litestar_ prefix (e.g., ext_litestar_0001) to prevent version conflicts with application migrations.
Main plugin for Litestar integration.
Features:
Automatic connection pool lifecycle
Dependency injection for drivers
Per-request session management
Transaction handling
Configuration from Litestar settings
Basic usage:
from litestar import Litestar, get from sqlspec import SQLSpec from sqlspec.adapters.asyncpg import AsyncpgConfig, AsyncpgDriver from sqlspec.extensions.litestar import SQLSpecPlugin sql = SQLSpec() db = sql.add_config( AsyncpgConfig( pool_config={"dsn": "postgresql://localhost/db"} ) ) plugin = SQLSpecPlugin(sqlspec=sql) @get("/users") async def get_users(db: AsyncpgDriver) -> list[dict]: result = await db.select("SELECT * FROM users") return result.all() app = Litestar(route_handlers=[get_users], plugins=[plugin])
- __init__(sqlspec, *, loader=None)[source]¶
Initialize SQLSpec plugin.
- Parameters:
sqlspec¶ (
SQLSpec) – Pre-configured SQLSpec instance with registered database configs.loader¶ (
SQLFileLoader|None) – Optional SQL file loader instance (SQLSpec may already have one).
- property config: list[SyncDatabaseConfig[TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any')] | NoPoolSyncConfig[TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any')] | AsyncDatabaseConfig[TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any')] | NoPoolAsyncConfig[TypeAliasForwardRef('typing.Any'), TypeAliasForwardRef('typing.Any')]]¶
Return the plugin configurations.
- Returns:
List of database configurations.
- on_app_init(app_config)[source]¶
Configure Litestar application with SQLSpec database integration.
Automatically registers NumPy array serialization when NumPy is installed.
- get_annotation(key)[source]¶
Return the annotation for the given configuration.
- Parameters:
key¶ (
Union[str,SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any],AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any],type[Union[SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any],AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any]]]]) – The configuration instance or key to lookup.- Raises:
KeyError – If no configuration is found for the given key.
- Return type:
type[Union[SyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolSyncConfig[typing.Any, typing.Any],AsyncDatabaseConfig[typing.Any, typing.Any, typing.Any],NoPoolAsyncConfig[typing.Any, typing.Any]]]- Returns:
The annotation for the configuration.
- provide_request_session(key, state, scope)[source]¶
Provide a database session for the specified configuration key from request scope.
- Parameters:
key¶ (
Union[str,TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]),TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]),type[Union[TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]),TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any])]]]) – The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) – The ASGI scope containing the request context.
- Return type:
- Returns:
A driver session instance for the specified database configuration.
- provide_sync_request_session(key, state, scope)[source]¶
Provide a sync database session for the specified configuration key from request scope.
- Parameters:
key¶ (
Union[str,TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]),type[TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any])]]) – The sync configuration identifier.scope¶ (
Union[HTTPScope,WebSocketScope]) – The ASGI scope containing the request context.
- Return type:
- Returns:
A sync driver session instance for the specified database configuration.
- provide_async_request_session(key, state, scope)[source]¶
Provide an async database session for the specified configuration key from request scope.
- Parameters:
key¶ (
Union[str,TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]),type[TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any])]]) – The async configuration identifier.scope¶ (
Union[HTTPScope,WebSocketScope]) – The ASGI scope containing the request context.
- Return type:
- Returns:
An async driver session instance for the specified database configuration.
- provide_request_connection(key, state, scope)[source]¶
Provide a database connection for the specified configuration key from request scope.
- Parameters:
key¶ (
Union[str,TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]),TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any]),type[Union[TypeVar(SyncConfigT, bound= SyncDatabaseConfig[Any, Any, Any] | NoPoolSyncConfig[Any, Any]),TypeVar(AsyncConfigT, bound= AsyncDatabaseConfig[Any, Any, Any] | NoPoolAsyncConfig[Any, Any])]]]) – The configuration identifier (same as get_config).scope¶ (
Union[HTTPScope,WebSocketScope]) – The ASGI scope containing the request context.
- Return type:
typing.Any
- Returns:
A database connection instance for the specified database configuration.
Configuration¶
Session Backend¶
- class sqlspec.extensions.litestar.BaseSQLSpecStore[source]¶
-
Base class for SQLSpec-backed Litestar session stores.
Implements the litestar.stores.base.Store protocol for server-side session storage using SQLSpec database adapters.
This abstract base class provides common functionality for all database-specific store implementations including: - Connection management via SQLSpec configs - Session expiration calculation - Table creation utilities
Subclasses must implement dialect-specific SQL queries.
- Parameters:
config¶ (
TypeVar(ConfigT)) – SQLSpec database configuration with extension_config[“litestar”] settings.
Example
from sqlspec.adapters.asyncpg import AsyncpgConfig from sqlspec.adapters.asyncpg.litestar.store import AsyncpgStore
- config = AsyncpgConfig(
pool_config={“dsn”: “postgresql://…”}, extension_config={“litestar”: {“session_table”: “my_sessions”}}
) store = AsyncpgStore(config) await store.create_table()
Notes
Configuration is read from config.extension_config[“litestar”]: - session_table: Table name (default: “litestar_session”)
Abstract base class for session storage backends.
- __init__(config)[source]¶
Initialize the session store.
Notes
Reads table_name from config.extension_config[“litestar”][“session_table”]. Defaults to “litestar_session” if not specified.
- property config: ConfigT¶
Return the database configuration.
- abstractmethod async get(key, renew_for=None)[source]¶
Get a session value by key.
- Parameters:
- Return type:
- Returns:
Session data as bytes if found and not expired, None otherwise.
- abstractmethod async delete_expired()[source]¶
Delete all expired sessions.
- Return type:
- Returns:
Number of sessions deleted.
- abstractmethod async create_table()[source]¶
Create the session table if it doesn’t exist.
- Return type:
Starlette Integration¶
Starlette extension for SQLSpec.
Provides middleware-based session management, automatic transaction handling, and connection pooling lifecycle management for Starlette applications.
- class sqlspec.extensions.starlette.SQLSpecAutocommitMiddleware[source]¶
Bases:
BaseHTTPMiddlewareMiddleware for autocommit transaction mode.
Acquires connection, commits on success status codes, rollbacks on error status codes.
- class sqlspec.extensions.starlette.SQLSpecManualMiddleware[source]¶
Bases:
BaseHTTPMiddlewareMiddleware for manual transaction mode.
Acquires connection from pool, stores in request.state, releases after request. No automatic commit or rollback - user code must handle transactions.
- class sqlspec.extensions.starlette.SQLSpecPlugin[source]¶
Bases:
objectSQLSpec integration for Starlette applications.
Provides middleware-based session management, automatic transaction handling, and connection pooling lifecycle management.
Example
from starlette.applications import Starlette from sqlspec import SQLSpec from sqlspec.adapters.asyncpg import AsyncpgConfig from sqlspec.extensions.starlette import SQLSpecPlugin
sqlspec = SQLSpec() sqlspec.add_config(AsyncpgConfig(
bind_key=”default”, pool_config={“dsn”: “postgresql://localhost/mydb”}, extension_config={
- “starlette”: {
“commit_mode”: “autocommit”, “session_key”: “db”
}
}
))
app = Starlette() db_ext = SQLSpecPlugin(sqlspec, app)
@app.route(“/users”) async def list_users(request):
db = db_ext.get_session(request) result = await db.execute(“SELECT * FROM users”) return JSONResponse({“users”: result.all()})
- get_session(request, key=None)[source]¶
Get or create database session for request.
Sessions are cached per request to ensure consistency.
aiosql Integration¶
SQLSpec aiosql integration for loading SQL files.
This module provides a simple way to load aiosql-style SQL files and use them with SQLSpec drivers. It focuses on just the file parsing functionality, returning SQL objects that work with existing SQLSpec execution.
- class sqlspec.extensions.aiosql.AiosqlAsyncAdapter[source]¶
Bases:
_AiosqlAdapterBase[AsyncDriverAdapterBase],AsyncDriverAdapterProtocolAsynchronous adapter that implements aiosql protocol using SQLSpec drivers.
This adapter bridges aiosql’s async driver protocol with SQLSpec’s async drivers, enabling queries loaded by aiosql to be executed with SQLSpec async drivers.
- __init__(driver)[source]¶
Initialize the async adapter.
- Parameters:
driver¶ (
AsyncDriverAdapterBase) – SQLSpec async driver to use for execution
- async insert_returning(conn, query_name, sql, parameters)[source]¶
Execute INSERT with RETURNING and return result.
- async insert_update_delete(conn, query_name, sql, parameters)[source]¶
Execute INSERT/UPDATE/DELETE.
- Parameters:
- Return type:
Note
Returns None per aiosql async protocol
- async insert_update_delete_many(conn, query_name, sql, parameters)[source]¶
Execute INSERT/UPDATE/DELETE with many parameter sets.
- Parameters:
- Return type:
Note
Returns None per aiosql async protocol
- async select(conn, query_name, sql, parameters, record_class=None)[source]¶
Execute a SELECT query and return results as list.
- Parameters:
- Return type:
- Returns:
List of query result rows
Note
The record_class parameter is ignored for compatibility. Use schema_type in driver.execute or _sqlspec_schema_type in parameters for type mapping.
- async select_cursor(conn, query_name, sql, parameters)[source]¶
Execute a SELECT query and return cursor context manager.
- async select_one(conn, query_name, sql, parameters, record_class=None)[source]¶
Execute a SELECT query and return first result.
- Parameters:
- Return type:
- Returns:
First result row or None
Note
The record_class parameter is ignored for compatibility. Use schema_type in driver.execute or _sqlspec_schema_type in parameters for type mapping.
- class sqlspec.extensions.aiosql.AiosqlSyncAdapter[source]¶
Bases:
_AiosqlAdapterBase[SyncDriverAdapterBase],SyncDriverAdapterProtocolSynchronous adapter that implements aiosql protocol using SQLSpec drivers.
This adapter bridges aiosql’s synchronous driver protocol with SQLSpec’s sync drivers, enabling queries loaded by aiosql to be executed with SQLSpec drivers.
- __init__(driver)[source]¶
Initialize the sync adapter.
- Parameters:
driver¶ (
SyncDriverAdapterBase) – SQLSpec sync driver to use for execution
- insert_returning(conn, query_name, sql, parameters)[source]¶
Execute INSERT with RETURNING and return result.
- insert_update_delete(conn, query_name, sql, parameters)[source]¶
Execute INSERT/UPDATE/DELETE and return affected rows.
- insert_update_delete_many(conn, query_name, sql, parameters)[source]¶
Execute INSERT/UPDATE/DELETE with many parameter sets.
- select(conn, query_name, sql, parameters, record_class=None)[source]¶
Execute a SELECT query and return results as generator.
- Parameters:
- Yields:
Query result rows
- Return type:
Note
The record_class parameter is ignored for compatibility. Use schema_type in driver.execute or _sqlspec_schema_type in parameters for type mapping.
- select_cursor(conn, query_name, sql, parameters)[source]¶
Execute a SELECT query and return cursor context manager.
- select_one(conn, query_name, sql, parameters, record_class=None)[source]¶
Execute a SELECT query and return first result.
- Parameters:
- Return type:
- Returns:
First result row or None
Note
The record_class parameter is ignored for compatibility. Use schema_type in driver.execute or _sqlspec_schema_type in parameters for type mapping.
See Also¶
Framework Integrations - Framework integration guide
SQLSpec Example Library - Framework integration examples
Base - SQLSpec configuration
Adapters - Database adapters