IBM Db2#

Integration with IBM Db2 Community Edition using the official icr.io/db2_community/db2:12.1.5.0 container image. The fixture is clientless and uses the in-container db2 CLI for readiness probing and worker database provisioning without requiring ibm-db to be installed in the base environment.

Installation#

pip install pytest-databases

Install ibm-db or your preferred Db2 driver in your project if your tests open host-side connections.

Docker Image & Runtime Capabilities#

The default image is icr.io/db2_community/db2:12.1.5.0 on container port 50000. Db2 adjusts kernel IPC parameters and allocates large SysV IPC semaphores during startup, so db2_service starts the container with privileged=True (as in IBM’s documented docker run) and defaults db2_ipc_mode to "host" across Docker and Podman to avoid private IPC exhaustion (SQL1042C / SQLSTATE=57019). Set DB2_IPC_MODE="" (or override db2_ipc_mode to None) if you run isolated IPC namespaces with enlarged container sysctls. Sample database creation is disabled (SAMPLEDB="false", AUTOCONFIG="false") for faster startup.

Storage with 4096-byte logical sectors (for example an overlay2 Docker root on a 4Kn or dm-crypt device) makes Db2’s default direct I/O fail with SQL0293N, and the initial database is never created. db2_service therefore sets the Db2 registry variables DB2_4K_DEVICE_SUPPORT=ON and DB2_DIRECT_IO=NO by default: the image setup script is patched to set them before its first db2start, and if the initial database is still missing after setup (SQL1013N or SQLSTATE 42705) the recovery path runs once under a host filelock.FileLock (under docker_service.temp_dir) and in-container flock serialization (db2stop force, registry update, db2start, and initial database creation). Both settings also work on 512-byte storage, and create_worker_database uses the same locking so concurrent pytest-xdist workers never race. Startup also fast-fails immediately with RuntimeError when SQL1042C or SQLSTATE=57019 appears in container logs. Override the db2_4k_device_support fixture to return False (or set DB2_4K_DEVICE_SUPPORT=off) to start the image unchanged.

Db2Service.exec_sql runs a statement through the in-container db2 command line processor. Exit code 1 (no rows, SQL0100W) and 2 (warnings) count as success and the warning text is returned with the output; error codes of 4 and above raise RuntimeError. By default db2_activate_database is enabled and runs db2 activate database (activate_db2_database() / activate_database()) so in-memory MON_GET_* monitoring snapshots persist across short-lived client connections. Custom fixtures calling provide_db2_service() can also pass registry_vars (extra db2set entries applied before db2start), env, host_port, ipc_mode, volumes, shm_size, mem_limit, platform, and one-shot init_sql scripts.

Note

Db2 database names are restricted to a maximum of 8 characters. Both db2_dbname (default pytestdb) and xdist worker database names (ptdb_0, ptdb_1, …) enforce this 8-character limit.

Usage Example#

from pytest_databases.docker.db2 import Db2Service

pytest_plugins = ["pytest_databases.docker.db2"]


def test_db2_query(db2_service: Db2Service) -> None:
    output = db2_service.exec_sql("SELECT 1 FROM SYSIBM.SYSDUMMY1")
    assert "1" in output
    assert db2_service.connection_config["database"] == db2_service.db_name
    assert "PROTOCOL=TCPIP;" in db2_service.dsn

Available Fixtures#

  • db2_image: Container image (default: icr.io/db2_community/db2:12.1.5.0, env DB2_IMAGE).

  • db2_dbname: 8-character-compliant database name (default: pytestdb, env DB2_DBNAME).

  • db2_username: Instance owner username (default: db2inst1, env DB2_USER).

  • db2_password: Instance owner password (default: pytest_db2_pwd, env DB2_PASSWORD).

  • db2_port: Optional pinned host TCP port for Db2 port 50000 (default: None, env DB2_PORT).

  • db2_startup_timeout: Startup timeout in seconds (default: 600, env DB2_STARTUP_TIMEOUT).

  • db2_4k_device_support: Apply DB2_4K_DEVICE_SUPPORT=ON and DB2_DIRECT_IO=NO (default: True, env DB2_4K_DEVICE_SUPPORT).

  • db2_activate_database: Explicitly activate the database so MON_GET_* metrics persist across disconnects (default: True, env DB2_ACTIVATE_DATABASE).

  • db2_ipc_mode: Container IPC mode (default: "host", env DB2_IPC_MODE; set DB2_IPC_MODE="" or override to None to disable).

  • db2_volumes: Optional volume mount mapping or sequence forwarded to provide_db2_service (default: None).

  • xdist_db2_isolation_level: "database" (per-worker ptdb_<n> database) or "server" (one transient db2_<n> container per xdist worker).

  • db2_service: Db2Service instance.

Service API#

IBM Db2 Community Edition container service fixtures and in-container CLI helpers.

class pytest_databases.docker.db2.Db2Service(container: docker.models.containers.Container, host: str, port: int, db_name: str, username: str, password: str, _lock_path: Path | None = None)[source]#

Bases: ServiceContainer

Connection metadata and CLI helpers for an IBM Db2 container service.

db_name: str#
username: str#
password: str#
property dsn: str#

The CLI/ODBC-style DSN string compatible with ibm_db.connect.

property connection_config: dict[str, str | int]#

Dictionary of connection parameters compatible with Db2 driver configurations.

exec_sql(sql: str, *, db_name: str | None = None) → str[source]#

Execute a SQL statement inside the Db2 container without a host Python driver.

create_worker_database(db_name: str) → None[source]#

Create an isolated Db2 database inside the container.

activate_database(db_name: str | None = None) → str[source]#

Pin db_name (defaults to self.db_name) active in Db2 shared memory.

Returns:

Decoded output from db2 activate database.

__init__(container: docker.models.containers.Container, host: str, port: int, db_name: str, username: str, password: str, _lock_path: Path | None = None) → None#
pytest_databases.docker.db2.activate_db2_database(container: docker.models.containers.Container, db_name: str, *, instance_user: str = 'db2inst1') → str[source]#

Explicitly activate db_name inside a Db2 container so MON_GET_* metrics persist across disconnects.

Without explicit activation, Db2 deactivates a database when the last client disconnects and resets in-memory bufferpool, lock, tablespace, and package-cache counters. CLP exit codes 0 through 2 (including SQL1490W when already active) are treated as idempotent success.

Parameters:
  • container – Running Db2 container.

  • db_name – Target Db2 database name (at most 8 characters).

  • instance_user – Db2 instance owner OS user inside the container.

Returns:

Decoded CLP stdout/stderr message text.

Raises:

RuntimeError – If db2 activate database fails with an error exit code.

pytest_databases.docker.db2.create_worker_database(container: docker.models.containers.Container, db_name: str, *, instance_user: str = 'db2inst1', lock_path: Path | None = None) → None[source]#

Create a Db2 database inside the container if it does not already exist.

Parameters:
  • container – Running Db2 container.

  • db_name – Target Db2 database name (at most 8 characters).

  • instance_user – Db2 instance owner OS user inside the container.

  • lock_path – Optional cross-worker host lock file path serializing catalog writes.

pytest_databases.docker.db2.db2_4k_device_support() → bool[source]#

Whether Db2 runs with DB2_4K_DEVICE_SUPPORT=ON and DB2_DIRECT_IO=NO.

Enabled by default so database creation works on storage with 4096-byte logical sectors. Set the DB2_4K_DEVICE_SUPPORT environment variable to 0/false/no/off or override this fixture to return False to keep the image defaults.

pytest_databases.docker.db2.db2_activate_database() → bool[source]#

Whether Db2 explicitly activates the database so MON_GET_* metrics persist across disconnects.

pytest_databases.docker.db2.db2_dbname(xdist_db2_isolation_level: Literal['database', 'server']) → str[source]#

Provide an 8-character-compliant Db2 database name.

pytest_databases.docker.db2.db2_image() → str[source]#

Provide the IBM Db2 Community Edition container image.

pytest_databases.docker.db2.db2_ipc_mode() → str | None[source]#

Provide the container IPC mode for Db2 (defaults to "host"; empty string omits ipc_mode).

pytest_databases.docker.db2.db2_password() → str[source]#

Provide the Db2 instance owner password.

pytest_databases.docker.db2.db2_port() → int | None[source]#

Provide an optional pinned host TCP port for Db2 (DB2_PORT).

pytest_databases.docker.db2.db2_service(container_service: ContainerService, db2_image: str, db2_dbname: str, db2_username: str, db2_password: str, db2_startup_timeout: int, xdist_db2_isolation_level: XdistIsolationLevel, db2_4k_device_support: bool, db2_activate_database: bool, db2_port: int | None, db2_ipc_mode: str | None, db2_volumes: dict[str, dict[str, str]] | list[str] | None) → Generator[Db2Service, None, None][source]#

Start and yield a ready IBM Db2 Community Edition service container.

Yields:

A configured Db2Service instance.

pytest_databases.docker.db2.db2_startup_timeout() → int[source]#

Provide the startup timeout in seconds for Db2 container initialization.

pytest_databases.docker.db2.db2_username() → str[source]#

Provide the Db2 instance owner username.

pytest_databases.docker.db2.db2_volumes() → dict[str, dict[str, str]] | list[str] | None[source]#

Optional container volume mounts for Db2 (for example {"/host/db2": {"bind": "/database", "mode": "rw"}}).

pytest_databases.docker.db2.exec_db2_sql(container: docker.models.containers.Container, sql: str, *, db_name: str, instance_user: str = 'db2inst1') → str[source]#

Execute a SQL statement inside a running Db2 container via the db2 CLI.

The command line processor exits with 1 when a statement finds no rows (SQL0100W) and with 2 for other warnings. Both count as success, and the CLP message text is part of the returned output so callers can inspect it. Exit codes of 4 and above (errors) raise. All db2 calls run in one shell process because the CLP back end, and therefore the connection, is tied to the calling shell; the connect output goes to a file instead of a command substitution for that reason.

Parameters:
  • container – Running Db2 container.

  • sql – SQL statement to execute.

  • db_name – Target Db2 database name (at most 8 characters).

  • instance_user – Db2 instance owner OS user inside the container.

Returns:

Decoded stdout/stderr from the db2 command sequence, including any warning text.

Raises:

RuntimeError – If connecting or executing the statement fails with a CLP exit code of 4 or higher.

pytest_databases.docker.db2.provide_db2_service(container_service: ContainerService, db2_image: str, db2_dbname: str, db2_username: str, db2_password: str, db2_startup_timeout: int, xdist_db2_isolation_level: XdistIsolationLevel, *, enable_4k_device_support: bool = True, activate_database: bool = True, host_port: int | None = None, env: Mapping[str, str] | None = None, registry_vars: Mapping[str, str] | None = None, shm_size: int | str | None = None, mem_limit: str | None = None, platform: str | None = None, ipc_mode: str | None = 'host', volumes: dict[str, dict[str, str]] | list[str] | None = None, init_sql: str | Path | Sequence[str | Path] | None = None) → Generator[Db2Service, None, None][source]#

Start and yield a ready IBM Db2 Community Edition service container.

With enable_4k_device_support (the default) the instance runs with DB2_4K_DEVICE_SUPPORT=ON and DB2_DIRECT_IO=NO so database creation works when the container storage has 4096-byte logical sectors. Additional db2set settings in registry_vars are chained onto the same pre-db2start setup hook. With activate_database (the default), db2 activate database keeps the database pinned in memory so MON_GET_* monitoring snapshots persist across short-lived client connections.

Parameters:
  • container_service – The container service manager.

  • db2_image – IBM Db2 Community Edition container image.

  • db2_dbname – Database name for the active worker.

  • db2_username – Db2 instance owner username.

  • db2_password – Db2 instance owner password.

  • db2_startup_timeout – Startup timeout in seconds.

  • xdist_db2_isolation_level – xdist isolation strategy (database or server).

  • enable_4k_device_support – Whether to apply the 4096-byte sector registry settings.

  • activate_database – Whether to run db2 activate database on the ready database.

  • host_port – Optional pinned host TCP port for Db2 port 50000.

  • env – Optional extra container environment variables merged over defaults.

  • registry_vars – Optional extra db2set registry KEY=VALUE settings applied before db2start.

  • shm_size – Optional /dev/shm size forwarded to container creation.

  • mem_limit – Optional memory limit forwarded to container creation.

  • platform – Optional OCI platform override (for example "linux/amd64" on Apple Silicon).

  • ipc_mode – Container IPC mode (defaults to "host"; pass None or "" to omit).

  • volumes – Optional container volume mounts (for example /database persistence).

  • init_sql – Optional SQL statement, .sql path, or sequence executed once per database.

Yields:

A configured Db2Service instance.

pytest_databases.docker.db2.validate_db2_database_name(db_name: str) → str[source]#

Validate that a Db2 database name conforms to the 8-character identifier rule.

Parameters:

db_name – Candidate Db2 database name.

Returns:

The validated database name.

Raises:

ValueError – If db_name exceeds 8 characters or contains invalid characters.

pytest_databases.docker.db2.xdist_db2_isolation_level() → Literal['database', 'server'][source]#

Provide the pytest-xdist isolation level for Db2.