This release is a pre-release and may not be stable for production use.
db2-native-driver — native IBM Db2 LUW driver for Python
Alpha software. APIs and protocol coverage may change before a stable release. Validate the driver against your own Db2 environment and workload before production use.
Native IBM Db2 LUW driver for Python that speaks DRDA/DDM directly over TCP/TLS. It does not require IBM CLI, ODBC, JDBC, the IBM .NET driver, or any other Db2 client runtime — the protocol is implemented in pure Python.
- PyPI package:
db2-native-driver - Python import:
py_db2
Independent project: this project is not maintained, endorsed, sponsored, or certified by IBM. IBM and Db2 are trademarks of International Business Machines Corporation.
Highlights
- PEP 249 / DB-API 2.0 synchronous API with
?(qmark) parameters.threadsafetyis1: use one connection per thread, or serialize access yourself. - Independent, idiomatic
asyncioAPI (py_db2.async_) sharing the same DRDA codecs, parser, and row decoder. - Direct and prepared SQL, transactions, streaming rows, LOB materialization and progressive LOB reads, stored procedures, bounded row import, bounded batch execution, and pooling.
- Password authentication (SECMEC 3), DES-encrypted password (SECMEC 7), and
encrypted EUSRIDPWD (SECMEC 9). A connection without a configured mechanism
follows an
AUTHENTICATION=SERVER_ENCRYPTserver by retrying with 9 (or 7) before any credentials are sent, like IBM CLI. - TLS 1.2/1.3 with certificate validation.
- General-purpose
CancelTokenfor sync and asyncio commands, batches, imports and streaming reads, with an idempotent, thread/task-safe DRDA interrupt. - Structured SQLCODE/SQLSTATE errors and fail-closed session cleanup when DRDA stream synchronization cannot be proven.
- Bounded materialization (16 MiB per LOB, 32 MiB per result set), a 1 GiB
streamed-LOB budget with 64 KiB chunks, and a shared 10 GiB spool
ResourceBudgetthat importers reserve against for staged LOB values. DSN protocol-limit keys are validated against documented hard ceilings. - Deterministic offline DRDA replay tests and a live Db2 LUW qualification harness. Protocol/API smoke tests on Linux, Windows, and macOS.
Requirements
- Python 3.11, 3.12, 3.13, 3.14 or 3.15. No mandatory third-party runtime dependency.
- An IBM Db2 LUW server reachable over TCP or TLS.
The maintained live qualification baseline is Db2 LUW 12.1.5 on Linux x64.
Windows and macOS are exercised by protocol/API smoke tests. See
docs/QUALIFICATION.md.
Compatibility
The driver targets Python 3.11, 3.12, 3.13, 3.14 and 3.15, and IBM Db2 LUW.
Live and offline qualification details are in docs/QUALIFICATION.md; the
supported API surface and stability tiers are in API-COMPATIBILITY.md.
Cross-driver contract
The observable behaviour implemented here is defined by JDC v1;
known gaps are recorded in the status file and
cross-driver differences in the parity matrix.
The self-contained contract and shared behaviour vectors are checked by the
offline suite (tests/test_jdc_vectors.py).
Installation
During the alpha phase, install with --pre so pip selects the pre-release:
pip install --pre db2-native-driver
import py_db2
DB-API quick start
import py_db2
conn = py_db2.connect("db2://user:password@localhost:50000/TESTDB")
cursor = conn.cursor()
cursor.execute(
"SELECT ID, NAME FROM APP.CUSTOMERS WHERE ID = ?",
(42,),
)
for row in cursor:
print(row)
conn.close()
Async quick start
from py_db2.async_ import connect
async with await connect("db2://user:password@localhost:50000/TESTDB") as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT ID, NAME FROM APP.CUSTOMERS WHERE ID = ?", (42,))
async for row in cur:
print(row)
Prepared statements
statement = conn.prepare("SELECT NAME FROM APP.CUSTOMERS WHERE ID = ?")
result = conn.query_prepared(statement, (42,))
Per-command options
Every Connection / AsyncConnection / Cursor operation accepts an optional
CommandOptions argument:
from py_db2 import CommandOptions
result = conn.query(
"SELECT * FROM APP.BIG",
options=CommandOptions(timeout_ms=5000), # None = connection timeout, 0 = no deadline
)
conn.execute(
"INSERT INTO APP.T VALUES (?)",
(1,),
options=CommandOptions(user="BATCH", client_info={"application_name": "loader"}),
)
The per-command user and client registers are applied before the operation and stay on the session afterwards (sticky). Omitted or empty client-info fields keep their current value.
Transactions
conn.autocommit = False
try:
conn.execute("INSERT INTO APP.T VALUES (?)", (1,))
conn.execute("INSERT INTO APP.T VALUES (?)", (2,))
conn.commit()
except py_db2.Error:
conn.rollback()
raise
Or use an explicit transaction scope:
with conn.begin_transaction("CS") as tx:
tx.execute("INSERT INTO APP.T VALUES (?)", (1,))
# committed on clean exit, rolled back on exception; isolation restored
Pooling
from py_db2 import Pool, PoolOptions
pool = Pool("db2://user:password@localhost:50000/TESTDB", PoolOptions())
with pool.connection() as conn:
print(conn.query("VALUES 1").rows)
# One-shot helpers acquire and return a lease for you.
print(pool.query("VALUES 1").rows)
pool.execute("INSERT INTO APP.T VALUES (?)", (1,))
pool.with_connection(lambda conn: conn.current_schema)
# query_stream keeps the lease until the reader is exhausted or closed.
for row in pool.query_stream("SELECT ID FROM APP.T"):
print(row)
print(pool.stats) # connections, idle, active, waiting, discarded, ...
pool.drain_idle() # close idle sessions, keep the pool usable
pool.shutdown(10) # stop admission, wait for leases, close everything
The asyncio pool has the same helpers (query, execute, execute_batch,
call_procedure, query_stream, with_connection):
from py_db2.async_ import AsyncPool, PoolOptions
pool = AsyncPool(dsn, PoolOptions(max_size=8))
async with await pool.acquire() as conn:
await conn.query("VALUES 1")
print((await pool.query("VALUES 1")).rows)
await pool.shutdown(10)
PoolOptions.connection_factory accepts a callable
factory(config, connect_timeout_ms=...) for injecting custom connections;
clear_all_pools() / clear_all_async_pools() shut down every live pool.
observe_diagnostics() subscribes to metadata-only timing events (connect,
acquire, execute, reset, discard) without ever receiving SQL or credentials.
PoolStats exposes connections, idle, active, waiting, discarded,
acquire_timeouts, exhausted, and created. Defaults are 10 connections,
100 waiters, 30 s acquire, 10 s connect, 300 s idle, 1800 s lifetime and 30 s
reap. An idle/lifetime reaper runs in the background (reap_interval); expiry
is also enforced on acquire and release. Every pool interval, including
reap_interval, must be positive.
Bulk import
ImportTarget builds a fully quoted INSERT; ImportPolicy chooses one atomic
transaction or a commit per bounded batch:
from py_db2 import ImportOptions, ImportPolicy, ImportTarget, import_rows
target = ImportTarget(
schema="APP", table="CUSTOMERS", columns=["ID", "NAME"],
expected_sql_types=[496, 448], # checked before the first write
)
progress = import_rows(
conn, target, source_rows,
ImportOptions(
policy=ImportPolicy.ATOMIC,
max_batch_rows=256,
max_batch_bytes=8 * 1024 * 1024, # soft: one oversized row is sent alone
table_lock=True, # exclusive lock inside the transaction
notify_after_rows=10_000,
on_progress=print,
),
)
print(progress.committed_rows, progress.committed_batches)
ImportOptions.commit_every/observer remain supported; the default policy is
ATOMIC and progress is reported every 10,000 rows. Pass policy=None
explicitly to use the commit-every-commit_every mode.
async_import_rows accepts a sync or async row source. table_lock requires
ImportPolicy.ATOMIC and an ImportTarget; invalid combinations fail before
any I/O.
With an ImportTarget, each batch is sent as a multi-row
INSERT ... VALUES (...), (...) statement (at most 1024 rows per statement),
with one cached prepared statement per chunk size. A plain SQL string still
uses one prepared insert per row.
Streaming and large objects
reader = conn.query_stream("SELECT ID, PAYLOAD FROM APP.BLOB_TABLE")
for row in reader:
print(row[0], len(row[1]))
Materialized LOBs are bounded to 16 MiB and a materialized result set to 32 MiB. Larger values use the streaming reader and progressive LOB locators.
Bind a file or stream as a LOB parameter:
from py_db2 import blob
conn.execute("INSERT INTO APP.BLOB_TABLE VALUES (?, ?)", (1, blob("/path/data.bin")))
Streamed LOB parameters are written as bounded EXTDTA/DSS segments (64 KiB by
default) and never materialized in memory. ProtocolLimits.max_streamed_lob_bytes
(default 1 GiB) rejects an oversized source before any SQL is sent, and
lob_chunk_bytes tunes the read size. A reader opened by the driver (a path or
in-memory buffer passed to blob/clob/xml) is closed after the value has
been streamed; a reader supplied by the caller stays open. Pass
CommandOptions(cancel=CancelToken()) to abort a stream between chunks
deterministically.
Cancellation
handle_conn.interrupt() # sends a DRDA SQL interrupt using the session token
from py_db2 import CancelToken, CommandOptions
token = CancelToken()
conn.execute_prepared(statement, params, options=CommandOptions(cancel=token))
token.cancel() # interrupts the running command from any thread/task
The same token works for sync and asyncio commands, execute_batch, imports
(ImportOptions(cancel=token)) and streaming reads. Cancellation before any
request is written is not_started; a confirmed -952 is OPERATION_CANCELLED
with outcome confirmed. interrupt() is idempotent and thread/task-safe.
An interrupt acknowledgment does not by itself prove that the original command has stopped; await the original operation, which may also complete normally if it won the race.
TLS
Use db2s:// and configure a trusted CA:
py_db2.connect(
"db2s://user:password@db2.example.com:50001/PRODDB"
"?ssl_root_ca=/etc/db2/ca.pem"
)
IBM CLI-style key/value strings are accepted for a documented subset, including
Security=SSL and SSLServerCertificate=.... Unsupported security modes fail
validation instead of silently falling back to plaintext.
Authentication
Mechanism selection:
- not set (default): request
3(USRIDPWD). If anAUTHENTICATION=SERVER_ENCRYPTserver refuses it and lists9or7, send a secondACCSECon the same connection with9, else7, before any credentials are sent. 3(Authentication=SERVER): cleartext user ID and password on the DRDA stream.7(usrencpwd,encrypted_password_security): cleartext user ID and a DES-CBC-encrypted password (ENCALG=1). AES (ENCALG=2) fails closed before credentials are sent.9(Authentication=SERVER_ENCRYPT,secmec9): Diffie-Hellman key agreement and encrypted user ID and password.11(kerberos,gssapi): caller-supplied GSSAPI token file; seedocs/KERBEROS.md. The driver never acquires tickets itself.
An explicitly configured mechanism, including 3, is never changed. When the
server refuses it, the error names every mechanism the server accepts and the
SECCHKCD, before SECCHK is sent.
py_db2.connect("db2://user:password@host:50000/TESTDB?security_mechanism=7")
Insert with identity
result = conn.execute_insert("INSERT INTO APP.T (VAL) VALUES (?)", (7,))
print(result.rows_affected, result.last_insert_id) # via IDENTITY_VAL_LOCAL()
cursor.execute_insert("INSERT INTO APP.T (VAL) VALUES (8)")
print(cursor.lastrowid)
Stored procedures
OUT and INOUT parameters are supported:
result = conn.call_procedure("CALL APP.GET_CUSTOMER(?, ?)", (42, None))
print(result.output_parameters)
Dynamic (cursor-returning) result sets are materialized in
ProcedureResult.result_sets; call_procedure_stream yields them lazily:
for event, columns, row in conn.call_procedure_stream("CALL APP.LIST_CUSTOMERS()"):
print(event, columns, row)
Supported types
| Db2 type | Python type |
|---|---|
SMALLINT / INTEGER / BIGINT |
int |
REAL / DOUBLE / FLOAT |
float |
DECIMAL / NUMERIC |
decimal.Decimal |
DECFLOAT |
decimal.Decimal |
CHAR / VARCHAR / CLOB / GRAPHIC / DBCLOB / XML |
str |
BINARY / VARBINARY / BLOB |
bytes |
BOOLEAN |
bool |
DATE |
datetime.date |
TIME |
datetime.time |
TIMESTAMP |
datetime.datetime |
NULL |
None |
Known limitations
- Db2 for z/OS and Db2 for IBM i are not verified and are not claimed as supported. Only Db2 LUW 12.1.5 is in the live baseline.
- Kerberos / GSSAPI (SECMEC 11) is experimental and requires a caller-supplied GSSAPI token file; there is no hidden fallback to password authentication.
- Trusted-context user switching requires matching server configuration and is experimental.
- Stored-procedure support covers OUT/INOUT parameters and dynamic result sets; exotic procedure shapes may still be incomplete.
Testing
Offline protocol and API tests:
PYTHONPATH=src python3 -m pytest tests -q
ruff check src tests
mypy
python3 -m build
Live Db2 tests start an isolated, pinned Db2 Community container:
./scripts/test-db2-integration.sh # smoke suite
./scripts/test-db2-integration.sh --full # full live suite + second DB
./scripts/test-db2-integration.sh --secmec7 # SERVER_ENCRYPT lane
./scripts/test-db2-integration.sh --tls # TLS lane
./scripts/test-db2-integration.sh --large-data # 1 GiB streamed BLOB lane
./scripts/test-db2-integration.sh --soak # pool/LOB soak lane
Running the IBM image means accepting its applicable license terms.
Documentation
docs/QUALIFICATION.md— qualification and compatibilitydocs/DRIVER-GUIDE.md— advanced driver guidedocs/DRIVER-CONTRACT.md— JDC v1 observable-behaviour contractdocs/DRIVER-CONTRACT-STATUS.md— repo-specific JDC conformance recorddocs/KERBEROS.md— SECMEC 11 / GSSAPI token path and limitationsdocs/CROSS-DRIVER-PARITY.md— cross-driver feature matrix and known divergencesAPI-COMPATIBILITY.md— API compatibility policyRELEASING.md— manual release checklistCONTRIBUTING.md— contributingSECURITY.md— security policyCHANGELOG.md— changelog
License and provenance
Licensed under the MIT License. The
implementation uses the MIT-licensed go-db2
project as a primary DRDA protocol reference; required notices are retained in
THIRD-PARTY-NOTICES.md. This project does not bundle IBM CLI libraries or IBM
driver binaries.
Metadata
Release files for db2-native-driver 0.1.0a1
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| db2_native_driver-0.1.0a1.tar.gz | 241.8 kB | Without provenance | Details for db2_native_driver-0.1.0a1.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| db2_native_driver-0.1.0a1-py3-none-any.whl | Python 3 | none | any | Details for db2_native_driver-0.1.0a1-py3-none-any.whl |
Total release size: 383.8 kB
Release files / db2_native_driver-0.1.0a1.tar.gz
| Download URL | db2_native_driver-0.1.0a1.tar.gz |
|---|---|
| Size | 241.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
4291facbd416ad5414b9aa7aac74790a7f003fb59e1acc8058aeee5ff1266182
|
|
BLAKE2b-256 checksum How to use checksums |
f9b706d774fb77d0e87de82adf2d3ba6a002c581be8776d5d3e028bf47cb6129
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Release files / db2_native_driver-0.1.0a1-py3-none-any.whl
| Download URL | db2_native_driver-0.1.0a1-py3-none-any.whl |
|---|---|
| Size | 142.0 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
1d6461315a3179701f548cfbeea55e86ede0b65774f9c9688ba07cc273c3e188
|
|
BLAKE2b-256 checksum How to use checksums |
15b4dcb411ad5025e9a1e18bd4bbc245654342a8f6f84296cc99750fc480e11f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.11.9
|
Security for db2-native-driver 0.1.0a1
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.