diff --git a/README.md b/README.md index 18a633c1..d2815e71 100644 --- a/README.md +++ b/README.md @@ -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 @@ -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) @@ -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 +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 diff --git a/composer.json b/composer.json index d84f5621..c95d9df4 100644 --- a/composer.json +++ b/composer.json @@ -7,7 +7,8 @@ "client", "php", "http", - "HTTP client" + "HTTP client", + "tcp" ], "homepage": "https://github.com/simPod/ClickHouseClient", "license": "MIT", @@ -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/" diff --git a/docs/adr/0001-native-tcp-client.md b/docs/adr/0001-native-tcp-client.md new file mode 100644 index 00000000..dcdd931f --- /dev/null +++ b/docs/adr/0001-native-tcp-client.md @@ -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). diff --git a/docs/native-tcp.md b/docs/native-tcp.md new file mode 100644 index 00000000..f0fd21aa --- /dev/null +++ b/docs/native-tcp.md @@ -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. diff --git a/src/Client/Native/BinaryStream.php b/src/Client/Native/BinaryStream.php new file mode 100644 index 00000000..2ff64693 --- /dev/null +++ b/src/Client/Native/BinaryStream.php @@ -0,0 +1,132 @@ +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); + } +} diff --git a/src/Client/Native/Block.php b/src/Client/Native/Block.php new file mode 100644 index 00000000..acfaaf94 --- /dev/null +++ b/src/Client/Native/Block.php @@ -0,0 +1,20 @@ + $columns + * @param list> $rows + */ + public function __construct( + public array $columns = [], + public array $rows = [], + public int $estimatedBytes = 0, + ) { + } +} diff --git a/src/Client/Native/BlockCodec.php b/src/Client/Native/BlockCodec.php new file mode 100644 index 00000000..4107b61c --- /dev/null +++ b/src/Client/Native/BlockCodec.php @@ -0,0 +1,130 @@ +types = new TypeCodec(); + } + + public function read(BinaryStream $stream): Block + { + if ($this->revision > 0) { + $this->readInfo($stream); + } + + $columnCount = $stream->readVarUInt(); + $rowCount = $stream->readVarUInt(); + $this->validateSize($columnCount, $rowCount); + $budget = new DecodeBudget(); + $budget->consume($rowCount * 256 + $columnCount * 256); + + $columns = []; + $rows = []; + for ($row = 0; $row < $rowCount; $row++) { + $rows[] = []; + } + + for ($column = 0; $column < $columnCount; $column++) { + $name = $stream->readString(65536); + $type = $stream->readString(4096); + $budget->consume(strlen($name) + strlen($type)); + if ($this->revision >= 54454 && ord($stream->read(1)) !== 0) { + throw new RuntimeException('Native custom serialization is not supported for type ' . $type . '.'); + } + + $columns[] = new Column($name, $type); + foreach ($this->types->read($stream, $type, $rowCount, $budget) as $row => $value) { + $rows[$row][] = $value; + } + } + + return new Block($columns, $rows, $budget->used); + } + + public function write(BinaryStream $stream, Block $block): void + { + $columnCount = count($block->columns); + $rowCount = count($block->rows); + $this->validateSize($columnCount, $rowCount); + // @phpstan-ignore function.alreadyNarrowedType, function.alreadyNarrowedType, booleanOr.alwaysFalse (Validate caller arrays before writing protocol bytes.) + if (! array_is_list($block->columns) || ! array_is_list($block->rows)) { + throw new RuntimeException('Native block columns and rows must be lists.'); + } + + foreach ($block->rows as $row) { + // @phpstan-ignore function.alreadyNarrowedType (PHP does not enforce list PHPDoc types at runtime.) + if (! array_is_list($row) || count($row) !== $columnCount) { + throw new RuntimeException('Native block row does not match its column count.'); + } + } + + if ($this->revision > 0) { + $stream->write("\x01\x00\x02\xff\xff\xff\xff\x00"); + } + + $stream->writeVarUInt($columnCount); + $stream->writeVarUInt($rowCount); + foreach ($block->columns as $index => $column) { + $stream->writeString($column->name); + $stream->writeString($column->type); + if ($this->revision >= 54454) { + $stream->write("\x00"); + } + + $values = []; + foreach ($block->rows as $row) { + $values[] = $row[$index]; + } + + $this->types->write($stream, $column->type, $values); + } + } + + private function readInfo(BinaryStream $stream): void + { + $seen = []; + while (($field = $stream->readVarUInt()) !== 0) { + if (isset($seen[$field])) { + throw new RuntimeException('Duplicate native BlockInfo field.'); + } + + $seen[$field] = true; + switch ($field) { + case 1: + if (ord($stream->read(1)) > 1) { + throw new RuntimeException('Invalid native BlockInfo overflow flag.'); + } + + break; + case 2: + $stream->read(4); + + break; + default: + throw new RuntimeException('Unsupported native BlockInfo field ' . $field . '.'); + } + } + } + + private function validateSize(int $columns, int $rows): void + { + if ($columns > 1024 || $rows > 1000000 || ($columns === 0 && $rows !== 0)) { + throw new RuntimeException('Native block exceeds column or row limits.'); + } + } +} diff --git a/src/Client/Native/Column.php b/src/Client/Native/Column.php new file mode 100644 index 00000000..d027bd5f --- /dev/null +++ b/src/Client/Native/Column.php @@ -0,0 +1,12 @@ +blockCodec = new BlockCodec(self::Revision); + } + + /** + * @param array $parameters + * @phpstan-param Settings $settings + */ + public function startQuery(string $sql, array $settings, array $parameters): string + { + if ($this->queryActive) { + throw new RuntimeException('A native TCP connection can run only one query at a time.'); + } + + if (count($settings) > 65536 || count($parameters) > 65536) { + throw new RuntimeException('Too many native query settings or parameters.'); + } + + // This changes the column framing and is not supported by this client. + if ((string) ($settings['output_format_native_encode_types_in_binary_format'] ?? 0) !== '0') { + throw new RuntimeException('Binary-encoded native type names are not supported.'); + } + + $this->connect(); + $stream = $this->stream; + assert($stream !== null); + try { + $id = bin2hex(random_bytes(16)); + } catch (RandomException $error) { + throw new RuntimeException('Cannot generate a native query identifier.', 0, $error); + } + + try { + $this->queryActive = true; + $stream->writeVarUInt(1); // Query + $stream->writeString($id); + $this->writeClientInfo($stream); + foreach ($settings as $name => $value) { + $stream->writeString($name); + $stream->writeVarUInt(1); // Important: do not silently ignore unknown settings. + $stream->writeString((string) $value); + } + + $stream->writeString(''); + $stream->writeString(''); // Inter-server secret (unused by external clients). + $stream->writeVarUInt(2); // Complete query processing stage. + $stream->writeVarUInt(0); // No compression. + $stream->writeString($sql); + foreach ($parameters as $name => $value) { + $stream->writeString($name); + $stream->writeVarUInt(2); // Custom setting: query parameter. + $stream->writeString($value); + } + + $stream->writeString(''); + // Finish external tables, including for INSERT. Insert rows follow the sample schema. + $this->sendBlock(new Block()); + } catch (Throwable $error) { + $this->close(); + + throw $error; + } + + return $id; + } + + /** @return array{int, Block|null} */ + public function receive(): array + { + $stream = $this->stream; + if ($stream === null || ! $this->queryActive) { + throw new RuntimeException('No active native TCP query.'); + } + + try { + $type = $stream->readVarUInt(); + switch ($type) { + case 1: // Data + case 7: // Totals + case 8: // Extremes + case 10: // Logs + case 14: // ProfileEvents + $stream->readString(); // External table name. + + return [$type, $this->blockCodec->read($stream)]; + case 2: + throw $this->readException($stream); + case 3: // Progress, revision 54459. + for ($i = 0; $i < 5; ++$i) { + $stream->readVarUInt(); + } + + break; + case 5: // EndOfStream: only this packet signals successful completion. + $this->queryActive = false; + + break; + case 6: // ProfileInfo + $stream->readVarUInt(); + $stream->readVarUInt(); + $stream->readVarUInt(); + $stream->read(1); + $stream->readVarUInt(); + $stream->read(1); + + break; + case 11: // TableColumns + $stream->readString(); + $stream->readString(); + + break; + default: + throw new RuntimeException('Unsupported native server packet: ' . $type); + } + + return [$type, null]; + } catch (Throwable $error) { + $this->close(); + + throw $error; + } + } + + public function sendBlock(Block $block): void + { + $stream = $this->stream; + if ($stream === null || ! $this->queryActive) { + throw new RuntimeException('No active native TCP query.'); + } + + try { + $stream->writeVarUInt(2); // Client Data + $stream->writeString(''); + $this->blockCodec->write($stream, $block); + } catch (Throwable $error) { + $this->close(); + + throw $error; + } + } + + public function close(): void + { + $this->stream?->close(); + $this->stream = null; + $this->queryActive = false; + } + + private function connect(): void + { + if ($this->stream !== null) { + return; + } + + $host = $this->config->host; + if (str_contains($host, ':') && $host[0] !== '[') { + $host = '[' . $host . ']'; + } + + $contextOptions = ['socket' => ['tcp_nodelay' => true]]; + if ($this->config->tls) { + $contextOptions['ssl'] = [ + 'verify_peer' => true, + 'verify_peer_name' => true, + 'allow_self_signed' => false, + 'peer_name' => $this->config->serverName ?? $this->config->host, + ]; + if ($this->config->caFile !== null) { + $contextOptions['ssl']['cafile'] = $this->config->caFile; + } + } + + $socket = @stream_socket_client( + ($this->config->tls ? 'tls://' : 'tcp://') . $host . ':' . $this->config->port, + $errorCode, + $errorMessage, + $this->config->connectTimeout, + STREAM_CLIENT_CONNECT, + stream_context_create($contextOptions), + ); + if ($socket === false) { + throw new RuntimeException('Cannot connect to native TCP endpoint: ' . $errorMessage, $errorCode ?? 0); + } + + $seconds = (int) $this->config->readTimeout; + $microseconds = (int) (($this->config->readTimeout - $seconds) * 1000000); + if (! stream_set_timeout($socket, $seconds, $microseconds)) { + $stream = new BinaryStream($socket); + $stream->close(); + + throw new RuntimeException('Cannot set native TCP I/O timeout.'); + } + + $this->stream = new BinaryStream($socket); + try { + $stream = $this->stream; + $stream->writeVarUInt(0); // Hello + $stream->writeString('ClickHouse PHP simpod/clickhouse-client'); + $stream->writeVarUInt(1); + $stream->writeVarUInt(0); + $stream->writeVarUInt(self::Revision); + $stream->writeString($this->config->database); + $stream->writeString($this->config->user); + $stream->writeString($this->config->password); + + $packet = $stream->readVarUInt(); + if ($packet === 2) { + throw $this->readException($stream); + } + + if ($packet !== 0) { + throw new RuntimeException('Expected native server Hello.'); + } + + $stream->readString(); // Server name. + $stream->readVarUInt(); // Major version. + $stream->readVarUInt(); // Minor version. + $revision = min(self::Revision, $stream->readVarUInt()); + if ($revision < self::Revision) { + throw new RuntimeException('Native TCP requires protocol revision 54459 or newer.'); + } + + $stream->readString(); // Timezone (retained in each temporal type where applicable). + $stream->readString(); // Display name. + $stream->readVarUInt(); // Patch version. + $stream->writeString(''); // Handshake Addendum quota key. + } catch (Throwable $error) { + $this->close(); + + throw $error; + } + } + + private function writeClientInfo(BinaryStream $stream): void + { + $stream->write("\x01"); // Initial query. + $stream->writeString(''); // Initial user. + $stream->writeString(''); // Initial query id. + $stream->writeString('0.0.0.0:0'); + $stream->write(pack('P', 0)); // Initial query time. + $stream->write("\x01"); // TCP interface. + $stream->writeString(''); // OS user. + $stream->writeString(''); // Hostname. + $stream->writeString('ClickHouse PHP simpod/clickhouse-client'); + $stream->writeVarUInt(1); + $stream->writeVarUInt(0); + $stream->writeVarUInt(self::Revision); + $stream->writeString(''); // Quota key. + $stream->writeVarUInt(0); // Distributed depth. + $stream->writeVarUInt(0); // Patch version. + $stream->write("\x00"); // No OpenTelemetry trace context. + $stream->writeVarUInt(0); // Collaborate with initiator. + $stream->writeVarUInt(0); // Participating replicas. + $stream->writeVarUInt(0); // Replica number. + } + + private function readException(BinaryStream $stream, int $depth = 0): NativeServerError + { + if ($depth >= 16) { + throw new RuntimeException('Native exception nesting exceeds the limit.'); + } + + $unpacked = unpack('Vcode', $stream->read(4)); + assert($unpacked !== false && is_int($unpacked['code'])); + $code = $unpacked['code']; + $code = $code > 2147483647 ? $code - 4294967296 : $code; + $name = $stream->readString(); + $message = $stream->readString(); + $stackTrace = $stream->readString(); + $hasNested = ord($stream->read(1)); + if ($hasNested !== 0 && $hasNested !== 1) { + throw new RuntimeException('Invalid native exception nesting marker.'); + } + + $previous = $hasNested === 1 ? $this->readException($stream, $depth + 1) : null; + + return new NativeServerError($code, $name, $message, $stackTrace, $previous); + } +} diff --git a/src/Client/Native/ConnectionConfig.php b/src/Client/Native/ConnectionConfig.php new file mode 100644 index 00000000..401becf1 --- /dev/null +++ b/src/Client/Native/ConnectionConfig.php @@ -0,0 +1,53 @@ +port = $port ?? ($tls ? 9440 : 9000); + if (PHP_INT_SIZE !== 8) { + throw new RuntimeException('Native TCP requires 64-bit PHP.'); + } + + if ($host === '' || strpbrk($host, "/@?#\0\r\n\t ") !== false) { + throw new RuntimeException('Native TCP host must be a hostname or IP address, not a URL.'); + } + + if ($this->port < 1 || $this->port > 65535 || $user === '') { + throw new RuntimeException('Native TCP requires a valid port and a non-empty user.'); + } + + if (! is_finite($connectTimeout) || ! is_finite($readTimeout) || $connectTimeout <= 0 || $readTimeout <= 0) { + throw new RuntimeException('Native TCP timeouts must be finite positive seconds.'); + } + + if (! $tls && ($caFile !== null || $serverName !== null)) { + throw new RuntimeException('TLS options require TLS to be enabled.'); + } + } +} diff --git a/src/Client/Native/DecodeBudget.php b/src/Client/Native/DecodeBudget.php new file mode 100644 index 00000000..f766fdcb --- /dev/null +++ b/src/Client/Native/DecodeBudget.php @@ -0,0 +1,23 @@ + 67108864 - $this->used) { + throw new RuntimeException('Native decoded data exceeds the 64 MiB allocation budget.'); + } + + $this->used += $bytes; + } +} diff --git a/src/Client/Native/Result.php b/src/Client/Native/Result.php new file mode 100644 index 00000000..386013bb --- /dev/null +++ b/src/Client/Native/Result.php @@ -0,0 +1,22 @@ + $columns + * @param list> $rows + * @param list> $totals + * @param list> $extremes + */ + public function __construct( + public array $columns, + public array $rows, + public array $totals = [], + public array $extremes = [], + ) { + } +} diff --git a/src/Client/Native/TypeCodec.php b/src/Client/Native/TypeCodec.php new file mode 100644 index 00000000..176d7662 --- /dev/null +++ b/src/Client/Native/TypeCodec.php @@ -0,0 +1,593 @@ + */ + public function read(BinaryStream $stream, string $type, int $rows, DecodeBudget|null $budget = null): array + { + $this->validateRows($rows); + + return $this->readValues($stream, $type, $rows, 0, $budget ?? new DecodeBudget()); + } + + /** @param array $values */ + public function write(BinaryStream $stream, string $type, array $values): void + { + if (! array_is_list($values)) { + throw new RuntimeException('Native column values must be a list for type ' . $type . '.'); + } + + $this->writeValues($stream, $type, $values, 0); + } + + /** @return list */ + private function readValues(BinaryStream $stream, string $type, int $rows, int $depth, DecodeBudget $budget): array + { + $this->validateDepth($depth); + $budget->consume($rows * 128); + $spec = $this->parse($type); + if ($spec['kind'] === 'Nullable') { + $map = $stream->read($rows); + for ($row = 0; $row < $rows; $row++) { + if (ord($map[$row]) > 1) { + throw new RuntimeException('Invalid native null map for type ' . $type . '.'); + } + } + + $values = $this->readValues($stream, $spec['arguments'][0], $rows, $depth + 1, $budget); + foreach ($values as $row => $value) { + if ($map[$row] === "\x01") { + $values[$row] = null; + } + } + + return $values; + } + + if ($spec['kind'] === 'Array') { + $offsets = []; + $last = 0; + for ($row = 0; $row < $rows; $row++) { + $offset = $this->readInteger($stream->read(8), 'UInt64'); + if (! is_int($offset) || $offset < $last || $offset > self::MaxRows) { + throw new RuntimeException('Invalid native array offset for type ' . $type . '.'); + } + + $offsets[] = $offset; + $last = $offset; + } + + $nested = $this->readValues($stream, $spec['arguments'][0], $last, $depth + 1, $budget); + $values = []; + $start = 0; + foreach ($offsets as $offset) { + $values[] = array_slice($nested, $start, $offset - $start); + $start = $offset; + } + + return $values; + } + + if ($spec['kind'] === 'Tuple') { + $values = []; + for ($row = 0; $row < $rows; $row++) { + $values[] = []; + } + + foreach ($spec['arguments'] as $argument) { + foreach ($this->readValues($stream, $argument, $rows, $depth + 1, $budget) as $row => $value) { + $values[$row][] = $value; + } + } + + return $values; + } + + $values = []; + if ($spec['kind'] === 'String') { + $size = 0; + for ($row = 0; $row < $rows; $row++) { + $length = $stream->readVarUInt(); + $size += $length; + if ($size > self::MaxBytes) { + throw new RuntimeException('Native column exceeds the 64 MiB limit for type ' . $type . '.'); + } + + $budget->consume($length); + $values[] = $stream->read($length); + } + + return $values; + } + + if ($rows * $spec['width'] > self::MaxBytes) { + throw new RuntimeException('Native column exceeds the 64 MiB limit for type ' . $type . '.'); + } + + $budget->consume($rows * $spec['width']); + $bytes = $stream->read($rows * $spec['width']); + for ($row = 0; $row < $rows; $row++) { + $value = substr($bytes, $row * $spec['width'], $spec['width']); + $values[] = match ($spec['kind']) { + 'FixedString' => $value, + 'Bool' => ord($value) !== 0, + 'Float32', 'Float64' => $this->readFloat($value, $spec['kind']), + 'Enum8', 'Enum16' => $this->readInteger($value, $spec['width'] === 1 ? 'Int8' : 'Int16'), + default => $this->readInteger($value, $spec['kind']), + }; + } + + return $values; + } + + /** @param list $values */ + private function writeValues(BinaryStream $stream, string $type, array $values, int $depth): void + { + $this->validateDepth($depth); + $this->validateRows(count($values)); + $spec = $this->parse($type); + if ($spec['kind'] === 'Enum8' || $spec['kind'] === 'Enum16') { + $indexes = $this->enumIndexes($spec['arguments']); + foreach ($values as $value) { + if (! is_int($value) || ! in_array($value, $indexes, true)) { + throw new RuntimeException('Expected a declared numeric index for native type ' . $type . '.'); + } + + $stream->write($this->writeInteger($value, $spec['width'] === 1 ? 'Int8' : 'Int16', $spec['width'])); + } + + return; + } + + if ($spec['kind'] === 'Nullable') { + $map = ''; + $nested = []; + $default = $this->defaultValue($spec['arguments'][0], $depth + 1); + foreach ($values as $value) { + $map .= $value === null ? "\x01" : "\x00"; + $nested[] = $value ?? $default; + } + + $stream->write($map); + $this->writeValues($stream, $spec['arguments'][0], $nested, $depth + 1); + + return; + } + + if ($spec['kind'] === 'Array') { + $nested = []; + $offset = 0; + foreach ($values as $value) { + if (! is_array($value) || ! array_is_list($value)) { + throw new RuntimeException('Expected a list for native type ' . $type . '.'); + } + + $offset += count($value); + $this->validateRows($offset); + $stream->write(pack('P', $offset)); + foreach ($value as $element) { + $nested[] = $element; + } + } + + $this->writeValues($stream, $spec['arguments'][0], $nested, $depth + 1); + + return; + } + + if ($spec['kind'] === 'Tuple') { + $tuples = []; + foreach ($values as $value) { + if (! is_array($value) || ! array_is_list($value) || count($value) !== count($spec['arguments'])) { + throw new RuntimeException('Invalid tuple value for native type ' . $type . '.'); + } + + $tuples[] = $value; + } + + foreach ($spec['arguments'] as $index => $argument) { + $nested = []; + foreach ($tuples as $tuple) { + $nested[] = $tuple[$index]; + } + + $this->writeValues($stream, $argument, $nested, $depth + 1); + } + + return; + } + + if ($spec['kind'] !== 'String' && count($values) * $spec['width'] > self::MaxBytes) { + throw new RuntimeException('Native column exceeds the 64 MiB limit for type ' . $type . '.'); + } + + $size = 0; + foreach ($values as $value) { + switch ($spec['kind']) { + case 'String': + case 'FixedString': + if (! is_string($value) || ($spec['kind'] === 'FixedString' && strlen($value) > $spec['width'])) { + throw new RuntimeException('Invalid string value for native type ' . $type . '.'); + } + + if ($spec['kind'] === 'String') { + $size += strlen($value); + if ($size > self::MaxBytes) { + throw new RuntimeException( + 'Native column exceeds the 64 MiB limit for type ' . $type . '.', + ); + } + + $stream->writeString($value); + } else { + $stream->write($value . str_repeat("\x00", $spec['width'] - strlen($value))); + } + + break; + case 'Bool': + if (! is_bool($value)) { + throw new RuntimeException('Expected a boolean for native type ' . $type . '.'); + } + + $stream->write($value ? "\x01" : "\x00"); + + break; + case 'Float32': + case 'Float64': + if (! is_int($value) && ! is_float($value)) { + throw new RuntimeException('Expected a number for native type ' . $type . '.'); + } + + $bytes = pack($spec['kind'] === 'Float32' ? 'g' : 'e', $value); + if (is_finite((float) $value) && ! is_finite($this->readFloat($bytes, $spec['kind']))) { + throw new RuntimeException('Float value is out of range for native type ' . $type . '.'); + } + + $stream->write($bytes); + + break; + default: + $stream->write($this->writeInteger($value, $spec['kind'], $spec['width'])); + } + } + } + + /** @phpstan-return array{kind: string, arguments: list, width: int} */ + private function parse(string $type): array + { + if (strlen($type) > 4096) { + throw new RuntimeException('Native type declaration exceeds its size limit.'); + } + + $type = trim($type); + $kind = $type; + $arguments = []; + $parameterized = preg_match('~^([A-Za-z][A-Za-z0-9]*)\((.*)\)$~sD', $type, $matches) === 1; + if ($parameterized) { + $kind = $matches[1]; + $arguments = $this->splitArguments($matches[2], $type); + } + + $width = 0; + if (preg_match('~^(U?Int)(8|16|32|64)$~D', $kind, $matches) === 1 && ! $parameterized) { + $width = intdiv((int) $matches[2], 8); + } elseif ($kind === 'String' && ! $parameterized) { + $width = 0; + } elseif ($kind === 'Bool' && ! $parameterized) { + $width = 1; + } elseif (($kind === 'Float32' || $kind === 'Float64') && ! $parameterized) { + $width = $kind === 'Float32' ? 4 : 8; + } elseif ($kind === 'Date' && ! $parameterized) { + $kind = 'UInt16'; + $width = 2; + } elseif ($kind === 'Date32' && ! $parameterized) { + $kind = 'Int32'; + $width = 4; + } elseif ( + $kind === 'DateTime' + && (! $parameterized || (count($arguments) === 1 && $this->isTimezone($arguments[0]))) + ) { + $kind = 'UInt32'; + $width = 4; + } elseif ( + $kind === 'DateTime64' + && (count($arguments) === 1 || count($arguments) === 2) + && preg_match('~^[0-9]$~D', $arguments[0]) === 1 + && (count($arguments) === 1 || $this->isTimezone($arguments[1])) + ) { + $kind = 'Int64'; + $width = 8; + } elseif ( + $kind === 'FixedString' + && count($arguments) === 1 + && preg_match('~^[1-9][0-9]{0,7}$~D', $arguments[0]) === 1 + && (int) $arguments[0] <= self::MaxBytes + ) { + $width = (int) $arguments[0]; + } elseif (($kind === 'Nullable' || $kind === 'Array') && count($arguments) === 1) { + $width = 0; + } elseif ($kind === 'Tuple' && count($arguments) <= 1024 && $parameterized) { + $width = 0; + } elseif (($kind === 'Enum8' || $kind === 'Enum16') && $parameterized) { + // ProfileEvents uses Enum8. Expose its signed index without changing its wire representation. + $width = $kind === 'Enum8' ? 1 : 2; + foreach ($this->enumIndexes($arguments) as $index) { + $this->writeInteger($index, $width === 1 ? 'Int8' : 'Int16', $width); + } + } else { + throw new RuntimeException('Unsupported native type ' . $type . '.'); + } + + return ['kind' => $kind, 'arguments' => $arguments, 'width' => $width]; + } + + /** @return list */ + private function splitArguments(string $parameters, string $type): array + { + if ($parameters === '') { + return []; + } + + $arguments = []; + $depth = 0; + $quoted = false; + $start = 0; + for ($index = 0; $index < strlen($parameters); $index++) { + $character = $parameters[$index]; + if ($quoted && $character === '\\') { + ++$index; + + continue; + } + + if ($character === "'") { + $quoted = ! $quoted; + } elseif (! $quoted) { + if ($character === '(') { + $depth++; + $this->validateDepth($depth); + } elseif ($character === ')') { + $depth--; + if ($depth < 0) { + throw new RuntimeException('Invalid native type ' . $type . '.'); + } + } elseif ($character === ',' && $depth === 0) { + $arguments[] = trim(substr($parameters, $start, $index - $start)); + $start = $index + 1; + } + } + } + + if ($quoted || $depth !== 0) { + throw new RuntimeException('Invalid native type ' . $type . '.'); + } + + $arguments[] = trim(substr($parameters, $start)); + foreach ($arguments as $argument) { + if ($argument === '') { + throw new RuntimeException('Invalid native type ' . $type . '.'); + } + } + + return $arguments; + } + + private function isTimezone(string $argument): bool + { + return preg_match("~^'[A-Za-z0-9_+./:-]+'$~D", $argument) === 1; + } + + private function defaultValue(string $type, int $depth): mixed + { + $this->validateDepth($depth); + $spec = $this->parse($type); + if ($spec['kind'] === 'Tuple') { + $values = []; + foreach ($spec['arguments'] as $argument) { + $values[] = $this->defaultValue($argument, $depth + 1); + } + + return $values; + } + + return match ($spec['kind']) { + 'Nullable' => null, + 'Array' => [], + 'String', 'FixedString' => '', + 'Bool' => false, + 'Float32', 'Float64' => 0.0, + 'Enum8', 'Enum16' => $this->enumIndexes($spec['arguments'])[0], + default => 0, + }; + } + + /** + * @param list $arguments + * + * @return non-empty-list + */ + private function enumIndexes(array $arguments): array + { + $indexes = []; + foreach ($arguments as $argument) { + if (preg_match("~^'(?:[^'\\\\]|\\\\.)*'\\s*=\\s*(-?[0-9]+)$~sD", $argument, $matches) !== 1) { + throw new RuntimeException('Invalid native enum declaration.'); + } + + $indexes[] = (int) $matches[1]; + } + + if ($indexes === []) { + throw new RuntimeException('Native enum must declare at least one value.'); + } + + return $indexes; + } + + private function readFloat(string $bytes, string $kind): float + { + /** @phpstan-var array{value: float} $value */ + $value = unpack($kind === 'Float32' ? 'gvalue' : 'evalue', $bytes); + + return $value['value']; + } + + private function readInteger(string $bytes, string $kind): int|string + { + $width = strlen($bytes); + if ($width === 8) { + /** @phpstan-var array{low: int, high: int} $parts */ + $parts = unpack('Vlow/Vhigh', $bytes); + if ($kind === 'UInt64' && $parts['high'] >= 2147483648) { + return $this->unsignedDecimal($bytes); + } + + $high = $parts['high']; + if ($kind === 'Int64' && $high >= 2147483648) { + $high -= 4294967296; + } + + return $high * 4294967296 + $parts['low']; + } + + /** @phpstan-var array{value: int} $parts */ + $parts = unpack(match ($width) { + 1 => 'Cvalue', + 2 => 'vvalue', + default => 'Vvalue', + }, $bytes); + $value = $parts['value']; + if ($kind[0] === 'I' && $value >= 1 << ($width * 8 - 1)) { + $value -= 1 << $width * 8; + } + + return $value; + } + + private function writeInteger(mixed $value, string $kind, int $width): string + { + if ($kind === 'UInt64' && is_string($value)) { + if ( + preg_match('~^(0|[1-9][0-9]{0,19})$~D', $value) !== 1 + || (strlen($value) === 20 && strcmp($value, '18446744073709551615') > 0) + ) { + throw new RuntimeException('Integer value is out of range for native type ' . $kind . '.'); + } + + return $this->decimalBytes($value); + } + + if (! is_int($value)) { + throw new RuntimeException('Expected an integer for native type ' . $kind . '.'); + } + + $signed = $kind[0] === 'I'; + $min = $signed ? ($width === 8 ? -PHP_INT_MAX - 1 : -(1 << ($width * 8 - 1))) : 0; + $max = $width === 8 ? PHP_INT_MAX : ($signed ? (1 << ($width * 8 - 1)) - 1 : (1 << $width * 8) - 1); + if ($value < $min || $value > $max) { + throw new RuntimeException('Integer value is out of range for native type ' . $kind . '.'); + } + + return pack(match ($width) { + 1 => 'C', + 2 => 'v', + 4 => 'V', + default => 'P', + }, $value); + } + + private function unsignedDecimal(string $bytes): string + { + $decimal = '0'; + for ($byte = 7; $byte >= 0; $byte--) { + $carry = ord($bytes[$byte]); + $result = ''; + for ($digit = strlen($decimal) - 1; $digit >= 0; $digit--) { + $carry += (ord($decimal[$digit]) - 48) * 256; + $result = chr(48 + $carry % 10) . $result; + $carry = intdiv($carry, 10); + } + + while ($carry > 0) { + $result = chr(48 + $carry % 10) . $result; + $carry = intdiv($carry, 10); + } + + $decimal = $result; + } + + return $decimal; + } + + private function decimalBytes(string $decimal): string + { + $bytes = ''; + for ($byte = 0; $byte < 8; $byte++) { + $carry = 0; + $quotient = ''; + for ($digit = 0; $digit < strlen($decimal); $digit++) { + $carry = $carry * 10 + ord($decimal[$digit]) - 48; + $current = intdiv($carry, 256); + if ($current !== 0 || $quotient !== '') { + $quotient .= (string) $current; + } + + $carry %= 256; + } + + $bytes .= pack('C', $carry); + $decimal = $quotient; + } + + return $bytes; + } + + private function validateDepth(int $depth): void + { + if ($depth > self::MaxDepth) { + throw new RuntimeException('Native type nesting exceeds its depth limit.'); + } + } + + private function validateRows(int $rows): void + { + if ($rows < 0 || $rows > self::MaxRows) { + throw new RuntimeException('Native column exceeds its row limit.'); + } + } +} diff --git a/src/Client/NativeClickHouseClient.php b/src/Client/NativeClickHouseClient.php new file mode 100644 index 00000000..e12b64ef --- /dev/null +++ b/src/Client/NativeClickHouseClient.php @@ -0,0 +1,358 @@ + 1000000) { + throw new RuntimeException('Native insert block size must be between 1 and 1000000 rows.'); + } + + $this->connection = new Connection($config); + $this->sqlFactory = new SqlFactory(new ValueFormatter()); + } + + public function executeQuery(string $query, SettingsProvider $settings = new EmptySettingsProvider()): void + { + $this->select($query, $settings); + } + + /** + * @param array $params + * + * @throws UnsupportedParamType + * @throws UnsupportedParamValue + */ + public function executeQueryWithParams( + string $query, + array $params, + SettingsProvider $settings = new EmptySettingsProvider(), + ): void { + $this->selectWithParams($query, $params, $settings); + } + + public function select(string $query, SettingsProvider $settings = new EmptySettingsProvider()): Result + { + return $this->runSelect($query, [], $settings); + } + + /** + * @param array $params + * + * @throws UnsupportedParamType + * @throws UnsupportedParamValue + */ + public function selectWithParams( + string $query, + array $params, + SettingsProvider $settings = new EmptySettingsProvider(), + ): Result { + $sql = $this->sqlFactory->createWithParameters($query, $params); + $parameters = $this->prepareParameters($sql, $params); + + return $this->runSelect($sql, $parameters, $settings); + } + + /** + * Sends binary column blocks using the schema returned by the server. + * Values must be positional lists, in the requested column order. + * + * @param iterable> $values + * @param list $columns + * + * @throws CannotInsert + */ + public function insert( + Table|string $table, + iterable $values, + array $columns = [], + SettingsProvider $settings = new EmptySettingsProvider(), + ): void { + if (! $table instanceof Table) { + if ($table === '') { + throw new RuntimeException('Native insert table must not be empty.'); + } + + $table = new Table($table); + } + + // @phpstan-ignore function.alreadyNarrowedType (Reject HTTP-style column maps from untyped callers.) + if (! array_is_list($columns)) { + throw new RuntimeException('Native insert columns must be a list of names.'); + } + + foreach ($columns as $column) { + // @phpstan-ignore function.alreadyNarrowedType (PHP arrays do not enforce the documented element type.) + if (! is_string($column) || $column === '') { + throw new RuntimeException('Native insert column names must be non-empty strings.'); + } + } + + $columnsSql = $columns === [] ? '' : '(' . implode( + ',', + array_map(Escaper::quoteIdentifier(...), $columns), + ) . ')'; + $sql = 'INSERT INTO ' . $table->fullName() . ' ' . $columnsSql . ' VALUES'; + $id = $this->connection->startQuery($sql, $settings->get() + $this->defaultSettings->get(), []); + + try { + $this->sqlLogger?->startQuery($id, $sql); + $schema = $this->receiveInsertSchema(); + $batch = []; + $sent = false; + foreach ($values as $row) { + // @phpstan-ignore function.alreadyNarrowedType (Never serialize associative caller rows as positional data.) + if (! array_is_list($row) || count($row) !== count($schema->columns)) { + throw new RuntimeException('Native insert row must match the server schema in column order.'); + } + + $batch[] = $row; + if (count($batch) < $this->insertBlockSize) { + continue; + } + + $this->sendInsertBlock(new Block($schema->columns, $batch)); + $sent = true; + $batch = []; + } + + if ($batch !== []) { + $this->sendInsertBlock(new Block($schema->columns, $batch)); + $sent = true; + } + + if (! $sent) { + throw CannotInsert::noValues(); + } + + $this->sendInsertBlock(new Block()); + do { + [$type] = $this->connection->receive(); + } while ($type !== 5); + } catch (Throwable $error) { + $this->connection->close(); + + throw $error; + } finally { + $this->sqlLogger?->stopQuery($id); + } + } + + public function close(): void + { + $this->connection->close(); + } + + /** @param array $parameters */ + private function runSelect(string $sql, array $parameters, SettingsProvider $settings): Result + { + $id = $this->connection->startQuery($sql, $settings->get() + $this->defaultSettings->get(), $parameters); + + try { + $this->sqlLogger?->startQuery($id, $sql); + $columns = []; + $rows = []; + $totals = []; + $extremes = []; + $budget = new DecodeBudget(); + while (true) { + [$type, $block] = $this->connection->receive(); + if ($type === 5) { + return new Result($columns, $rows, $totals, $extremes); + } + + if ($block === null || $block->columns === []) { + continue; + } + + if ($type === 1) { + $budget->consume($block->estimatedBytes); + if ($columns === []) { + $columns = $block->columns; + } elseif (! $this->sameSchema($columns, $block->columns)) { + throw new RuntimeException('Native result schema changed between blocks.'); + } + + foreach ($block->rows as $row) { + $rows[] = $row; + } + } elseif ($type === 7) { + $budget->consume($block->estimatedBytes); + $totals = $block->rows; + } elseif ($type === 8) { + $budget->consume($block->estimatedBytes); + $extremes = $block->rows; + } + } + } catch (Throwable $error) { + $this->connection->close(); + + throw $error; + } finally { + $this->sqlLogger?->stopQuery($id); + } + } + + private function receiveInsertSchema(): Block + { + while (true) { + [$type, $block] = $this->connection->receive(); + if ($type === 1) { + assert($block !== null); + if ($block->columns === [] || $block->rows !== []) { + throw new RuntimeException('Expected a native insert schema block.'); + } + + return $block; + } + + if ($type === 5) { + throw new RuntimeException('Native insert ended without a schema block.'); + } + } + } + + private function sendInsertBlock(Block $block): void + { + $this->connection->sendBlock($block); + // Revision 54456+ acknowledges each insert block with ProfileEvents. + while (true) { + [$type] = $this->connection->receive(); + if ($type === 14) { + return; + } + + if ($type === 5 || $type === 1) { + throw new RuntimeException('Native insert ended before acknowledging the data block.'); + } + } + } + + /** + * @param list $expected + * @param list $actual + */ + private function sameSchema(array $expected, array $actual): bool + { + if (count($expected) !== count($actual)) { + return false; + } + + foreach ($expected as $i => $column) { + if ($column->name !== $actual[$i]->name || $column->type !== $actual[$i]->type) { + return false; + } + } + + return true; + } + + /** + * @param array $params + * + * @return array + * + * @throws UnsupportedParamType + * @throws UnsupportedParamValue + */ + private function prepareParameters(string $sql, array $params): array + { + $parameters = []; + foreach (NativeParameterParser::parse($sql) as $name => $type) { + if (! array_key_exists($name, $params)) { + continue; // The server reports a missing parameter with its normal error code. + } + + $value = $params[$name]; + if ($value === null) { + $nullable = $type; + while ($nullable->name === 'LowCardinality') { + $nullable = Type::fromString($nullable->params); + } + + if ($nullable->name !== 'Nullable') { + throw UnsupportedParamValue::type($value); + } + + $text = '\\N'; + } else { + // Registry converters are an external value boundary and can return custom values. + /** @var mixed $converted */ + $converted = $this->paramValueConverterRegistry->get($type)->__invoke($value, $type, false); + if (! is_scalar($converted)) { + throw UnsupportedParamValue::type($converted); + } + + $text = is_bool($converted) ? ($converted ? '1' : '0') : (string) $converted; + $base = $type; + while ($base->name === 'Nullable' || $base->name === 'LowCardinality') { + $base = Type::fromString($base->params); + } + + if ($name === '_request_body' && in_array($base->name, ['String', 'FixedString'], true)) { + // The reserved parameter uses whole-text parsing, not escaped-text parsing. + $text = stripcslashes($text); + } elseif ($name !== '_request_body' && in_array($base->name, ['Enum8', 'Enum16'], true)) { + // Enum converters return raw labels; scalar String converters already escape text. + $text = Escaper::escape($text); + } + } + + // Native parameters carry a String Field dump, not an HTTP param_* value. + $parameters[$name] = "'" . Escaper::escape($text) . "'"; + } + + return $parameters; + } +} diff --git a/src/Exception/NativeServerError.php b/src/Exception/NativeServerError.php new file mode 100644 index 00000000..b03d1d9c --- /dev/null +++ b/src/Exception/NativeServerError.php @@ -0,0 +1,20 @@ +stream($bytes . "\xa5"); + $codec = new BlockCodec($revision); + + $actual = $codec->read($stream); + self::assertEquals($expected->columns, $actual->columns); + self::assertSame($expected->rows, $actual->rows); + self::assertSame("\xa5", $stream->read(1)); + + $output = fopen('php://memory', 'w+b'); + self::assertIsResource($output); + $writer = new BinaryStream($output); + $codec->write($writer, $expected); + rewind($output); + + self::assertSame($bytes, stream_get_contents($output)); + } + + /** @phpstan-return Generator */ + public static function provideWireBlocks(): Generator + { + yield 'Native empty sentinel' => [54459, '010002ffffffff000000', new Block()]; + yield 'Native schema header' => [ + 54459, + '010002ffffffff00010001310555496e743800', + new Block([new Column('1', 'UInt8')]), + ]; + + yield 'Native columnar result' => [ + 54459, + '010002ffffffff000202016e0655496e743136000100ffff017306537472696e67000161020062', + new Block([new Column('n', 'UInt16'), new Column('s', 'String')], [[1, 'a'], [65535, "\x00b"]]), + ]; + + yield 'Before custom serialization revision' => [ + 54453, + '010002ffffffff00010101310555496e743801', + new Block([new Column('1', 'UInt8')], [[1]]), + ]; + + yield 'Native format revision zero' => [ + 0, + '010101310555496e743801', + new Block([new Column('1', 'UInt8')], [[1]]), + ]; + } + + #[DataProvider('provideMalformedBlocks')] + public function testMalformedBlocks(string $hex): void + { + $bytes = hex2bin($hex); + self::assertIsString($bytes); + self::expectException(RuntimeException::class); + new BlockCodec(54459)->read($this->stream($bytes)); + } + + /** @phpstan-return Generator */ + public static function provideMalformedBlocks(): Generator + { + yield 'Unknown BlockInfo field' => ['03']; + yield 'Duplicate BlockInfo field' => ['01000100']; + yield 'Invalid BlockInfo overflow flag' => ['0102']; + yield 'Excessive columns' => ['00810800']; + yield 'Excessive rows' => ['0001c1843d']; + yield 'Individually valid dimensions exceed allocation budget' => ['008008c0843d']; + yield 'Rows without columns' => ['000001']; + yield 'Custom column serialization' => ['00010101310555496e743801']; + yield 'Unsupported type in header' => ['0001000178045555494400']; + yield 'Truncated column data' => ['00010101310555496e743800']; + } + + #[DataProvider('provideInvalidBlocks')] + public function testInvalidBlocks(Block $block): void + { + self::expectException(RuntimeException::class); + new BlockCodec(54459)->write($this->stream(''), $block); + } + + /** @phpstan-return Generator */ + public static function provideInvalidBlocks(): Generator + { + yield 'Missing row value' => [new Block([new Column('n', 'UInt8')], [[]])]; + yield 'Extra row value' => [new Block([new Column('n', 'UInt8')], [[1, 2]])]; + yield 'Rows without columns' => [new Block([], [[1]])]; + yield 'Too many columns' => [new Block(array_fill(0, 1025, new Column('n', 'UInt8')))]; + } + + private function stream(string $bytes): BinaryStream + { + $resource = fopen('php://memory', 'w+b'); + self::assertIsResource($resource); + fwrite($resource, $bytes); + rewind($resource); + + return new BinaryStream($resource); + } +} diff --git a/tests/Client/Native/ScriptedNativeServer.php b/tests/Client/Native/ScriptedNativeServer.php new file mode 100644 index 00000000..a53b2355 --- /dev/null +++ b/tests/Client/Native/ScriptedNativeServer.php @@ -0,0 +1,349 @@ +listener = $listener; + $address = stream_socket_get_name($listener, false); + if ($address === false) { + throw new RuntimeException('Cannot read scripted server address.'); + } + + $port = strrchr($address, ':'); + if ($port === false) { + throw new RuntimeException('Scripted server address has no port.'); + } + + fwrite(STDOUT, substr($port, 1) . "\n"); + } + + public function run(string $scenario): void + { + $this->accept(); + switch ($scenario) { + case 'select': + $this->query( + 'SELECT {label:String}, {missing:Nullable(String)}, ' + . '{kind:Enum8(\'a\\\\t\' = 1)}, {_request_body:String}, 9', + ['max_block_size' => [1, '2'], 'max_threads' => [1, '1']], + [ + 'label' => [2, "'a\\'b\\\\\\\\c'"], + 'missing' => [2, "'\\\\N'"], + 'kind' => [2, "'a\\\\\\\\t'"], + '_request_body' => [2, "'raw\\\\t'"], + ], + ); + $this->send($this->block(1, 0, '', '')); + $this->send($this->block(1, 2, "\x07\x09", "\x03one\x03two")); + $this->send("\x03\x02\x08\x03\x00\x00"); // Progress: rows, bytes, total rows, written rows/bytes. + $this->send("\x06\x02\x01\x08\x00\x02\x01"); // ProfileInfo. + $this->send($this->profileEvents()); + $this->send($this->block(1, 1, "\x0b", "\x05three")); + $this->send($this->block(7, 1, "\x1b", "\x05total")); + $this->send($this->block(8, 2, "\x07\x0b", "\x03min\x03max")); + $this->send($this->emptyBlock(1) . "\x05"); + $this->query('SELECT empty', ['max_block_size' => [1, '100'], 'max_threads' => [1, '1']]); + $this->send("\x01\x00" . self::BlockInfo . "\x01\x00\x05empty\x06UInt16\x00" + . $this->emptyBlock(1) . "\x05"); + + break; + case 'insert': + $this->query('INSERT INTO `events` (`label`,`id`) VALUES'); + $this->send($this->insertBlock(1, 0, '', '')); + foreach ( + [ + $this->insertBlock(2, 2, "\x03one\x03two", "\x07\x09"), + $this->insertBlock(2, 1, "\x05three", "\x0b"), + $this->emptyBlock(2), + ] as $block + ) { + $this->expect($block); + $read = [$this->socket]; + $write = []; + $except = []; + if (stream_select($read, $write, $except, 0, 100000) !== 0) { + throw new RuntimeException( + 'Client sent another block before its ProfileEvents acknowledgement.', + ); + } + + $this->send("\x03\x01\x01\x00\x01\x01" . $this->profileEvents()); + } + + $this->send("\x05"); + $this->query('SELECT inserted'); + $this->send($this->block(1, 1, "\x03", "\x04done") . "\x05"); + + break; + case 'exception': + case 'truncated': + $this->query('SELECT failing'); + $this->send($this->block(1, 1, "\x07", "\x07partial")); + if ($scenario === 'exception') { + $this->send("\x02" . pack('V', 241) . $this->string('MEMORY_LIMIT_EXCEEDED') + . $this->string('Query exceeded its memory limit') . $this->string('server.cpp:42') . "\x00"); + $this->expectDisconnect(); + } else { + // The next String promises five bytes, but only two arrive before EOF. + $this->send($this->block(1, 1, "\x08", "\x05ab")); + } + + $this->reconnect(); + + break; + case 'budget': + $this->query('SELECT failing'); + for ($i = 0; $i < 5; ++$i) { + $this->send("\x01\x00" . self::BlockInfo . "\x01" . $this->varUInt(40000) + . $this->string('empty') . $this->string('Tuple()') . "\x00"); + } + + $this->expectDisconnect(); + $this->reconnect(); + + break; + case 'invalid-insert': + $this->query('INSERT INTO `events` (`label`,`id`) VALUES'); + $this->send($this->insertBlock(1, 0, '', '')); + $this->expectDisconnect(); + $this->reconnect(); + + break; + default: + throw new RuntimeException('Unknown scripted native server scenario.'); + } + + $this->expectDisconnect(); + fclose($this->socket); + fclose($this->listener); + } + + private function reconnect(): void + { + fclose($this->socket); + $this->accept(); + $this->query('SELECT recovered'); + $this->send($this->block(1, 1, "\x2a", "\x05fresh") . "\x05"); + } + + private function accept(): void + { + $socket = stream_socket_accept($this->listener, 5); + if ($socket === false) { + throw new RuntimeException('Client did not connect.'); + } + + $this->socket = $socket; + stream_set_timeout($socket, 5); + $this->expect("\x00"); // Client Hello. + $this->readString(); // Client name. + $this->readVarUInt(); // Major version. + $this->readVarUInt(); // Minor version. + $this->equal(54459, $this->readVarUInt()); + $this->equal('analytics', $this->readString()); + $this->equal('reader', $this->readString()); + $this->equal('test-password', $this->readString()); + // Server revision can be newer; only fields at the advertised client revision follow. + $this->send("\x00" . $this->string('ClickHouse') . "\x19\x01" . $this->varUInt(54465) + . $this->string('UTC') . $this->string('scripted') . "\x01"); + $this->expect("\x00"); // Handshake Addendum quota key, before the first query. + } + + /** + * @phpstan-param array $settings + * @phpstan-param array $parameters + */ + private function query(string $sql, array $settings = [], array $parameters = []): void + { + $this->expect("\x01"); + if ($this->readString() === '') { + throw new RuntimeException('Query id must not be empty.'); + } + + $this->expect("\x01"); // Initial-query ClientInfo. + $this->readString(); // Initial user. + $this->readString(); // Initial query id. + $this->readString(); // Initial address. + $this->read(8); // Initial query time, UInt64. + $this->expect("\x01"); // TCP interface. + $this->readString(); // OS user. + $this->readString(); // Hostname. + $this->readString(); // Client name. + $this->readVarUInt(); // Major version. + $this->readVarUInt(); // Minor version. + $this->equal(54459, $this->readVarUInt()); + $this->readString(); // Quota key. + $this->readVarUInt(); // Distributed depth. + $this->readVarUInt(); // Patch version. + $this->expect("\x00\x00\x00\x00"); // No trace context or parallel replicas. + $this->equal($settings, $this->readSettings()); + $this->expect("\x00\x02\x00"); // Empty inter-server secret, complete stage, no compression. + $this->equal($sql, $this->readString()); + $this->equal($parameters, $this->readSettings()); + $this->expect($this->emptyBlock(2)); // End of external tables, also required before INSERT schema. + } + + /** @phpstan-return array */ + private function readSettings(): array + { + $settings = []; + while (($name = $this->readString()) !== '') { + $settings[$name] = [$this->readVarUInt(), $this->readString()]; + } + + return $settings; + } + + /** @param int<0, 127> $packet */ + private function block(int $packet, int $rows, string $ids, string $labels): string + { + return chr($packet) . "\x00" . self::BlockInfo . "\x02" . $this->varUInt($rows) + . "\x02id\x05UInt8\x00" . $ids . "\x05label\x06String\x00" . $labels; + } + + /** @param int<0, 127> $packet */ + private function insertBlock(int $packet, int $rows, string $labels, string $ids): string + { + return chr($packet) . "\x00" . self::BlockInfo . "\x02" . $this->varUInt($rows) + . "\x05label\x06String\x00" . $labels . "\x02id\x05UInt8\x00" . $ids; + } + + /** @param int<0, 127> $packet */ + private function emptyBlock(int $packet): string + { + return chr($packet) . "\x00" . self::BlockInfo . "\x00\x00"; + } + + private function profileEvents(): string + { + return "\x0e\x00" . self::BlockInfo . "\x01\x01" . $this->string('type') + . $this->string("Enum8('Increment' = 1, 'Gauge' = 2)") . "\x00\x01"; + } + + private function expectDisconnect(): void + { + if (fread($this->socket, 1) !== '' || ! feof($this->socket)) { + throw new RuntimeException('Client did not disconnect, or sent unexpected data.'); + } + } + + private function expect(string $bytes): void + { + $actual = $this->read(strlen($bytes)); + if ($actual !== $bytes) { + throw new RuntimeException('Expected wire bytes ' . bin2hex($bytes) . ', received ' . bin2hex($actual)); + } + } + + private function equal(mixed $expected, mixed $actual): void + { + if ($expected !== $actual) { + throw new RuntimeException('Unexpected query, setting, parameter, or handshake field.'); + } + } + + private function send(string $bytes): void + { + while ($bytes !== '') { + $written = fwrite($this->socket, $bytes); + if ($written === false || $written === 0) { + throw new RuntimeException('Cannot write scripted server response.'); + } + + $bytes = substr($bytes, $written); + } + } + + private function read(int $size): string + { + $bytes = ''; + $remaining = $size; + while ($remaining > 0) { + $chunk = fread($this->socket, $remaining); + if ($chunk === false || $chunk === '') { + throw new RuntimeException('Client packet ended early or timed out.'); + } + + $bytes .= $chunk; + $remaining -= strlen($chunk); + } + + return $bytes; + } + + private function readVarUInt(): int + { + $value = 0; + for ($shift = 0; $shift < 63; $shift += 7) { + $byte = ord($this->read(1)); + $value |= ($byte & 127) << $shift; + if ($byte < 128) { + return $value; + } + } + + throw new RuntimeException('Invalid fixture VarUInt.'); + } + + private function readString(): string + { + return $this->read($this->readVarUInt()); + } + + private function varUInt(int $value): string + { + $bytes = ''; + do { + $byte = $value & 127; + $value >>= 7; + $bytes .= pack('C', $byte | ($value === 0 ? 0 : 128)); + } while ($value !== 0); + + return $bytes; + } + + private function string(string $value): string + { + return $this->varUInt(strlen($value)) . $value; + } +} diff --git a/tests/Client/Native/TypeCodecTest.php b/tests/Client/Native/TypeCodecTest.php new file mode 100644 index 00000000..7839a61a --- /dev/null +++ b/tests/Client/Native/TypeCodecTest.php @@ -0,0 +1,256 @@ + $values */ + #[DataProvider('provideWireValues')] + public function testWireValues(string $type, string $hex, array $values): void + { + $bytes = hex2bin($hex); + self::assertIsString($bytes); + $stream = $this->stream($bytes . "\xa5"); + $codec = new TypeCodec(); + + self::assertSame($values, $codec->read($stream, $type, count($values))); + self::assertSame("\xa5", $stream->read(1)); + + $output = fopen('php://memory', 'w+b'); + self::assertIsResource($output); + $writer = new BinaryStream($output); + $codec->write($writer, $type, $values); + rewind($output); + + self::assertSame($bytes, stream_get_contents($output)); + } + + /** @phpstan-return Generator}> */ + public static function provideWireValues(): Generator + { + yield 'UInt8' => ['UInt8', '00ff', [0, 255]]; + yield 'UInt16' => ['UInt16', '00003412ffff', [0, 4660, 65535]]; + yield 'UInt32' => ['UInt32', '0000000078563412ffffffff', [0, 305419896, 4294967295]]; + yield 'UInt64' => [ + 'UInt64', + '0000000000000000ffffffffffffff7f0000000000000080ffffffffffffffffd20a1feb8ca954ab', + [0, PHP_INT_MAX, '9223372036854775808', '18446744073709551615', '12345678901234567890'], + ]; + + yield 'Int8' => ['Int8', '80ff007f', [-128, -1, 0, 127]]; + yield 'Int16' => ['Int16', '0080ffff0000ff7f', [-32768, -1, 0, 32767]]; + yield 'Int32' => ['Int32', '00000080ffffffff00000000ffffff7f', [-2147483648, -1, 0, 2147483647]]; + yield 'Int64' => [ + 'Int64', + '0000000000000080ffffffffffffffff0000000000000000ffffffffffffff7f', + [PHP_INT_MIN, -1, 0, PHP_INT_MAX], + ]; + + yield 'Float32' => ['Float32', '0000c03f000010c0', [1.5, -2.25]]; + yield 'Float64' => ['Float64', '000000000000f83f00000000000002c0', [1.5, -2.25]]; + yield 'Bool' => ['Bool', '010001', [true, false, true]]; + yield 'ProfileEvents enum' => ["Enum8('Increment' = 1, 'Gauge' = 2)", '0102', [1, 2]]; + yield 'Signed enum values' => ["Enum16('negative' = -1, 'large' = 30000)", 'ffff3075', [-1, 30000]]; + yield 'Nullable enum with non-zero default' => ["Nullable(Enum8('ready' = 7))", '01000707', [null, 7]]; + yield 'Escaped enum labels' => ["Enum8('a\\'b' = 1, 'a,b' = 2)", '0102', [1, 2]]; + yield 'String binary values' => ['String', '000361006203e29883', ['', "a\x00b", '☃']]; + yield 'FixedString preserves null bytes' => ['FixedString(3)', '610000780079', ["a\x00\x00", "x\x00y"]]; + yield 'Date day count' => ['Date', '0100ffff', [1, 65535]]; + yield 'Date32 signed day count' => ['Date32', '219cffffffffffff', [-25567, -1]]; + yield 'DateTime seconds' => ['DateTime', '685bf465ffffffff', [1710513000, 4294967295]]; + yield 'DateTime timezone metadata' => ['DateTime(\'Europe/Prague\')', '685bf465', [1710513000]]; + yield 'DateTime64 ticks' => ['DateTime64(3)', '83511a0d8d010000ffffffffffffffff', [1705321845123, -1]]; + yield 'DateTime64 timezone metadata' => ['DateTime64(9, \'UTC\')', 'ffffffffffffffff', [-1]]; + yield 'Nullable values and defaults' => ['Nullable(Int16)', '00010000ffff000000000700', [-1, null, 0, 7]]; + yield 'Array offsets and binary strings' => [ + 'Array(String)', + '020000000000000002000000000000000300000000000000016100020078', + [['a', ''], [], ["\x00x"]], + ]; + + yield 'Nested array offsets' => [ + 'Array(Array(UInt8))', + '02000000000000000300000000000000020000000000000002000000000000000300000000000000010203', + [[[1, 2], []], [[3]]], + ]; + + yield 'Nullable array elements' => [ + 'Array(Nullable(UInt8))', + '0300000000000000000100010002', + [[1, null, 2]], + ]; + + yield 'Tuple columns' => [ + 'Tuple(UInt8, Array(DateTime64(3, \'UTC\')))', + '010201000000000000000100000000000000ffffffffffffffff', + [[1, [-1]], [2, []]], + ]; + + yield 'Nullable tuple defaults' => [ + 'Nullable(Tuple(UInt8, String))', + '01000007000178', + [null, [7, 'x']], + ]; + + yield 'Empty tuple' => ['Tuple()', '', [[], []]]; + } + + public function testFixedStringPadsShortValues(): void + { + $resource = fopen('php://memory', 'w+b'); + self::assertIsResource($resource); + $stream = new BinaryStream($resource); + new TypeCodec()->write($stream, 'FixedString(4)', ['a', '']); + rewind($resource); + + self::assertSame("a\x00\x00\x00\x00\x00\x00\x00", stream_get_contents($resource)); + } + + public function testBoolAcceptsNonCanonicalTrue(): void + { + self::assertSame([true], new TypeCodec()->read($this->stream("\xff"), 'Bool', 1)); + } + + public function testNullableMasksNonDefaultPayload(): void + { + self::assertSame([null, 0], new TypeCodec()->read($this->stream("\x01\x00\xff\x00"), 'Nullable(UInt8)', 2)); + } + + public function testColumnValuesMustBeAList(): void + { + self::expectException(RuntimeException::class); + new TypeCodec()->write($this->stream(''), 'UInt8', ['key' => 1]); + } + + public function testNestedContainersShareAllocationBudget(): void + { + self::expectException(RuntimeException::class); + self::expectExceptionMessage('allocation budget'); + // Empty tuples have no payload bytes but still allocate a container for each row. + new TypeCodec()->read($this->stream(''), 'Tuple(Tuple(), Tuple())', 200000); + } + + /** @param list $values */ + #[DataProvider('provideInvalidValues')] + public function testInvalidValues(string $type, array $values): void + { + self::expectException(RuntimeException::class); + new TypeCodec()->write($this->stream(''), $type, $values); + } + + /** @phpstan-return Generator}> */ + public static function provideInvalidValues(): Generator + { + yield 'Unsigned negative' => ['UInt8', [-1]]; + yield 'Unsigned overflow' => ['UInt16', [65536]]; + yield 'Signed underflow' => ['Int32', [-2147483649]]; + yield 'Signed overflow' => ['Int8', [128]]; + yield 'Unsigned 64 negative' => ['UInt64', [-1]]; + yield 'Unsigned 64 decimal overflow' => ['UInt64', ['18446744073709551616']]; + yield 'Unsigned 64 negative string' => ['UInt64', ['-1']]; + yield 'Unsigned 64 noncanonical decimal' => ['UInt64', ['01']]; + yield 'Undeclared enum index' => ["Enum8('ready' = 7)", [0]]; + yield 'Unsigned 64 scientific notation' => ['UInt64', ['1e3']]; + yield 'Integer precision loss' => ['Int64', [1.0]]; + yield 'Integer numeric string' => ['UInt32', ['1']]; + yield 'Float invalid type' => ['Float64', ['1.5']]; + yield 'Float32 overflow' => ['Float32', [1.0e100]]; + yield 'Bool integer coercion' => ['Bool', [1]]; + yield 'String null coercion' => ['String', [null]]; + yield 'FixedString truncation' => ['FixedString(2)', ['abc']]; + yield 'Date range' => ['Date', [-1]]; + yield 'DateTime range' => ['DateTime(\'UTC\')', [4294967296]]; + yield 'Array nonlist' => ['Array(UInt8)', [['key' => 1]]]; + yield 'Array invalid inner value' => ['Array(UInt8)', [[256]]]; + yield 'Tuple width mismatch' => ['Tuple(UInt8, String)', [[1]]]; + yield 'Nullable invalid present value' => ['Nullable(Int8)', [128]]; + } + + #[DataProvider('provideInvalidTypes')] + public function testInvalidTypesEvenInEmptyColumns(string $type): void + { + self::expectException(RuntimeException::class); + new TypeCodec()->read($this->stream(''), $type, 0); + } + + /** @phpstan-return Generator */ + public static function provideInvalidTypes(): Generator + { + yield 'Unsupported leaf' => ['Decimal(10, 2)']; + yield 'Unsupported nested leaf' => ['Array(LowCardinality(String))']; + yield 'Empty nullable' => ['Nullable()']; + yield 'Empty array' => ['Array()']; + yield 'Unexpected scalar parameters' => ['UInt8()']; + yield 'Malformed tuple' => ['Tuple(UInt8,,String)']; + yield 'Unbalanced nesting' => ['Array(Tuple(UInt8, String)']; + yield 'Named tuple unsupported' => ['Tuple(id UInt8)']; + yield 'FixedString zero' => ['FixedString(0)']; + yield 'FixedString unreasonable size' => ['FixedString(67108865)']; + yield 'DateTime empty parameter' => ['DateTime()']; + yield 'DateTime unquoted timezone' => ['DateTime(UTC)']; + yield 'DateTime64 missing scale' => ['DateTime64']; + yield 'DateTime64 invalid scale' => ['DateTime64(10)']; + yield 'DateTime64 malformed timezone' => ["DateTime64(3, 'UTC)"]; + yield 'Nesting limit' => [str_repeat('Array(', 33) . 'UInt8' . str_repeat(')', 33)]; + yield 'Declaration size limit' => [str_repeat('x', 4097)]; + } + + #[DataProvider('provideMalformedData')] + public function testMalformedData(string $type, string $hex, int $rows): void + { + $bytes = hex2bin($hex); + self::assertIsString($bytes); + self::expectException(RuntimeException::class); + new TypeCodec()->read($this->stream($bytes), $type, $rows); + } + + /** @phpstan-return Generator */ + public static function provideMalformedData(): Generator + { + yield 'Invalid null map' => ['Nullable(UInt8)', '0200', 1]; + yield 'Descending array offsets' => ['Array(UInt8)', '02000000000000000100000000000000', 2]; + yield 'Array offset above element bound' => ['Array(UInt8)', '41420f0000000000', 1]; + yield 'Array offset above PHP range' => ['Array(UInt8)', 'ffffffffffffffff', 1]; + yield 'Nested array offset bound' => ['Array(Array(UInt8))', '010000000000000041420f0000000000', 1]; + yield 'Truncated fixed width data' => ['UInt32', '010000', 1]; + yield 'Truncated string data' => ['String', '0261', 1]; + yield 'String above byte bound' => ['String', '81808020', 1]; + yield 'Fixed width column above byte bound' => ['FixedString(67108864)', '', 2]; + yield 'Negative row count' => ['UInt8', '', -1]; + yield 'Excessive row count' => ['UInt8', '', 1000001]; + } + + private function stream(string $bytes): BinaryStream + { + $resource = fopen('php://memory', 'w+b'); + self::assertIsResource($resource); + fwrite($resource, $bytes); + rewind($resource); + + return new BinaryStream($resource); + } +} diff --git a/tests/Client/Native/server.php b/tests/Client/Native/server.php new file mode 100644 index 00000000..ed9feba9 --- /dev/null +++ b/tests/Client/Native/server.php @@ -0,0 +1,20 @@ +run($scenario); +} catch (Throwable $error) { + fwrite(STDERR, $error->getMessage() . "\n"); + exit(1); +} diff --git a/tests/Client/NativeClickHouseClientTest.php b/tests/Client/NativeClickHouseClientTest.php new file mode 100644 index 00000000..eedaab43 --- /dev/null +++ b/tests/Client/NativeClickHouseClientTest.php @@ -0,0 +1,189 @@ + */ + private array $pipes = []; + + public function testSelect(): void + { + $client = $this->startServer( + 'select', + new ArraySettingsProvider(['max_block_size' => 100, 'max_threads' => 1]), + ); + $result = $client->selectWithParams( + 'SELECT {label:String}, {missing:Nullable(String)}, ' + . '{kind:Enum8(\'a\\\\t\' = 1)}, {_request_body:String}, :limit', + ['label' => "a'b\\c", 'missing' => null, 'kind' => 'a\\t', '_request_body' => 'raw\\t', 'limit' => 9], + new ArraySettingsProvider(['max_block_size' => 2]), + ); + + self::assertEquals([new Column('id', 'UInt8'), new Column('label', 'String')], $result->columns); + self::assertSame([[7, 'one'], [9, 'two'], [11, 'three']], $result->rows); + self::assertSame([[27, 'total']], $result->totals); + self::assertSame([[7, 'min'], [11, 'max']], $result->extremes); + + // A zero-row schema must survive the empty Data boundary; the same socket is reusable after EOS. + $empty = $client->select('SELECT empty'); + self::assertEquals([new Column('empty', 'UInt16')], $empty->columns); + self::assertSame([], $empty->rows); + self::assertSame([], $empty->totals); + self::assertSame([], $empty->extremes); + $this->finishServer(); + } + + public function testInsert(): void + { + $client = $this->startServer('insert'); + $rows = static function (): Generator { + yield ['one', 7]; + yield ['two', 9]; + yield ['three', 11]; + }; + + $client->insert('events', $rows(), ['label', 'id']); + self::assertSame([[3, 'done']], $client->select('SELECT inserted')->rows); + $this->finishServer(); + } + + public function testNullParameterRequiresNullableType(): void + { + $this->client = new NativeClickHouseClient(new ConnectionConfig('127.0.0.1', 1)); + self::expectException(UnsupportedParamValue::class); + $this->client->selectWithParams('SELECT {missing:String}', ['missing' => null]); + } + + #[DataProvider('provideFailedSelect')] + public function testFailedSelectDiscardsPartialRowsAndReconnects(string $scenario): void + { + $client = $this->startServer($scenario); + try { + $client->select('SELECT failing'); + self::fail('A partial result must not be returned before EndOfStream.'); + } catch (RuntimeException $error) { + if ($scenario === 'exception') { + self::assertInstanceOf(NativeServerError::class, $error); + self::assertSame(241, $error->getCode()); + self::assertSame('MEMORY_LIMIT_EXCEEDED', $error->name); + self::assertSame('Query exceeded its memory limit', $error->getMessage()); + self::assertSame('server.cpp:42', $error->serverStackTrace); + } elseif ($scenario === 'budget') { + self::assertStringContainsString('allocation budget', $error->getMessage()); + } else { + self::assertNotInstanceOf(NativeServerError::class, $error); + self::assertStringContainsString('closed connection', $error->getMessage()); + } + } + + self::assertSame([[42, 'fresh']], $client->select('SELECT recovered')->rows); + $this->finishServer(); + } + + /** @phpstan-return Generator */ + public static function provideFailedSelect(): Generator + { + yield 'server error after a complete data block' => ['exception']; + yield 'connection closes inside a string column' => ['truncated']; + yield 'individually valid blocks exceed total result budget' => ['budget']; + } + + public function testInsertRejectsMismatchedRowsAndReconnects(): void + { + $client = $this->startServer('invalid-insert'); + try { + $client->insert('events', [['missing-id']], ['label', 'id']); + self::fail('An insert row must match the returned schema.'); + } catch (RuntimeException $error) { + self::assertStringContainsString('match the server schema', $error->getMessage()); + } + + self::assertSame([[42, 'fresh']], $client->select('SELECT recovered')->rows); + $this->finishServer(); + } + + protected function tearDown(): void + { + $this->client?->close(); + if (is_resource($this->server)) { + proc_terminate($this->server); + proc_close($this->server); + } + + foreach ($this->pipes as $pipe) { + if (is_resource($pipe)) { + fclose($pipe); + } + } + } + + private function startServer( + string $scenario, + ArraySettingsProvider $defaults = new ArraySettingsProvider([]), + ): NativeClickHouseClient { + $server = proc_open( + [PHP_BINARY, __DIR__ . '/Native/server.php', $scenario], + [0 => ['pipe', 'r'], 1 => ['pipe', 'w'], 2 => ['pipe', 'w']], + $pipes, + ); + self::assertIsResource($server); + $this->server = $server; + $this->pipes = $pipes; + stream_set_timeout($pipes[1], 5); + $port = fgets($pipes[1]); + self::assertNotFalse($port, 'Scripted server did not report its listening port.'); + + $this->client = new NativeClickHouseClient( + new ConnectionConfig('127.0.0.1', (int) $port, 'analytics', 'reader', 'test-password', readTimeout: 5), + defaultSettings: $defaults, + insertBlockSize: 2, + ); + + return $this->client; + } + + private function finishServer(): void + { + $this->client?->close(); + $errors = stream_get_contents($this->pipes[2]); + self::assertIsResource($this->server); + $exitCode = proc_close($this->server); + $this->server = null; + self::assertSame(0, $exitCode, $errors === false ? 'Cannot read scripted server errors.' : $errors); + } +} diff --git a/tests/Client/NativeClickHouseIntegrationTest.php b/tests/Client/NativeClickHouseIntegrationTest.php new file mode 100644 index 00000000..9a8edb3c --- /dev/null +++ b/tests/Client/NativeClickHouseIntegrationTest.php @@ -0,0 +1,122 @@ +client->selectWithParams( + 'SELECT toUInt8(number + :offset) AS id, {label:String} AS label, ' + . '{missing:Nullable(String)} AS missing, ' + . '{missingNumber:Nullable(Int16)} AS missing_number, ' + . 'CAST([1, 65535] AS Array(UInt16)) AS items, ' + . 'CAST(tuple(toInt8(-3), \'x\') AS Tuple(Int8, String)) AS pair, ' + . 'toUInt64(\'18446744073709551615\') AS large, ' + . 'CAST(\'ab\' AS FixedString(4)) AS fixed, ' + . 'toInt8({kind:Enum8(\'a\\\\t\' = 1)}) AS kind, ' + . '{_request_body:String} AS body, ' + . 'toUInt64(getSetting(\'max_block_size\')) AS block_size ' + . 'FROM numbers(2) ORDER BY number', + [ + 'offset' => 7, + 'label' => $label, + 'missing' => null, + 'missingNumber' => null, + 'kind' => 'a\\t', + '_request_body' => $body, + ], + new ArraySettingsProvider(['max_block_size' => 1, 'max_threads' => 1]), + ); + + self::assertEquals( + [ + new Column('id', 'UInt8'), + new Column('label', 'String'), + new Column('missing', 'Nullable(String)'), + new Column('missing_number', 'Nullable(Int16)'), + new Column('items', 'Array(UInt16)'), + new Column('pair', 'Tuple(Int8, String)'), + new Column('large', 'UInt64'), + new Column('fixed', 'FixedString(4)'), + new Column('kind', 'Int8'), + new Column('body', 'String'), + new Column('block_size', 'UInt64'), + ], + $result->columns, + ); + $expectedValues = [$label, null, null, [1, 65535], [-3, 'x'], '18446744073709551615', "ab\0\0", 1, $body, 1]; + self::assertSame([[7, ...$expectedValues], [8, ...$expectedValues]], $result->rows); + } + + public function testInsertBatchesIntoTemporaryTable(): void + { + // Temporary tables belong to this connection and disappear when it closes. + $this->client->executeQueryWithParams( + 'CREATE TEMPORARY TABLE native_batches ' + . '(id UInt8, label Nullable(String) DEFAULT :fallback, items Array(Int16))', + ['fallback' => 'fallback-label'], + ); + $rows = static function (): Generator { + yield ["a'b\\c", [-1, 2], 7]; + yield [null, [], 9]; + yield ["\0last", [32767], 11]; + }; + $this->client->insert('native_batches', $rows(), ['label', 'items', 'id']); + $this->client->insert('native_batches', [[13]], ['id']); + + self::assertSame( + [[7, "a'b\\c", [-1, 2]], [9, null, []], [11, "\0last", [32767]], [13, 'fallback-label', []]], + $this->client->select('SELECT id, label, items FROM native_batches ORDER BY id')->rows, + ); + } + + protected function setUp(): void + { + $caFile = self::environment('CLICKHOUSE_TCP_CA_FILE', ''); + $serverName = self::environment('CLICKHOUSE_TCP_SERVER_NAME', ''); + $this->client = new NativeClickHouseClient( + new ConnectionConfig( + self::environment('CLICKHOUSE_TCP_HOST', '127.0.0.1'), + (int) self::environment('CLICKHOUSE_TCP_PORT', '9000'), + self::environment('CLICKHOUSE_DATABASE', 'default'), + self::environment('CLICKHOUSE_USER', 'default'), + self::environment('CLICKHOUSE_PASSWORD', ''), + tls: self::environment('CLICKHOUSE_TCP_TLS', '0') === '1', + caFile: $caFile === '' ? null : $caFile, + serverName: $serverName === '' ? null : $serverName, + ), + defaultSettings: new ArraySettingsProvider(['max_block_size' => 100]), + insertBlockSize: 2, + ); + } + + protected function tearDown(): void + { + $this->client->close(); + } + + private static function environment(string $name, string $fallback): string + { + $value = getenv($name); + + return $value === false ? $fallback : $value; + } +}