Metadata-Version: 2.4
Name: db2-native-driver
Version: 0.1.0a1
Summary: Native IBM Db2 LUW driver for Python speaking DRDA/DDM directly over TCP/TLS
Author: Krzysztof Dusko
License-Expression: MIT
Keywords: db2,ibm,drda,ddm,database,dbapi,asyncio
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Topic :: Database
Classifier: Topic :: Database :: Front-Ends
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: THIRD-PARTY-NOTICES.md
Provides-Extra: dev
Requires-Dist: pytest>=9.2.0; extra == "dev"
Requires-Dist: pytest-asyncio>=1.4.1.post1; extra == "dev"
Requires-Dist: pytest-cov>=7.1.0; extra == "dev"
Requires-Dist: coverage[toml]>=7.17.2; extra == "dev"
Requires-Dist: ruff>=0.17.4; extra == "dev"
Requires-Dist: mypy>=2.4.1; extra == "dev"
Requires-Dist: build>=1.6.1; extra == "dev"
Requires-Dist: twine>=7.0.0; extra == "dev"
Requires-Dist: pip-audit>=2.10.1; extra == "dev"
Provides-Extra: ibm-parity
Requires-Dist: ibm_db>=3.3.0; extra == "ibm-parity"
Requires-Dist: pytest>=9.2.0; extra == "ibm-parity"
Dynamic: license-file

# db2-native-driver — native IBM Db2 LUW driver for Python

[![status: alpha](https://img.shields.io/badge/status-alpha-orange.svg)](https://pypi.org/project/db2-native-driver/)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/license/mit)
[![Python](https://img.shields.io/badge/python-3.11%20%7C%203.12%20%7C%203.13%20%7C%203.14%20%7C%203.15-blue)](https://www.python.org/downloads/)

> **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.
  `threadsafety` is `1`: use one connection per thread, or serialize access
  yourself.
- Independent, idiomatic `asyncio` API (`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_ENCRYPT` server by retrying with 9 (or 7)
  before any credentials are sent, like IBM CLI.
- TLS 1.2/1.3 with certificate validation.
- General-purpose `CancelToken` for 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
  `ResourceBudget` that 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](docs/DRIVER-CONTRACT.md);
known gaps are recorded in [the status file](docs/DRIVER-CONTRACT-STATUS.md) and
cross-driver differences in [the parity matrix](docs/CROSS-DRIVER-PARITY.md).
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:

```bash
pip install --pre db2-native-driver
```

```python
import py_db2
```

## DB-API quick start

```python
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

```python
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

```python
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:

```python
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

```python
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:

```python
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

```python
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`):

```python
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:

```python
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

```python
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:

```python
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

```python
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:

```python
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 an
  `AUTHENTICATION=SERVER_ENCRYPT` server refuses it and lists `9` or `7`, send
  a second `ACCSEC` on the same connection with `9`, else `7`, 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; see
  `docs/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.

```python
py_db2.connect("db2://user:password@host:50000/TESTDB?security_mechanism=7")
```

## Insert with identity

```python
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:

```python
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:

```python
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:

```bash
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:

```bash
./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 compatibility
- `docs/DRIVER-GUIDE.md` — advanced driver guide
- `docs/DRIVER-CONTRACT.md` — JDC v1 observable-behaviour contract
- `docs/DRIVER-CONTRACT-STATUS.md` — repo-specific JDC conformance record
- `docs/KERBEROS.md` — SECMEC 11 / GSSAPI token path and limitations
- `docs/CROSS-DRIVER-PARITY.md` — cross-driver feature matrix and known divergences
- `API-COMPATIBILITY.md` — API compatibility policy
- `RELEASING.md` — manual release checklist
- `CONTRIBUTING.md` — contributing
- `SECURITY.md` — security policy
- `CHANGELOG.md` — changelog

## License and provenance

Licensed under the [MIT License](https://opensource.org/license/mit). The
implementation uses the MIT-licensed [`go-db2`](https://github.com/go-db2/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.
