Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ Naming used here is the same as in ClickHouse docs.
- Logging ([PSR-3 compliant](https://www.php-fig.org/psr/psr-3/))
- SQL Factory for [parameters "binding"](#parameters-binding)
- [Native query parameters](#native-query-parameters) support
- Native TCP alongside HTTP, with typed binary results and row inserts

## Contents

Expand All @@ -28,6 +29,7 @@ Naming used here is the same as in ClickHouse docs.
- [Insert](#insert)
- [Async API](#async-api)
- [Select](#select-1)
- [Native TCP](#native-tcp)
- [Parameters "binding"](#parameters-binding)
- [Native Query Parameters](#native-query-parameters)
- [Custom Query Parameter Value Conversion](#custom-query-parameter-value-conversion)
Expand Down Expand Up @@ -249,6 +251,49 @@ $client = new PsrClickHouseAsyncClient(
$output = $client->select('SELECT 1 AS data', new JsonEachRow())->await();
```

## Native TCP

Native TCP is a separate, synchronous client. Existing HTTP clients and their format-based interfaces are unchanged.
It uses the actual ClickHouse TCP protocol, not `FORMAT Native` over HTTP.

```php
<?php

use SimPod\ClickHouseClient\Client\Native\ConnectionConfig;
use SimPod\ClickHouseClient\Client\NativeClickHouseClient;

$client = new NativeClickHouseClient(new ConnectionConfig(
host: 'localhost',
database: 'default',
user: 'default',
password: '',
));

try {
$result = $client->selectWithParams(
'SELECT {name:String} AS name, toUInt32(42) AS count',
['name' => 'Alice'],
);

// Column metadata: $result->columns[0]->name and ->type.
// Positional rows in column order: [['Alice', 42]].
$rows = $result->rows;

// Binary column blocks; the server supplies the column types.
$client->insert('events', [[42, 'Alice']], ['id', 'name']);
} finally {
$client->close();
}
```

For remote connections, enable verified TLS with `tls: true` (default port `9440`).
Without TLS, port `9000` is used and credentials travel unencrypted. Use plaintext only on a trusted network.
Custom ports, connection/I/O timeouts, a CA file, and a TLS server name are supported.

This first version has buffered results, bounded insert batches, no compression, and no async TCP or arbitrary format streams.
It is not a drop-in implementation of the HTTP `ClickHouseClient` interface.
See [native TCP capabilities and value mappings](docs/native-tcp.md) before migrating queries.

## Parameters "binding"

```php
Expand Down
6 changes: 5 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@
"client",
"php",
"http",
"HTTP client"
"HTTP client",
"tcp"
],
"homepage": "https://github.com/simPod/ClickHouseClient",
"license": "MIT",
Expand Down Expand Up @@ -50,6 +51,9 @@
"phpunit/phpunit": "^13.0",
"symfony/http-client": "^8.0"
},
"suggest": {
"ext-openssl": "Required for verified TLS connections with the native TCP client."
},
"autoload": {
"psr-4": {
"SimPod\\ClickHouseClient\\": "src/"
Expand Down
58 changes: 58 additions & 0 deletions docs/adr/0001-native-tcp-client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
# Native TCP alongside HTTP

## Status

Accepted

## Context

The client currently uses ClickHouse HTTP. Its public interface requires a SQL output
format and parses formatted response bytes. Native TCP instead carries typed column
blocks and has a stateful query and insert exchange. A TCP client must handle protocol
revision gates, binary column encodings, and complete packet sequences.

Native TCP support must not change existing HTTP callers or require converting native
blocks into JSON merely to reuse HTTP output parsers.

## Decision

Add `NativeClickHouseClient` with a separate result interface. Keep the HTTP interfaces
and implementations unchanged. Reuse existing SQL preparation, parameter discovery,
parameter value converters, server settings, table identifiers, and SQL logging where
their contracts apply.

The initial implementation uses synchronous PHP streams on 64-bit PHP and advertises
protocol revision 54459. Newer servers negotiate that revision; older revisions are
rejected. Implement only the fields and column encodings supported at that revision.
TLS verifies the peer certificate and name. Plain TCP remains available for trusted
networks. Add no native extensions or protocol dependencies.

Return buffered positional rows and column metadata. Send inserts in bounded batches,
using the schema supplied by the server. Drain responses through `EndOfStream` before
connection reuse. Close on any protocol, I/O, server, or caller-supplied insert failure.
Do not automatically retry a query with an uncertain outcome.

Compression, async TCP, streamed query results, arbitrary formatted payloads, external
tables, and unsupported binary types are outside the initial implementation. Report
unsupported types explicitly instead of changing values or silently selecting HTTP.

## Consequences

HTTP behavior remains compatible. Native TCP callers learn a small separate interface
and receive typed values without JSON conversion. They cannot use HTTP format parsers
or HTTP-only snippets directly with the native client.

Buffered results consume memory in proportion to the result size and have a cumulative
allocation budget. Decoders share a per-block budget, including nested values, before
allocation. One connection runs one query at a time. Applications need separate clients
for independent operations.
Insert errors can leave previously accepted blocks on the server, so callers must not
assume rollback or retry inserts without their own deduplication policy.

Supporting more types and newer revisions requires explicit wire codecs and independent
protocol fixtures plus server integration coverage. Native TCP performance must be
measured rather than assumed.

See [native TCP capabilities](../native-tcp.md), the
[native protocol specification](https://clickhouse.com/docs/resources/develop-contribute/native-protocol/protocol),
and the [native format specification](https://clickhouse.com/docs/resources/develop-contribute/native-protocol/format).
110 changes: 110 additions & 0 deletions docs/native-tcp.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# Native TCP

`Client\NativeClickHouseClient` uses ClickHouse's native TCP protocol alongside the
existing HTTP clients. It requires 64-bit PHP and a server supporting protocol revision
54459 or newer. The existing CI server matrix starts at ClickHouse 24.3.

## Connection

Pass `Client\Native\ConnectionConfig` to the client. Connections open lazily and remain
open after successful operations. `close()` releases the socket; the next operation
opens a new connection. Each client owns one connection and runs one operation at a time.

The default port is 9000, or 9440 with `tls: true`. TLS always checks the server
certificate and hostname. `caFile` selects a private CA, and `serverName` selects the
verified TLS name when connecting through a tunnel. There is no option to disable
certificate verification. The PHP OpenSSL extension is required for TLS.

`connectTimeout` defaults to 5 seconds. `readTimeout` defaults to 30 seconds and is an
I/O timeout, not a whole-query deadline. Without TLS, credentials are sent in plaintext.

## Operations and results

- `select($sql, $settings)` returns a buffered `Native\Result`.
- `selectWithParams($sql, $params, $settings)` supports existing `:name` SQL substitution
and server-side `{name:Type}` parameters. Native parameters are serialized as String
Field dumps, not HTTP `param_*` values.
- `executeQuery()` and `executeQueryWithParams()` execute SQL and discard result rows.
- `insert($table, $values, $columns, $settings)` sends binary blocks, not SQL value literals.

Per-operation settings override constructor defaults. Unknown server settings are
important and cause a server error instead of being silently ignored. The
`output_format_native_encode_types_in_binary_format` setting is not supported.

`Result::$columns` contains ordered `Column` objects with `name` and `type` strings.
`Result::$rows` contains positional lists in that order. This retains duplicate column
names without overwriting data. `totals` and `extremes` contain their separate rows when
requested by the query. Progress, logs, and profile packets are consumed internally.

Results are fully received before returning, including any late server exception.
Zero-row schema and boundary blocks do not end a query; only `EndOfStream` does.
There is no `Format` argument: TCP always carries native blocks, even if SQL includes
a `FORMAT` clause. Use HTTP when server-produced JSON, CSV, or other formats are needed.

## Binary value mappings

Supported types are `Int8/16/32/64`, `UInt8/16/32/64`, `Float32/64`, `Bool`, `String`,
`FixedString(N)`, `Date`, `Date32`, `DateTime`, `DateTime64`, `Nullable(T)`, `Array(T)`, and
unnamed `Tuple(T, ...)`.
`Enum8` and `Enum16` use signed numeric indexes. Inserts require an index declared
by the enum type; enum query parameters instead use label strings.

Integers map to PHP integers. `UInt64` values above `PHP_INT_MAX` map to exact decimal
strings, never floats. Insert values must fit the declared column type.
Floats map to PHP floats; booleans map to PHP booleans. Strings retain arbitrary bytes,
including NUL; they need not be UTF-8. Fixed strings retain padding bytes.

Dates use integer day counts since 1970-01-01. `DateTime` uses integer Unix seconds.
`DateTime64` uses integer ticks at its declared scale. Timezone annotations remain in
column metadata; values are not converted to formatted local dates. Inserts use the
same representations. Nullable values use PHP `null`; arrays and tuples use ordered PHP lists.

Unsupported types fail explicitly. This includes wide integers, decimals, UUID/IP
types, named tuples, LowCardinality, Map, JSON/Dynamic/Variant, and aggregate states.
Type support for query parameters is independent of binary result support:
a parameter converter does not make that type readable in a result block.
Nested nullable nulls and nested date values are not supported by the existing parameter
converter registry. For those composite parameters, supply correctly serialized text
or use a custom converter. Top-level nullable nulls are supported.

## Inserts and failures

Provide positional row lists and optionally an ordered list of column names. Omit
column names to use the server's insert schema order. Associative rows and HTTP-style
name-to-type column maps are not supported. Iterable input is consumed in batches;
`insertBlockSize` defaults to 10000 and is limited to 1000000 rows per block.

Empty input is rejected. Every row must match the returned schema. The codec validates
values rather than truncating or wrapping them. Server errors use `NativeServerError`,
with the ClickHouse error code, exception name, and server stack trace. I/O, unsupported
type, and malformed protocol errors use `RuntimeException`.

Any failure closes the connection. A later operation reconnects, but the failed operation
is never retried automatically. Previously accepted insert blocks may remain stored;
there is no client rollback guarantee. Apply a deliberate deduplication policy before
retrying an insert whose outcome is uncertain.

Received strings and individual binary reads are limited to 64 MiB, blocks to 1024
columns and 1000000 rows, and nested encodings to a bounded depth. Column names are
limited to 64 KiB and type declarations to 4096 bytes. A shared 64 MiB allocation budget
accounts conservatively for decoded containers, cells, and payload bytes within a block.
Buffered results have the same cumulative budget across data, totals, and extremes.
This is an allocation estimate, not a limit on PHP process memory. Use HTTP streaming
for larger unbounded reads until native result streaming is available.

## Initial limits

No compression, async TCP, native result streaming, external tables, pooling, cancellation,
or arbitrary formatted payload insertion is included. Do not share one client across
concurrent operations. No automatic fallback to HTTP is performed.

The [architecture decision](adr/0001-native-tcp-client.md) explains the separate interfaces
and protocol revision choice.

## Integration configuration

Native integration tests use `CLICKHOUSE_TCP_HOST` and `CLICKHOUSE_TCP_PORT`, defaulting
to `127.0.0.1:9000`. Set `CLICKHOUSE_TCP_TLS=1` for TLS; `CLICKHOUSE_TCP_CA_FILE` and
`CLICKHOUSE_TCP_SERVER_NAME` select the CA file and verified certificate name.
Database and credentials use the existing `CLICKHOUSE_DATABASE`, `CLICKHOUSE_USER`,
and `CLICKHOUSE_PASSWORD` variables. Insert tests use connection-local temporary tables.
132 changes: 132 additions & 0 deletions src/Client/Native/BinaryStream.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
<?php

declare(strict_types=1);

namespace SimPod\ClickHouseClient\Client\Native;

use RuntimeException;
use SensitiveParameter;

use function fclose;
use function fread;
use function fwrite;
use function is_resource;
use function ord;
use function pack;
use function strlen;
use function substr;

/** @internal */
final class BinaryStream
{
/** @param resource $stream */
public function __construct(private mixed $stream)
{
if (! is_resource($stream)) {
throw new RuntimeException('Expected an open native protocol stream.');
}
}

public function __destruct()
{
$this->close();
}

public function read(int $length): string
{
if ($length < 0 || $length > 67108864) {
throw new RuntimeException('Native protocol read exceeds the 64 MiB limit.');
}

$bytes = '';
$remaining = $length;
while ($remaining > 0) {
$chunk = @fread($this->stream, $remaining);
if ($chunk === false || $chunk === '') {
throw new RuntimeException('Native protocol read failed: timeout or closed connection.');
}

$bytes .= $chunk;
$remaining -= strlen($chunk);
}

return $bytes;
}

public function write(
#[SensitiveParameter]
string $bytes,
): void {
$offset = 0;
$length = strlen($bytes);
while ($offset < $length) {
$written = @fwrite($this->stream, substr($bytes, $offset));
if ($written === false || $written === 0) {
throw new RuntimeException('Native protocol write failed: timeout or closed connection.');
}

$offset += $written;
}
}

public function readVarUInt(): int
{
$value = 0;
for ($shift = 0; $shift <= 56; $shift += 7) {
$byte = ord($this->read(1));
$value |= ($byte & 127) << $shift;
if (($byte & 128) === 0) {
return $value;
}
}

throw new RuntimeException('Native protocol VarUInt exceeds PHP_INT_MAX.');
}

public function writeVarUInt(int $value): void
{
if ($value < 0) {
throw new RuntimeException('Native protocol VarUInt must not be negative.');
}

$bytes = '';
do {
$byte = $value & 127;
$value >>= 7;
$bytes .= pack('C', $byte | ($value > 0 ? 128 : 0));
} while ($value > 0);

$this->write($bytes);
}

public function readString(int $maxBytes = 67108864): string
{
$length = $this->readVarUInt();
if ($length > $maxBytes) {
throw new RuntimeException('Native protocol string exceeds its size limit.');
}

return $this->read($length);
}

public function writeString(
#[SensitiveParameter]
string $value,
): void {
if (strlen($value) > 67108864) {
throw new RuntimeException('Native protocol string exceeds the 64 MiB limit.');
}

$this->writeVarUInt(strlen($value));
$this->write($value);
}

public function close(): void
{
if (! is_resource($this->stream)) {
return;
}

fclose($this->stream);
}
}
Loading
Loading