Skip to main content

st-clickhouse-py

Python bindings for the ClickHouse native TCP protocol - 100% Rust core via PyO3.

A high-performance ClickHouse client that speaks the native protocol directly. No HTTP, no REST, no SQL parsing in Python - the entire protocol is implemented in Rust with Python bindings via PyO3.

Features

  • Native TCP protocol - direct connection to ClickHouse, no HTTP overhead
  • Sync + Async - Client (sync) and AsyncClient (async) APIs
  • Connection pooling - transparent pool (2-8 connections, health checks, idle reaper)
  • True streaming - Rust reader thread + bounded channel, zero thread pool overhead
  • Type-aware conversion - Date to datetime.date, DateTime to datetime.datetime, UUID to string, IPv4/IPv6 to strings
  • Column-oriented access - Block and Column objects for efficient columnar data access
  • GIL-free I/O - all blocking operations release the GIL during network reads/writes
  • Cancellation - cancelling a task aborts its server-side query (the pooled connection is killed and transparently replaced); cancel() fails closed with guidance
  • uvloop compatible - standard asyncio APIs only
  • Python 3.12+ (GIL builds, abi3 wheels) and free-threaded Python 3.14t+ (version-specific cp3XXt wheels). Free threading is supported from 3.14 onward; 3.13 free-threaded builds are not supported (pyo3 0.29 dropped them).
  • Compression - LZ4 and ZSTD support

Quick Start

import st_clickhouse as ch

# Sync
with ch.connect("127.0.0.1:9000") as client:
    rows = client.query("SELECT number FROM system.numbers LIMIT 5")
    for row in rows:
        print(row)

# Async
import asyncio

async def main():
    async with ch.connect_async(
        "127.0.0.1:9000",
        pool_min_size=2,
        pool_max_size=8,
    ) as client:
        rows = await client.query("SELECT 1 AS x")
        print(rows)

asyncio.run(main())

# Streaming (sync)
for block in client.query_stream("SELECT * FROM huge_table"):
    col_a = block["a"]
    values = col_a.to_list()  # → [1, 2, 3, ...]

# Streaming (async) — zero thread pool threads blocked
async for block in client.query_stream("SELECT * FROM huge_table"):
    process(block)

Installation

pip install st-clickhouse-py

Or build from source:

pip install maturin
cd st-clickhouse-py
maturin build --release
pip install target/wheels/st_clickhouse_py-*.whl

API Overview

Sync Client

Method Description
execute(query) DDL/DML, no result rows
query(query) SELECT → list of dicts
query_blocks(query) SELECT → list of Block objects
query_stream(query) SELECT → iterator of Block objects
insert(query, rows) INSERT from list of dicts
insert_blocks(query, table, blocks) INSERT from Block objects
insert_stream(query) → InsertStream Streaming INSERT session
ping() Health check
cancel() Always raises RuntimeError — see Cancellation
server_info() Server metadata (cached)
set_setting(name, value) Session setting

Async Client

Same methods prefixed with async/await, plus connection pooling:

client = AsyncClient(
    "127.0.0.1:9000",
    pool_min_size=2,
    pool_max_size=8,
    pool_acquire_timeout=30.0,
    pool_health_check_interval=30.0,
    pool_max_idle_time=300.0,
)

Cancellation

cancel() on Client, AsyncClient, and AsyncSession always raises RuntimeError. A Cancel packet can only be delivered over the connection running the query, and that connection is blocked inside the query call; sending it anywhere else poisons idle connections. Use the real mechanisms instead:

  • Cancel the awaiting task (task.cancel()): the pooled connection running the query is killed immediately — the server aborts the query — and the pool transparently creates a replacement on the next acquire. The task unwinds in O(1) instead of waiting for the query.
  • Abandon a stream: break out of query_stream (sync or async). If the response never reached its terminal packet (EndOfStream or server exception), the connection is killed the same way. The async pool replaces it; the sync Client is closed and must be recreated (its single connection was left mid-response).
  • Query deadline: Client(..., query_timeout=...) bounds every query.

A stream that is fully consumed releases its connection cleanly and keeps the client/pool usable.

Connection Pool

The pool manages TCP connections transparently:

  • Acquire/release: each operation gets a connection, uses it, returns it
  • Lazy growth: connections created on demand up to pool_max_size
  • Health checks: idle connections are pinged before being served
  • Idle reaper: background thread closes stale connections above min_size
  • Backpressure: asyncio.Queue + Rust channel — if consumer is slow, the reader thread blocks on TCP write, telling ClickHouse to slow down

Architecture

┌─────────────────────────────────────────────────────────────┐
│                     PYTHON                                  │
│  AsyncClient                                                │
│    ├── query/execute → Pool.acquire() → client.query()      │
│    │                              (GIL released during I/O) │
│    └── query_stream → Pool.acquire() → [held for stream]    │
│         └── Rust Reader Thread → mpsc Channel → Forwarder   │
│             (TCP I/O, no GIL)    (bounded 32)  → Queue      │
│                                                    ↓        │
│                                              async for       │
└─────────────────────────────────────────────────────────────┘

Running Tests

Requires a running ClickHouse server:

# Using Docker
docker run -d -p 9000:9000 --name ch-test clickhouse/clickhouse-server

uv run --extra test maturin develop --release
uv run --extra test python -m pytest

Performance

  • Single query: ~50μs overhead over raw TCP (PyO3 FFI + type conversion)
  • Streaming: zero copy per block (Rust reader thread → Python async for)
  • Concurrent: up to pool_max_size parallel queries on separate TCP connections
  • GIL release: all I/O-bound operations release the GIL

License

Apache-2.0

Metadata

Release files for st-clickhouse-py 0.3.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distributions (wheels)

Table of built distributions (wheels) for st-clickhouse-py 0.3.0
File Interpreter ABI Platform Actions
st_clickhouse_py-0.3.0-cp312-abi3-win_amd64.whl CPython 3.12 abi3 Windows x86-64 Details for st_clickhouse_py-0.3.0-cp312-abi3-win_amd64.whl
st_clickhouse_py-0.3.0-cp312-abi3-manylinux_2_34_x86_64.whl CPython 3.12 abi3 Linux glibc 2.34+ x86-64 Details for st_clickhouse_py-0.3.0-cp312-abi3-manylinux_2_34_x86_64.whl
st_clickhouse_py-0.3.0-cp312-abi3-macosx_11_0_arm64.whl CPython 3.12 abi3 macOS 11.0+ ARM64 Details for st_clickhouse_py-0.3.0-cp312-abi3-macosx_11_0_arm64.whl

Total release size: 4.1 MB

Release files / st_clickhouse_py-0.3.0-cp312-abi3-win_amd64.whl

Download URL st_clickhouse_py-0.3.0-cp312-abi3-win_amd64.whl
Size 1.3 MB
Tags CPython 3.12 Windows x86-64 abi3
SHA-256 checksum
How to use checksums
26292254e6d8c31837ebf1bccf5d4a832d73928d0e09be9a007f48ea93110162
BLAKE2b-256 checksum
How to use checksums
8346bb3df9a6861e2e95607fc9d6af1d9b3cb257f3c4ee63eef6d507f8e6bf02
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

Release files / st_clickhouse_py-0.3.0-cp312-abi3-manylinux_2_34_x86_64.whl

Download URL st_clickhouse_py-0.3.0-cp312-abi3-manylinux_2_34_x86_64.whl
Size 1.5 MB
Tags CPython 3.12 Linux glibc 2.34+ x86-64 abi3
SHA-256 checksum
How to use checksums
d0a3c0f2c5d3741d0007e506f27372a1361f7294931f1e52b9a61ec147a36cf0
BLAKE2b-256 checksum
How to use checksums
301c20094234ffbb4b32e40c08b7288a20bdac14a21ff179f6225d9e14ea8c2e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

Release files / st_clickhouse_py-0.3.0-cp312-abi3-macosx_11_0_arm64.whl

Download URL st_clickhouse_py-0.3.0-cp312-abi3-macosx_11_0_arm64.whl
Size 1.3 MB
Tags CPython 3.12 abi3 macOS 11.0+ ARM64
SHA-256 checksum
How to use checksums
1a118c43c8bf052cc0cc3ffbd419baa05d571f66562ae153eedfa59dcaedadec
BLAKE2b-256 checksum
How to use checksums
a698912522c8b133cdb66ad78dfd5daa86bdef2fc4ab5f5473c7209482fac29d
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.14

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.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

Security for st-clickhouse-py 0.3.0

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.

Full provenance

All 3 files in this release have been uploaded with provenance metadata.

Select from 3 files

Attestation for st_clickhouse_py-0.3.0-cp312-abi3-win_amd64.whl

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Sep 2, 2026.

Transparency log

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.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page