Skip to content

duckdb Adapter

from sqlspec.adapters.duckdb import (
    DuckDBConfig,
    DuckDBConnectionParams,
    DuckDBConnectionPool,
    DuckDBDriver,
    DuckDBDriverFeatures,
    DuckDBExceptionHandler,
    DuckDBExtensionConfig,
    DuckDBPoolParams,
    DuckDBSecretConfig,
)

Embedded analytical database adapter built on duckdb with zero-copy Apache Arrow, Parquet, and Polars integration. Inherited execution methods are documented on SyncDriverAdapterBase. See the DuckDB Setup Guide for extensions, secrets, and Arrow streaming examples, and the DuckDB Data Dictionary & SQL Catalog.

Configuration & Parameters

DuckDBConfig

Bases: SyncDatabaseConfig[DuckDBConnection, DuckDBConnectionPool, DuckDBDriver]

DuckDB configuration with connection pooling.

Supports extensions, secrets, Arrow transfers, and direct file queries. Connections recycle after 24 hours by default; set recycling to 0 to disable. Omitted, empty, or ':memory:' databases are assigned an isolated :memory:sqlspec_<uuid> catalog per config while explicit :memory:<name> databases remain shared.

Set driver_features["json_serializer"] to a serializer that returns text for dict/list parameters. The default is sqlspec.utils.serializers.to_json.

driver_features["enable_uuid_conversion"] converts UUID parameters to strings by default. Disable it to pass UUID parameters through unchanged. UUID result columns always return UUID objects; VARCHAR columns remain strings.

DuckDBConnectionParams

Bases: TypedDict

DuckDB connection parameters forwarded to duckdb.connect or its config dictionary.

Attributes:

Name Type Description
database NotRequired[str]

Database file path, ':memory:' / ':memory:<name>' memory identifier, or MotherDuck URI.

read_only NotRequired[bool]

Open the database file in read-only mode without taking a write lock.

config NotRequired[dict[str, Any]]

Raw DuckDB engine configuration dictionary merged with modeled settings.

memory_limit NotRequired[str]

Maximum buffer-manager memory ceiling (for example '4GB').

memory_ceiling_fraction NotRequired[float]

Fraction of container or host memory used as an upper ceiling when memory_limit is unset or exceeds available memory (defaults to 0.8).

threads NotRequired[int]

Number of DuckDB execution worker threads.

temp_directory NotRequired[str]

Directory path used when spilling out-of-core intermediates to disk.

reject_tmpfs_temp_directory NotRequired[bool]

Raise ImproperConfigurationError when temp_directory resides on an in-memory tmpfs or ramfs mount (defaults to False).

max_temp_directory_size NotRequired[str]

Maximum disk space cap for temp_directory spill files (for example '20GB').

autoload_known_extensions NotRequired[bool]

Automatically load installed DuckDB extensions when referenced by SQL syntax.

autoinstall_known_extensions NotRequired[bool]

Automatically download and install known DuckDB extensions on first reference.

allow_community_extensions NotRequired[bool]

Permit installing extensions from the DuckDB Community Extensions repository.

allow_unsigned_extensions NotRequired[bool]

Permit loading unsigned local or third-party DuckDB extension binaries.

extension_directory NotRequired[str]

Custom filesystem directory where DuckDB stores downloaded extensions.

custom_extension_repository NotRequired[str]

Custom HTTP or local repository URL searched when installing extensions.

autoinstall_extension_repository NotRequired[str]

Repository URL used specifically for automatic on-demand extension installs.

allow_persistent_secrets NotRequired[bool]

Allow reading and writing persistent secrets on disk.

enable_external_access NotRequired[bool]

Allow SQL statements to access local files, HTTP URLs, and object stores.

secret_directory NotRequired[str]

Filesystem directory storing persistent DuckDB secret files.

enable_object_cache NotRequired[bool]

Cache parsed Parquet metadata and object-store footers in memory.

parquet_metadata_cache NotRequired[bool]

Enable caching of Parquet file footers across repeated scans.

enable_external_file_cache NotRequired[bool]

Cache remote HTTP and object-store byte ranges in DuckDB's buffer pool.

checkpoint_threshold NotRequired[str]

WAL size threshold triggering an automatic database checkpoint (for example '16MB').

enable_progress_bar NotRequired[bool]

Display interactive terminal progress bars during long-running queries.

progress_bar_time NotRequired[int]

Milliseconds elapsed before DuckDB displays the query progress bar.

enable_logging NotRequired[bool]

Enable DuckDB internal query and engine logging.

log_query_path NotRequired[str]

Filesystem path receiving logged SQL queries when logging is enabled.

logging_level NotRequired[str]

Minimum severity level recorded by DuckDB's internal logger.

preserve_insertion_order NotRequired[bool]

Preserve input row ordering during table scans and bulk operations.

default_null_order NotRequired[str]

Default NULLS FIRST or NULLS LAST ordering when ORDER BY omits null placement.

default_order NotRequired[str]

Default ASC or DESC sort direction when ORDER BY omits direction.

ieee_floating_point_ops NotRequired[bool]

Follow IEEE-754 floating-point division-by-zero semantics instead of returning NULL.

binary_as_string NotRequired[bool]

Interpret untyped Parquet binary columns as VARCHAR strings.

arrow_large_buffer_size NotRequired[bool]

Emit 64-bit LargeUtf8 and LargeBinary Arrow buffers on Arrow exports.

errors_as_json NotRequired[bool]

Format DuckDB exception payloads as structured JSON strings.

extra NotRequired[dict[str, Any]]

Additional DuckDB configuration options merged into config.

DuckDBPoolParams

Bases: DuckDBConnectionParams

Complete pool configuration for DuckDB adapter.

Extends DuckDBConnectionParams with lifecycle settings consumed by SQLSpec's thread-local DuckDB connection manager.

Attributes:

Name Type Description
pool_recycle_seconds NotRequired[int]

Maximum connection lifetime in seconds before recycling (defaults to 86400; 0 disables).

health_check_interval NotRequired[float]

Idle seconds between lightweight connection health checks.

DuckDBDriverFeatures

Bases: TypedDict

DuckDB driver feature flags controlling extension/secret management, codecs, and statement profiling.

Attributes:

Name Type Description
extensions NotRequired[Sequence[DuckDBExtensionConfig]]

Extensions installed and loaded automatically when each pooled connection opens.

secrets NotRequired[Sequence[DuckDBSecretConfig]]

Secrets provisioned on new connections for object stores and external catalogs.

on_connection_create NotRequired[Callable[[DuckDBConnection], DuckDBConnection | None]]

Callback invoked when a new DuckDBPyConnection is opened.

reset_session_on_release NotRequired[bool]

Drop temporary objects and detach added databases when a connection is released (defaults to False).

json_serializer NotRequired[Callable[[Any], str]]

Serializer converting dict/list parameters to JSON text (defaults to sqlspec.utils.serializers.to_json).

enable_uuid_conversion NotRequired[bool]

Convert UUID parameters to strings on bind while returning UUID objects from UUID columns (defaults to True).

extension_flags NotRequired[dict[str, Any]]

Startup-only extension security flags merged into connection_config before duckdb.connect.

enable_events NotRequired[bool]

Enable SQLSpec table-backed event channel support.

events_backend NotRequired[Literal['poll_queue']]

Event queue backend name ('poll_queue').

enable_statement_profiling NotRequired[bool]

Capture per-statement DuckDB JSON operator profiles on StatementEvent.profile (defaults to False).

DuckDBExtensionConfig

Bases: TypedDict

DuckDB extension configuration for auto-management.

Attributes:

Name Type Description
name str

Name of the extension to install/load.

version NotRequired[str]

Specific version of the extension.

repository NotRequired[str]

Repository for the extension (core, community, or custom URL).

repository_url NotRequired[str]

Custom repository URL for the extension.

force_install NotRequired[bool]

Force reinstallation of the extension.

install NotRequired[bool]

Force an explicit install_extension() call even for a name-only config.

required NotRequired[bool]

When True, install/load failure raises instead of best-effort WARNING.

storage_protocols NotRequired[Sequence[str]]

Additional URI schemes handled by this extension's configured filesystem.

DuckDBSecretConfig

Bases: TypedDict

DuckDB secret configuration for AI/API integrations.

Attributes:

Name Type Description
secret_type str

Type of secret.

name str

Name of the secret. DuckDB matches secret names case-insensitively.

value NotRequired[dict[str, Any]]

Secret configuration values, applied only when the secret is created or replace is set.

value_provider NotRequired[Callable[[], dict[str, Any]]]

Callable returning dynamic secret configuration values (such as short-lived OAuth or STS tokens).

refresh_interval_seconds NotRequired[float]

Interval in seconds after which a secret backed by value_provider is refreshed via CREATE OR REPLACE SECRET (defaults to 1800.0 when value_provider is set).

provider NotRequired[str]

Secret provider, such as config or credential_chain.

scope NotRequired[str]

Optional path or storage-prefix scope for the secret.

persistent NotRequired[bool]

Persist the secret to DuckDB's configured secret directory.

replace NotRequired[bool]

When True, overwrite an existing secret of the same name, such as after rotating credentials. Default False.

required NotRequired[bool]

When True, raise instead of skipping the secret with a warning. Default False.

Driver, Pool & Data Dictionary

DuckDBDriver

Bases: SyncDriverAdapterBase

Synchronous DuckDB database driver.

Provides SQL statement execution, transaction management, and result handling for DuckDB databases. Supports multiple parameter styles including QMARK, NUMERIC, and NAMED_DOLLAR formats.

The driver handles script execution, batch operations, and integrates with the sqlspec.core modules for statement processing and caching.

DuckDBExceptionHandler

Bases: BaseSyncExceptionHandler

Context manager for handling DuckDB database exceptions.

Maps DuckDB exception types and error messages to SQLSpec exceptions stored on pending_exception.

DuckDBConnectionPool

Thread-local connection manager for DuckDB.

Isolates DuckDB connections per thread using thread-local storage because native DuckDB connections and cursors are not safe for concurrent multi-threaded sharing.

DuckDBDataDictionary

Bases: SyncDataDictionaryBase

DuckDB-specific sync data dictionary.

Extension Stores & Configs

DuckDBStore

Bases: BaseSQLSpecStore['DuckDBConfig']

DuckDB session store using synchronous DuckDB driver.

Implements server-side session storage for Litestar using DuckDB via the synchronous duckdb driver. Uses Litestar's sync_to_thread utility to provide an async interface compatible with the Store protocol.

Provides efficient session management with
  • Sync operations wrapped for async compatibility
  • INSERT OR REPLACE for UPSERT functionality
  • Native TIMESTAMP type support
  • Automatic expiration handling
  • Efficient cleanup of expired sessions
  • Columnar storage optimized for analytical queries

Parameters:

Name Type Description Default
config DuckDBConfig

DuckDBConfig instance.

required

DuckDBADKConfig

Bases: ADKConfig

DuckDB-specific ADK extension settings.

Use these keys inside extension_config["adk"] with the DuckDB ADK stores. Shared ADK table and service settings are inherited from :class:ADKConfig.

Attributes:

Name Type Description
enable_event_generated_columns NotRequired[bool]

Create DuckDB virtual generated columns for common ADK event JSON paths.

enable_event_generated_column_indexes NotRequired[bool]

Index generated event projection columns when generated columns are enabled.

memory_fts_options NotRequired[DuckDBADKFTSOptions]

DuckDB FTS PRAGMA create_fts_index options for ADK memory search.

DuckDBADKFTSOptions

Bases: TypedDict

DuckDB FTS PRAGMA create_fts_index options for ADK memory search.

Attributes:

Name Type Description
stemmer NotRequired[str]

Stemmer name. Defaults to "porter".

stopwords NotRequired[str]

Stopword table/name. Defaults to "english".

ignore NotRequired[str]

Regular expression ignored by DuckDB tokenization.

strip_accents NotRequired[bool | int]

Whether DuckDB strips accents during tokenization. Defaults to 1.

lower NotRequired[bool | int]

Whether DuckDB lowercases text during tokenization. Defaults to 1.

overwrite NotRequired[bool | int]

Whether initial FTS index creation overwrites an existing index. Defaults to 0.

DuckDBADKStore

Bases: BaseSyncADKStore['DuckDBConfig']

DuckDB ADK store for Google Agent Development Kit.

Implements session and event storage for Google Agent Development Kit using DuckDB's synchronous driver with a synchronous public API. Provides: - Session state management with native JSON type - Event history with single JSON blob (event_data) plus indexed scalars - Native TIMESTAMPTZ type support - Manual cascade delete (DuckDB has no FK CASCADE) - Columnar storage for analytical queries

Parameters:

Name Type Description Default
config DuckDBConfig

DuckDBConfig with extension_config["adk"] settings.

required

DuckDBADKMemoryStore

Bases: BaseSyncADKMemoryStore['DuckDBConfig']

DuckDB ADK memory store using synchronous DuckDB driver with async wrappers.

Implements memory entry storage for Google Agent Development Kit using DuckDB's synchronous driver with a synchronous public API. Provides: - Session memory storage with native JSON type - Simple ILIKE search or BM25 full-text search via FTS extension - Native TIMESTAMP type support - Deduplication via (app_name, user_id, event_id) unique constraint - Efficient upserts using ON CONFLICT DO NOTHING - Columnar storage for analytical queries

Parameters:

Name Type Description Default
config DuckDBConfig

DuckDBConfig with extension_config["adk"] settings.

required

DuckDBEventQueueStore

Bases: BaseEventQueueStore[DuckDBConfig]

DuckDB event queue store with native JSON support.

DuckDB supports native JSON type for efficient JSON storage and querying. The table uses TIMESTAMP for event ordering with microsecond precision.

Parameters:

Name Type Description Default
config ConfigT

DuckDBConfig with optional extension_config["events"] settings.

required