: test hints can name an error instead of giving its code."
+ sed -n 's/^ *M(\([0-9][0-9]*\), *\([A-Z0-9_][A-Z0-9_]*\)).*/\1\t\2/p' "${src_file}"
+} > "${out}"
+echo "Wrote $(grep -vc '^#' "${out}") error codes from ${ref} to ${out}" >&2
diff --git a/tests/clickhouse-client/scripts/pinned-version.sh b/tests/clickhouse-client/scripts/pinned-version.sh
new file mode 100755
index 000000000..b70b0b388
--- /dev/null
+++ b/tests/clickhouse-client/scripts/pinned-version.sh
@@ -0,0 +1,11 @@
+#!/usr/bin/env bash
+# Prints the pinned ClickHouse server version from ../clickhouse-version.
+set -euo pipefail
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+file="${SCRIPT_DIR}/../clickhouse-version"
+version="$(grep -v '^[[:space:]]*#' "${file}" | tr -d '[:space:]')"
+if ! [[ "${version}" =~ ^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
+ echo "Error: ${file} must contain one version such as 26.10.4.207 (got: '${version}')." >&2
+ exit 1
+fi
+echo "${version}"
diff --git a/tests/clickhouse-client/scripts/run-upstream-tests.sh b/tests/clickhouse-client/scripts/run-upstream-tests.sh
new file mode 100755
index 000000000..09de0f0e9
--- /dev/null
+++ b/tests/clickhouse-client/scripts/run-upstream-tests.sh
@@ -0,0 +1,245 @@
+#!/usr/bin/env bash
+# Runs the allowlisted upstream ClickHouse SQL tests through clickhouse-java.
+#
+# Usage: scripts/run-upstream-tests.sh [...]
+#
+# See ../README.md for the environment variables.
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+RUNNER_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
+
+UPSTREAM_CLICKHOUSE_DIR="${UPSTREAM_CLICKHOUSE_DIR:-${RUNNER_DIR}/.upstream/ClickHouse}"
+UPSTREAM_TEST_LIST="${UPSTREAM_TEST_LIST:-${RUNNER_DIR}/allowlist.txt}"
+CLICKHOUSE_CLIENT_CLI_IMPL="${CLICKHOUSE_CLIENT_CLI_IMPL:-client}"
+SHARD_INDEX="${SHARD_INDEX:-1}"
+SHARD_TOTAL="${SHARD_TOTAL:-1}"
+backend="${CLICKHOUSE_CLIENT_CLI_IMPL}"
+
+case "${backend}" in
+ client|jdbc|text) ;;
+ *)
+ echo "Error: CLICKHOUSE_CLIENT_CLI_IMPL must be client, jdbc or text (got: '${backend}')." >&2
+ exit 1
+ ;;
+esac
+
+if [[ ! -f "${UPSTREAM_CLICKHOUSE_DIR}/tests/clickhouse-test" ]]; then
+ echo "Error: ${UPSTREAM_CLICKHOUSE_DIR}/tests/clickhouse-test not found." >&2
+ echo "Run scripts/fetch-upstream.sh, or set UPSTREAM_CLICKHOUSE_DIR to a checkout of ClickHouse/ClickHouse." >&2
+ exit 1
+fi
+
+# The server and the tests must be of the same release: the `.reference`
+# files of another release do not match the output of the server.
+upstream_ref="$(cat "${UPSTREAM_CLICKHOUSE_DIR}/.upstream-ref" 2>/dev/null || echo unknown)"
+server_host="${CLICKHOUSE_HOST:-localhost}"
+server_url="http"'://'"${server_host}:${CLICKHOUSE_PORT_HTTP:-8123}/"
+if ! server_version="$(curl -fsS --noproxy '*' --data-binary 'SELECT version()' "${server_url}")"; then
+ echo "Error: cannot get the server version from ${server_url}. Start the server first." >&2
+ exit 1
+fi
+if [[ "${upstream_ref}" != "v${server_version}-stable" && "${ALLOW_VERSION_MISMATCH:-0}" != "1" ]]; then
+ echo "Error: the server is ${server_version}, but the upstream tests are ${upstream_ref}." >&2
+ echo "Start the server of the pinned version (scripts/pinned-version.sh) and run scripts/fetch-upstream.sh," >&2
+ echo "or set ALLOW_VERSION_MISMATCH=1 to run anyway." >&2
+ exit 1
+fi
+echo "Server ${server_version}, upstream tests ${upstream_ref}" >&2
+
+# Read the allowlist: one test name per line; '#' starts a comment.
+#
+# runs on every backend
+# # only=: runs on that backend only
+# # known=: [] known failure of group on that
+# backend; runs on the other backends
+# # # [] known failure of group ; does not run
+#
+# With KNOWN_FAILURES, read the known failures of this backend instead: the
+# lines of the groups in KNOWN_FAILURES (comma-separated IDs, or `all`). Use
+# it to check whether a fix makes the tests of a group pass.
+selected_group() {
+ [[ "${KNOWN_FAILURES}" == "all" || ",${KNOWN_FAILURES}," == *",$1,"* ]]
+}
+known_re='#[[:space:]]*known=([a-z]+):[[:space:]]*\[([a-z0-9-]+)\]'
+tests=()
+known_mode=0
+[[ -n "${KNOWN_FAILURES:-}" ]] && known_mode=1
+while IFS= read -r line || [[ -n "${line}" ]]; do
+ if [[ "${line}" =~ ^#[[:space:]]*([A-Za-z0-9_.-]+)[[:space:]]+#[[:space:]]*\[([a-z0-9-]+)\] ]]; then
+ if (( known_mode )) && selected_group "${BASH_REMATCH[2]}"; then
+ tests+=("${BASH_REMATCH[1]}")
+ fi
+ continue
+ fi
+ name="${line%%#*}"
+ name="${name#"${name%%[![:space:]]*}"}"
+ name="${name%"${name##*[![:space:]]}"}"
+ [[ -z "${name}" ]] && continue
+ # `only=`: the test cannot pass on the other backends.
+ if [[ "${line}" =~ \#[[:space:]]*only=([a-z]+) && "${BASH_REMATCH[1]}" != "${backend}" ]]; then
+ continue
+ fi
+ # `known=: []`: a known failure on that backend.
+ known_id=""
+ rest="${line}"
+ while [[ "${rest}" =~ ${known_re} ]]; do
+ if [[ "${BASH_REMATCH[1]}" == "${backend}" ]]; then
+ known_id="${BASH_REMATCH[2]}"
+ fi
+ rest="${rest#*"${BASH_REMATCH[0]}"}"
+ done
+ if (( known_mode )); then
+ if [[ -n "${known_id}" ]] && selected_group "${known_id}"; then
+ tests+=("${name}")
+ fi
+ elif [[ -z "${known_id}" ]]; then
+ tests+=("${name}")
+ fi
+done < "${UPSTREAM_TEST_LIST}"
+if (( known_mode )); then
+ echo "Selected ${#tests[@]} known failure(s) of ${KNOWN_FAILURES} for ${backend} from ${UPSTREAM_TEST_LIST}" >&2
+else
+ echo "Selected ${#tests[@]} test(s) for ${backend} from ${UPSTREAM_TEST_LIST}" >&2
+fi
+
+# Upstream renames and removes tests. A name that selects no test file runs
+# nothing and fails nothing, so report it.
+missing=()
+for t in "${tests[@]}"; do
+ if [[ ! -e "${UPSTREAM_CLICKHOUSE_DIR}/tests/queries/0_stateless/${t}.sql" &&
+ ! -e "${UPSTREAM_CLICKHOUSE_DIR}/tests/queries/0_stateless/${t}.sql.j2" ]]; then
+ missing+=("${t}")
+ fi
+done
+if [[ ${#missing[@]} -gt 0 ]]; then
+ msg="${#missing[@]} allowlisted test(s) are not in the upstream checkout (${upstream_ref}): ${missing[*]}"
+ if [[ -n "${GITHUB_ACTIONS:-}" ]]; then echo "::warning::${msg}"; else echo "Warning: ${msg}" >&2; fi
+fi
+
+# Round-robin sharding: keep the tests at positions i where
+# i % SHARD_TOTAL == SHARD_INDEX - 1.
+if ! [[ "${SHARD_TOTAL}" =~ ^[1-9][0-9]*$ && "${SHARD_INDEX}" =~ ^[1-9][0-9]*$ ]] || (( SHARD_INDEX > SHARD_TOTAL )); then
+ echo "Error: SHARD_INDEX and SHARD_TOTAL must be positive integers with SHARD_INDEX <= SHARD_TOTAL (got: ${SHARD_INDEX}/${SHARD_TOTAL})." >&2
+ exit 1
+fi
+if (( SHARD_TOTAL > 1 )); then
+ sharded=()
+ for i in "${!tests[@]}"; do
+ if (( i % SHARD_TOTAL == SHARD_INDEX - 1 )); then
+ sharded+=("${tests[$i]}")
+ fi
+ done
+ tests=("${sharded[@]}")
+ echo "Shard ${SHARD_INDEX}/${SHARD_TOTAL}: ${#tests[@]} test(s)" >&2
+fi
+
+# tests/clickhouse-test runs ALL tests when it gets no test names.
+if [[ ${#tests[@]} -eq 0 ]]; then
+ echo "Error: no tests selected from ${UPSTREAM_TEST_LIST}. Refusing to run the full upstream suite." >&2
+ exit 1
+fi
+
+# Build the shim against the clickhouse-java source of this repository
+# (SKIP_BUILD=1 uses the jar that is already in target/, for example from an
+# earlier CI job). tests/clickhouse-test calls `clickhouse` and
+# `clickhouse-client`; both names go to bin/clickhouse.
+JAR="${RUNNER_DIR}/target/clickhouse-client-cli-1.0.0.jar"
+if [[ "${SKIP_BUILD:-0}" != "1" ]]; then
+ "${SCRIPT_DIR}/build.sh" -DskipTests
+fi
+if [[ ! -f "${JAR}" ]]; then
+ echo "Error: ${JAR} not found. Run scripts/build.sh first." >&2
+ exit 1
+fi
+export PATH="${RUNNER_DIR}/bin:${PATH}"
+export CLICKHOUSE_CLIENT_CLI_IMPL
+
+# The runner starts the shim once per test. A class data sharing archive of
+# the classes of one run of this backend makes the JVM start faster.
+cds="${RUNNER_DIR}/target/clickhouse-client-cli-${backend}.jsa"
+if [[ ! -f "${cds}" || "${cds}" -ot "${JAR}" ]]; then
+ rm -f "${cds}"
+ echo "Making the class data sharing archive ${cds}" >&2
+ if ! CLICKHOUSE_CLIENT_CLI_CDS="" CLICKHOUSE_CLIENT_CLI_JAVA_OPTS="-XX:ArchiveClassesAtExit=${cds}" \
+ CLICKHOUSE_CLIENT_CLI_LOG="" clickhouse-client --host "${server_host}" --query \
+ "SELECT number, toString(number), [number], (number, 'a'), map('k', number), toDateTime64(number, 3), toDecimal64(number, 2), toNullable(number) FROM numbers(3) FORMAT Null" \
+ > /dev/null; then
+ echo "Warning: cannot make the class data sharing archive; the tests run without it." >&2
+ rm -f "${cds}"
+ fi
+fi
+
+if [[ -n "${CLICKHOUSE_CLIENT_CLI_LOG:-}" ]]; then
+ mkdir -p "$(dirname "${CLICKHOUSE_CLIENT_CLI_LOG}")"
+ export CLICKHOUSE_CLIENT_CLI_LOG
+fi
+# tests/clickhouse-test gives the client `--database` for each test; a
+# CLICKHOUSE_DATABASE in the environment would give it a second one.
+unset CLICKHOUSE_DATABASE
+
+# shellcheck source=selectors.sh
+source "${SCRIPT_DIR}/selectors.sh"
+build_selectors "${tests[@]}"
+
+echo "Backend: ${backend}" >&2
+cd "${UPSTREAM_CLICKHOUSE_DIR}"
+# --dont_retry_failures: by default the runner runs a failed test again when its
+# output has one of its MESSAGES_TO_RETRY (for example "No such file or
+# directory"), and reports a pass as OK. RETRY_FAILED is the only retry here.
+runner=(python3 tests/clickhouse-test --no-stateful --no-random-settings --no-random-merge-tree-settings
+ --dont_retry_failures)
+
+retries="${RETRY_FAILED:-0}"
+if ! [[ "${retries}" =~ ^[0-9]+$ ]]; then
+ echo "Error: RETRY_FAILED must be a number of retries (got: '${retries}')." >&2
+ exit 1
+fi
+if (( retries == 0 )); then
+ exec "${runner[@]}" "$@" -- "${selectors[@]}"
+fi
+
+# RETRY_FAILED=: run the failed tests again, at most n times. A test that
+# passes on a retry is reported as a warning; a test that fails on every
+# attempt fails the run. Do not use this to grow or check the allowlist: a test
+# that needs a retry is not reliable.
+
+# run_attempt runs the runner on the current selectors and sets
+# attempt_status, attempt_failed and attempt_passed.
+run_attempt() {
+ local log="$1" t
+ shift
+ set +e
+ "${runner[@]}" --max-failures-chain 1000000 "$@" -- "${selectors[@]}" 2>&1 | tee "${log}"
+ attempt_status=${PIPESTATUS[0]}
+ set -e
+ attempt_failed=()
+ while IFS= read -r t; do
+ attempt_failed+=("${t}")
+ done < <(sed -nE 's/^\[[ 0-9]+\/[ 0-9]+\] ([^ :]+): +\[ FAIL \].*/\1/p' "${log}" | sort -u)
+ attempt_passed="$(sed -nE 's/^\[[ 0-9]+\/[ 0-9]+\] ([^ :]+): +\[ OK \].*/\1/p' "${log}" | sort -u | tr '\n' ' ')"
+}
+
+log="$(mktemp)"
+trap 'rm -f "${log}"' EXIT
+runner_args=("$@")
+run_attempt "${log}" "${runner_args[@]}"
+passed_on_retry=""
+attempt=0
+while (( attempt_status != 0 && attempt < retries )); do
+ if [[ ${#attempt_failed[@]} -eq 0 ]]; then
+ echo "Error: the run failed (exit code ${attempt_status}), but no test failed. See the output above." >&2
+ exit "${attempt_status}"
+ fi
+ attempt=$(( attempt + 1 ))
+ echo "Retry ${attempt}/${retries}: ${#attempt_failed[@]} failed test(s): ${attempt_failed[*]}" >&2
+ build_selectors "${attempt_failed[@]}"
+ run_attempt "${log}" "${runner_args[@]}"
+ passed_on_retry="${passed_on_retry}${attempt_passed}"
+done
+
+if [[ -n "${passed_on_retry}" ]]; then
+ msg="These tests failed and then passed on a retry: ${passed_on_retry}"
+ if [[ -n "${GITHUB_ACTIONS:-}" ]]; then echo "::warning::${msg}"; else echo "Warning: ${msg}" >&2; fi
+fi
+exit "${attempt_status}"
diff --git a/tests/clickhouse-client/scripts/run-with-real-client.sh b/tests/clickhouse-client/scripts/run-with-real-client.sh
new file mode 100755
index 000000000..acf995225
--- /dev/null
+++ b/tests/clickhouse-client/scripts/run-with-real-client.sh
@@ -0,0 +1,68 @@
+#!/usr/bin/env bash
+# Runs upstream tests through the REAL clickhouse-client in the server
+# container, not through clickhouse-java. Use it as the reference when you
+# triage a failure: if a test fails here too, the cause is the environment
+# (server config, missing cluster, ...), not clickhouse-java or the shim.
+#
+# Usage: scripts/run-with-real-client.sh [...]
+#
+# It reads the same UPSTREAM_CLICKHOUSE_DIR and UPSTREAM_TEST_LIST as
+# run-upstream-tests.sh. CLICKHOUSE_CONTAINER is the name of the server
+# container (default: clickhouse).
+set -euo pipefail
+
+SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
+RUNNER_DIR="$(cd "${SCRIPT_DIR}/.." && pwd)"
+
+UPSTREAM_CLICKHOUSE_DIR="${UPSTREAM_CLICKHOUSE_DIR:-${RUNNER_DIR}/.upstream/ClickHouse}"
+UPSTREAM_TEST_LIST="${UPSTREAM_TEST_LIST:-${RUNNER_DIR}/allowlist.txt}"
+CLICKHOUSE_CONTAINER="${CLICKHOUSE_CONTAINER:-clickhouse}"
+
+if ! docker exec "${CLICKHOUSE_CONTAINER}" clickhouse-client --query "SELECT 1" > /dev/null; then
+ echo "Error: cannot run clickhouse-client in container '${CLICKHOUSE_CONTAINER}'. Set CLICKHOUSE_CONTAINER." >&2
+ exit 1
+fi
+
+# A clickhouse binary that forwards to the real one in the container.
+BIN_DIR="${RUNNER_DIR}/.bin-real-client"
+mkdir -p "${BIN_DIR}"
+cat > "${BIN_DIR}/clickhouse" <&2
+ exit 1
+fi
+# shellcheck source=selectors.sh
+source "${SCRIPT_DIR}/selectors.sh"
+build_selectors "${tests[@]}"
+
+export PATH="${BIN_DIR}:${PATH}"
+cd "${UPSTREAM_CLICKHOUSE_DIR}"
+exec python3 tests/clickhouse-test --no-stateful --no-random-settings --no-random-merge-tree-settings "$@" -- "${selectors[@]}"
diff --git a/tests/clickhouse-client/scripts/selectors.sh b/tests/clickhouse-client/scripts/selectors.sh
new file mode 100755
index 000000000..a737c0ab5
--- /dev/null
+++ b/tests/clickhouse-client/scripts/selectors.sh
@@ -0,0 +1,29 @@
+# shellcheck shell=bash
+# Sourced by run-upstream-tests.sh and run-with-real-client.sh.
+#
+# build_selectors ... sets the array `selectors` to anchored regular
+# expressions that select exactly the given tests.
+#
+# tests/clickhouse-test reads each test argument as a regular expression and
+# selects every file that it matches anywhere in the name, so `00396_uuid`
+# would also select `00396_uuid_v7`. An anchored alternation selects exactly
+# the listed tests, and is much faster than one expression per test. Linux
+# limits one argument to 128 KiB, so the alternation is split into several
+# arguments of at most selector_max_bytes.
+selector_max_bytes=65536
+
+build_selectors() {
+ selectors=()
+ local chunk="" t
+ for t in "$@"; do
+ t="${t//./\\.}"
+ if [[ -n "${chunk}" && $(( ${#chunk} + ${#t} + 32 )) -gt ${selector_max_bytes} ]]; then
+ selectors+=("^(${chunk})\\.(sql|sql\\.j2)\$")
+ chunk=""
+ fi
+ chunk="${chunk:+${chunk}|}${t}"
+ done
+ if [[ -n "${chunk}" ]]; then
+ selectors+=("^(${chunk})\\.(sql|sql\\.j2)\$")
+ fi
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Backend.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Backend.java
new file mode 100644
index 000000000..aa9e44034
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Backend.java
@@ -0,0 +1,49 @@
+package com.clickhouse.client.cli;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Runs statements through one client API on one session. Selected by {@code CLICKHOUSE_CLIENT_CLI_IMPL}.
+ */
+interface Backend extends AutoCloseable {
+
+ /**
+ * Runs one statement.
+ *
+ * @param sql the statement text, as {@code clickhouse-client} sends it
+ * @param settings the command-line settings that go with the statement
+ * @param database the current database of the session
+ * @return the result set, or null when the statement has no result set
+ */
+ Result execute(String sql, Map settings, String database) throws Exception;
+
+ /** Called when the test changes a forwarded setting with SET: the setting no longer goes with each query. */
+ default void settingsChanged(Map settings) throws Exception {
+ }
+
+ @Override
+ void close() throws Exception;
+
+ /** A result set: column names and types from the metadata, and the values as the client returns them. */
+ interface Result extends AutoCloseable {
+ List names();
+
+ List types();
+
+ boolean next() throws Exception;
+
+ /** Returns the value of column i (0-based) of the current row, with the client's normal type mapping. */
+ Object get(int i) throws Exception;
+
+ /**
+ * For a pass-through backend: the raw response text, written as it is. Null for the typed backends.
+ */
+ default byte[] rawText() throws Exception {
+ return null;
+ }
+
+ @Override
+ void close() throws Exception;
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ChType.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ChType.java
new file mode 100644
index 000000000..0522878ac
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ChType.java
@@ -0,0 +1,281 @@
+package com.clickhouse.client.cli;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * A parsed ClickHouse data type, for example {@code Array(Nullable(DateTime64(3, 'UTC')))}.
+ *
+ * The shim parses the type name that the server sends itself, so that the renderer does not depend on the type
+ * parser of the client. {@link #args} holds the parameters inside the parentheses. A parameter is either a nested
+ * type ({@code type != null}) or a literal ({@code literal != null}), such as the {@code 3} and {@code 'UTC'} above
+ * or the {@code 'a' = 1} of an {@code Enum8}. {@code name} is set for the named elements of a {@code Tuple} or
+ * {@code Nested}, as in {@code Tuple(a Int32, b String)}.
+ */
+final class ChType {
+
+ static final class Arg {
+ final String name;
+ final ChType type;
+ final String literal;
+
+ Arg(String name, ChType type, String literal) {
+ this.name = name;
+ this.type = type;
+ this.literal = literal;
+ }
+ }
+
+ final String base;
+ final List args;
+
+ ChType(String base, List args) {
+ this.base = base;
+ this.args = args;
+ }
+
+ static ChType of(String base) {
+ return new ChType(base, Collections.emptyList());
+ }
+
+ /** Returns the nested type of argument i, or null. */
+ ChType typeArg(int i) {
+ return i < args.size() ? args.get(i).type : null;
+ }
+
+ /** Returns the literal of argument i without its single quotes, or null when argument i is absent. */
+ String literalArg(int i) {
+ if (i >= args.size() || args.get(i).literal == null) {
+ return null;
+ }
+ String s = args.get(i).literal;
+ if (s.length() >= 2 && s.startsWith("'") && s.endsWith("'")) {
+ s = s.substring(1, s.length() - 1);
+ }
+ return s;
+ }
+
+ @Override
+ public String toString() {
+ if (args.isEmpty()) {
+ return base;
+ }
+ StringBuilder sb = new StringBuilder(base).append('(');
+ for (int i = 0; i < args.size(); i++) {
+ if (i > 0) {
+ sb.append(", ");
+ }
+ Arg a = args.get(i);
+ if (a.type != null && a.name != null) {
+ sb.append(a.name).append(' ').append(a.type);
+ } else if (a.type != null) {
+ sb.append(a.type);
+ } else {
+ sb.append(a.literal);
+ }
+ }
+ return sb.append(')').toString();
+ }
+
+ /** Parses the type name that the server sends in the result header. */
+ static ChType parse(String s) {
+ String in = s.trim();
+ String[] rest = new String[1];
+ ChType t = parseAt(in, rest);
+ if (!rest[0].trim().isEmpty()) {
+ throw new IllegalArgumentException("parse type \"" + s + "\": unexpected trailing text \"" + rest[0] + "\"");
+ }
+ return t;
+ }
+
+ private static ChType parseAt(String s, String[] rest) {
+ int i = 0;
+ while (i < s.length() && (SqlText.isWordChar(s.charAt(i)) || s.charAt(i) == '.')) {
+ i++;
+ }
+ if (i == 0) {
+ throw new IllegalArgumentException("expected a type name at \"" + s + "\"");
+ }
+ String base = s.substring(0, i);
+ String after = stripLeadingSpaces(s.substring(i));
+ if (!after.startsWith("(")) {
+ rest[0] = after;
+ return of(base);
+ }
+ List parts = new ArrayList<>();
+ rest[0] = splitArgs(after, parts, s);
+ List args = new ArrayList<>(parts.size());
+ for (String p : parts) {
+ args.add(parseArg(base, p));
+ }
+ return new ChType(base, args);
+ }
+
+ private static String stripLeadingSpaces(String s) {
+ int i = 0;
+ while (i < s.length() && s.charAt(i) == ' ') {
+ i++;
+ }
+ return s.substring(i);
+ }
+
+ /** Parses a whole string as a type, or returns null. */
+ private static ChType tryParse(String s) {
+ try {
+ String[] rest = new String[1];
+ ChType t = parseAt(s, rest);
+ return rest[0].trim().isEmpty() ? t : null;
+ } catch (IllegalArgumentException e) {
+ return null;
+ }
+ }
+
+ /** Turns one raw parameter into a nested type, a named nested type, or a literal. */
+ private static Arg parseArg(String base, String raw) {
+ raw = raw.trim();
+ if (raw.isEmpty() || raw.charAt(0) == '\'' || raw.charAt(0) == '-'
+ || (raw.charAt(0) >= '0' && raw.charAt(0) <= '9')) {
+ return new Arg(null, null, raw);
+ }
+ switch (base) {
+ case "Enum8":
+ case "Enum16":
+ case "Enum":
+ return new Arg(null, null, raw);
+ case "AggregateFunction":
+ case "SimpleAggregateFunction": {
+ // The first argument is a function name, such as `sum` or `quantiles(0.5, 0.9)`. It is not a type.
+ ChType t = tryParse(raw);
+ if (t != null && KNOWN_TYPES.contains(t.base)) {
+ return new Arg(null, t, null);
+ }
+ return new Arg(null, null, raw);
+ }
+ case "Tuple":
+ case "Nested":
+ case "JSON":
+ case "Object":
+ case "Variant": {
+ // Named element: `name Type` (the name can be quoted with backticks).
+ String[] named = splitNamedElement(raw);
+ if (named != null) {
+ ChType t = tryParse(named[1]);
+ if (t != null) {
+ return new Arg(named[0], t, null);
+ }
+ }
+ break;
+ }
+ default:
+ break;
+ }
+ ChType t = tryParse(raw);
+ if (t != null) {
+ return new Arg(null, t, null);
+ }
+ return new Arg(null, null, raw);
+ }
+
+ /**
+ * Splits {@code name Type} into its two parts. Returns null for an element that is only a type, such as
+ * {@code Int32} or {@code Array(String)}.
+ */
+ private static String[] splitNamedElement(String raw) {
+ if (raw.startsWith("`")) {
+ StringBuilder name = new StringBuilder();
+ int i = 1;
+ while (i < raw.length()) {
+ char c = raw.charAt(i);
+ if (c == '\\' && i + 1 < raw.length()) {
+ name.append(raw.charAt(i + 1));
+ i += 2;
+ } else if (c == '`' && i + 1 < raw.length() && raw.charAt(i + 1) == '`') {
+ name.append('`');
+ i += 2;
+ } else if (c == '`') {
+ return new String[] {name.toString(), raw.substring(i + 1).trim()};
+ } else {
+ name.append(c);
+ i++;
+ }
+ }
+ return null;
+ }
+ int i = 0;
+ while (i < raw.length() && (SqlText.isWordChar(raw.charAt(i)) || raw.charAt(i) == '.')) {
+ i++;
+ }
+ if (i == 0 || i >= raw.length() || raw.charAt(i) != ' ') {
+ return null;
+ }
+ return new String[] {raw.substring(0, i), raw.substring(i).trim()};
+ }
+
+ /**
+ * Splits {@code (a, b(c, d), 'e,f')rest} into its top-level parameters and returns the text after the closing
+ * parenthesis.
+ */
+ private static String splitArgs(String s, List parts, String whole) {
+ int depth = 0;
+ int start = 1;
+ char quote = 0;
+ for (int i = 0; i < s.length(); i++) {
+ char c = s.charAt(i);
+ if (quote != 0) {
+ if (c == '\\') {
+ i++;
+ } else if (c == quote) {
+ quote = 0;
+ }
+ continue;
+ }
+ switch (c) {
+ case '\'':
+ case '`':
+ case '"':
+ quote = c;
+ break;
+ case '(':
+ depth++;
+ break;
+ case ')':
+ depth--;
+ if (depth == 0) {
+ String p = s.substring(start, i).trim();
+ if (!p.isEmpty() || !parts.isEmpty()) {
+ parts.add(p);
+ }
+ return s.substring(i + 1);
+ }
+ break;
+ case ',':
+ if (depth == 1) {
+ parts.add(s.substring(start, i).trim());
+ start = i + 1;
+ }
+ break;
+ default:
+ break;
+ }
+ }
+ throw new IllegalArgumentException("unbalanced parentheses in \"" + whole + "\"");
+ }
+
+ /**
+ * Used only to tell {@code SimpleAggregateFunction(sum, UInt64)} (function name, then type) apart; a false
+ * negative only makes the renderer report an unsupported type.
+ */
+ private static final Set KNOWN_TYPES = new HashSet<>(Arrays.asList(
+ "Int8", "Int16", "Int32", "Int64", "Int128", "Int256",
+ "UInt8", "UInt16", "UInt32", "UInt64", "UInt128", "UInt256",
+ "Float32", "Float64", "BFloat16", "Bool", "String", "FixedString",
+ "Date", "Date32", "DateTime", "DateTime64", "Time", "Time64", "UUID", "IPv4", "IPv6",
+ "Decimal", "Decimal32", "Decimal64", "Decimal128", "Decimal256",
+ "Enum8", "Enum16", "Nullable", "LowCardinality", "Array", "Tuple", "Map", "Nothing",
+ "Point", "Ring", "LineString", "MultiLineString", "Polygon", "MultiPolygon", "MultiPoint", "Geometry",
+ "JSON", "Object", "Dynamic", "Variant", "Nested", "QBit"));
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/CliOptions.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/CliOptions.java
new file mode 100644
index 000000000..55dfe3471
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/CliOptions.java
@@ -0,0 +1,198 @@
+package com.clickhouse.client.cli;
+
+import org.apache.commons.cli.CommandLine;
+import org.apache.commons.cli.DefaultParser;
+import org.apache.commons.cli.HelpFormatter;
+import org.apache.commons.cli.Option;
+import org.apache.commons.cli.Options;
+import org.apache.commons.cli.ParseException;
+
+import java.io.PrintWriter;
+import java.io.StringWriter;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/** The {@code clickhouse-client} command line, as far as {@code tests/clickhouse-test} uses it. */
+final class CliOptions {
+
+ /**
+ * The command-line settings that the shim sends to the server. {@code tests/clickhouse-test} also adds many
+ * randomized settings to the command line. The shim drops them: they only change performance-related paths in
+ * the server, and some of them are client-only.
+ *
+ * {@code async_insert} and {@code enable_parallel_replicas} are not randomized: {@code tests/clickhouse-test}
+ * sets them to 0 for a test with the tag {@code no-async-insert} or {@code no-parallel-replicas}
+ * ({@code FEATURE_TAG_OVERRIDES}), because the test does not work with the feature. The server default of
+ * {@code async_insert} is 1, so the shim must send them.
+ */
+ static final Set SERVER_SETTINGS = new HashSet<>(Arrays.asList(
+ "log_comment", "max_insert_threads", "max_threads", "send_logs_level",
+ "async_insert", "enable_parallel_replicas"));
+
+ String host = "localhost";
+ /** The port of the command line, or null when not given. */
+ Integer port;
+ String user = "default";
+ String password = "";
+ String database = "default";
+ String query;
+ boolean secure;
+ boolean help;
+ /** The command-line settings that go to the server, in command-line order. */
+ final Map settings = new LinkedHashMap<>();
+ /** The query parameters from {@code --param_=}. */
+ final Map params = new LinkedHashMap<>();
+
+ static Options baseOptions() {
+ Options options = new Options();
+ options.addOption(Option.builder("h").longOpt("host").hasArg().argName("HOST")
+ .desc("Server host (default: localhost)").build());
+ options.addOption(Option.builder().longOpt("port").hasArg().argName("PORT")
+ .desc("Server port. The native port of the test runner (CLICKHOUSE_PORT_TCP) maps to"
+ + " CLICKHOUSE_PORT_HTTP (default: 8123)").build());
+ options.addOption(Option.builder("u").longOpt("user").hasArg().argName("USER")
+ .desc("User name (default: default)").build());
+ options.addOption(Option.builder().longOpt("password").hasArg().argName("PASSWORD")
+ .desc("Password (default: empty)").build());
+ options.addOption(Option.builder("d").longOpt("database").hasArg().argName("DB")
+ .desc("Database (default: default)").build());
+ options.addOption(Option.builder("q").longOpt("query").hasArg().argName("SQL")
+ .desc("Queries to run; without it, the queries are read from stdin").build());
+ options.addOption(Option.builder("s").longOpt("secure").desc("Use HTTPS").build());
+ options.addOption(Option.builder().longOpt("no-secure").desc("Use HTTP (default)").build());
+ // As in clickhouse-client: `-n` is `--multiquery`, `-m` is `--multiline`. The shim always runs every
+ // statement of the input.
+ options.addOption(Option.builder("n").longOpt("multiquery").desc("Ignored").build());
+ options.addOption(Option.builder().longOpt("multi-query").desc("Ignored").build());
+ options.addOption(Option.builder("m").longOpt("multiline").desc("Ignored").build());
+ options.addOption(Option.builder().longOpt("help").desc("Show this help").build());
+ // Accepted and ignored.
+ options.addOption(Option.builder("C").longOpt("config-file").hasArg().argName("FILE").desc("Ignored").build());
+ options.addOption(Option.builder().longOpt("client_logs_file").hasArg().argName("FILE").desc("Ignored").build());
+ options.addOption(Option.builder().longOpt("allow_repeated_settings").desc("Ignored").build());
+ return options;
+ }
+
+ static CliOptions parse(String[] argv) throws ParseException {
+ Options options = baseOptions();
+ Set known = new HashSet<>();
+ for (Option o : options.getOptions()) {
+ if (o.getLongOpt() != null) {
+ known.add(o.getLongOpt());
+ }
+ }
+ // Any other long option is a setting (`--max_threads=1`) or a query parameter (`--param_x=1`), with an
+ // optional value. Unknown short options are ignored, as in the other language ports.
+ List args = new ArrayList<>();
+ for (String arg : argv) {
+ if (arg.startsWith("--") && arg.length() > 2) {
+ int eq = arg.indexOf('=');
+ String name = eq >= 0 ? arg.substring(2, eq) : arg.substring(2);
+ if (!name.isEmpty() && !known.contains(name) && !options.hasLongOption(name)) {
+ options.addOption(Option.builder().longOpt(name).hasArg().optionalArg(true).build());
+ }
+ } else if (isIgnoredShortOption(arg, options)) {
+ continue;
+ }
+ args.add(arg);
+ }
+
+ CommandLine cmd = DefaultParser.builder().setAllowPartialMatching(false).build()
+ .parse(options, args.toArray(new String[0]));
+ CliOptions o = new CliOptions();
+ o.help = cmd.hasOption("help");
+ o.host = cmd.getOptionValue("host", o.host);
+ String port = cmd.getOptionValue("port");
+ if (port != null) {
+ try {
+ o.port = Integer.valueOf(port);
+ } catch (NumberFormatException e) {
+ throw new ParseException("bad --port value \"" + port + "\"");
+ }
+ }
+ o.user = cmd.getOptionValue("user", o.user);
+ o.password = cmd.getOptionValue("password", o.password);
+ o.database = cmd.getOptionValue("database", o.database);
+ o.query = cmd.getOptionValue("query");
+ for (Option opt : cmd.getOptions()) {
+ String name = opt.getLongOpt();
+ if ("secure".equals(name)) {
+ o.secure = true;
+ } else if ("no-secure".equals(name)) {
+ o.secure = false;
+ }
+ if (name == null || known.contains(name)) {
+ continue;
+ }
+ String value = opt.getValue() == null ? "1" : opt.getValue();
+ if (name.startsWith("param_")) {
+ o.params.put(name.substring("param_".length()), value);
+ continue;
+ }
+ String setting = name.replace('-', '_');
+ if (SERVER_SETTINGS.contains(setting)) {
+ o.settings.put(setting, value);
+ }
+ }
+ return o;
+ }
+
+ /** An unknown short option, such as {@code -x}. {@link #parse} drops it before commons-cli reads the arguments. */
+ private static boolean isIgnoredShortOption(String arg, Options options) {
+ return arg.length() > 1 && arg.charAt(0) == '-' && Character.isLetter(arg.charAt(1))
+ && !options.hasShortOption(arg.substring(1, 2));
+ }
+
+ /**
+ * Returns the arguments with the password replaced by {@code ***}, for the invocation log. {@link #parse} takes
+ * the password from {@code --password X} and {@code --password=X}, and, after an unknown option {@code --p}, also
+ * from {@code -password X}, {@code -password=X} and {@code -passwordX}. After {@code --password} or
+ * {@code -password}, each argument is hidden up to and including the next argument that {@link #parse} keeps:
+ * {@link #parse} drops unknown short options, so in {@code --password -x secret} the password is {@code secret}.
+ * All other arguments stay as they are.
+ */
+ static String[] redactPassword(String[] argv) {
+ Options options = baseOptions();
+ String[] out = argv.clone();
+ for (int i = 0; i < argv.length; i++) {
+ String arg = argv[i];
+ boolean doubleDash = arg.startsWith("--");
+ String name = doubleDash ? arg.substring(2) : arg.startsWith("-") ? arg.substring(1) : "";
+ if (name.equals("password")) {
+ for (int j = i + 1; j < argv.length; j++) {
+ out[j] = "***";
+ if (!isIgnoredShortOption(argv[j], options)) {
+ break;
+ }
+ }
+ } else if (name.startsWith("password=")) {
+ out[i] = (doubleDash ? "--" : "-") + "password=***";
+ } else if (!doubleDash && name.startsWith("password")) {
+ out[i] = "-password***";
+ }
+ }
+ return out;
+ }
+
+ static String usage() {
+ StringWriter sw = new StringWriter();
+ HelpFormatter formatter = new HelpFormatter();
+ formatter.setOptionComparator(null);
+ String header = "\nA clickhouse-client imitation that runs queries through clickhouse-java, so that the"
+ + " ClickHouse tests/clickhouse-test runner can drive it. Every \";\"-separated statement runs."
+ + " --SETTING=VALUE: log_comment, max_insert_threads, max_threads, send_logs_level, async_insert"
+ + " and enable_parallel_replicas go to the server, other settings are ignored."
+ + " --param_NAME=VALUE: a query parameter.\n\n";
+ String footer = "\nEnvironment variables:\n"
+ + " CLICKHOUSE_CLIENT_CLI_IMPL client (default, client-v2), jdbc (jdbc-v2) or text (transport only)\n"
+ + " CLICKHOUSE_CLIENT_CLI_LOG Log file for troubleshooting\n";
+ formatter.printHelp(new PrintWriter(sw), 100, "clickhouse-client [options]", header, baseOptions(), 2, 2,
+ footer, true);
+ return sw.toString();
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ClientBackend.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ClientBackend.java
new file mode 100644
index 000000000..0aa439be9
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ClientBackend.java
@@ -0,0 +1,176 @@
+package com.clickhouse.client.cli;
+
+import com.clickhouse.client.api.Client;
+import com.clickhouse.client.api.ClientConfigProperties;
+import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader;
+import com.clickhouse.client.api.metadata.TableSchema;
+import com.clickhouse.client.api.query.QueryResponse;
+import com.clickhouse.client.api.query.QuerySettings;
+import com.clickhouse.data.ClickHouseColumn;
+
+import java.io.ByteArrayOutputStream;
+import java.io.InputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * The {@code client} backend: client-v2 over HTTP.
+ *
+ * Every statement runs with {@link Client#query(String, Map, QuerySettings)} in the default format of the
+ * client ({@code RowBinaryWithNamesAndTypes}). The values come from
+ * {@link ClickHouseBinaryFormatReader#readValue(int)}, and the column types from the {@link TableSchema} of the
+ * reader. The session is the client's {@code session_id}.
+ *
+ *
With {@code text} (transport only), the client sends no format header, so the server writes the text of the
+ * FORMAT clause of the statement (or {@code TabSeparated}), and the shim copies the bytes. That checks only the
+ * transport, not the decoding.
+ */
+final class ClientBackend implements Backend {
+
+ private final Client client;
+ private final Map params;
+ private final boolean text;
+
+ ClientBackend(CliOptions opts, int port, String sessionId, boolean text, InvocationLog log) {
+ String endpoint = (opts.secure ? "https" : "http") + "://" + opts.host + ":" + port;
+ log.add("endpoint", endpoint);
+ this.client = new Client.Builder()
+ .addEndpoint(endpoint)
+ .setUsername(opts.user)
+ .setPassword(opts.password)
+ .setDefaultDatabase(opts.database)
+ .setSessionId(sessionId)
+ .build();
+ this.params = opts.params.isEmpty() ? null : new LinkedHashMap<>(opts.params);
+ this.text = text;
+ }
+
+ @Override
+ public Result execute(String sql, Map settings, String database) throws Exception {
+ QuerySettings qs = new QuerySettings().setDatabase(database);
+ for (Map.Entry e : settings.entrySet()) {
+ qs.serverSetting(e.getKey(), e.getValue());
+ }
+ if (text) {
+ // No X-ClickHouse-Format header: the FORMAT clause of the statement selects the output.
+ qs.setOption(ClientConfigProperties.INPUT_OUTPUT_FORMAT.getKey(), null);
+ }
+ QueryResponse response = Errors.unwrap(() -> client.query(sql, params, qs).get());
+ if (text) {
+ return new TextResult(response);
+ }
+ ClickHouseBinaryFormatReader reader;
+ try {
+ reader = client.newBinaryFormatReader(response);
+ } catch (Exception e) {
+ response.close();
+ throw e;
+ }
+ TableSchema schema = reader.getSchema();
+ if (schema == null) {
+ // No result set (for example an INSERT or a DDL statement).
+ reader.close();
+ response.close();
+ return null;
+ }
+ return new ReaderResult(response, reader, schema);
+ }
+
+ @Override
+ public void close() {
+ client.close();
+ }
+
+ private static final class ReaderResult implements Result {
+ private final QueryResponse response;
+ private final ClickHouseBinaryFormatReader reader;
+ private final List names = new ArrayList<>();
+ private final List types = new ArrayList<>();
+
+ ReaderResult(QueryResponse response, ClickHouseBinaryFormatReader reader, TableSchema schema) {
+ this.response = response;
+ this.reader = reader;
+ for (ClickHouseColumn c : schema.getColumns()) {
+ names.add(c.getColumnName());
+ types.add(c.getOriginalTypeName());
+ }
+ }
+
+ @Override
+ public List names() {
+ return names;
+ }
+
+ @Override
+ public List types() {
+ return types;
+ }
+
+ @Override
+ public boolean next() {
+ return reader.next() != null;
+ }
+
+ @Override
+ public Object get(int i) {
+ return reader.readValue(i + 1);
+ }
+
+ @Override
+ public void close() throws Exception {
+ try {
+ reader.close();
+ } finally {
+ response.close();
+ }
+ }
+ }
+
+ private static final class TextResult implements Result {
+ private final QueryResponse response;
+
+ TextResult(QueryResponse response) {
+ this.response = response;
+ }
+
+ @Override
+ public List names() {
+ return new ArrayList<>();
+ }
+
+ @Override
+ public List types() {
+ return new ArrayList<>();
+ }
+
+ @Override
+ public boolean next() {
+ return false;
+ }
+
+ @Override
+ public Object get(int i) {
+ throw new IllegalStateException("no values in the text backend");
+ }
+
+ @Override
+ public byte[] rawText() throws Exception {
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ try (InputStream in = response.getInputStream()) {
+ byte[] buf = new byte[8192];
+ int n;
+ while ((n = in.read(buf)) != -1) {
+ out.write(buf, 0, n);
+ }
+ }
+ return out.toByteArray();
+ }
+
+ @Override
+ public void close() throws Exception {
+ response.close();
+ }
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ErrorCodes.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ErrorCodes.java
new file mode 100644
index 000000000..c525bfd23
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/ErrorCodes.java
@@ -0,0 +1,61 @@
+package com.clickhouse.client.cli;
+
+import java.io.BufferedReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.UncheckedIOException;
+import java.nio.charset.StandardCharsets;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+/**
+ * The error codes of ClickHouse's {@code src/Common/ErrorCodes.cpp}. Test hints can name an error instead of giving
+ * its code. {@code scripts/gen-error-codes.sh} generates the table ({@code error-codes.tsv}) from the upstream
+ * checkout, so it always matches the tests.
+ */
+final class ErrorCodes {
+
+ private static final Map CODES;
+ private static final Map NAMES;
+
+ static {
+ Map codes = new HashMap<>();
+ Map names = new HashMap<>();
+ try (InputStream in = ErrorCodes.class.getResourceAsStream("error-codes.tsv")) {
+ if (in == null) {
+ throw new IllegalStateException("error-codes.tsv is not on the class path; run scripts/gen-error-codes.sh");
+ }
+ BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
+ String line;
+ while ((line = reader.readLine()) != null) {
+ int tab = line.indexOf('\t');
+ if (line.startsWith("#") || tab < 0) {
+ continue;
+ }
+ int code = Integer.parseInt(line.substring(0, tab));
+ String name = line.substring(tab + 1);
+ codes.put(name, code);
+ names.put(code, name);
+ }
+ } catch (IOException e) {
+ throw new UncheckedIOException(e);
+ }
+ CODES = Collections.unmodifiableMap(codes);
+ NAMES = Collections.unmodifiableMap(names);
+ }
+
+ private ErrorCodes() {
+ }
+
+ /** Returns the code of an error name, or null. */
+ static Integer code(String name) {
+ return CODES.get(name);
+ }
+
+ /** Returns the name of an error code, or null. */
+ static String name(int code) {
+ return NAMES.get(code);
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Errors.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Errors.java
new file mode 100644
index 000000000..1153036d4
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Errors.java
@@ -0,0 +1,116 @@
+package com.clickhouse.client.cli;
+
+import com.clickhouse.client.api.ServerException;
+
+import java.sql.SQLException;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CompletionException;
+import java.util.concurrent.ExecutionException;
+
+/** Error helpers: the server error code of an exception, and the error text that clickhouse-client writes. */
+final class Errors {
+
+ static final int SYNTAX_ERROR = 62;
+
+ private Errors() {
+ }
+
+ /** Runs call and removes the ExecutionException wrapper of a future. */
+ static T unwrap(Callable call) throws Exception {
+ try {
+ return call.call();
+ } catch (ExecutionException | CompletionException e) {
+ Throwable cause = e.getCause();
+ if (cause instanceof Exception) {
+ throw (Exception) cause;
+ }
+ throw e;
+ }
+ }
+
+ /** A result that does not match the test hint of the statement. */
+ static final class HintException extends Exception {
+ final int code;
+
+ HintException(String message, int code) {
+ super(message);
+ this.code = code;
+ }
+ }
+
+ /** Returns the ServerException in the cause chain, or null. */
+ static ServerException serverException(Throwable e) {
+ for (Throwable t = e; t != null; t = t.getCause()) {
+ if (t instanceof ServerException) {
+ return (ServerException) t;
+ }
+ if (t.getCause() == t) {
+ break;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Returns the server error code of an exception: the code of a ServerException in the cause chain, or the
+ * vendor code of a SQLException. Returns null for an error that did not come from the server.
+ */
+ static Integer serverCode(Throwable e) {
+ if (e == null) {
+ return null;
+ }
+ ServerException se = serverException(e);
+ if (se != null) {
+ return se.getCode();
+ }
+ for (Throwable t = e; t != null; t = t.getCause()) {
+ if (t instanceof SQLException && ((SQLException) t).getErrorCode() > 0) {
+ return ((SQLException) t).getErrorCode();
+ }
+ if (t.getCause() == t) {
+ break;
+ }
+ }
+ return null;
+ }
+
+ /**
+ * Writes a server error the way clickhouse-client does, {@code Code: N. DB::Exception: ... (NAME)}, so that the
+ * error name is in the text.
+ */
+ static String formatServerError(Throwable e, int code) {
+ ServerException se = serverException(e);
+ String msg = se != null ? se.getMessage() : e.getMessage();
+ if (msg == null) {
+ msg = e.toString();
+ }
+ msg = msg.trim();
+ String name = ErrorCodes.name(code);
+ if (!msg.startsWith("Code:")) {
+ msg = "Code: " + code + ". DB::Exception: " + msg;
+ }
+ if (name != null && !msg.contains("(" + name + ")")) {
+ msg += " (" + name + ")";
+ }
+ return msg;
+ }
+
+ /** Returns the message of an exception with the messages of its causes. */
+ static String describe(Throwable e) {
+ StringBuilder sb = new StringBuilder();
+ for (Throwable t = e; t != null; t = t.getCause()) {
+ if (sb.length() > 0) {
+ sb.append(": ");
+ }
+ String m = t.getMessage();
+ sb.append(t.getClass().getSimpleName());
+ if (m != null && !m.isEmpty()) {
+ sb.append(" ").append(m);
+ }
+ if (t.getCause() == t) {
+ break;
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/FloatFormat.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/FloatFormat.java
new file mode 100644
index 000000000..b1fd2087a
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/FloatFormat.java
@@ -0,0 +1,141 @@
+package com.clickhouse.client.cli;
+
+import java.math.BigDecimal;
+import java.math.MathContext;
+import java.math.RoundingMode;
+
+/**
+ * Writes floating-point values as ClickHouse does: the shortest text that reads back as the same value, in
+ * positional notation when the decimal exponent is in [-6, 21), else in scientific notation without a {@code +}
+ * sign or exponent padding ({@code 1e21}, {@code 1.5e-7}). This is the same layout as JavaScript's
+ * {@code Number.prototype.toString}.
+ *
+ * {@link Double#toString(double)} is not a substitute: before JDK 19 it sometimes gives more digits than
+ * necessary, and it uses another layout. The digits come from the exact decimal value of the binary value
+ * ({@link BigDecimal}), rounded to the smallest precision that reads back as the same value.
+ */
+final class FloatFormat {
+
+ private FloatFormat() {
+ }
+
+ static String formatDouble(double f) {
+ String special = special(f, Double.isNaN(f), Double.isInfinite(f), f == 0, 1 / f < 0);
+ if (special != null) {
+ return special;
+ }
+ BigDecimal exact = new BigDecimal(Math.abs(f));
+ int hi = significantDigits(Double.toString(Math.abs(f)));
+ BigDecimal shortest = shortest(exact, hi, 17, p -> Double.parseDouble(p.toString()) == Math.abs(f));
+ return layout(f < 0, shortest);
+ }
+
+ static String formatFloat(float f) {
+ String special = special(f, Float.isNaN(f), Float.isInfinite(f), f == 0, 1 / f < 0);
+ if (special != null) {
+ return special;
+ }
+ float abs = Math.abs(f);
+ BigDecimal exact = new BigDecimal(abs);
+ int hi = significantDigits(Float.toString(abs));
+ BigDecimal shortest = shortest(exact, hi, 9, p -> Float.parseFloat(p.toString()) == abs);
+ return layout(f < 0, shortest);
+ }
+
+ private static String special(double f, boolean nan, boolean inf, boolean zero, boolean negZero) {
+ if (nan) {
+ return "nan";
+ }
+ if (inf) {
+ return f > 0 ? "inf" : "-inf";
+ }
+ if (zero) {
+ return negZero ? "-0" : "0";
+ }
+ return null;
+ }
+
+ private interface RoundTrip {
+ boolean test(BigDecimal candidate);
+ }
+
+ /**
+ * Returns the exact value rounded to the smallest precision that reads back as the same value. Rounding to
+ * more digits only comes closer to the value, so the round-trip test is monotonic in the precision.
+ * {@code hint} (the digit count of {@code Double.toString}, which reads back) bounds the search.
+ */
+ private static BigDecimal shortest(BigDecimal exact, int hint, int max, RoundTrip roundTrip) {
+ int hi = Math.max(1, Math.min(hint, max));
+ BigDecimal best = round(exact, hi);
+ if (!roundTrip.test(best)) {
+ hi = max;
+ best = round(exact, hi);
+ }
+ int lo = 1;
+ while (lo < hi) {
+ int mid = (lo + hi) >>> 1;
+ BigDecimal candidate = round(exact, mid);
+ if (roundTrip.test(candidate)) {
+ hi = mid;
+ best = candidate;
+ } else {
+ lo = mid + 1;
+ }
+ }
+ return best;
+ }
+
+ private static BigDecimal round(BigDecimal exact, int precision) {
+ return exact.round(new MathContext(precision, RoundingMode.HALF_EVEN));
+ }
+
+ /** Counts the significant digits of the text of Double.toString or Float.toString. */
+ private static int significantDigits(String s) {
+ int e = s.indexOf('E');
+ String mantissa = e >= 0 ? s.substring(0, e) : s;
+ String digits = mantissa.replace(".", "");
+ int start = 0;
+ while (start < digits.length() - 1 && digits.charAt(start) == '0') {
+ start++;
+ }
+ int end = digits.length();
+ while (end > start + 1 && digits.charAt(end - 1) == '0') {
+ end--;
+ }
+ return end - start;
+ }
+
+ /** Writes the decimal value v (positive) in the layout of JavaScript's Number.prototype.toString. */
+ private static String layout(boolean negative, BigDecimal v) {
+ BigDecimal stripped = v.stripTrailingZeros();
+ String digits = stripped.unscaledValue().toString();
+ // The value is 0.digits x 10^n.
+ int k = digits.length();
+ int n = k - stripped.scale();
+ StringBuilder out = new StringBuilder(k + 8);
+ if (negative) {
+ out.append('-');
+ }
+ if (k <= n && n <= 21) {
+ out.append(digits);
+ for (int i = 0; i < n - k; i++) {
+ out.append('0');
+ }
+ } else if (0 < n && n <= 21) {
+ out.append(digits, 0, n).append('.').append(digits, n, k);
+ } else if (-6 < n && n <= 0) {
+ out.append("0.");
+ for (int i = 0; i < -n; i++) {
+ out.append('0');
+ }
+ out.append(digits);
+ } else {
+ out.append(digits.charAt(0));
+ if (k > 1) {
+ out.append('.').append(digits, 1, k);
+ }
+ out.append('e').append(n - 1);
+ }
+ return out.toString();
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/InvocationLog.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/InvocationLog.java
new file mode 100644
index 000000000..e8acd9afd
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/InvocationLog.java
@@ -0,0 +1,56 @@
+package com.clickhouse.client.cli;
+
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardOpenOption;
+import java.time.Instant;
+
+/**
+ * Collects troubleshooting lines for one invocation and appends them to the file named by
+ * {@code CLICKHOUSE_CLIENT_CLI_LOG}. Without that variable, it does nothing. The lines are written in one write, so
+ * the lines of parallel invocations do not mix.
+ */
+final class InvocationLog {
+ static final String LOG_PATH_ENV = "CLICKHOUSE_CLIENT_CLI_LOG";
+
+ private final Path path;
+ private final StringBuilder lines = new StringBuilder();
+
+ InvocationLog(String path) {
+ this.path = path == null || path.isEmpty() ? null : Paths.get(path);
+ add("=== clickhouse-client invocation", Instant.now().toString());
+ }
+
+ void add(String key, String value) {
+ if (path == null) {
+ return;
+ }
+ lines.append(key).append('=').append(String.valueOf(value).replace("\n", "\\n")).append('\n');
+ }
+
+ /**
+ * Appends the lines to the log file. A log that cannot be written must not change the result of a test, so a
+ * write error is ignored here; the missing lines in the log show it.
+ */
+ void flush() {
+ if (path == null) {
+ return;
+ }
+ try {
+ Path parent = path.toAbsolutePath().getParent();
+ if (parent != null) {
+ Files.createDirectories(parent);
+ }
+ try (FileChannel channel = FileChannel.open(path, StandardOpenOption.CREATE, StandardOpenOption.WRITE,
+ StandardOpenOption.APPEND)) {
+ channel.write(ByteBuffer.wrap(lines.toString().getBytes(StandardCharsets.UTF_8)));
+ }
+ } catch (Exception ignored) {
+ // See the method comment.
+ }
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/JdbcBackend.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/JdbcBackend.java
new file mode 100644
index 000000000..3204482ae
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/JdbcBackend.java
@@ -0,0 +1,130 @@
+package com.clickhouse.client.cli;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.ResultSetMetaData;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+
+/**
+ * The {@code jdbc} backend: jdbc-v2 over HTTP, through {@link DriverManager}.
+ *
+ *
Every statement runs with {@link Statement#execute(String)} on one {@link Statement}. The values come from
+ * {@link ResultSet#getObject(int)}, and the column types from {@link ResultSetMetaData#getColumnTypeName(int)}. The
+ * session is the {@code session_id} server setting of the connection. The driver handles {@code USE} itself.
+ *
+ *
The command-line settings are connection properties ({@code clickhouse_setting_}), so they go with each
+ * request. When the test changes one of them with SET, the backend opens the connection again (with the same
+ * session) without it, so that the session value counts. The query parameters of the command line
+ * ({@code --param_}) go as {@code param_} server settings, which the HTTP interface reads as query
+ * parameters.
+ */
+final class JdbcBackend implements Backend {
+
+ private static final String SETTING_PREFIX = "clickhouse_setting_";
+
+ private final String baseUrl;
+ private final CliOptions opts;
+ private final String sessionId;
+ private final InvocationLog log;
+ private Connection conn;
+ private Statement stmt;
+ private String database;
+
+ JdbcBackend(CliOptions opts, int port, String sessionId, Map settings, InvocationLog log)
+ throws SQLException {
+ this.baseUrl = "jdbc:clickhouse:" + (opts.secure ? "https" : "http") + "://" + opts.host + ":" + port + "/";
+ this.opts = opts;
+ this.sessionId = sessionId;
+ this.log = log;
+ this.database = opts.database;
+ open(settings);
+ }
+
+ private void open(Map settings) throws SQLException {
+ Properties props = new Properties();
+ props.setProperty("user", opts.user);
+ props.setProperty("password", opts.password);
+ props.setProperty(SETTING_PREFIX + "session_id", sessionId);
+ for (Map.Entry e : settings.entrySet()) {
+ props.setProperty(SETTING_PREFIX + e.getKey(), e.getValue());
+ }
+ for (Map.Entry e : opts.params.entrySet()) {
+ props.setProperty(SETTING_PREFIX + "param_" + e.getKey(), e.getValue());
+ }
+ String url = baseUrl + database;
+ log.add("jdbc_url", url);
+ conn = DriverManager.getConnection(url, props);
+ stmt = conn.createStatement();
+ }
+
+ @Override
+ public void settingsChanged(Map settings) throws Exception {
+ close();
+ open(settings);
+ }
+
+ @Override
+ public Result execute(String sql, Map settings, String currentDatabase) throws Exception {
+ // The shim tracks the current database only to open the connection again in it.
+ this.database = currentDatabase;
+ if (!stmt.execute(sql)) {
+ return null;
+ }
+ ResultSet rs = stmt.getResultSet();
+ if (rs == null) {
+ return null;
+ }
+ ResultSetMetaData meta = rs.getMetaData();
+ List names = new ArrayList<>();
+ List types = new ArrayList<>();
+ for (int i = 1; i <= meta.getColumnCount(); i++) {
+ names.add(meta.getColumnLabel(i));
+ types.add(meta.getColumnTypeName(i));
+ }
+ return new Result() {
+ @Override
+ public List names() {
+ return names;
+ }
+
+ @Override
+ public List types() {
+ return types;
+ }
+
+ @Override
+ public boolean next() throws SQLException {
+ return rs.next();
+ }
+
+ @Override
+ public Object get(int i) throws SQLException {
+ return rs.getObject(i + 1);
+ }
+
+ @Override
+ public void close() throws SQLException {
+ rs.close();
+ }
+ };
+ }
+
+ @Override
+ public void close() throws SQLException {
+ try {
+ if (stmt != null) {
+ stmt.close();
+ }
+ } finally {
+ if (conn != null) {
+ conn.close();
+ }
+ }
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Main.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Main.java
index 3c55ddba7..5b1df97b5 100644
--- a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Main.java
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Main.java
@@ -1,710 +1,235 @@
package com.clickhouse.client.cli;
-import com.clickhouse.client.api.Client;
-import com.clickhouse.client.api.query.QueryResponse;
-import com.clickhouse.client.api.query.QuerySettings;
-import com.clickhouse.data.ClickHouseFormat;
-import org.apache.commons.cli.CommandLine;
-import org.apache.commons.cli.CommandLineParser;
-import org.apache.commons.cli.DefaultParser;
-import org.apache.commons.cli.HelpFormatter;
-import org.apache.commons.cli.Option;
-import org.apache.commons.cli.Options;
import org.apache.commons.cli.ParseException;
-import org.apache.commons.csv.CSVFormat;
-import org.apache.commons.csv.CSVPrinter;
-import java.io.BufferedReader;
+import java.io.BufferedOutputStream;
+import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStreamWriter;
+import java.io.OutputStream;
+import java.io.PrintStream;
import java.nio.charset.StandardCharsets;
-import java.nio.ByteBuffer;
-import java.nio.channels.FileChannel;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.StandardOpenOption;
-import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.ResultSet;
-import java.sql.ResultSetMetaData;
-import java.sql.Statement;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.LinkedHashSet;
+import java.security.SecureRandom;
+import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import java.util.LinkedHashMap;
-import java.util.Properties;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
/**
- * Simple CLI tool that mimics clickhouse-client.
- * Executes a SQL query against a ClickHouse server and prints results in TSV format.
+ * A CLI that imitates {@code clickhouse-client} well enough for the ClickHouse core test runner
+ * ({@code tests/clickhouse-test}) to drive it, and runs every query through clickhouse-java. It reads the result
+ * values that the client decoded and writes them as {@code TabSeparated} text, so the upstream {@code .reference}
+ * files check the decoding of the client.
*
- * Supports two backend implementations selected via the {@code CLICKHOUSE_CLIENT_CLI_IMPL}
- * environment variable:
+ *
The backend is selected by the {@code CLICKHOUSE_CLIENT_CLI_IMPL} environment variable:
*
- * - {@code client} (default) – uses the ClickHouse client-v2 API
- * - {@code jdbc} – uses the ClickHouse JDBC driver
+ * - {@code client} (default): client-v2, values from {@code ClickHouseBinaryFormatReader.readValue}
+ * - {@code jdbc}: jdbc-v2, values from {@code ResultSet.getObject}
+ * - {@code text}: client-v2, the server's own text output copied as it is. Transport only: this backend does
+ * not check the decoding of the client.
*
*
- * Usage:
- * java -jar clickhouse-client-cli.jar [options]
- *
- * Options:
- * --host, -h Server host (default: localhost)
- * --port HTTP port (default: 8123)
- * --user, -u Username (default: default)
- * --password Password (default: empty)
- * --database, -d Database (default: default)
- * --query, -q SQL query to execute
- * --log_comment Comment for query_log records
- * --send_logs_level Server log level to send with result
- * --max_insert_threads Max insert threads setting
- * --multiquery Execute multiple ';'-separated queries
- * --multiline, -n (ignored, accepted for compatibility)
- * --help Print usage
- *
- * If --query is not specified, the query is read from stdin.
+ * See {@code README.md} for how to run the upstream SQL tests with it.
*/
-public class Main {
-
- private static final long QUERY_TIMEOUT_SECONDS = 300;
- private static final String LOG_PATH_ENV = "CLICKHOUSE_CLIENT_CLI_LOG";
- private static final String IMPL_ENV = "CLICKHOUSE_CLIENT_CLI_IMPL";
- private static final String IMPL_CLIENT = "client";
- private static final String IMPL_JDBC = "jdbc";
- private static final Path DEFAULT_LOG_PATH = Paths.get("/tmp/clickhouse-client-cli.log");
- private static final Path FALLBACK_LOG_PATH = Paths.get("clickhouse-client-cli.log");
- private static final CSVFormat CLICKHOUSE_TSV_FORMAT = CSVFormat.TDF.builder()
- .setQuote(null)
- .setEscape('\\')
- .setRecordSeparator('\n')
- .setNullString("\\N")
- .build();
- private static final String USAGE_HEADER = System.lineSeparator()
- + "Known server settings are forwarded to ClickHouse."
- + System.lineSeparator()
- + "Client-only and unknown settings are accepted but not sent to server."
- + System.lineSeparator()
- + "If --query is not specified, the query is read from stdin."
- + System.lineSeparator()
- + System.lineSeparator()
- + "Environment variables:"
- + System.lineSeparator()
- + " CLICKHOUSE_CLIENT_CLI_IMPL Backend implementation: 'client' (default) or 'jdbc'"
- + System.lineSeparator()
- + " CLICKHOUSE_CLIENT_CLI_LOG Path to log file for troubleshooting";
- private static final Set CLIENT_ONLY_SETTINGS = createClientOnlySettings();
- private static final Set SERVER_SETTINGS = createServerSettings();
+public final class Main {
- public static void main(String[] args) {
- String host = "localhost";
- int port = 8123;
- String user = "default";
- String password = "";
- String database = "default";
- String logComment = null;
- String sendLogsLevel = null;
- String maxInsertThreads = null;
- String query = null;
- boolean secure = false;
- boolean multiquery = false;
- Map extraServerSettings = new LinkedHashMap<>();
- Path logPath = resolveLogPath();
- Options options = createBaseOptions();
- Set knownLongOptions = collectLongOptionNames(options);
+ static final String IMPL_ENV = "CLICKHOUSE_CLIENT_CLI_IMPL";
- appendLog(logPath, "=== clickhouse-client invocation ===");
- appendLog(logPath, "timestamp=" + new Date());
- appendLog(logPath, "argv=" + String.join(" ", args));
+ private Main() {
+ }
- registerDynamicLongOptions(options, knownLongOptions, args);
+ public static void main(String[] args) {
+ int code = run(args, System.in, System.out, System.err, System::getenv);
+ System.out.flush();
+ System.exit(code);
+ }
- CommandLineParser parser = DefaultParser.builder()
- .setAllowPartialMatching(false)
- .build();
- CommandLine cmd;
+ /** Runs one invocation. env gives the environment variables (the live tests give their own). */
+ static int run(String[] argv, InputStream stdin, OutputStream stdout, PrintStream stderr,
+ Function env) {
+ InvocationLog log = new InvocationLog(env.apply(InvocationLog.LOG_PATH_ENV));
try {
- cmd = parser.parse(options, args);
- } catch (ParseException e) {
- System.err.println("Error: " + e.getMessage());
- printUsage(options);
- System.exit(1);
- return;
- }
-
- if (cmd.hasOption("help")) {
- printUsage(options);
- System.exit(0);
+ return runLogged(argv, stdin, stdout, stderr, env, log);
+ } finally {
+ log.flush();
}
+ }
- host = cmd.getOptionValue("host", host);
- String portValue = cmd.getOptionValue("port");
- if (portValue != null) {
- port = Integer.parseInt(portValue);
+ private static int runLogged(String[] argv, InputStream stdin, OutputStream stdout, PrintStream stderr,
+ Function env, InvocationLog log) {
+ log.add("argv", String.join(" ", CliOptions.redactPassword(argv)));
+ if (argv.length > 0 && argv[0].equals("extract-from-config")) {
+ return extractFromConfig(argv, stdout);
}
- user = cmd.getOptionValue("user", user);
- password = cmd.getOptionValue("password", password);
- database = cmd.getOptionValue("database", database);
- query = cmd.getOptionValue("query", query);
- logComment = firstNonNullOptionValue(cmd, "log_comment", "log-comment");
- sendLogsLevel = firstNonNullOptionValue(cmd, "send_logs_level", "send-logs-level");
- maxInsertThreads = firstNonNullOptionValue(cmd, "max_insert_threads", "max-insert-threads");
- secure = cmd.hasOption("secure");
- multiquery = cmd.hasOption("multiquery") || cmd.hasOption("multi-query");
-
- for (Option option : cmd.getOptions()) {
- String longOpt = option.getLongOpt();
- if (longOpt == null || knownLongOptions.contains(longOpt)) {
- continue;
- }
- String settingName = longOpt.replace('-', '_');
- String settingValue = option.hasArg() ? option.getValue() : null;
- if (settingValue == null) {
- settingValue = "1";
- }
- if (classifySetting(settingName) == SettingScope.SERVER) {
- extraServerSettings.put(settingName, settingValue);
- }
+ CliOptions opts;
+ try {
+ opts = CliOptions.parse(argv);
+ } catch (ParseException e) {
+ stderr.print("Error: " + e.getMessage() + "\n\n" + CliOptions.usage());
+ return 1;
}
-
- if (query == null) {
- query = readStdin();
+ if (opts.help) {
+ write(stdout, CliOptions.usage());
+ return 0;
}
-
- if (query == null || query.isBlank()) {
- System.err.println("No query provided. Use --query or pipe SQL via stdin.");
- System.exit(1);
+ String impl = env.apply(IMPL_ENV);
+ if (impl == null || impl.isEmpty()) {
+ impl = "client";
}
- List queries = multiquery ? splitQueries(query) : List.of(query);
- if (queries.isEmpty()) {
- System.err.println("No query provided. Use --query or pipe SQL via stdin.");
- System.exit(1);
+ if (!impl.equals("client") && !impl.equals("jdbc") && !impl.equals("text")) {
+ stderr.println("Error: unknown " + IMPL_ENV + " \"" + impl + "\": use client, jdbc or text");
+ return 1;
}
+ log.add("impl", impl);
- String impl = System.getenv(IMPL_ENV);
- if (impl == null || impl.isBlank()) {
- impl = IMPL_CLIENT;
+ String text = opts.query;
+ if (text == null) {
+ try {
+ text = new String(readAll(stdin), StandardCharsets.UTF_8);
+ } catch (IOException e) {
+ stderr.println("Error: read stdin: " + e.getMessage());
+ return 1;
+ }
}
-
- appendLog(logPath, "impl=" + impl);
- appendLog(logPath, "database=" + database + ", user=" + user + ", secure=" + secure + ", multiquery=" + multiquery);
- appendLog(logPath, "log_comment=" + safeForLog(logComment));
- appendLog(logPath, "send_logs_level=" + safeForLog(sendLogsLevel));
- appendLog(logPath, "max_insert_threads=" + safeForLog(maxInsertThreads));
- appendLog(logPath, "server_settings=" + extraServerSettings);
- appendLog(logPath, "queries_count=" + queries.size());
- for (int qi = 0; qi < queries.size(); qi++) {
- appendLog(logPath, "query[" + qi + "]=" + queries.get(qi));
+ if (text.trim().isEmpty()) {
+ stderr.println("Error: no query. Use --query or write the queries to stdin.");
+ return 1;
+ }
+ List statements = StatementSplitter.split(text);
+ log.add("statements", String.valueOf(statements.size()));
+ if (statements.isEmpty()) {
+ return 0;
}
+ String sessionId = newSessionId();
+ log.add("session_id", sessionId);
+ int port = httpPort(opts.port, opts.secure, env);
+ Map settings = new LinkedHashMap<>(opts.settings);
+ OutputStream out = new BufferedOutputStream(stdout, 1 << 16);
+ Exception error = null;
+ Backend backend = null;
try {
- switch (impl) {
- case IMPL_CLIENT:
- executeWithClient(host, port, user, password, database, secure,
- logComment, sendLogsLevel, maxInsertThreads,
- extraServerSettings, queries, logPath);
- break;
- case IMPL_JDBC:
- executeWithJdbc(host, port, user, password, database, secure,
- logComment, sendLogsLevel, maxInsertThreads,
- extraServerSettings, queries, logPath);
- break;
- default:
- System.err.println("Unknown " + IMPL_ENV + " value: " + impl
- + ". Supported: " + IMPL_CLIENT + ", " + IMPL_JDBC);
- System.exit(1);
- }
+ backend = impl.equals("jdbc")
+ ? new JdbcBackend(opts, port, sessionId, settings, log)
+ : new ClientBackend(opts, port, sessionId, impl.equals("text"), log);
+ new Runner(backend, opts, settings, out, log).run(statements);
} catch (Exception e) {
- appendLog(logPath, "error=" + e.getMessage());
- System.err.println("Error: " + e.getMessage());
- System.exit(1);
- }
- }
-
- private static void executeWithClient(String host, int port, String user, String password,
- String database, boolean secure,
- String logComment, String sendLogsLevel, String maxInsertThreads,
- Map extraServerSettings,
- List queries, Path logPath) throws Exception {
- String endpoint = (secure ? "https://" : "http://") + host + ":" + port;
- appendLog(logPath, "endpoint=" + endpoint);
-
- try (Client client = new Client.Builder()
- .addEndpoint(endpoint)
- .setUsername(user)
- .setPassword(password)
- .setDefaultDatabase(database)
- .build()) {
-
- QuerySettings settings = new QuerySettings()
- .setFormat(ClickHouseFormat.TabSeparated);
- if (logComment != null && !logComment.isBlank()) {
- settings.logComment(logComment);
- }
- if (sendLogsLevel != null && !sendLogsLevel.isBlank()) {
- settings.serverSetting("send_logs_level", sendLogsLevel);
- }
- if (maxInsertThreads != null && !maxInsertThreads.isBlank()) {
- settings.serverSetting("max_insert_threads", maxInsertThreads);
- }
- for (Map.Entry entry : extraServerSettings.entrySet()) {
- if (entry.getValue() != null && !entry.getValue().isBlank()) {
- settings.serverSetting(entry.getKey(), entry.getValue());
- }
- }
-
- for (String q : queries) {
- appendLog(logPath, "executing_query=" + q);
- try (QueryResponse response = client.query(q, settings)
- .get(QUERY_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
- try (InputStream is = response.getInputStream()) {
- byte[] buf = new byte[8192];
- int n;
- while ((n = is.read(buf)) != -1) {
- System.out.write(buf, 0, n);
- }
- System.out.flush();
- }
- }
- }
+ error = e;
}
- }
-
- private static void executeWithJdbc(String host, int port, String user, String password,
- String database, boolean secure,
- String logComment, String sendLogsLevel, String maxInsertThreads,
- Map extraServerSettings,
- List queries, Path logPath) throws Exception {
- String protocol = secure ? "https" : "http";
- String jdbcUrl = "jdbc:clickhouse:" + protocol + "://" + host + ":" + port + "/" + database;
- appendLog(logPath, "jdbc_url=" + jdbcUrl);
-
- Properties props = new Properties();
- props.setProperty("user", user);
- props.setProperty("password", password);
-
- addServerSetting(props, "log_comment", logComment);
- addServerSetting(props, "send_logs_level", sendLogsLevel);
- addServerSetting(props, "max_insert_threads", maxInsertThreads);
- for (Map.Entry entry : extraServerSettings.entrySet()) {
- addServerSetting(props, entry.getKey(), entry.getValue());
+ try {
+ out.flush();
+ } catch (IOException e) {
+ error = error == null ? e : error;
}
-
- try (Connection conn = DriverManager.getConnection(jdbcUrl, props);
- Statement stmt = conn.createStatement()) {
-
- for (String q : queries) {
- appendLog(logPath, "executing_query=" + q);
- boolean hasResultSet = stmt.execute(q);
- if (hasResultSet) {
- try (ResultSet rs = stmt.getResultSet()) {
- writeResultSetAsTsv(rs);
- }
- }
+ if (backend != null) {
+ try {
+ backend.close();
+ } catch (Exception e) {
+ error = error == null ? e : error;
}
}
- }
-
- private static void addServerSetting(Properties props, String name, String value) {
- if (value != null && !value.isBlank()) {
- props.setProperty("clickhouse_setting_" + name, value);
+ if (error != null) {
+ log.add("error", Errors.describe(error));
+ return reportError(stderr, error);
}
+ return 0;
}
- private static void writeResultSetAsTsv(ResultSet rs) throws Exception {
- ResultSetMetaData meta = rs.getMetaData();
- int columnCount = meta.getColumnCount();
- CSVPrinter printer = new CSVPrinter(new OutputStreamWriter(System.out, StandardCharsets.UTF_8), CLICKHOUSE_TSV_FORMAT);
- while (rs.next()) {
- for (int i = 1; i <= columnCount; i++) {
- printer.print(rs.getString(i));
+ /**
+ * Writes the error to stderr and returns the exit code. As in clickhouse-client, the exit code is the error
+ * code modulo 256 when it is a server error.
+ */
+ static int reportError(PrintStream stderr, Throwable e) {
+ int code = 0;
+ if (e instanceof Errors.HintException) {
+ stderr.println("Error: " + e.getMessage());
+ code = ((Errors.HintException) e).code;
+ } else {
+ Integer serverCode = Errors.serverCode(e);
+ if (serverCode != null) {
+ stderr.println("Received exception from server:\n" + Errors.formatServerError(e, serverCode));
+ code = serverCode;
+ } else {
+ stderr.println("Error: " + Errors.describe(e));
}
- printer.println();
}
- printer.flush();
+ stderr.flush();
+ return code % 256 != 0 ? code % 256 : 1;
}
- private static Options createBaseOptions() {
- Options options = new Options();
- options.addOption(Option.builder("h").longOpt("host").hasArg().argName("HOST")
- .desc("Server host (default: localhost)").build());
- options.addOption(Option.builder().longOpt("port").hasArg().argName("PORT")
- .desc("HTTP port (default: 8123)").build());
- options.addOption(Option.builder("u").longOpt("user").hasArg().argName("USER")
- .desc("Username (default: default)").build());
- options.addOption(Option.builder().longOpt("password").hasArg().argName("PASSWORD")
- .desc("Password (default: empty)").build());
- options.addOption(Option.builder("d").longOpt("database").hasArg().argName("DB")
- .desc("Database (default: default)").build());
- options.addOption(Option.builder("q").longOpt("query").hasArg().argName("SQL")
- .desc("SQL query to execute").build());
- options.addOption(Option.builder().longOpt("log_comment").hasArg().argName("VALUE")
- .desc("Comment for query_log records").build());
- options.addOption(Option.builder().longOpt("log-comment").hasArg().argName("VALUE").build());
- options.addOption(Option.builder().longOpt("send_logs_level").hasArg().argName("VALUE")
- .desc("Server log level to send with result").build());
- options.addOption(Option.builder().longOpt("send-logs-level").hasArg().argName("VALUE").build());
- options.addOption(Option.builder().longOpt("max_insert_threads").hasArg().argName("VALUE")
- .desc("Max insert threads setting").build());
- options.addOption(Option.builder().longOpt("max-insert-threads").hasArg().argName("VALUE").build());
- options.addOption(Option.builder("s").longOpt("secure")
- .desc("Use HTTPS").build());
- options.addOption(Option.builder("n").longOpt("multiline")
- .desc("(ignored, accepted for compatibility)").build());
- options.addOption(Option.builder().longOpt("multiquery")
- .desc("Execute multiple ';'-separated queries").build());
- options.addOption(Option.builder().longOpt("multi-query").build());
- options.addOption(Option.builder().longOpt("help")
- .desc("Print this help").build());
- return options;
- }
-
- private static Set collectLongOptionNames(Options options) {
- Set names = new HashSet<>();
- for (Option option : options.getOptions()) {
- if (option.getLongOpt() != null) {
- names.add(option.getLongOpt());
- }
- }
- return names;
- }
-
- private static void registerDynamicLongOptions(Options options, Set knownLongOptions, String[] args) {
- Set added = new LinkedHashSet<>();
- for (String arg : args) {
- if (arg == null || !arg.startsWith("--") || "--".equals(arg)) {
- continue;
- }
- int eq = arg.indexOf('=');
- String longOpt = eq >= 0 ? arg.substring(2, eq) : arg.substring(2);
- if (longOpt.isBlank() || knownLongOptions.contains(longOpt) || added.contains(longOpt)) {
- continue;
- }
- options.addOption(Option.builder()
- .longOpt(longOpt)
- .hasArg()
- .optionalArg(true)
- .argName("VALUE")
- .build());
- added.add(longOpt);
+ /**
+ * Maps the port that {@code tests/clickhouse-test} gives (the native TCP port, from CLICKHOUSE_PORT_TCP) to the
+ * HTTP port that the runner exports. Any other port is used as given.
+ */
+ static int httpPort(Integer port, boolean secure, Function env) {
+ String nativeEnv = secure ? "CLICKHOUSE_PORT_TCP_SECURE" : "CLICKHOUSE_PORT_TCP";
+ String httpEnv = secure ? "CLICKHOUSE_PORT_HTTPS" : "CLICKHOUSE_PORT_HTTP";
+ int nativeDefault = secure ? 9440 : 9000;
+ int httpDefault = secure ? 8443 : 8123;
+ int nativePort = envInt(env.apply(nativeEnv), nativeDefault);
+ if (port != null && port != 0 && port != nativePort) {
+ return port;
}
+ return envInt(env.apply(httpEnv), httpDefault);
}
- private static String firstNonNullOptionValue(CommandLine cmd, String... optionNames) {
- for (String optionName : optionNames) {
- String value = cmd.getOptionValue(optionName);
- if (value != null) {
- return value;
- }
+ private static int envInt(String v, int def) {
+ if (v == null) {
+ return def;
}
- return null;
- }
-
- private static Path resolveLogPath() {
- String fromEnv = System.getenv(LOG_PATH_ENV);
- if (fromEnv != null && !fromEnv.isBlank()) {
- return Paths.get(fromEnv);
+ try {
+ return Integer.parseInt(v.trim());
+ } catch (NumberFormatException e) {
+ return def;
}
- return DEFAULT_LOG_PATH;
}
- private static void appendLog(Path path, String line) {
- String payload = line + System.lineSeparator();
- if (appendLogInternal(path, payload)) {
- return;
- }
- if (!FALLBACK_LOG_PATH.equals(path)) {
- appendLogInternal(FALLBACK_LOG_PATH, payload);
+ private static String newSessionId() {
+ byte[] b = new byte[16];
+ new SecureRandom().nextBytes(b);
+ StringBuilder sb = new StringBuilder("clickhouse-java-cli-");
+ for (byte x : b) {
+ sb.append(String.format("%02x", x));
}
+ return sb.toString();
}
- private static boolean appendLogInternal(Path path, String payload) {
- try {
- Path parent = path.getParent();
- if (parent != null) {
- Files.createDirectories(parent);
- }
- byte[] bytes = payload.getBytes(StandardCharsets.UTF_8);
- try (FileChannel channel = FileChannel.open(path,
- StandardOpenOption.CREATE,
- StandardOpenOption.WRITE,
- StandardOpenOption.APPEND)) {
- channel.write(ByteBuffer.wrap(bytes));
- channel.force(true);
+ /**
+ * Answers {@code clickhouse extract-from-config --key }, which {@code tests/clickhouse-test} runs to read
+ * the server config. Only {@code listen_host} has an answer; for other keys the output is empty, as for a key
+ * that is not in the config. ({@code bin/clickhouse} answers it without a JVM; this is for direct use.)
+ */
+ static int extractFromConfig(String[] argv, OutputStream stdout) {
+ String key = null;
+ for (int i = 1; i < argv.length; i++) {
+ if (argv[i].equals("--key") && i + 1 < argv.length) {
+ key = argv[++i];
+ } else if (argv[i].startsWith("--key=")) {
+ key = argv[i].substring("--key=".length());
}
- return true;
- } catch (Exception ignored) {
- // Logging must never break CLI behavior in tests.
- return false;
}
+ if ("listen_host".equals(key)) {
+ write(stdout, "127.0.0.1\n");
+ }
+ return 0;
}
- private static String safeForLog(String value) {
- return value == null ? "" : value;
- }
-
- private static String readStdin() {
+ private static void write(OutputStream out, String s) {
try {
- StringBuilder sb = new StringBuilder();
- try (BufferedReader reader = new BufferedReader(new InputStreamReader(System.in))) {
- String line;
- while ((line = reader.readLine()) != null) {
- if (sb.length() > 0) {
- sb.append('\n');
- }
- sb.append(line);
- }
- }
- return sb.isEmpty() ? null : sb.toString();
+ out.write(s.getBytes(StandardCharsets.UTF_8));
+ out.flush();
} catch (IOException e) {
- return null;
- }
- }
-
- private static List splitQueries(String sql) {
- List queries = new ArrayList<>();
- StringBuilder current = new StringBuilder();
-
- boolean inSingleQuote = false;
- boolean inDoubleQuote = false;
- boolean inBacktick = false;
- boolean escaping = false;
-
- for (int i = 0; i < sql.length(); i++) {
- char ch = sql.charAt(i);
-
- if (escaping) {
- current.append(ch);
- escaping = false;
- continue;
- }
-
- if ((inSingleQuote || inDoubleQuote) && ch == '\\') {
- current.append(ch);
- escaping = true;
- continue;
- }
-
- if (!inDoubleQuote && !inBacktick && ch == '\'') {
- inSingleQuote = !inSingleQuote;
- current.append(ch);
- continue;
- }
- if (!inSingleQuote && !inBacktick && ch == '"') {
- inDoubleQuote = !inDoubleQuote;
- current.append(ch);
- continue;
- }
- if (!inSingleQuote && !inDoubleQuote && ch == '`') {
- inBacktick = !inBacktick;
- current.append(ch);
- continue;
- }
-
- if (!inSingleQuote && !inDoubleQuote && !inBacktick && ch == ';') {
- String statement = current.toString().trim();
- if (!statement.isEmpty()) {
- queries.add(statement);
- }
- current.setLength(0);
- continue;
- }
-
- current.append(ch);
+ // Nothing to do: stdout is gone.
}
-
- String trailing = current.toString().trim();
- if (!trailing.isEmpty()) {
- queries.add(trailing);
- }
-
- return queries;
- }
-
- private static void printUsage(Options options) {
- HelpFormatter formatter = new HelpFormatter();
- formatter.setOptionComparator(null);
- formatter.printHelp("clickhouse-client [options]", USAGE_HEADER, options, "", true);
}
- private static SettingScope classifySetting(String settingName) {
- if (SERVER_SETTINGS.contains(settingName)) {
- return SettingScope.SERVER;
- }
- if (CLIENT_ONLY_SETTINGS.contains(settingName)) {
- return SettingScope.CLIENT_ONLY;
+ private static byte[] readAll(InputStream in) throws IOException {
+ ByteArrayOutputStream buf = new ByteArrayOutputStream();
+ byte[] b = new byte[8192];
+ int n;
+ while ((n = in.read(b)) != -1) {
+ buf.write(b, 0, n);
}
- return SettingScope.UNKNOWN;
- }
-
- private enum SettingScope {
- SERVER,
- CLIENT_ONLY,
- UNKNOWN
- }
-
- private static Set createServerSettings() {
- Set settings = new HashSet<>();
- Collections.addAll(settings,
- "max_insert_threads",
- "send_logs_level");
- return Collections.unmodifiableSet(settings);
- }
-
- private static Set createClientOnlySettings() {
- Set settings = new HashSet<>();
- Collections.addAll(settings,
- "group_by_two_level_threshold",
- "group_by_two_level_threshold_bytes",
- "distributed_aggregation_memory_efficient",
- "fsync_metadata",
- "output_format_parallel_formatting",
- "input_format_parallel_parsing",
- "min_chunk_bytes_for_parallel_parsing",
- "max_read_buffer_size",
- "prefer_localhost_replica",
- "max_block_size",
- "max_joined_block_size_rows",
- "joined_block_split_single_row",
- "join_output_by_rowlist_perkey_rows_threshold",
- "max_threads",
- "optimize_append_index",
- "use_hedged_requests",
- "optimize_if_chain_to_multiif",
- "optimize_if_transform_strings_to_enum",
- "optimize_read_in_order",
- "optimize_or_like_chain",
- "optimize_substitute_columns",
- "enable_multiple_prewhere_read_steps",
- "read_in_order_two_level_merge_threshold",
- "optimize_aggregation_in_order",
- "aggregation_in_order_max_block_bytes",
- "use_uncompressed_cache",
- "min_bytes_to_use_direct_io",
- "min_bytes_to_use_mmap_io",
- "local_filesystem_read_method",
- "remote_filesystem_read_method",
- "local_filesystem_read_prefetch",
- "filesystem_cache_segments_batch_size",
- "read_from_filesystem_cache_if_exists_otherwise_bypass_cache",
- "throw_on_error_from_cache_on_write_operations",
- "remote_filesystem_read_prefetch",
- "distributed_cache_discard_connection_if_unread_data",
- "distributed_cache_use_clients_cache_for_write",
- "distributed_cache_use_clients_cache_for_read",
- "allow_prefetched_read_pool_for_remote_filesystem",
- "filesystem_prefetch_max_memory_usage",
- "filesystem_prefetches_limit",
- "filesystem_prefetch_min_bytes_for_single_read_task",
- "filesystem_prefetch_step_marks",
- "filesystem_prefetch_step_bytes",
- "enable_filesystem_cache",
- "enable_filesystem_cache_on_write_operations",
- "compile_expressions",
- "compile_aggregate_expressions",
- "compile_sort_description",
- "merge_tree_coarse_index_granularity",
- "optimize_distinct_in_order",
- "max_bytes_before_remerge_sort",
- "min_compress_block_size",
- "max_compress_block_size",
- "merge_tree_compact_parts_min_granules_to_multibuffer_read",
- "optimize_sorting_by_input_stream_properties",
- "http_response_buffer_size",
- "http_wait_end_of_query",
- "enable_memory_bound_merging_of_aggregation_results",
- "min_count_to_compile_expression",
- "min_count_to_compile_aggregate_expression",
- "min_count_to_compile_sort_description",
- "session_timezone",
- "use_page_cache_for_disks_without_file_cache",
- "use_page_cache_for_local_disks",
- "use_page_cache_for_object_storage",
- "page_cache_inject_eviction",
- "merge_tree_read_split_ranges_into_intersecting_and_non_intersecting_injection_probability",
- "prefer_external_sort_block_bytes",
- "cross_join_min_rows_to_compress",
- "cross_join_min_bytes_to_compress",
- "min_external_table_block_size_bytes",
- "max_parsing_threads",
- "optimize_functions_to_subcolumns",
- "parallel_replicas_local_plan",
- "query_plan_join_swap_table",
- "enable_vertical_final",
- "optimize_extract_common_expressions",
- "optimize_syntax_fuse_functions",
- "use_async_executor_for_materialized_views",
- "use_query_condition_cache",
- "secondary_indices_enable_bulk_filtering",
- "use_skip_indexes_if_final",
- "use_skip_indexes_on_data_read",
- "optimize_rewrite_like_perfect_affix",
- "input_format_parquet_use_native_reader_v3",
- "enable_lazy_columns_replication",
- "allow_special_serialization_kinds_in_output_formats",
- "short_circuit_function_evaluation_for_nulls_threshold",
- "automatic_parallel_replicas_mode",
- "temporary_files_buffer_size",
- "query_plan_optimize_join_order_algorithm",
- "max_bytes_before_external_sort",
- "max_bytes_before_external_group_by",
- "max_bytes_ratio_before_external_sort",
- "max_bytes_ratio_before_external_group_by",
- "allow_repeated_settings",
- "use_skip_indexes_if_final_exact_mode",
- "ratio_of_defaults_for_sparse_serialization",
- "prefer_fetch_merged_part_size_threshold",
- "vertical_merge_algorithm_min_rows_to_activate",
- "vertical_merge_algorithm_min_columns_to_activate",
- "allow_vertical_merges_from_compact_to_wide_parts",
- "min_merge_bytes_to_use_direct_io",
- "index_granularity_bytes",
- "merge_max_block_size",
- "index_granularity",
- "min_bytes_for_wide_part",
- "compress_marks",
- "compress_primary_key",
- "marks_compress_block_size",
- "primary_key_compress_block_size",
- "replace_long_file_name_to_hash",
- "max_file_name_length",
- "min_bytes_for_full_part_storage",
- "compact_parts_max_bytes_to_buffer",
- "compact_parts_max_granules_to_buffer",
- "compact_parts_merge_max_bytes_to_prefetch_part",
- "cache_populated_by_fetch",
- "concurrent_part_removal_threshold",
- "old_parts_lifetime",
- "prewarm_mark_cache",
- "use_const_adaptive_granularity",
- "enable_index_granularity_compression",
- "enable_block_number_column",
- "enable_block_offset_column",
- "use_primary_key_cache",
- "prewarm_primary_key_cache",
- "object_serialization_version",
- "object_shared_data_serialization_version",
- "object_shared_data_serialization_version_for_zero_level_parts",
- "object_shared_data_buckets_for_compact_part",
- "object_shared_data_buckets_for_wide_part",
- "dynamic_serialization_version",
- "auto_statistics_types",
- "serialization_info_version",
- "string_serialization_version",
- "nullable_serialization_version",
- "enable_shared_storage_snapshot_in_query",
- "min_columns_to_activate_adaptive_write_buffer",
- "reduce_blocking_parts_sleep_ms",
- "shared_merge_tree_outdated_parts_group_size",
- "shared_merge_tree_max_outdated_parts_to_process_at_once");
- return Collections.unmodifiableSet(settings);
+ return buf.toByteArray();
}
}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/OutputFormat.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/OutputFormat.java
new file mode 100644
index 000000000..597900f9f
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/OutputFormat.java
@@ -0,0 +1,156 @@
+package com.clickhouse.client.cli;
+
+import java.util.Locale;
+
+/**
+ * How the shim writes a result set. The Java client reads every result in a binary format (the server prefers the
+ * {@code X-ClickHouse-Format} request header to a FORMAT clause), and the shim writes the values itself, so it
+ * supports only the {@code TabSeparated} family and {@code Null}.
+ */
+final class OutputFormat {
+ static final OutputFormat DEFAULT = new OutputFormat("TabSeparated", false, false, false, false, true);
+
+ final String name;
+ /** A header line with the column names. */
+ final boolean names;
+ /** A header line with the column types. */
+ final boolean types;
+ /** Top-level strings and the header lines are not escaped. */
+ final boolean raw;
+ /** The {@code Null} format: the values are read, but not written. */
+ final boolean discard;
+ final boolean supported;
+
+ private OutputFormat(String name, boolean names, boolean types, boolean raw, boolean discard, boolean supported) {
+ this.name = name;
+ this.names = names;
+ this.types = types;
+ this.raw = raw;
+ this.discard = discard;
+ this.supported = supported;
+ }
+
+ /** Returns the output format of a statement: its top-level FORMAT clause, else TabSeparated. */
+ static OutputFormat of(String sql) {
+ String name = findFormatName(sql);
+ if (name == null) {
+ return DEFAULT;
+ }
+ // Format names are case-insensitive.
+ switch (name.toLowerCase(Locale.ROOT)) {
+ case "tabseparated":
+ case "tsv":
+ return new OutputFormat(name, false, false, false, false, true);
+ case "tabseparatedwithnames":
+ case "tsvwithnames":
+ return new OutputFormat(name, true, false, false, false, true);
+ case "tabseparatedwithnamesandtypes":
+ case "tsvwithnamesandtypes":
+ return new OutputFormat(name, true, true, false, false, true);
+ case "tabseparatedraw":
+ case "tsvraw":
+ case "raw":
+ return new OutputFormat(name, false, false, true, false, true);
+ case "tabseparatedrawwithnames":
+ case "tsvrawwithnames":
+ case "rawwithnames":
+ return new OutputFormat(name, true, false, true, false, true);
+ case "tabseparatedrawwithnamesandtypes":
+ case "tsvrawwithnamesandtypes":
+ case "rawwithnamesandtypes":
+ return new OutputFormat(name, true, true, true, false, true);
+ case "null":
+ return new OutputFormat(name, false, false, false, true, true);
+ default:
+ return new OutputFormat(name, false, false, false, false, false);
+ }
+ }
+
+ /** Returns the name of the top-level {@code FORMAT } clause of sql, or null. */
+ static String findFormatName(String sql) {
+ int depth = 0;
+ int i = 0;
+ while (i < sql.length()) {
+ char c = sql.charAt(i);
+ if (c == '\'' || c == '"' || c == '`') {
+ i = SqlText.skipQuoted(sql, i);
+ } else if (SqlText.lineCommentAt(sql, i)) {
+ i = SqlText.skipLineComment(sql, i);
+ } else if (sql.startsWith("/*", i)) {
+ i = SqlText.skipBlockComment(sql, i);
+ } else if (c == '$') {
+ int e = SqlText.heredocEnd(sql, i);
+ i = e > 0 ? e : i + 1;
+ } else if (c == '(' || c == '[') {
+ depth++;
+ i++;
+ } else if (c == ')' || c == ']') {
+ depth--;
+ i++;
+ } else if (SqlText.isWordChar(c)) {
+ int j = i;
+ while (j < sql.length() && SqlText.isWordChar(sql.charAt(j))) {
+ j++;
+ }
+ if (depth == 0 && j - i == 6 && sql.regionMatches(true, i, "FORMAT", 0, 6)
+ && (i == 0 || sql.charAt(i - 1) != '.')) {
+ // `ORDER BY format DESC` ends the query too: a clause keyword after FORMAT shows an identifier
+ // named `format`.
+ int[] end = new int[1];
+ String name = formatName(sql, j, end);
+ if (name != null && !SqlText.isClauseKeyword(name) && endsQuery(sql, end[0])) {
+ return name;
+ }
+ }
+ i = j;
+ } else {
+ i++;
+ }
+ }
+ return null;
+ }
+
+ /** Reads the format name after the FORMAT keyword that ends at j; sets end[0] to the end of the name. */
+ private static String formatName(String sql, int j, int[] end) {
+ int k = SqlText.skipWhitespaceAndComments(sql, j);
+ if (k == j || k >= sql.length()) {
+ return null;
+ }
+ if (sql.charAt(k) == '`' || sql.charAt(k) == '"') {
+ // A quoted format name: FORMAT `Null`.
+ int m = SqlText.skipQuoted(sql, k);
+ end[0] = m;
+ return SqlText.unquoteIdentifier(sql.substring(k, m));
+ }
+ int m = k;
+ while (m < sql.length() && SqlText.isWordChar(sql.charAt(m))) {
+ m++;
+ }
+ if (m == k) {
+ return null;
+ }
+ end[0] = m;
+ return sql.substring(k, m);
+ }
+
+ /**
+ * Tells if the text from i on can follow the FORMAT clause of a query: nothing, a semicolon, or a SETTINGS
+ * clause. Otherwise FORMAT is an identifier, as in {@code SELECT format FROM t}.
+ */
+ private static boolean endsQuery(String sql, int i) {
+ int k = SqlText.skipWhitespaceAndComments(sql, i);
+ if (k >= sql.length() || sql.charAt(k) == ';') {
+ return true;
+ }
+ int m = k;
+ while (m < sql.length() && SqlText.isWordChar(sql.charAt(m))) {
+ m++;
+ }
+ return sql.substring(k, m).equalsIgnoreCase("SETTINGS");
+ }
+
+ @Override
+ public String toString() {
+ return name;
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Runner.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Runner.java
new file mode 100644
index 000000000..05e7cd535
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Runner.java
@@ -0,0 +1,321 @@
+package com.clickhouse.client.cli;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * Runs the statements of one shim invocation on one session, as {@code clickhouse-client} does.
+ *
+ * Session state ({@code SET}, {@code USE}, temporary tables) must survive from one statement to the next. Both
+ * backends use HTTP with one {@code session_id}; the server keeps the session after an error.
+ *
+ *
The shim sends nothing that {@code clickhouse-client} does not send, because some tests read their own queries
+ * from {@code system.query_log}.
+ */
+final class Runner {
+
+ private final Backend backend;
+ private final OutputStream out;
+ private final InvocationLog log;
+ private final Map params;
+
+ /** The current database of the session. */
+ private String database;
+ /**
+ * The command-line settings that go with each query, as clickhouse-client sends them. A SET of the same
+ * setting in the test removes it from here, because the session then holds the value.
+ */
+ private final Map settings;
+ /** The value of the last {@code SET dialect}. */
+ private String dialect;
+ /** The session value of {@code ignore_format_null_for_explain} (default on). */
+ private boolean ignoreFormatNullForExplain = true;
+ /** The output of the current statement, until the runner knows whether it echoes the statement first. */
+ private final TsvOutput result = new TsvOutput();
+
+ Runner(Backend backend, CliOptions opts, Map settings, OutputStream out, InvocationLog log) {
+ this.backend = backend;
+ this.out = out;
+ this.log = log;
+ this.params = opts.params;
+ this.database = opts.database;
+ this.settings = settings;
+ }
+
+ /** Runs the statements in order. Stops at the first statement whose result does not match its hint. */
+ void run(List statements) throws Exception {
+ for (Statement st : statements) {
+ runOne(st);
+ }
+ }
+
+ private void runOne(Statement st) throws Exception {
+ if (st.hint.parseError != null) {
+ echo(st);
+ out.flush();
+ throw new Errors.HintException(st.hint.parseError, 0);
+ }
+ log.add("query", st.sql);
+ result.reset();
+ Exception err = null;
+ try {
+ execute(st.sql);
+ } catch (Exception e) {
+ err = e;
+ }
+ Integer code = Errors.serverCode(err);
+ // clickhouse-client parses a statement before it echoes it, so it does not echo a statement with a syntax
+ // error.
+ if (code == null || code != Errors.SYNTAX_ERROR) {
+ echo(st);
+ }
+ result.writeTo(out);
+ out.flush();
+
+ if (st.hint.expectsError() && err == null) {
+ throw new Errors.HintException("expected " + st.hint.label() + ", but the query succeeded (query: "
+ + st.full + ")", 0);
+ }
+ if (st.hint.expectsError() && code != null) {
+ if (!st.hint.matches(code)) {
+ throw new Errors.HintException("expected " + st.hint.label() + ", but got "
+ + Errors.formatServerError(err, code) + " (query: " + st.full + ")", code);
+ }
+ log.add("expected_error_matched", st.hint.label());
+ return;
+ }
+ if (err != null) {
+ throw err;
+ }
+ afterSuccess(st.sql);
+ }
+
+ /** Writes the statement for the {@code echo} test hints. */
+ private void echo(Statement st) throws IOException {
+ if (st.echo) {
+ out.write((st.full + "\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
+ }
+ }
+
+ private void execute(String sql) throws Exception {
+ boolean other = otherDialect(sql);
+ String query = sql;
+ if (other) {
+ // Over HTTP the server parses the request body as one query, and the parsers of other dialects do not
+ // accept a trailing semicolon.
+ query = StatementSplitter.trimRight(sql);
+ if (query.endsWith(";")) {
+ query = query.substring(0, query.length() - 1);
+ }
+ }
+ try (Backend.Result rs = backend.execute(query, settings, database)) {
+ if (rs != null) {
+ writeRows(rs, sql, other);
+ }
+ }
+ }
+
+ private void writeRows(Backend.Result rs, String sql, boolean other) throws Exception {
+ byte[] raw = rs.rawText();
+ if (raw != null) {
+ result.write(raw);
+ return;
+ }
+ // The FORMAT clause is SQL; other dialects can use the word differently (the `format` pipe of LogsQL).
+ OutputFormat format = other ? OutputFormat.DEFAULT : OutputFormat.of(sql);
+ if (!format.supported) {
+ throw new ShimException("output format " + format.name + " is not supported: the Java client reads"
+ + " results in a binary format, and the shim writes them only as TabSeparated");
+ }
+ boolean discard = format.discard;
+ if (discard && ignoreFormatNullForExplain && "EXPLAIN".equals(SqlText.leadingKeyword(sql))) {
+ // With ignore_format_null_for_explain (on by default), the server ignores `FORMAT Null` for EXPLAIN
+ // and clickhouse-client prints the plan.
+ discard = false;
+ }
+ List names = rs.names();
+ List types = rs.types();
+ List renderers = new ArrayList<>(types.size());
+ for (String t : types) {
+ renderers.add(new TsvRenderer(t));
+ }
+ if (!discard && format.names) {
+ writeHeader(names, format.raw);
+ }
+ if (!discard && format.types) {
+ writeHeader(types, format.raw);
+ }
+ while (rs.next()) {
+ for (int i = 0; i < renderers.size(); i++) {
+ Object v = rs.get(i);
+ if (discard) {
+ continue;
+ }
+ if (i > 0) {
+ result.write('\t');
+ }
+ try {
+ renderers.get(i).render(result, v, format.raw);
+ } catch (RuntimeException e) {
+ throw new ShimException("column " + names.get(i) + ": " + e.getMessage(), e);
+ }
+ }
+ if (!discard) {
+ result.write('\n');
+ }
+ }
+ }
+
+ /**
+ * Writes a header line (names or types). A Raw format writes it without escapes, as its rows: the server does
+ * the same (TabSeparatedRowOutputFormat::writeLine).
+ */
+ private void writeHeader(List values, boolean raw) {
+ for (int i = 0; i < values.size(); i++) {
+ if (i > 0) {
+ result.write('\t');
+ }
+ if (raw) {
+ result.write(values.get(i));
+ } else {
+ TsvRenderer.writeEscaped(result, values.get(i), false);
+ }
+ }
+ result.write('\n');
+ }
+
+ /**
+ * Tells if the session uses another query language than SQL ({@code SET dialect = 'kusto'}, 'prql', ...).
+ */
+ private boolean otherDialect(String sql) {
+ return dialect != null && !dialect.equalsIgnoreCase("clickhouse")
+ && !"SET".equals(SqlText.leadingKeyword(sql));
+ }
+
+ /** Updates the session state after a USE or SET statement. */
+ private void afterSuccess(String sql) throws Exception {
+ String keyword = SqlText.leadingKeyword(sql);
+ if (keyword.equals("USE")) {
+ String db = parseUseDatabase(sql, params);
+ if (db == null) {
+ throw new ShimException("cannot read the database name of \"" + sql + "\"");
+ }
+ database = db;
+ } else if (keyword.equals("SET")) {
+ boolean changed = false;
+ for (Map.Entry e : parseSetAssignments(sql).entrySet()) {
+ if (settings.remove(e.getKey()) != null) {
+ changed = true;
+ }
+ if (e.getKey().equals("dialect")) {
+ dialect = e.getValue();
+ } else if (e.getKey().equals("ignore_format_null_for_explain")) {
+ ignoreFormatNullForExplain = !isFalse(e.getValue());
+ }
+ }
+ if (changed) {
+ backend.settingsChanged(settings);
+ }
+ }
+ }
+
+ /** Tells if the value of a Bool setting in a SET statement is false ({@code 0} or {@code false}). */
+ static boolean isFalse(String value) {
+ String v = value.trim();
+ return v.equals("0") || v.equalsIgnoreCase("false");
+ }
+
+ /**
+ * Returns the database name of a USE statement, or null. A {@code {name:Identifier}} query parameter is
+ * replaced by its value.
+ */
+ static String parseUseDatabase(String sql, Map params) {
+ int i = SqlText.skipWhitespaceAndComments(sql, 0) + "USE".length();
+ String rest = sql.substring(Math.min(i, sql.length())).trim();
+ if (rest.endsWith(";")) {
+ rest = rest.substring(0, rest.length() - 1).trim();
+ }
+ int sp = rest.indexOf(' ');
+ if (sp > 0 && rest.substring(0, sp).equalsIgnoreCase("DATABASE")) {
+ rest = rest.substring(sp + 1).trim();
+ }
+ if (rest.isEmpty()) {
+ return null;
+ }
+ char c = rest.charAt(0);
+ if (c == '`' || c == '"') {
+ return SqlText.unquoteIdentifier(rest);
+ }
+ if (c == '{') {
+ String inner = rest.replaceAll("^\\{|}$", "");
+ int colon = inner.indexOf(':');
+ if (colon < 0) {
+ return null;
+ }
+ return params.get(inner.substring(0, colon).trim());
+ }
+ for (int j = 0; j < rest.length(); j++) {
+ if (!SqlText.isWordChar(rest.charAt(j))) {
+ return null;
+ }
+ }
+ return rest;
+ }
+
+ /**
+ * Returns the settings that a {@code SET a = 1, b = 'x'} statement assigns, with their values (string values
+ * without quotes).
+ */
+ static Map parseSetAssignments(String sql) {
+ int i = SqlText.skipWhitespaceAndComments(sql, 0) + "SET".length();
+ String body = sql.substring(Math.min(i, sql.length())).trim();
+ if (body.endsWith(";")) {
+ body = body.substring(0, body.length() - 1);
+ }
+ Map out = new LinkedHashMap<>();
+ int depth = 0;
+ int start = 0;
+ for (int j = 0; j < body.length(); j++) {
+ char c = body.charAt(j);
+ if (c == '\'' || c == '"' || c == '`') {
+ j = SqlText.skipQuoted(body, j) - 1;
+ } else if (c == '(' || c == '[') {
+ depth++;
+ } else if (c == ')' || c == ']') {
+ depth--;
+ } else if (c == ',' && depth == 0) {
+ addAssignment(out, body.substring(start, j));
+ start = j + 1;
+ }
+ }
+ addAssignment(out, body.substring(start));
+ return out;
+ }
+
+ private static void addAssignment(Map out, String part) {
+ int eq = part.indexOf('=');
+ if (eq < 0) {
+ return;
+ }
+ String value = part.substring(eq + 1).trim();
+ if (value.length() >= 2 && value.startsWith("'") && value.endsWith("'")) {
+ value = value.substring(1, value.length() - 1);
+ }
+ out.put(part.substring(0, eq).trim(), value);
+ }
+
+ /** An error of the shim itself, not of the client or the server. */
+ static final class ShimException extends Exception {
+ ShimException(String message) {
+ super(message);
+ }
+
+ ShimException(String message, Throwable cause) {
+ super(message, cause);
+ }
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/SqlText.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/SqlText.java
new file mode 100644
index 000000000..6bec706ea
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/SqlText.java
@@ -0,0 +1,221 @@
+package com.clickhouse.client.cli;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Locale;
+import java.util.Set;
+
+/**
+ * Lexical helpers for SQL text: quotes, comments, heredocs and keywords, as the ClickHouse lexer reads them. All
+ * the syntax characters are ASCII, so the helpers work on {@code char} positions.
+ */
+final class SqlText {
+
+ private SqlText() {
+ }
+
+ /**
+ * SQL words that can follow a column or an alias named {@code format}, as in
+ * {@code INSERT INTO t SELECT format FROM s}. No input or output format has such a name, so after FORMAT they
+ * show an identifier, not the FORMAT clause.
+ */
+ private static final Set CLAUSE_KEYWORDS = new HashSet<>(Arrays.asList(
+ "FROM", "WHERE", "PREWHERE", "AS", "AND", "OR", "NOT", "IN", "IS", "LIKE", "ILIKE", "BETWEEN",
+ "GROUP", "ORDER", "LIMIT", "OFFSET", "HAVING", "QUALIFY", "WINDOW", "UNION", "EXCEPT", "INTERSECT",
+ "JOIN", "INNER", "LEFT", "RIGHT", "FULL", "CROSS", "ARRAY", "ON", "USING", "SETTINGS", "INTO",
+ "ASC", "DESC", "NULLS", "COLLATE", "WITH", "THEN", "ELSE", "END", "WHEN", "OVER",
+ "GLOBAL", "DIV", "MOD", "REGEXP", "FINAL", "SAMPLE", "FILL", "TIES", "BY"));
+
+ static boolean isClauseKeyword(String word) {
+ return CLAUSE_KEYWORDS.contains(word.toUpperCase(Locale.ROOT));
+ }
+
+ static boolean isWordChar(char c) {
+ return c == '_' || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9');
+ }
+
+ static boolean isSpace(char c) {
+ return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == 0x0B;
+ }
+
+ /** Tells if a line comment starts at i: {@code --}, {@code #!} or {@code # }. */
+ static boolean lineCommentAt(String text, int i) {
+ return text.startsWith("--", i) || text.startsWith("#!", i) || text.startsWith("# ", i);
+ }
+
+ /** Returns the end of the quoted text that starts at i (after the closing quote). */
+ static int skipQuoted(String text, int i) {
+ char q = text.charAt(i);
+ for (int j = i + 1; j < text.length(); j++) {
+ char c = text.charAt(j);
+ if (c == '\\') {
+ j++;
+ } else if (c == q) {
+ // A doubled quote is an escaped quote.
+ if (j + 1 < text.length() && text.charAt(j + 1) == q) {
+ j++;
+ continue;
+ }
+ return j + 1;
+ }
+ }
+ return text.length();
+ }
+
+ /** Returns the position of the newline that ends the line comment at i, or the end of the text. */
+ static int skipLineComment(String text, int i) {
+ int nl = text.indexOf('\n', i);
+ return nl >= 0 ? nl : text.length();
+ }
+
+ /** Returns the end of the block comment at i. Block comments nest in ClickHouse. */
+ static int skipBlockComment(String text, int i) {
+ int depth = 0;
+ int j = i;
+ while (j < text.length() - 1) {
+ if (text.charAt(j) == '/' && text.charAt(j + 1) == '*') {
+ depth++;
+ j += 2;
+ } else if (text.charAt(j) == '*' && text.charAt(j + 1) == '/') {
+ depth--;
+ j += 2;
+ if (depth == 0) {
+ return j;
+ }
+ } else {
+ j++;
+ }
+ }
+ return text.length();
+ }
+
+ /**
+ * Returns the end of the {@code $tag$ ... $tag$} heredoc that starts at i, or 0 when the {@code $} at i does
+ * not start one.
+ */
+ static int heredocEnd(String text, int i) {
+ int tagEnd = text.indexOf('$', i + 1);
+ if (tagEnd < 0) {
+ return 0;
+ }
+ for (int k = i + 1; k < tagEnd; k++) {
+ if (!isWordChar(text.charAt(k))) {
+ return 0;
+ }
+ }
+ String delim = text.substring(i, tagEnd + 1);
+ int end = text.indexOf(delim, tagEnd + 1);
+ if (end < 0) {
+ return 0;
+ }
+ return end + delim.length();
+ }
+
+ static int skipWhitespace(String text, int i) {
+ while (i < text.length() && isSpace(text.charAt(i))) {
+ i++;
+ }
+ return i;
+ }
+
+ static int skipWhitespaceAndComments(String text, int i) {
+ while (i < text.length()) {
+ if (isSpace(text.charAt(i))) {
+ i++;
+ } else if (lineCommentAt(text, i)) {
+ i = skipLineComment(text, i);
+ } else if (text.startsWith("/*", i)) {
+ i = skipBlockComment(text, i);
+ } else {
+ return i;
+ }
+ }
+ return i;
+ }
+
+ static boolean hasSignificantToken(String text, int from) {
+ return skipWhitespaceAndComments(text, from) < text.length();
+ }
+
+ /**
+ * Returns the first word of a statement in upper case, after comments, whitespace and opening parentheses.
+ */
+ static String leadingKeyword(String sql) {
+ int i = skipWhitespaceAndComments(sql, 0);
+ while (i < sql.length() && (sql.charAt(i) == '(' || isSpace(sql.charAt(i)))) {
+ i = skipWhitespaceAndComments(sql, i + 1);
+ }
+ int j = i;
+ while (j < sql.length() && isWordChar(sql.charAt(j))) {
+ j++;
+ }
+ return sql.substring(i, j).toUpperCase(Locale.ROOT);
+ }
+
+ /** Returns the words of sql outside quotes, heredocs, comments and parentheses. */
+ static List topLevelWords(String sql) {
+ List words = new ArrayList<>();
+ int depth = 0;
+ int i = 0;
+ while (i < sql.length()) {
+ char c = sql.charAt(i);
+ if (c == '\'' || c == '"' || c == '`') {
+ i = skipQuoted(sql, i);
+ } else if (c == '$') {
+ int end = heredocEnd(sql, i);
+ i = end > 0 ? end : i + 1;
+ } else if (lineCommentAt(sql, i)) {
+ i = skipLineComment(sql, i);
+ } else if (sql.startsWith("/*", i)) {
+ i = skipBlockComment(sql, i);
+ } else if (c == '(' || c == '[') {
+ depth++;
+ i++;
+ } else if (c == ')' || c == ']') {
+ depth--;
+ i++;
+ } else if (isWordChar(c)) {
+ int j = i;
+ while (j < sql.length() && isWordChar(sql.charAt(j))) {
+ j++;
+ }
+ if (depth == 0) {
+ words.add(sql.substring(i, j));
+ }
+ i = j;
+ } else {
+ i++;
+ }
+ }
+ return words;
+ }
+
+ /**
+ * Removes the quotes of a quoted identifier ({@code `a b`} or {@code "a b"}); returns null when s is not one.
+ */
+ static String unquoteIdentifier(String s) {
+ if (s.length() < 2) {
+ return null;
+ }
+ char q = s.charAt(0);
+ if (s.charAt(s.length() - 1) != q) {
+ return null;
+ }
+ StringBuilder sb = new StringBuilder();
+ for (int i = 1; i < s.length() - 1; i++) {
+ char c = s.charAt(i);
+ if (c == '\\' && i + 1 < s.length() - 1) {
+ i++;
+ sb.append(s.charAt(i));
+ } else if (c == q && i + 1 < s.length() - 1 && s.charAt(i + 1) == q) {
+ i++;
+ sb.append(q);
+ } else {
+ sb.append(c);
+ }
+ }
+ return sb.toString();
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Statement.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Statement.java
new file mode 100644
index 000000000..0a86a32f6
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/Statement.java
@@ -0,0 +1,33 @@
+package com.clickhouse.client.cli;
+
+/**
+ * One query of a multi-query script, split the way {@code clickhouse-client} splits it (see
+ * {@code ClientBase::executeMultiQuery}).
+ */
+final class Statement {
+ /**
+ * The text to send to the server: from the first non-whitespace character (leading comments included) to the
+ * end of the query, with the semicolon.
+ */
+ final String sql;
+ /**
+ * {@link #sql} plus the semicolon and the same-line trailing comment. The client reads the test hints from this
+ * text and prints it for {@code echo}.
+ */
+ final String full;
+ final TestHint hint;
+ /** Tells if this statement is printed before it runs ({@code echo}, {@code echoOn}). */
+ final boolean echo;
+
+ Statement(String sql, String full, TestHint hint, boolean echo) {
+ this.sql = sql;
+ this.full = full;
+ this.hint = hint;
+ this.echo = echo;
+ }
+
+ @Override
+ public String toString() {
+ return sql;
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/StatementSplitter.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/StatementSplitter.java
new file mode 100644
index 000000000..abb6840ee
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/StatementSplitter.java
@@ -0,0 +1,231 @@
+package com.clickhouse.client.cli;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Locale;
+
+/**
+ * Splits a script into statements as {@code clickhouse-client} does ({@code ClientBase::executeMultiQuery}):
+ *
+ * - The {@code -- Tags:} header (the first line and the {@code --} lines after it) is not part of any
+ * statement.
+ * - A statement ends at a top-level {@code ;}. A comment on the same line after the {@code ;} belongs to that
+ * statement; this is where test hints are.
+ * - The inline data of {@code INSERT ... FORMAT
} (other than {@code Values}) ends at an empty line, not
+ * at {@code ;}.
+ * - Comment-only text after the last statement is not a statement.
+ *
+ */
+final class StatementSplitter {
+
+ private StatementSplitter() {
+ }
+
+ static List split(String text) {
+ List out = new ArrayList<>();
+ int pos = testTagsLength(text);
+ boolean echo = false;
+ while (true) {
+ pos = SqlText.skipWhitespace(text, pos);
+ if (pos >= text.length() || !SqlText.hasSignificantToken(text, pos)) {
+ return out;
+ }
+ int begin = pos;
+ int end = scanStatementEnd(text, pos);
+ int sqlEnd = end;
+ // Consume the semicolons after the statement.
+ pos = end;
+ while (pos < text.length() && text.charAt(pos) == ';') {
+ pos++;
+ int next = SqlText.skipWhitespaceAndComments(text, pos);
+ if (next < text.length() && text.charAt(next) == ';') {
+ pos = next;
+ }
+ }
+ // Add the same-line trailing comment when the next statement starts after the end of this line.
+ int newline = text.indexOf('\n', pos);
+ if (newline < 0) {
+ newline = text.length();
+ }
+ if (newline <= SqlText.skipWhitespaceAndComments(text, pos)) {
+ pos = newline;
+ }
+ // clickhouse-client sends the statement with its semicolon. Tests that read system.query_log see it.
+ String sql = trimRight(text.substring(begin, sqlEnd));
+ if (sqlEnd < text.length() && text.charAt(sqlEnd) == ';') {
+ sql = text.substring(begin, sqlEnd + 1);
+ }
+ String full = trimRight(text.substring(begin, pos));
+ if (sqlEnd == text.length()) {
+ // The last statement has no semicolon: clickhouse-client echoes all the rest of the text, with its
+ // trailing newlines.
+ full = text.substring(begin);
+ }
+ TestHint hint = TestHint.parse(full);
+ if (hint.echo != null) {
+ echo = hint.echo;
+ }
+ out.add(new Statement(sql, full, hint, echo));
+ }
+ }
+
+ static String trimRight(String s) {
+ int end = s.length();
+ while (end > 0) {
+ char c = s.charAt(end - 1);
+ if (c != ' ' && c != '\t' && c != '\r' && c != '\n') {
+ break;
+ }
+ end--;
+ }
+ return s.substring(0, end);
+ }
+
+ /**
+ * Mirrors {@code getTestTagsLength}: the length of the leading {@code -- Tags: ...} line and the {@code --}
+ * comment lines right after it.
+ */
+ static int testTagsLength(String text) {
+ int pos = 0;
+ boolean first = true;
+ while (true) {
+ int lineStart = pos;
+ while (pos < text.length() && (text.charAt(pos) == ' ' || text.charAt(pos) == '\t')) {
+ pos++;
+ }
+ if (!text.startsWith("--", pos)) {
+ return lineStart;
+ }
+ pos += 2;
+ if (first) {
+ while (pos < text.length() && (text.charAt(pos) == ' ' || text.charAt(pos) == '\t')) {
+ pos++;
+ }
+ if (!text.startsWith("Tags:", pos)) {
+ return 0;
+ }
+ pos += "Tags:".length();
+ first = false;
+ }
+ int eol = -1;
+ for (int k = pos; k < text.length(); k++) {
+ char c = text.charAt(k);
+ if (c == '\r' || c == '\n') {
+ eol = k;
+ break;
+ }
+ }
+ if (eol < 0) {
+ return text.length();
+ }
+ int eolLen = 1;
+ if (eol + 1 < text.length() && (text.charAt(eol + 1) == '\r' || text.charAt(eol + 1) == '\n')
+ && text.charAt(eol + 1) != text.charAt(eol)) {
+ eolLen = 2;
+ }
+ pos = eol + eolLen;
+ }
+ }
+
+ /** Returns the offset of the {@code ;} that ends the statement at start, or the length of the text. */
+ static int scanStatementEnd(String text, int start) {
+ int parens = 0;
+ int i = start;
+ while (i < text.length()) {
+ char c = text.charAt(i);
+ if (c == '\'' || c == '"' || c == '`') {
+ i = SqlText.skipQuoted(text, i);
+ } else if (c == '-' && text.startsWith("--", i)) {
+ i = SqlText.skipLineComment(text, i);
+ } else if (c == '#' && (text.startsWith("#!", i) || text.startsWith("# ", i))) {
+ i = SqlText.skipLineComment(text, i);
+ } else if (c == '/' && text.startsWith("/*", i)) {
+ i = SqlText.skipBlockComment(text, i);
+ } else if (c == '$') {
+ int end = SqlText.heredocEnd(text, i);
+ i = end > 0 ? end : i + 1;
+ } else if (c == '(' || c == '[') {
+ parens++;
+ i++;
+ } else if (c == ')' || c == ']') {
+ parens--;
+ i++;
+ } else if (c == ';' && parens <= 0) {
+ return i;
+ } else if (SqlText.isWordChar(c)) {
+ int j = i;
+ while (j < text.length() && SqlText.isWordChar(text.charAt(j))) {
+ j++;
+ }
+ if (parens <= 0 && text.regionMatches(true, i, "FORMAT", 0, 6) && j - i == 6) {
+ int dataStart = insertDataStart(text, start, j);
+ if (dataStart >= 0) {
+ // The inline data ends at an empty line.
+ int k = text.indexOf("\n\n", dataStart);
+ return k >= 0 ? k : text.length();
+ }
+ }
+ i = j;
+ } else {
+ i++;
+ }
+ }
+ return text.length();
+ }
+
+ /**
+ * Tells whether the {@code FORMAT} keyword that ends at formatEnd starts the inline data of an INSERT statement
+ * that begins at start. Returns the offset of the data after the format name, or -1. The {@code Values} format
+ * is excluded: its data ends at {@code ;}, like a query.
+ */
+ static int insertDataStart(String text, int start, int formatEnd) {
+ if (!"INSERT".equals(SqlText.leadingKeyword(text.substring(start, formatEnd)))) {
+ return -1;
+ }
+ int i = formatEnd;
+ if (i >= text.length() || !isBlank(text.charAt(i))) {
+ return -1;
+ }
+ while (i < text.length() && isBlank(text.charAt(i))) {
+ i++;
+ }
+ int j = i;
+ while (j < text.length() && SqlText.isWordChar(text.charAt(j))) {
+ j++;
+ }
+ String name = text.substring(i, j);
+ if (j == i || name.toUpperCase(Locale.ROOT).equals("VALUES") || SqlText.isClauseKeyword(name)) {
+ return -1;
+ }
+ // After a SELECT, the FORMAT clause comes at the end of the SELECT, so after its top-level FROM:
+ // `INSERT INTO t SELECT * FROM input('x UInt8') FORMAT TSV`. Before that FROM, `format` is in the select
+ // list (`SELECT format x FROM s`, `SELECT format DIV 2 FROM s`).
+ if (!formatAfterSelectFrom(text.substring(start, formatEnd - "FORMAT".length()))) {
+ return -1;
+ }
+ return j;
+ }
+
+ private static boolean isBlank(char c) {
+ return c == ' ' || c == '\t' || c == '\n' || c == '\r';
+ }
+
+ /**
+ * Tells if a FORMAT that follows head can be the FORMAT clause of an INSERT: head has no top-level SELECT, or a
+ * top-level FROM follows its last top-level SELECT.
+ */
+ static boolean formatAfterSelectFrom(String head) {
+ boolean afterSelect = false;
+ boolean sawFrom = false;
+ for (String w : SqlText.topLevelWords(head)) {
+ String u = w.toUpperCase(Locale.ROOT);
+ if (u.equals("SELECT")) {
+ afterSelect = true;
+ sawFrom = false;
+ } else if (u.equals("FROM")) {
+ sawFrom = true;
+ }
+ }
+ return !afterSelect || sawFrom;
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TestHint.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TestHint.java
new file mode 100644
index 000000000..6efcdc099
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TestHint.java
@@ -0,0 +1,177 @@
+package com.clickhouse.client.cli;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.stream.Collectors;
+
+/**
+ * The test hints of one statement, as {@code clickhouse-client} parses them ({@code src/Client/TestHint.cpp}):
+ *
+ *
+ * SELECT throwIf(1); -- { serverError FUNCTION_THROW_IF_VALUE_IS_NON_ZERO }
+ * SELECT 1 / 0; -- { serverError 153, 6 }
+ * -- { echoOn }
+ *
+ *
+ * An error hint counts only when it is not in a leading comment. An {@code echo} hint counts in any comment.
+ */
+final class TestHint {
+ final List serverErrors = new ArrayList<>();
+ final List clientErrors = new ArrayList<>();
+ /** Set by {@code echo}, {@code echoOn} (true) or {@code echoOff} (false); null when there is no echo hint. */
+ Boolean echo;
+ /** Set when a hint is malformed or names an unknown error. */
+ String parseError;
+
+ boolean expectsError() {
+ return !serverErrors.isEmpty() || !clientErrors.isEmpty();
+ }
+
+ /**
+ * Tells if the error code satisfies the hint. Through the Java client the server finds every error, including
+ * syntax errors that {@code clickhouse-client} finds locally, so a server error can satisfy a
+ * {@code clientError} hint too.
+ */
+ boolean matches(int code) {
+ return serverErrors.contains(code) || clientErrors.contains(code);
+ }
+
+ String label() {
+ if (!serverErrors.isEmpty() && !clientErrors.isEmpty()) {
+ return "error " + codes(serverErrors);
+ }
+ if (!serverErrors.isEmpty()) {
+ return "serverError " + codes(serverErrors);
+ }
+ return "clientError " + codes(clientErrors);
+ }
+
+ private static String codes(List list) {
+ return list.stream().map(c -> {
+ String name = ErrorCodes.name(c);
+ return name != null ? name : String.valueOf(c);
+ }).collect(Collectors.joining(", "));
+ }
+
+ static TestHint parse(String full) {
+ TestHint h = new TestHint();
+ boolean leading = true;
+ int i = 0;
+ while (i < full.length()) {
+ char c = full.charAt(i);
+ int end;
+ if (SqlText.isSpace(c)) {
+ i++;
+ continue;
+ } else if (SqlText.lineCommentAt(full, i)) {
+ end = SqlText.skipLineComment(full, i);
+ } else if (full.startsWith("/*", i)) {
+ end = SqlText.skipBlockComment(full, i);
+ } else if (c == '\'' || c == '"' || c == '`') {
+ leading = false;
+ i = SqlText.skipQuoted(full, i);
+ continue;
+ } else if (c == '$') {
+ leading = false;
+ int e = SqlText.heredocEnd(full, i);
+ i = e > 0 ? e : i + 1;
+ continue;
+ } else {
+ leading = false;
+ i++;
+ continue;
+ }
+ String comment = full.substring(i, end);
+ int open = comment.indexOf('{');
+ if (open >= 0) {
+ int close = comment.indexOf('}', open);
+ if (close >= 0) {
+ h.parseBody(comment.substring(open + 1, close), leading);
+ }
+ }
+ i = end;
+ }
+ return h;
+ }
+
+ private void parseBody(String body, boolean leading) {
+ List tokens = tokenize(body);
+ for (int i = 0; i < tokens.size(); i++) {
+ String tok = tokens.get(i);
+ switch (tok) {
+ case "echo":
+ case "echoOn":
+ echo = Boolean.TRUE;
+ break;
+ case "echoOff":
+ echo = Boolean.FALSE;
+ break;
+ case "retry":
+ // `retry N until|while serverError X` is used by a few tests that wait for a background
+ // process. It is not supported.
+ parseError = "the \"retry\" test hint is not supported";
+ return;
+ case "serverError":
+ case "clientError":
+ case "error": {
+ if (leading) {
+ continue;
+ }
+ List codes = new ArrayList<>();
+ for (String t : tokens.subList(i + 1, tokens.size())) {
+ if (t.equals(",")) {
+ continue;
+ }
+ Integer code = parseCode(t);
+ if (code == null) {
+ parseError = "unknown error name \"" + t + "\" in test hint";
+ return;
+ }
+ codes.add(code);
+ }
+ if (tok.equals("serverError")) {
+ serverErrors.addAll(codes);
+ } else if (tok.equals("clientError")) {
+ clientErrors.addAll(codes);
+ } else {
+ serverErrors.addAll(codes);
+ clientErrors.addAll(codes);
+ }
+ return;
+ }
+ default:
+ break;
+ }
+ }
+ }
+
+ private static Integer parseCode(String t) {
+ try {
+ return Integer.valueOf(t);
+ } catch (NumberFormatException e) {
+ return ErrorCodes.code(t);
+ }
+ }
+
+ private static List tokenize(String body) {
+ List out = new ArrayList<>();
+ int i = 0;
+ while (i < body.length()) {
+ char c = body.charAt(i);
+ if (SqlText.isSpace(c)) {
+ i++;
+ } else if (c == ',') {
+ out.add(",");
+ i++;
+ } else {
+ int j = i;
+ while (j < body.length() && !SqlText.isSpace(body.charAt(j)) && body.charAt(j) != ',') {
+ j++;
+ }
+ out.add(body.substring(i, j));
+ i = j;
+ }
+ }
+ return out;
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvOutput.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvOutput.java
new file mode 100644
index 000000000..a47da991a
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvOutput.java
@@ -0,0 +1,75 @@
+package com.clickhouse.client.cli;
+
+import java.io.IOException;
+import java.io.OutputStream;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
+
+/** A growable byte buffer for the text that the shim writes to stdout. Text is written as UTF-8. */
+final class TsvOutput {
+ private byte[] buf = new byte[8192];
+ private int len;
+
+ int size() {
+ return len;
+ }
+
+ void reset() {
+ len = 0;
+ }
+
+ /** Removes the bytes after position size, for a value that failed to render. */
+ void truncate(int size) {
+ len = size;
+ }
+
+ TsvOutput write(int b) {
+ ensure(1);
+ buf[len++] = (byte) b;
+ return this;
+ }
+
+ TsvOutput write(byte[] b) {
+ ensure(b.length);
+ System.arraycopy(b, 0, buf, len, b.length);
+ len += b.length;
+ return this;
+ }
+
+ TsvOutput write(String s) {
+ boolean ascii = true;
+ for (int i = 0; i < s.length(); i++) {
+ if (s.charAt(i) >= 0x80) {
+ ascii = false;
+ break;
+ }
+ }
+ if (!ascii) {
+ return write(s.getBytes(StandardCharsets.UTF_8));
+ }
+ ensure(s.length());
+ for (int i = 0; i < s.length(); i++) {
+ buf[len++] = (byte) s.charAt(i);
+ }
+ return this;
+ }
+
+ void writeTo(OutputStream out) throws IOException {
+ out.write(buf, 0, len);
+ }
+
+ byte[] toByteArray() {
+ return Arrays.copyOf(buf, len);
+ }
+
+ @Override
+ public String toString() {
+ return new String(buf, 0, len, StandardCharsets.UTF_8);
+ }
+
+ private void ensure(int n) {
+ if (len + n > buf.length) {
+ buf = Arrays.copyOf(buf, Math.max(buf.length * 2, len + n));
+ }
+ }
+}
diff --git a/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvRenderer.java b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvRenderer.java
new file mode 100644
index 000000000..4d7db386f
--- /dev/null
+++ b/tests/clickhouse-client/src/main/java/com/clickhouse/client/cli/TsvRenderer.java
@@ -0,0 +1,764 @@
+package com.clickhouse.client.cli;
+
+import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader;
+import com.clickhouse.client.api.data_formats.internal.StringValue;
+
+import java.math.BigDecimal;
+import java.math.BigInteger;
+import java.net.Inet4Address;
+import java.net.Inet6Address;
+import java.net.InetAddress;
+import java.nio.charset.StandardCharsets;
+import java.sql.SQLException;
+import java.sql.Timestamp;
+import java.time.Duration;
+import java.time.LocalDate;
+import java.time.LocalDateTime;
+import java.time.LocalTime;
+import java.time.OffsetDateTime;
+import java.time.Period;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+/**
+ * Writes the Java values that the client returns as the text that the server writes for the {@code TabSeparated}
+ * format. The upstream {@code .reference} files hold the server's text, so a test passes only when the client
+ * decoded every value correctly.
+ *
+ * The rendering is type-directed: the column type from the result metadata selects the text form, because the
+ * Java value alone is not sufficient (for example, the precision of a {@code DateTime64} is in the type only).
+ * The renderer accepts the Java types of both backends (client-v2 {@code readValue} and jdbc-v2
+ * {@code getObject}); any other Java type for a column type is an error, so a test cannot pass by accident.
+ *
+ *
ClickHouse uses two text forms:
+ *
+ * - top level ({@code serializeTextEscaped}): strings are escaped, not quoted, and NULL is {@code \N};
+ * - nested in {@code Array}, {@code Tuple} and {@code Map} ({@code serializeTextQuoted}): strings are quoted,
+ * and NULL is {@code NULL}.
+ *
+ */
+final class TsvRenderer {
+
+ /** A column type that the renderer does not support. The statement fails. */
+ static final class UnsupportedTypeException extends RuntimeException {
+ UnsupportedTypeException(String type) {
+ super("clickhouse-client-cli: no TabSeparated renderer for type " + type);
+ }
+ }
+
+ /** A Java value that does not fit the column type. The statement fails. */
+ static final class ValueMismatchException extends RuntimeException {
+ ValueMismatchException(ChType type, Object value) {
+ super("clickhouse-client-cli: unexpected Java value " + describe(value) + " for type " + type);
+ }
+
+ private static String describe(Object value) {
+ String text = String.valueOf(value);
+ if (text.length() > 80) {
+ text = text.substring(0, 80) + "...";
+ }
+ return value.getClass().getName() + " (" + text + ")";
+ }
+ }
+
+ private final ChType type;
+
+ TsvRenderer(String typeName) {
+ this.type = ChType.parse(typeName);
+ }
+
+ /**
+ * Writes one top-level value. With raw (the {@code TSVRaw} formats), a top-level string is written without
+ * escapes.
+ */
+ void render(TsvOutput out, Object value, boolean raw) {
+ if (raw && value != null && isStringType(type)) {
+ byte[] bytes = stringBytes(type, value);
+ if (bytes != null) {
+ out.write(bytes);
+ return;
+ }
+ }
+ renderValue(out, type, value, false);
+ }
+
+ static void renderValue(TsvOutput out, ChType t, Object v, boolean nested) {
+ switch (t.base) {
+ case "Nullable":
+ case "LowCardinality": {
+ ChType inner = t.typeArg(0);
+ if (inner == null) {
+ throw new UnsupportedTypeException(t.toString());
+ }
+ renderValue(out, inner, v, nested);
+ return;
+ }
+ case "SimpleAggregateFunction": {
+ ChType inner = t.typeArg(t.args.size() - 1);
+ if (inner == null) {
+ throw new UnsupportedTypeException(t.toString());
+ }
+ renderValue(out, inner, v, nested);
+ return;
+ }
+ default:
+ break;
+ }
+ if (v == null) {
+ out.write(nested ? "NULL" : "\\N");
+ return;
+ }
+ switch (t.base) {
+ case "Int8":
+ case "Int16":
+ case "Int32":
+ case "Int64":
+ case "Int128":
+ case "Int256":
+ case "UInt8":
+ case "UInt16":
+ case "UInt32":
+ case "UInt64":
+ case "UInt128":
+ case "UInt256":
+ if (v instanceof Byte || v instanceof Short || v instanceof Integer || v instanceof Long
+ || v instanceof BigInteger) {
+ out.write(v.toString());
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "Float32":
+ case "BFloat16":
+ if (v instanceof Float) {
+ out.write(FloatFormat.formatFloat((Float) v));
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "Float64":
+ if (v instanceof Double) {
+ out.write(FloatFormat.formatDouble((Double) v));
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "Bool":
+ if (v instanceof Boolean) {
+ out.write(v.toString());
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "String":
+ case "FixedString":
+ case "Enum8":
+ case "Enum16":
+ case "Enum": {
+ byte[] bytes = stringBytes(t, v);
+ if (bytes == null) {
+ throw new ValueMismatchException(t, v);
+ }
+ writeEscaped(out, bytes, nested);
+ return;
+ }
+ case "Decimal":
+ case "Decimal32":
+ case "Decimal64":
+ case "Decimal128":
+ case "Decimal256":
+ if (v instanceof BigDecimal) {
+ out.write(formatDecimal((BigDecimal) v));
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "Date":
+ case "Date32":
+ quotedIf(out, formatDate(t, v), nested);
+ return;
+ case "DateTime":
+ case "DateTime32":
+ quotedIf(out, formatDateTime(t, v, 0), nested);
+ return;
+ case "DateTime64": {
+ int precision = precision(t, 0);
+ quotedIf(out, formatDateTime(t, v, precision), nested);
+ return;
+ }
+ case "Time":
+ quotedIf(out, formatTime(t, v, 0), nested);
+ return;
+ case "Time64":
+ quotedIf(out, formatTime(t, v, precision(t, 0)), nested);
+ return;
+ case "UUID":
+ if (v instanceof UUID) {
+ quotedIf(out, v.toString(), nested);
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "IPv4":
+ if (v instanceof Inet4Address) {
+ quotedIf(out, ((Inet4Address) v).getHostAddress(), nested);
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "IPv6":
+ if (v instanceof Inet6Address) {
+ quotedIf(out, formatIPv6(((Inet6Address) v).getAddress()), nested);
+ return;
+ }
+ if (v instanceof Inet4Address) {
+ // InetAddress.getByAddress gives an IPv4-mapped address (::ffff:a.b.c.d) as Inet4Address.
+ byte[] b = new byte[16];
+ b[10] = (byte) 0xff;
+ b[11] = (byte) 0xff;
+ System.arraycopy(((InetAddress) v).getAddress(), 0, b, 12, 4);
+ quotedIf(out, formatIPv6(b), nested);
+ return;
+ }
+ throw new ValueMismatchException(t, v);
+ case "Nothing":
+ // A `Nothing` column has no values; a value here is a NULL.
+ out.write(nested ? "NULL" : "\\N");
+ return;
+ case "Array": {
+ ChType inner = t.typeArg(0);
+ List> items = sequence(v);
+ if (inner == null || items == null) {
+ throw new ValueMismatchException(t, v);
+ }
+ renderSequence(out, inner, items, '[', ']');
+ return;
+ }
+ case "Nested": {
+ // Nested(a T, b U) (with flatten_nested = 0) is Array(Tuple(a T, b U)).
+ List> items = sequence(v);
+ if (items == null) {
+ throw new ValueMismatchException(t, v);
+ }
+ renderSequence(out, new ChType("Tuple", t.args), items, '[', ']');
+ return;
+ }
+ case "Tuple":
+ renderTuple(out, t, v);
+ return;
+ case "Map":
+ renderMap(out, t, v);
+ return;
+ case "Point":
+ renderPoint(out, t, v);
+ return;
+ case "Ring":
+ case "LineString":
+ case "MultiPoint":
+ renderGeo(out, t, v, ChType.of("Point"));
+ return;
+ case "Polygon":
+ case "MultiLineString":
+ renderGeo(out, t, v, ChType.of("Ring"));
+ return;
+ case "MultiPolygon":
+ renderGeo(out, t, v, ChType.of("Polygon"));
+ return;
+ case "Geometry":
+ renderGeometry(out, t, v);
+ return;
+ case "Variant":
+ renderVariant(out, t, v, nested);
+ return;
+ case "QBit": {
+ // QBit(T, dimension) is written as an array of its element type.
+ ChType inner = t.typeArg(0);
+ List> items = sequence(v);
+ if (inner == null || items == null) {
+ throw new ValueMismatchException(t, v);
+ }
+ renderSequence(out, inner, items, '[', ']');
+ return;
+ }
+ default:
+ if (t.base.startsWith("Interval")) {
+ out.write(formatInterval(t, v));
+ return;
+ }
+ throw new UnsupportedTypeException(t.toString());
+ }
+ }
+
+ static boolean isStringType(ChType t) {
+ while ((t.base.equals("Nullable") || t.base.equals("LowCardinality")) && t.typeArg(0) != null) {
+ t = t.typeArg(0);
+ }
+ switch (t.base) {
+ case "String":
+ case "FixedString":
+ case "Enum8":
+ case "Enum16":
+ case "Enum":
+ return true;
+ default:
+ return false;
+ }
+ }
+
+ /** Returns the bytes of a string-like value, or null when v is not one. */
+ private static byte[] stringBytes(ChType t, Object v) {
+ if (v instanceof String) {
+ return ((String) v).getBytes(StandardCharsets.UTF_8);
+ }
+ if (v instanceof StringValue) {
+ return ((StringValue) v).toByteArray();
+ }
+ if (v instanceof BinaryStreamReader.EnumValue && t.base.startsWith("Enum")) {
+ return ((BinaryStreamReader.EnumValue) v).getName().getBytes(StandardCharsets.UTF_8);
+ }
+ return null;
+ }
+
+ /**
+ * Writes s with the escapes of ClickHouse's {@code writeAnyEscapedString} (with the single quote as the quote
+ * character), quoted when nested.
+ */
+ static void writeEscaped(TsvOutput out, byte[] s, boolean nested) {
+ if (nested) {
+ out.write('\'');
+ }
+ for (byte b : s) {
+ switch (b) {
+ case '\\':
+ out.write('\\').write('\\');
+ break;
+ case '\'':
+ out.write('\\').write('\'');
+ break;
+ case '\b':
+ out.write('\\').write('b');
+ break;
+ case '\f':
+ out.write('\\').write('f');
+ break;
+ case '\n':
+ out.write('\\').write('n');
+ break;
+ case '\r':
+ out.write('\\').write('r');
+ break;
+ case '\t':
+ out.write('\\').write('t');
+ break;
+ case 0:
+ out.write('\\').write('0');
+ break;
+ default:
+ out.write(b);
+ }
+ }
+ if (nested) {
+ out.write('\'');
+ }
+ }
+
+ static void writeEscaped(TsvOutput out, String s, boolean nested) {
+ writeEscaped(out, s.getBytes(StandardCharsets.UTF_8), nested);
+ }
+
+ /** Writes text that has no characters to escape (dates, UUIDs, addresses), quoted when nested. */
+ private static void quotedIf(TsvOutput out, String s, boolean nested) {
+ if (nested) {
+ out.write('\'').write(s).write('\'');
+ } else {
+ out.write(s);
+ }
+ }
+
+ private static int precision(ChType t, int arg) {
+ String p = t.literalArg(arg);
+ try {
+ int n = Integer.parseInt(p);
+ if (n >= 0 && n <= 9) {
+ return n;
+ }
+ } catch (NumberFormatException | NullPointerException e) {
+ // reported below
+ }
+ throw new UnsupportedTypeException(t.toString());
+ }
+
+ static String formatDecimal(BigDecimal d) {
+ if (d.signum() == 0) {
+ return "0";
+ }
+ return d.stripTrailingZeros().toPlainString();
+ }
+
+ private static String formatDate(ChType t, Object v) {
+ LocalDate d;
+ if (v instanceof LocalDate) {
+ d = (LocalDate) v;
+ } else if (v instanceof java.sql.Date) {
+ d = ((java.sql.Date) v).toLocalDate();
+ } else {
+ throw new ValueMismatchException(t, v);
+ }
+ if (d.getYear() > MAX_TEXT_YEAR) {
+ return "9999-12-31";
+ }
+ if (d.getYear() < 0) {
+ return "0000-01-01";
+ }
+ return String.format("%04d-%02d-%02d", d.getYear(), d.getMonthValue(), d.getDayOfMonth());
+ }
+
+ /**
+ * The last year that the server writes as text. The server writes a {@code Date32} or {@code DateTime64} value
+ * after year 9999 as {@code 9999-12-31 [23:59:59]}, and a value before year 0 as {@code 0000-01-01 [00:00:00]}
+ * (the wall-clock time in the time zone of the column; the fractional digits stay those of the value).
+ */
+ private static final int MAX_TEXT_YEAR = 9999;
+
+ /** Writes the wall-clock time of the value, in the time zone that the client gave it. */
+ private static String formatDateTime(ChType t, Object v, int precision) {
+ LocalDateTime ldt;
+ if (v instanceof ZonedDateTime) {
+ ldt = ((ZonedDateTime) v).toLocalDateTime();
+ } else if (v instanceof OffsetDateTime) {
+ ldt = ((OffsetDateTime) v).toLocalDateTime();
+ } else if (v instanceof LocalDateTime) {
+ ldt = (LocalDateTime) v;
+ } else if (v instanceof Timestamp) {
+ ldt = ((Timestamp) v).toLocalDateTime();
+ } else {
+ throw new ValueMismatchException(t, v);
+ }
+ StringBuilder sb = new StringBuilder(32);
+ if (ldt.getYear() > MAX_TEXT_YEAR) {
+ sb.append("9999-12-31 23:59:59");
+ } else if (ldt.getYear() < 0) {
+ sb.append("0000-01-01 00:00:00");
+ } else {
+ sb.append(String.format("%04d-%02d-%02d %02d:%02d:%02d", ldt.getYear(), ldt.getMonthValue(),
+ ldt.getDayOfMonth(), ldt.getHour(), ldt.getMinute(), ldt.getSecond()));
+ }
+ if (precision > 0) {
+ sb.append('.').append(String.format("%09d", ldt.getNano()), 0, precision);
+ }
+ return sb.toString();
+ }
+
+ private static final long MAX_TIME_SECONDS = 999L * 3600 + 59 * 60 + 59;
+
+ /**
+ * Writes a {@code Time} / {@code Time64} value: {@code [-]HH:MM:SS[.fff]}. The hours can be more than 24. The
+ * client-v2 reader gives the value as a LocalDateTime on 1970-01-01 (the value is the time since its start).
+ */
+ private static String formatTime(ChType t, Object v, int precision) {
+ long seconds;
+ long nanos;
+ if (v instanceof LocalDateTime) {
+ LocalDateTime ldt = (LocalDateTime) v;
+ seconds = ldt.toEpochSecond(ZoneOffset.UTC);
+ nanos = ldt.getNano();
+ } else if (v instanceof Duration) {
+ seconds = ((Duration) v).getSeconds();
+ nanos = ((Duration) v).getNano();
+ } else if (v instanceof LocalTime) {
+ seconds = ((LocalTime) v).toSecondOfDay();
+ nanos = ((LocalTime) v).getNano();
+ } else if (v instanceof java.sql.Time) {
+ // jdbc-v2 gives Time and Time64 as java.sql.Time (a time of day) without the sign, the hours over 23
+ // and the fraction (known failures in allowlist.txt). toLocalTime() drops the milliseconds that a
+ // java.sql.Time can hold, so take them from getTime().
+ java.sql.Time time = (java.sql.Time) v;
+ seconds = time.toLocalTime().toSecondOfDay();
+ nanos = Math.floorMod(time.getTime(), 1000L) * 1_000_000L;
+ } else {
+ throw new ValueMismatchException(t, v);
+ }
+ // (seconds, nanos) with 0 <= nanos < 1e9 is the value seconds + nanos / 1e9.
+ boolean negative = seconds < 0;
+ if (negative) {
+ if (nanos > 0) {
+ seconds = -seconds - 1;
+ nanos = 1_000_000_000L - nanos;
+ } else {
+ seconds = -seconds;
+ }
+ }
+ // The server writes a value above 999:59:59 as 999:59:59, with a zero fraction.
+ if (seconds > MAX_TIME_SECONDS) {
+ seconds = MAX_TIME_SECONDS;
+ nanos = 0;
+ }
+ StringBuilder sb = new StringBuilder(24);
+ if (negative) {
+ sb.append('-');
+ }
+ sb.append(String.format("%02d:%02d:%02d", seconds / 3600, seconds / 60 % 60, seconds % 60));
+ if (precision > 0) {
+ sb.append('.').append(String.format("%09d", nanos), 0, precision);
+ }
+ return sb.toString();
+ }
+
+ private static String formatInterval(ChType t, Object v) {
+ if (v instanceof Byte || v instanceof Short || v instanceof Integer || v instanceof Long
+ || v instanceof BigInteger) {
+ return v.toString();
+ }
+ if (v instanceof Period) {
+ Period p = (Period) v;
+ switch (t.base) {
+ case "IntervalYear":
+ return String.valueOf(p.toTotalMonths() / 12);
+ case "IntervalQuarter":
+ return String.valueOf(p.toTotalMonths() / 3);
+ case "IntervalMonth":
+ return String.valueOf(p.toTotalMonths());
+ case "IntervalWeek":
+ return String.valueOf(p.getDays() / 7);
+ case "IntervalDay":
+ return String.valueOf(p.getDays());
+ default:
+ break;
+ }
+ } else if (v instanceof Duration) {
+ Duration d = (Duration) v;
+ switch (t.base) {
+ case "IntervalHour":
+ return String.valueOf(d.toHours());
+ case "IntervalMinute":
+ return String.valueOf(d.toMinutes());
+ case "IntervalSecond":
+ return String.valueOf(d.getSeconds());
+ case "IntervalMillisecond":
+ return String.valueOf(d.toMillis());
+ case "IntervalMicrosecond":
+ return String.valueOf(d.toNanos() / 1000);
+ case "IntervalNanosecond":
+ return String.valueOf(d.toNanos());
+ default:
+ break;
+ }
+ }
+ throw new ValueMismatchException(t, v);
+ }
+
+ /**
+ * Returns the elements of an array-like value: the client's ArrayValue, a List, a Java array or a
+ * java.sql.Array. Returns null for any other value.
+ */
+ static List> sequence(Object v) {
+ if (v instanceof BinaryStreamReader.ArrayValue) {
+ return ((BinaryStreamReader.ArrayValue) v).asList();
+ }
+ if (v instanceof List) {
+ return (List>) v;
+ }
+ if (v instanceof Object[]) {
+ return Arrays.asList((Object[]) v);
+ }
+ if (v != null && v.getClass().isArray()) {
+ int n = java.lang.reflect.Array.getLength(v);
+ List