Skip to content

db2 Adapter

from sqlspec.adapters.db2 import (
    Db2AsyncConfig,
    Db2AsyncDriver,
    Db2AsyncExceptionHandler,
    Db2AsyncGlobalVariableStrategy,
    Db2AsyncPoolParams,
    Db2ConnectionParams,
    Db2DriverFeatures,
    Db2PoolParams,
    Db2SyncConfig,
    Db2SyncDriver,
    Db2SyncExceptionHandler,
    Db2SyncGlobalVariableStrategy,
)

Synchronous and asynchronous IBM Db2 LUW adapters built on ibm_db. Inherited execution methods are documented on SyncDriverAdapterBase and AsyncDriverAdapterBase. See the IBM Db2 Setup Guide for usage examples and the IBM Db2 Data Dictionary & SQL Catalog.

Configuration & Parameters

Db2SyncConfig

Bases: SyncDatabaseConfig[Db2SyncConnection, Db2SyncConnectionPool, Db2SyncDriver]

Configuration for IBM Db2 synchronous connections.

Db2AsyncConfig

Bases: AsyncDatabaseConfig[Db2AsyncConnection, Db2AsyncConnectionPool, Db2AsyncDriver]

Configuration for IBM Db2 asynchronous connections over ibm_db_dbi.AsyncConnection.

Db2ConnectionParams

Bases: TypedDict

IBM Db2 CLI connection parameters compiled into a KEY=VALUE;... DSN.

Attributes:

Name Type Description
conn_options NotRequired[dict[int, Any]]

Native CLI connection attributes copied for each connection.

read_only NotRequired[bool]

Open connections using native CLI read-only access mode.

database NotRequired[str]

Database name or cataloged alias mapped to the DATABASE CLI keyword.

hostname NotRequired[str]

Db2 server hostname mapped to HOSTNAME (omit for cataloged local aliases).

port NotRequired[int]

Db2 TCP listener port mapped to PORT (defaults to 50000 when hostname is set).

protocol NotRequired[str]

Communications protocol mapped to PROTOCOL (defaults to 'TCPIP' when hostname is set).

user NotRequired[str]

Authentication username mapped to the UID CLI keyword.

password NotRequired[str]

Authentication password mapped to the PWD CLI keyword.

current_schema NotRequired[str]

Default SQL schema mapped to the CURRENTSCHEMA CLI keyword.

security NotRequired[str]

Transport security mode mapped to SECURITY (for example 'SSL').

ssl_server_certificate NotRequired[str]

Server certificate file path mapped to the SSLSERVERCERTIFICATE CLI keyword.

authentication NotRequired[str]

Db2 authentication mechanism mapped to the AUTHENTICATION CLI keyword.

connect_timeout NotRequired[int]

Connection establishment timeout in seconds mapped to CONNECTTIMEOUT.

autocommit NotRequired[bool]

Initial connection autocommit state applied via ibm_db_dbi outside the DSN.

dsn NotRequired[str]

Base KEY=VALUE;... string or db2:// URL overridden by explicit keyword parameters.

extra NotRequired[dict[str, str | int | bool]]

Additional CLI keywords appended verbatim to the compiled DSN string.

Db2PoolParams

Bases: Db2ConnectionParams

IBM Db2 thread-local connection pool parameters.

Attributes:

Name Type Description
pool_recycle_seconds NotRequired[int]

Maximum connection age in seconds before replacement (defaults to 86400).

health_check_interval NotRequired[float]

Idle seconds elapsed before a pooled connection is pinged on reuse (defaults to 30.0).

Db2AsyncPoolParams

Bases: Db2PoolParams

IBM Db2 bounded asyncio connection pool parameters.

Attributes:

Name Type Description
max_size NotRequired[int]

Maximum number of connections checked out or opening concurrently (defaults to 10).

acquire_timeout NotRequired[float]

Maximum seconds to wait for a free connection before raising ConnectionTimeoutError (defaults to 30.0).

Db2DriverFeatures

Bases: TypedDict

IBM Db2 driver feature flags controlling JSON codecs, column casing, and event queues.

Attributes:

Name Type Description
tenant_strategy NotRequired[SyncTenantStrategy | AsyncTenantStrategy | TenantStrategyShorthand | None]

Opt-in tenant strategy, or the "rcac" shorthand, applied to every session and connection lease.

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

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

json_deserializer NotRequired[Callable[[str], Any]]

Deserializer parsing JSON text payloads (defaults to sqlspec.utils.serializers.from_json).

on_connection_create NotRequired[Callable[[Any], Any]]

Callback invoked with the raw ibm_db_dbi sync or async connection after open.

enable_events NotRequired[bool]

Enable SQLSpec table-backed event channel support.

events_backend NotRequired[Literal['poll_queue']]

Event queue backend name ('poll_queue').

enable_lowercase_column_names NotRequired[bool]

Normalize unquoted uppercase Db2 column names to lowercase (defaults to True).

Tenant Strategies

Set driver_features={"tenant_strategy": "rcac"}; "global_variable", "default", and True select the same mode-specific strategy. The strategy writes the tenant identity into a session global variable that row and column access control (RCAC) permissions and masks read. The default variable is APP.CURRENT_TENANT_ID; pass tenant_variable= and variable_keys= to an explicit strategy to use other schema-qualified variables. Names are validated as ordinary identifiers and folded to upper case; values are always bound.

A DBA provisions the variable and the policy, and grants the application READ and WRITE on the variable:

CREATE VARIABLE APP.CURRENT_TENANT_ID VARCHAR(256) DEFAULT NULL;
CREATE PERMISSION APP.PROJECTS_TENANT ON APP.PROJECTS
    FOR ROWS WHERE TENANT_ID = APP.CURRENT_TENANT_ID
    ENFORCED FOR ALL ACCESS ENABLE;
ALTER TABLE APP.PROJECTS ACTIVATE ROW ACCESS CONTROL;

Session global variable values are not affected by COMMIT or ROLLBACK. Checkout reads the previous values, assigns the payload with one SET, and reads the values back; checkin assigns the captured values and verifies them again. A failed verification disposes of the connection: the synchronous adapter uses one standalone connection per lease and closes it, and the asynchronous pool discards the connection instead of returning it. Standalone create_connection() is rejected in tenant mode. Tenant leases keep the native commit behavior: sessions roll back unfinished work before release, as they do without a tenant strategy.

Missing tenant identity raises TenantContextError before acquisition. Failed cleanup raises TenantCleanupError when no body exception is pending; otherwise the body error keeps its identity and receives a cleanup note. See Multi-Tenancy and Tenant Operations.

Db2SyncGlobalVariableStrategy

Bases: _Db2GlobalVariables

Set, verify, and restore Db2 session global variables on a synchronous connection.

RCAC permissions and masks read the variables; database policies enforce row access.

__init__

__init__(*, tenant_variable=DEFAULT_DB2_TENANT_VARIABLE, variable_keys=None)

Configure the owned global variables.

Parameters:

Name Type Description Default
tenant_variable object

Schema-qualified global variable receiving the tenant identity.

DEFAULT_DB2_TENANT_VARIABLE
variable_keys Mapping[str, str] | None

Payload variable names mapped to schema-qualified global variables.

None

Raises:

Type Description
ImproperConfigurationError

A name is invalid or two keys target the same variable.

checkout

checkout(connection, payload)

Capture the previous values, assign the payload, and verify the server values.

checkin

checkin(connection, state)

Restore the captured values and verify them before the connection is reused.

Db2AsyncGlobalVariableStrategy

Bases: _Db2GlobalVariables

Set, verify, and restore Db2 session global variables on an asynchronous connection.

RCAC permissions and masks read the variables; database policies enforce row access.

__init__

__init__(*, tenant_variable=DEFAULT_DB2_TENANT_VARIABLE, variable_keys=None)

Configure the owned global variables.

Parameters:

Name Type Description Default
tenant_variable object

Schema-qualified global variable receiving the tenant identity.

DEFAULT_DB2_TENANT_VARIABLE
variable_keys Mapping[str, str] | None

Payload variable names mapped to schema-qualified global variables.

None

Raises:

Type Description
ImproperConfigurationError

A name is invalid or two keys target the same variable.

checkout

checkout(connection, payload)

Capture the previous values, assign the payload, and verify the server values.

checkin

checkin(connection, state)

Restore the captured values and verify them before the connection is reused.

Driver, Pool & Data Dictionary

Db2SyncDriver

Bases: SyncDriverAdapterBase

IBM Db2 database driver.

Db2AsyncDriver

Bases: AsyncDriverAdapterBase

IBM Db2 async database driver over ibm_db_dbi.AsyncConnection.

Db2SyncExceptionHandler

Bases: BaseSyncExceptionHandler

Context manager that maps ibm_db_dbi errors to SQLSpec exceptions.

Exceptions that do not come from the driver propagate unchanged.

Db2AsyncExceptionHandler

Bases: BaseAsyncExceptionHandler

Async context manager that maps ibm_db_dbi errors to SQLSpec exceptions.

Exceptions that do not come from the driver propagate unchanged.

Db2SyncDataDictionary

Bases: SyncDataDictionaryBase

IBM Db2 sync data dictionary for metadata reflection.

Db2AsyncDataDictionary

Bases: AsyncDataDictionaryBase

IBM Db2 async data dictionary for metadata reflection.

Extension Stores & Configs

Db2SyncStore

Bases: BaseSQLSpecStore['Db2SyncConfig']

IBM Db2-backed session store using synchronous Db2 sessions.

Every timestamp written or compared is a naive-UTC value bound from Python, so expiry does not depend on the server's time zone.

Db2AsyncStore

Bases: BaseSQLSpecStore['Db2AsyncConfig']

IBM Db2-backed session store using asynchronous Db2 sessions.

Runs the same statements with the same parameters as Db2SyncStore; every timestamp written or compared is a naive-UTC value bound from Python.

Db2SyncADKStore

Bases: _Db2ADKStoreMixin, BaseSyncADKStore[Db2SyncConfig]

Synchronous IBM Db2 ADK session/event store.

Db2AsyncADKStore

Bases: _Db2ADKStoreMixin, BaseAsyncADKStore[Db2AsyncConfig]

Asynchronous IBM Db2 ADK session/event store.

Db2SyncADKMemoryStore

Bases: _Db2ADKMemoryStoreMixin, BaseSyncADKMemoryStore[Db2SyncConfig]

IBM Db2 ADK memory store for synchronous configs.

Db2AsyncADKMemoryStore

Bases: _Db2ADKMemoryStoreMixin, BaseAsyncADKMemoryStore[Db2AsyncConfig]

IBM Db2 ADK memory store for asynchronous configs.

Db2SyncEventQueueStore

Bases: _Db2EventStoreMixin, BaseEventQueueStore[Db2SyncConfig]

IBM Db2 event queue store for synchronous configs.

Db2AsyncEventQueueStore

Bases: _Db2EventStoreMixin, BaseEventQueueStore[Db2AsyncConfig]

IBM Db2 event queue store for asynchronous configs.