Descriptions} in the package of each top-level enum that has constants annotated
+ * with {@code com.clickhouse.client.api.internal.ConfigDescription}. The static method {@code getDescriptions()} of
+ * the generated class returns an unmodifiable map from each constant of the enum to its description.
+ *
+ * All constants of such an enum must have a description that is not blank. A constant without a description, a
+ * blank description, or the annotation on an element that is not a constant of a top-level enum fails the
+ * compilation.
+ */
+@SupportedAnnotationTypes(DescriptionProcessor.DESCRIPTION_ANNOTATION)
+public class DescriptionProcessor extends AbstractProcessor {
+
+ static final String DESCRIPTION_ANNOTATION = "com.clickhouse.client.api.internal.ConfigDescription";
+
+ static final String CLASS_NAME_SUFFIX = "Descriptions";
+
+ @Override
+ public SourceVersion getSupportedSourceVersion() {
+ return SourceVersion.latestSupported();
+ }
+
+ @Override
+ public boolean process(Set extends TypeElement> annotations, RoundEnvironment roundEnv) {
+ for (TypeElement annotation : annotations) {
+ Set enums = new LinkedHashSet<>();
+ for (Element element : roundEnv.getElementsAnnotatedWith(annotation)) {
+ if (element.getKind() != ElementKind.ENUM_CONSTANT) {
+ error(element, "@ConfigDescription is allowed only on enum constants");
+ } else if (((TypeElement) element.getEnclosingElement()).getNestingKind() != NestingKind.TOP_LEVEL) {
+ error(element, "@ConfigDescription is allowed only on constants of top-level enums");
+ } else {
+ enums.add((TypeElement) element.getEnclosingElement());
+ }
+ }
+ for (TypeElement enumType : enums) {
+ Map descriptions = readDescriptions(enumType);
+ if (descriptions != null) {
+ writeDescriptionsClass(enumType, descriptions);
+ }
+ }
+ }
+ return true;
+ }
+
+ /**
+ * Returns the descriptions of all constants of the enum by constant name, in declaration order, or {@code null}
+ * when a constant has no description or a blank description.
+ */
+ private Map readDescriptions(TypeElement enumType) {
+ Map descriptions = new LinkedHashMap<>();
+ boolean valid = true;
+ for (Element constant : enumType.getEnclosedElements()) {
+ if (constant.getKind() != ElementKind.ENUM_CONSTANT) {
+ continue;
+ }
+ String name = enumType.getSimpleName() + "." + constant.getSimpleName();
+ String description = descriptionOf(constant);
+ if (description == null) {
+ error(constant, "Enum constant " + name + " has no @ConfigDescription");
+ valid = false;
+ } else if (description.trim().isEmpty()) {
+ error(constant, "Enum constant " + name + " has a blank @ConfigDescription");
+ valid = false;
+ } else {
+ descriptions.put(constant.getSimpleName().toString(), description);
+ }
+ }
+ return valid ? descriptions : null;
+ }
+
+ private static String descriptionOf(Element constant) {
+ for (AnnotationMirror mirror : constant.getAnnotationMirrors()) {
+ TypeElement type = (TypeElement) mirror.getAnnotationType().asElement();
+ if (!type.getQualifiedName().contentEquals(DESCRIPTION_ANNOTATION)) {
+ continue;
+ }
+ for (Map.Entry extends ExecutableElement, ? extends AnnotationValue> value
+ : mirror.getElementValues().entrySet()) {
+ if (value.getKey().getSimpleName().contentEquals("value")) {
+ return String.valueOf(value.getValue().getValue());
+ }
+ }
+ }
+ return null;
+ }
+
+ private void writeDescriptionsClass(TypeElement enumType, Map descriptions) {
+ String packageName = processingEnv.getElementUtils().getPackageOf(enumType).getQualifiedName().toString();
+ String enumName = enumType.getSimpleName().toString();
+ String className = enumName + CLASS_NAME_SUFFIX;
+ String visibility = enumType.getModifiers().contains(Modifier.PUBLIC) ? "public " : "";
+
+ StringBuilder src = new StringBuilder();
+ if (!packageName.isEmpty()) {
+ src.append("package ").append(packageName).append(";\n\n");
+ }
+ src.append("/**\n")
+ .append(" * Descriptions of the constants of {@link ").append(enumName)
+ .append("}, from their {@code @ConfigDescription} annotations.\n")
+ .append(" * Generated by {@code ").append(DescriptionProcessor.class.getName())
+ .append("}. Do not edit.\n")
+ .append(" */\n")
+ .append("@SuppressWarnings({\"deprecation\", \"removal\"})\n")
+ .append(visibility).append("final class ").append(className).append(" {\n\n")
+ .append(" private static final java.util.Map<").append(enumName)
+ .append(", java.lang.String> DESCRIPTIONS;\n\n")
+ .append(" static {\n")
+ .append(" java.util.Map<").append(enumName)
+ .append(", java.lang.String> descriptions = new java.util.EnumMap<>(")
+ .append(enumName).append(".class);\n");
+ for (Map.Entry description : descriptions.entrySet()) {
+ src.append(" descriptions.put(").append(enumName).append('.').append(description.getKey())
+ .append(", ").append(toJavaLiteral(description.getValue())).append(");\n");
+ }
+ src.append(" DESCRIPTIONS = java.util.Collections.unmodifiableMap(descriptions);\n")
+ .append(" }\n\n")
+ .append(" private ").append(className).append("() {\n")
+ .append(" }\n\n")
+ .append(" /**\n")
+ .append(" * Returns an unmodifiable map from each constant of {@link ").append(enumName)
+ .append("} to its description.\n")
+ .append(" *\n")
+ .append(" * @return the descriptions, in the order of the constants\n")
+ .append(" */\n")
+ .append(" public static java.util.Map<").append(enumName)
+ .append(", java.lang.String> getDescriptions() {\n")
+ .append(" return DESCRIPTIONS;\n")
+ .append(" }\n")
+ .append("}\n");
+
+ String qualifiedName = packageName.isEmpty() ? className : packageName + "." + className;
+ try (Writer writer = processingEnv.getFiler().createSourceFile(qualifiedName, enumType).openWriter()) {
+ writer.write(src.toString());
+ } catch (IOException e) {
+ error(enumType, "Failed to write " + qualifiedName + ": " + e.getMessage());
+ }
+ }
+
+ /**
+ * Returns the Java string literal of the value. Uses octal escapes for control characters and Unicode escapes
+ * for characters that are not ASCII: a Unicode escape of a line terminator, a quote or a backslash would end or
+ * break the literal, because the compiler translates Unicode escapes before it reads the literal.
+ */
+ static String toJavaLiteral(String value) {
+ StringBuilder literal = new StringBuilder(value.length() + 2).append('"');
+ for (int i = 0; i < value.length(); i++) {
+ char c = value.charAt(i);
+ if (c == '"' || c == '\\') {
+ literal.append('\\').append(c);
+ } else if (c < 0x20 || c == 0x7f) {
+ literal.append(String.format("\\%03o", (int) c));
+ } else if (c > 0x7f) {
+ literal.append(String.format("\\u%04x", (int) c));
+ } else {
+ literal.append(c);
+ }
+ }
+ return literal.append('"').toString();
+ }
+
+ private void error(Element element, String message) {
+ processingEnv.getMessager().printMessage(Diagnostic.Kind.ERROR, message, element);
+ }
+}
diff --git a/clickhouse-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor b/clickhouse-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor
new file mode 100644
index 000000000..4166356f8
--- /dev/null
+++ b/clickhouse-annotation-processor/src/main/resources/META-INF/services/javax.annotation.processing.Processor
@@ -0,0 +1 @@
+com.clickhouse.processor.DescriptionProcessor
diff --git a/clickhouse-annotation-processor/src/test/java/com/clickhouse/processor/DescriptionProcessorTest.java b/clickhouse-annotation-processor/src/test/java/com/clickhouse/processor/DescriptionProcessorTest.java
new file mode 100644
index 000000000..8e5a8242c
--- /dev/null
+++ b/clickhouse-annotation-processor/src/test/java/com/clickhouse/processor/DescriptionProcessorTest.java
@@ -0,0 +1,190 @@
+package com.clickhouse.processor;
+
+import org.testng.annotations.AfterMethod;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import javax.tools.Diagnostic;
+import javax.tools.DiagnosticCollector;
+import javax.tools.JavaCompiler;
+import javax.tools.JavaFileObject;
+import javax.tools.SimpleJavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+import java.io.File;
+import java.io.IOException;
+import java.lang.reflect.Modifier;
+import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.assertFalse;
+import static org.testng.Assert.assertNotNull;
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.expectThrows;
+
+public class DescriptionProcessorTest {
+
+ private static final String DESCRIPTION_SOURCE = "package com.clickhouse.client.api.internal;\n"
+ + "@java.lang.annotation.Retention(java.lang.annotation.RetentionPolicy.SOURCE)\n"
+ + "@java.lang.annotation.Target(java.lang.annotation.ElementType.FIELD)\n"
+ + "public @interface ConfigDescription { String value(); }\n";
+
+ private Path outputDir;
+
+ private DiagnosticCollector diagnostics;
+
+ @BeforeMethod
+ public void setUp() throws IOException {
+ outputDir = Files.createTempDirectory("description-processor");
+ diagnostics = new DiagnosticCollector<>();
+ }
+
+ @AfterMethod(alwaysRun = true)
+ public void tearDown() throws IOException {
+ try (Stream files = Files.walk(outputDir)) {
+ for (Path file : files.sorted(Comparator.reverseOrder()).collect(Collectors.toList())) {
+ Files.delete(file);
+ }
+ }
+ }
+
+ @Test
+ public void testGeneratesDescriptions() throws Exception {
+ assertTrue(compile("p.Settings",
+ "package p;\n"
+ + "import com.clickhouse.client.api.internal.ConfigDescription;\n"
+ + "public enum Settings {\n"
+ + " @ConfigDescription(\"Plain text.\") PLAIN(\"plain\"),\n"
+ + " @Deprecated @ConfigDescription(\"Quote \\\" and backslash \\\\ and \\\\u0022.\")\n"
+ + " QUOTED(\"quoted\"),\n"
+ + " @ConfigDescription(\"Line 1\\nline 2\\ttab \\u00b5s \\u20ac.\") ESCAPED(\"escaped\") {\n"
+ + " @Override public String key() { return \"other\"; }\n"
+ + " };\n"
+ + " private final String key;\n"
+ + " Settings(String key) { this.key = key; }\n"
+ + " public String key() { return key; }\n"
+ + "}\n"), diagnostics.getDiagnostics().toString());
+ assertTrue(diagnostics.getDiagnostics().isEmpty(), diagnostics.getDiagnostics().toString());
+
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {outputDir.toUri().toURL()})) {
+ Class> generated = loader.loadClass("p.SettingsDescriptions");
+ assertTrue(Modifier.isPublic(generated.getModifiers()));
+ assertTrue(Modifier.isFinal(generated.getModifiers()));
+
+ Map, ?> descriptions = (Map, ?>) generated.getMethod("getDescriptions").invoke(null);
+ Map byName = new LinkedHashMap<>();
+ descriptions.forEach((constant, description) -> byName.put(((Enum>) constant).name(), (String) description));
+ Map expected = new LinkedHashMap<>();
+ expected.put("PLAIN", "Plain text.");
+ expected.put("QUOTED", "Quote \" and backslash \\ and \\u0022.");
+ expected.put("ESCAPED", "Line 1\nline 2\ttab \u00b5s \u20ac.");
+ assertEquals(new ArrayList<>(byName.entrySet()), new ArrayList<>(expected.entrySet()));
+ expectThrows(UnsupportedOperationException.class, () -> descriptions.clear());
+ }
+ }
+
+ @Test
+ public void testPackagePrivateEnum() throws Exception {
+ assertTrue(compile("p.Hidden",
+ "package p;\n"
+ + "enum Hidden { @com.clickhouse.client.api.internal.ConfigDescription(\"Only constant.\") ONLY }\n"),
+ diagnostics.getDiagnostics().toString());
+
+ try (URLClassLoader loader = new URLClassLoader(new URL[] {outputDir.toUri().toURL()})) {
+ Class> generated = loader.loadClass("p.HiddenDescriptions");
+ assertFalse(Modifier.isPublic(generated.getModifiers()));
+ }
+ }
+
+ @Test
+ public void testIgnoresEnumWithoutDescriptions() throws Exception {
+ assertTrue(compile("p.Plain", "package p;\npublic enum Plain { A, B }\n"),
+ diagnostics.getDiagnostics().toString());
+ assertTrue(Files.exists(outputDir.resolve("p/Plain.class")));
+ assertFalse(Files.exists(outputDir.resolve("p/PlainDescriptions.java")));
+ assertFalse(Files.exists(outputDir.resolve("p/PlainDescriptions.class")));
+ }
+
+ @DataProvider(name = "invalidUses")
+ public Object[][] invalidUses() {
+ return new Object[][] {
+ {"package p;\nimport com.clickhouse.client.api.internal.ConfigDescription;\n"
+ + "public enum Invalid { @ConfigDescription(\"First.\") FIRST, SECOND }\n",
+ "Enum constant Invalid.SECOND has no @ConfigDescription"},
+ {"package p;\nimport com.clickhouse.client.api.internal.ConfigDescription;\n"
+ + "public enum Invalid { @ConfigDescription(\"First.\") FIRST, @ConfigDescription(\" \") SECOND }\n",
+ "Enum constant Invalid.SECOND has a blank @ConfigDescription"},
+ {"package p;\nimport com.clickhouse.client.api.internal.ConfigDescription;\n"
+ + "public class Invalid { @ConfigDescription(\"Field.\") static final String FIELD = \"field\"; }\n",
+ "@ConfigDescription is allowed only on enum constants"},
+ {"package p;\nimport com.clickhouse.client.api.internal.ConfigDescription;\n"
+ + "public class Invalid { enum Nested { @ConfigDescription(\"Nested.\") NESTED } }\n",
+ "@ConfigDescription is allowed only on constants of top-level enums"},
+ };
+ }
+
+ @Test(dataProvider = "invalidUses")
+ public void testRejectsInvalidUse(String source, String expectedError) throws Exception {
+ assertFalse(compile("p.Invalid", source));
+ List errors = diagnostics.getDiagnostics().stream()
+ .filter(d -> d.getKind() == Diagnostic.Kind.ERROR)
+ .map(d -> d.getMessage(null))
+ .collect(Collectors.toList());
+ assertEquals(errors, Collections.singletonList(expectedError));
+ assertFalse(Files.exists(outputDir.resolve("p/InvalidDescriptions.java")));
+ }
+
+ @Test
+ public void testToJavaLiteral() {
+ assertEquals(DescriptionProcessor.toJavaLiteral("a\"b\\c\r\n\u0000\u007f\u00e4"),
+ "\"a\\\"b\\\\c\\015\\012\\000\\177\\u00e4\"");
+ }
+
+ /**
+ * Compiles the source together with the {@code ConfigDescription} annotation, with only
+ * {@link DescriptionProcessor}.
+ * Writes the generated sources and the classes to {@link #outputDir}.
+ */
+ private boolean compile(String className, String source) throws IOException {
+ JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
+ assertNotNull(compiler, "Tests need a JDK");
+ try (StandardJavaFileManager fileManager = compiler.getStandardFileManager(diagnostics, null,
+ StandardCharsets.UTF_8)) {
+ List output = Collections.singletonList(outputDir.toFile());
+ fileManager.setLocation(StandardLocation.CLASS_OUTPUT, output);
+ fileManager.setLocation(StandardLocation.SOURCE_OUTPUT, output);
+ JavaCompiler.CompilationTask task = compiler.getTask(null, fileManager, diagnostics,
+ Arrays.asList("-Xlint:deprecation,rawtypes,unchecked", "-implicit:none"), null,
+ Arrays.asList(source("com.clickhouse.client.api.internal.ConfigDescription", DESCRIPTION_SOURCE),
+ source(className, source)));
+ task.setProcessors(Collections.singletonList(new DescriptionProcessor()));
+ return task.call();
+ }
+ }
+
+ private static JavaFileObject source(String className, String code) {
+ return new SimpleJavaFileObject(URI.create("string:///" + className.replace('.', '/') + ".java"),
+ JavaFileObject.Kind.SOURCE) {
+ @Override
+ public CharSequence getCharContent(boolean ignoreEncodingErrors) {
+ return code;
+ }
+ };
+ }
+}
diff --git a/client-v2/pom.xml b/client-v2/pom.xml
index b74b57e59..8c8ea733c 100644
--- a/client-v2/pom.xml
+++ b/client-v2/pom.xml
@@ -221,9 +221,23 @@
lombok
1.18.38
+
+
+ ${project.parent.groupId}
+ clickhouse-annotation-processor
+ ${revision}
+
8
+
+
+
+ ${project.parent.groupId}
+ clickhouse-annotation-processor
+ ${revision}
+
+
diff --git a/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java b/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java
index 17d4f701c..61a23cbe3 100644
--- a/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java
+++ b/client-v2/src/main/java/com/clickhouse/client/api/ClientConfigProperties.java
@@ -4,6 +4,7 @@
import com.clickhouse.client.api.data_formats.internal.AbstractBinaryFormatReader;
import com.clickhouse.client.api.enums.SSLMode;
import com.clickhouse.client.api.internal.CompressedBlockOutputStream;
+import com.clickhouse.client.api.internal.ConfigDescription;
import com.clickhouse.client.api.internal.WorkloadIdentitySupport;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.data.ClickHouseFormat;
@@ -32,42 +33,64 @@
*/
public enum ClientConfigProperties {
+ @ConfigDescription("Comma-separated list of roles that the server applies to each query.")
SESSION_DB_ROLES("session_db_roles", List.class),
+ @ConfigDescription("Comment that the server writes to system.query_log for each query (server setting log_comment).")
SETTING_LOG_COMMENT(serverSetting("log_comment"), String.class),
+ @ConfigDescription("Sends the user and the password with HTTP Basic authentication. Set to false to send them in the "
+ + "X-ClickHouse-User and X-ClickHouse-Key headers.")
HTTP_USE_BASIC_AUTH("http_use_basic_auth", Boolean.class, "true"),
+ @ConfigDescription("User name for authentication.")
USER("user", String.class, "default"),
+ @ConfigDescription("Password for authentication.")
PASSWORD("password", String.class),
/**
* Maximum number of active connection in internal connection pool.
*/
+ @ConfigDescription("Maximum number of open connections to one server in the connection pool.")
HTTP_MAX_OPEN_CONNECTIONS("max_open_connections", Integer.class, "10"),
/**
* HTTP keep-alive timeout override.
*/
+ @ConfigDescription("HTTP keep-alive timeout in milliseconds. It overrides the keep-alive timeout of the server. When it "
+ + "is not set, the client uses the server value.")
HTTP_KEEP_ALIVE_TIMEOUT("http_keep_alive_timeout", Long.class),
+ @ConfigDescription("Uses the server time zone to decode Date and DateTime values.")
USE_SERVER_TIMEZONE("use_server_time_zone", Boolean.class, "true"),
+ @ConfigDescription("Time zone ID that the client uses to decode Date and DateTime values instead of the server time "
+ + "zone.")
USE_TIMEZONE("use_time_zone", TimeZone.class),
+ @ConfigDescription("Server version that Client#getServerVersion() of client-v2 returns before the client reads the "
+ + "version from the server. The JDBC driver does not use it.")
SERVER_VERSION("server_version", String.class),
+ @ConfigDescription("Time zone ID of the server. The client uses it to decode Date and DateTime values when "
+ + "use_server_time_zone is true and the server response does not give a time zone.")
SERVER_TIMEZONE("server_time_zone", TimeZone.class, "UTC"),
+ @ConfigDescription("Runs each operation in a separate thread.")
ASYNC_OPERATIONS("async", Boolean.class, "false"),
+ @ConfigDescription("Time in milliseconds that a connection can stay in the connection pool. After this time, the pool "
+ + "does not reuse the connection. -1 means no limit.")
CONNECTION_TTL("connection_ttl", Long.class, "-1"),
+ @ConfigDescription("Timeout in milliseconds to open a connection to the server.")
CONNECTION_TIMEOUT("connection_timeout", Long.class),
+ @ConfigDescription("Order in which the connection pool reuses idle connections. Choices: FIFO, LIFO.")
CONNECTION_REUSE_STRATEGY("connection_reuse_strategy", ConnectionReuseStrategy.class, String.valueOf(ConnectionReuseStrategy.FIFO)),
+ @ConfigDescription("Timeout in milliseconds to wait for data from the server. 0 means no timeout.")
SOCKET_OPERATION_TIMEOUT("socket_timeout", Integer.class, "0"),
/**
@@ -75,6 +98,8 @@ public enum ClientConfigProperties {
* sizes and auto-tunes the buffer. Setting it disables that auto-tuning and is not recommended
* unless a measurement shows a benefit.
*/
+ @ConfigDescription("Socket receive buffer size in bytes (SO_RCVBUF). When it is not set, the operating system sets and "
+ + "tunes the size.")
SOCKET_RCVBUF_OPT("socket_rcvbuf", Integer.class),
/**
@@ -82,78 +107,124 @@ public enum ClientConfigProperties {
* sizes and auto-tunes the buffer. Setting it disables that auto-tuning and is not recommended
* unless a measurement shows a benefit.
*/
+ @ConfigDescription("Socket send buffer size in bytes (SO_SNDBUF). When it is not set, the operating system sets and "
+ + "tunes the size.")
SOCKET_SNDBUF_OPT("socket_sndbuf", Integer.class),
+ @ConfigDescription("Reserved for the socket option SO_REUSEADDR. The client does not apply it.")
SOCKET_REUSEADDR_OPT("socket_reuseaddr", Boolean.class),
+ @ConfigDescription("Reserved for the socket option SO_KEEPALIVE. The client does not apply it.")
SOCKET_KEEPALIVE_OPT("socket_keepalive", Boolean.class),
+ @ConfigDescription("Sets the socket option TCP_NODELAY. This disables the Nagle algorithm.")
SOCKET_TCP_NO_DELAY_OPT("socket_tcp_nodelay", Boolean.class),
+ @ConfigDescription("Socket linger time in seconds (SO_LINGER).")
SOCKET_LINGER_OPT("socket_linger", Integer.class),
+ @ConfigDescription("Default database for operations.")
DATABASE("database", String.class, "default"),
+ @ConfigDescription("Asks the server to compress the response data.")
COMPRESS_SERVER_RESPONSE("compress", Boolean.class, "true"), // actually a server setting, but has client effect too
+ @ConfigDescription("Compresses the request data that the client sends to the server.")
COMPRESS_CLIENT_REQUEST("decompress", Boolean.class, "false"), // actually a server setting, but has client effect too
+ @ConfigDescription("Uses HTTP compression. The Content-Encoding and Accept-Encoding headers control the compression of "
+ + "requests and responses.")
USE_HTTP_COMPRESSION("client.use_http_compression", Boolean.class, "false"),
+ @ConfigDescription("Size in bytes of the buffer for uncompressed data in block compression and decompression (LZ4 and "
+ + "ZSTD).")
COMPRESSION_LZ4_UNCOMPRESSED_BUF_SIZE("compression.lz4.uncompressed_buffer_size", Integer.class, String.valueOf(CompressedBlockOutputStream.UNCOMPRESSED_BUFF_SIZE)),
+ @ConfigDescription("Compression method for the request data that the client sends. Choices: LZ4, ZSTD.")
COMPRESSION_METHOD("compression.method", CompressionMethod.class, CompressionMethod.ZSTD.name()),
+ @ConfigDescription("Uses the Java implementation of LZ4 instead of the native implementation.")
DISABLE_NATIVE_COMPRESSION("disable_native_compression", Boolean.class, "false"),
+ @ConfigDescription("Type of the proxy server, in upper case. Choices: HTTP, SOCKS.")
PROXY_TYPE("proxy_type", String.class), // "http"
+ @ConfigDescription("Host name or IP address of the proxy server.")
PROXY_HOST("proxy_host", String.class),
+ @ConfigDescription("Port of the proxy server.")
PROXY_PORT("proxy_port", Integer.class),
+ @ConfigDescription("User name for authentication with the HTTP proxy server.")
PROXY_USER("proxy_user", String.class),
+ @ConfigDescription("Password for authentication with the HTTP proxy server.")
PROXY_PASSWORD("proxy_password", String.class),
+ @ConfigDescription("Maximum time in milliseconds that the client waits for the result of a blocking operation, for "
+ + "example ping or queryAll. 0 means no limit. The client does not send it to the server. For the server "
+ + "limit, use clickhouse_setting_max_execution_time (seconds).")
MAX_EXECUTION_TIME("max_execution_time", Integer.class,"0"),
+ @ConfigDescription("Path to the trust store file that the client uses to verify the server certificate.")
SSL_TRUST_STORE("trust_store", String.class),
+ @ConfigDescription("Type of the trust store file, for example JKS or PKCS12.")
SSL_KEYSTORE_TYPE("key_store_type", String.class),
+ @ConfigDescription("Reserved. The client does not use this property.")
SSL_KEY_STORE("ssl_key_store", String.class),
+ @ConfigDescription("Password of the trust store file.")
SSL_KEY_STORE_PASSWORD("key_store_password", String.class),
+ @ConfigDescription("File path or PEM content of the private key of the client certificate.")
SSL_KEY("ssl_key", String.class),
+ @ConfigDescription("File path or PEM content of the CA certificate that the client uses to verify the server "
+ + "certificate.")
CA_CERTIFICATE("sslrootcert", String.class),
+ @ConfigDescription("File path or PEM content of the client certificate for mutual TLS and for SSL authentication.")
SSL_CERTIFICATE("sslcert", String.class),
+ @ConfigDescription("How the client verifies the server on secure connections. Choices: STRICT, VERIFY_CA, TRUST, "
+ + "DISABLED. The JDBC driver also accepts none for TRUST.")
SSL_MODE("ssl_mode", SSLMode.class, SSLMode.STRICT.name()),
+ @ConfigDescription("A javax.net.ssl.SSLContext object for secure connections. Set it with Properties.put(). A string "
+ + "value is not accepted.")
SSL_CONTEXT("ssl_context", SSLContext.class),
+ @ConfigDescription("Maximum number of retries for the failure causes in client_retry_on_failures.")
RETRY_ON_FAILURE("retry", Integer.class, "3"),
+ @ConfigDescription("Default data format of query results.")
INPUT_OUTPUT_FORMAT("format", ClickHouseFormat.class, ClickHouseFormat.RowBinaryWithNamesAndTypes.name()),
+ @ConfigDescription("Reserved. The client does not use this property.")
MAX_THREADS_PER_CLIENT("max_threads_per_client", Integer.class, "0"),
+ @ConfigDescription("Query ID that the client sends with the request.")
QUERY_ID("query_id", String.class), // actually a server setting, but has client effect too
+ @ConfigDescription("Size in bytes of the buffer that copies data between the socket and the application.")
CLIENT_NETWORK_BUFFER_SIZE("client_network_buffer_size", Integer.class, "300000"),
+ @ConfigDescription("Access token for authentication. The client sends it as is in the HTTP Authorization header.")
ACCESS_TOKEN("access_token", String.class),
+ @ConfigDescription("Uses the client certificate (sslcert) for authentication with the server.")
SSL_AUTH("ssl_authentication", Boolean.class, "false"),
+ @ConfigDescription("Enables the connection pool.")
CONNECTION_POOL_ENABLED("connection_pool_enabled", Boolean.class, "true"),
+ @ConfigDescription("Timeout in milliseconds to get a connection from the connection pool.")
CONNECTION_REQUEST_TIMEOUT("connection_request_timeout", Long.class, "10000"),
+ @ConfigDescription("Comma-separated list of failure causes that the client retries. The values are the names of "
+ + "ClientFaultCause constants. None disables the retries.")
CLIENT_RETRY_ON_FAILURE("client_retry_on_failures", List.class,
String.join(",", ClientFaultCause.NoHttpResponse.name(), ClientFaultCause.ConnectTimeout.name(),
ClientFaultCause.ConnectionRequestTimeout.name(), ClientFaultCause.ServerRetryable.name())) {
@@ -170,33 +241,43 @@ public Object parseValue(String value) {
}
},
+ @ConfigDescription("Name of the application. The client sends it at the start of the User-Agent header.")
CLIENT_NAME("client_name", String.class, ""),
/**
* An old alias to {@link ClientConfigProperties#CLIENT_NAME}. Using the last one is preferred.
*/
@Deprecated
+ @ConfigDescription("Deprecated. Use client_name.")
PRODUCT_NAME("product_name", String.class),
+ @ConfigDescription("Bearer token for authentication. The client sends it in the HTTP Authorization header after the "
+ + "Bearer prefix.")
BEARERTOKEN_AUTH ("bearer_token", String.class),
/**
* Indicates that data provided for write operation is compressed by application.
*/
+ @ConfigDescription("Tells the client that the application compresses the data that it inserts.")
APP_COMPRESSED_DATA("app_compressed_data", Boolean.class, "false"),
/**
* Name of the group under which client metrics appear
*/
+ @ConfigDescription("Name of the group of the connection pool metrics.")
METRICS_GROUP_NAME("metrics_name", String.class, "ch-http-pool"),
+ @ConfigDescription("Keeps the HTTP cookies from the server and sends them back to the server.")
HTTP_SAVE_COOKIES("client.http.cookies_enabled", Boolean.class, "false"),
+ @ConfigDescription("Lets the binary format reader reuse its buffers for numbers. This decreases memory allocation.")
BINARY_READER_USE_PREALLOCATED_BUFFERS("client_allow_binary_reader_to_reuse_buffers", Boolean.class, "false"),
/**
* Defines mapping between ClickHouse data type and target Java type
* Used by binary readers to convert values into desired Java type.
*/
+ @ConfigDescription("Mapping of ClickHouse data types to the Java classes that the binary readers of client-v2 use for "
+ + "values. The JDBC driver sets its own mapping. Use jdbc_type_mappings.")
TYPE_HINT_MAPPING("type_hint_mapping", Map.class),
/**
@@ -204,11 +285,14 @@ public Object parseValue(String value) {
* instead of decoding them into a {@link String}. Improves working with large strings and lets
* {@link ClickHouseFormatReader#getByteArray} be used more effectively. Can be configured per operation.
*/
+ @ConfigDescription("Reads String and FixedString columns into byte arrays instead of String objects.")
BINARY_STRING_SUPPORT("binary_string_support", Boolean.class, "false"),
/**
* SNI SSL parameter that will be set for each outbound SSL socket.
*/
+ @ConfigDescription("Server name for SNI (Server Name Indication) on each SSL socket. When it is set, the client also "
+ + "sends this name in the Host header and does not verify the host name in the server certificate.")
SSL_SOCKET_SNI("ssl_socket_sni", String.class,""),
/**
@@ -216,18 +300,23 @@ public Object parseValue(String value) {
* Note: work only with Server side compression. If compression is enabled on client level it will be disabled
* for query requests with parameters.
*/
+ @ConfigDescription("Sends a query that has parameters as HTTP form data in the request body. This works only with "
+ + "server compression.")
HTTP_SEND_PARAMS_IN_BODY("client.http.use_form_request_for_query", Boolean.class, "false"),
/**
* When enabled for JSONEachRow queries, asks ClickHouse to emit large integer,
* floating-point, and decimal values as JSON numbers instead of quoted strings.
*/
+ @ConfigDescription("For JSONEachRow queries, asks the server to write large integer, floating-point and decimal values "
+ + "as JSON numbers instead of quoted strings.")
JSON_DISABLE_NUMBER_QUOTING("json_disable_number_quoting", Boolean.class, "false"),
/**
* Prefix for custom settings. Should be aligned with server configuration.
* See ClickHouse Docs
*/
+ @ConfigDescription("Prefix of custom server settings. It must agree with the server configuration.")
CUSTOM_SETTINGS_PREFIX("custom_settings_prefix", String.class, "custom_"),
/**
@@ -244,6 +333,8 @@ public Object parseValue(String value) {
* Appended at the end of the enum on purpose: adding a constant in the middle would shift the ordinal
* of every following constant (see {@code docs/changes_checklist.md}).
*/
+ @ConfigDescription("Comma-separated list of TLS cipher suites that the client can use. When it is not set, the client "
+ + "uses the default cipher suites of the transport.")
SSL_CIPHER_SUITES("ssl_cipher_suites", List.class) {
@Override
@SuppressWarnings("unchecked")
@@ -265,6 +356,7 @@ public Object parseValue(String value) {
* setting: it is not read from operation settings. See {@link Client.Builder#setClientName(String, Map)} for the
* format and the rules for keys and values.
*/
+ @ConfigDescription("Comma-separated key=value pairs that the client adds to the comment part of the User-Agent header.")
CLIENT_ID_METADATA("client_id_metadata", Map.class) {
@Override
@SuppressWarnings("unchecked")
diff --git a/client-v2/src/main/java/com/clickhouse/client/api/internal/ConfigDescription.java b/client-v2/src/main/java/com/clickhouse/client/api/internal/ConfigDescription.java
new file mode 100644
index 000000000..8277afc57
--- /dev/null
+++ b/client-v2/src/main/java/com/clickhouse/client/api/internal/ConfigDescription.java
@@ -0,0 +1,30 @@
+package com.clickhouse.client.api.internal;
+
+import java.lang.annotation.Documented;
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/**
+ * Short description of a configuration property for users. Each constant of
+ * {@link com.clickhouse.client.api.ClientConfigProperties} and of {@code com.clickhouse.jdbc.DriverProperties} has
+ * one. For internal use of the client and the driver only.
+ *
+ * At build time, an annotation processor generates the class {@code Descriptions} next to each enum with such
+ * constants, for example {@code ClientConfigPropertiesDescriptions}. Its method {@code getDescriptions()} returns a
+ * map from each constant to its description. A constant of such an enum that has no description, or has a blank
+ * description, fails the build.
+ */
+@Documented
+@Retention(RetentionPolicy.SOURCE)
+@Target(ElementType.FIELD)
+public @interface ConfigDescription {
+
+ /**
+ * Returns the description.
+ *
+ * @return the description, not blank
+ */
+ String value();
+}
diff --git a/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java b/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java
index a721ad248..d2dd71f8a 100644
--- a/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java
+++ b/client-v2/src/test/java/com/clickhouse/client/api/ClientConfigPropertiesTest.java
@@ -132,4 +132,14 @@ public void testFromKeyValuePairsRoundTrip() {
Map parsed = ClientConfigProperties.toKeyValuePairs(ClientConfigProperties.fromKeyValuePairs(pairs));
Assert.assertEquals(new ArrayList<>(parsed.entrySet()), new ArrayList<>(pairs.entrySet()));
}
+
+ @Test(groups = {"unit"})
+ public void testDescriptions() {
+ Map descriptions = ClientConfigPropertiesDescriptions.getDescriptions();
+ Assert.assertEquals(new ArrayList<>(descriptions.keySet()), Arrays.asList(ClientConfigProperties.values()));
+ descriptions.forEach((p, d) -> Assert.assertFalse(d.trim().isEmpty(), "Description of " + p));
+ Assert.assertEquals(descriptions.get(ClientConfigProperties.USER), "User name for authentication.");
+ Assert.expectThrows(UnsupportedOperationException.class,
+ () -> descriptions.put(ClientConfigProperties.USER, "a"));
+ }
}
\ No newline at end of file
diff --git a/docs/changes_checklist.md b/docs/changes_checklist.md
index 59f3d062d..7fafb8645 100644
--- a/docs/changes_checklist.md
+++ b/docs/changes_checklist.md
@@ -101,6 +101,7 @@ For each change:
- The declared `valueType` must match parsing behavior and the default value must parse into that type.
- If the property affects connection, retry, timeout, compression, SQL rendering, or authentication behavior, treat it as compatibility-sensitive and add focused tests.
- If the property becomes user-visible in `client-v2` or `jdbc-v2`, consider whether `docs/features.md` should be updated.
+- A new `ClientConfigProperties` or `DriverProperties` constant has a short, useful `@ConfigDescription` annotation. `Driver#getPropertyInfo` returns this description. The build fails when a constant has no description.
# Existing configuration property changed
@@ -113,6 +114,7 @@ For each change:
## Context Check
- For `ClientConfigProperties`, no key change is allowed accidentally.
+- If the units, the default, or the meaning change, update the `@ConfigDescription` annotation of the property.
- If the default changes, review behavior for callers who never set the property explicitly.
- If the value type changes, verify parsing, stored defaults, docs, and all call sites that cast or compare values.
- If the property is passed through JDBC URLs, HTTP parameters, or headers, check the full end-to-end path.
diff --git a/docs/clickhouse-docs/jdbc.mdx b/docs/clickhouse-docs/jdbc.mdx
index d6685ac41..c423163f2 100644
--- a/docs/clickhouse-docs/jdbc.mdx
+++ b/docs/clickhouse-docs/jdbc.mdx
@@ -72,6 +72,7 @@ There are a few things to note about the URL syntax:
### Connection Properties
Main configuration parameters are defined in the [java client](/integrations/language-clients/java/client#client-configuration). They should be passed
as is to the driver. Driver has some own properties that aren't part of the client configuration they're listed below.
+`Driver#getPropertyInfo` returns all client and driver properties with their default values and descriptions.
**Driver properties**:
| Property | Default | Description |
diff --git a/docs/features.md b/docs/features.md
index 53001a34a..6bf386be1 100644
--- a/docs/features.md
+++ b/docs/features.md
@@ -40,6 +40,7 @@ This document lists stable, user-visible behavior in `client-v2` and `jdbc-v2` t
- Span recording (tracing SPI): `Client.Builder.setSpanRecorder(SpanRecorder)` registers a backend-agnostic recorder (package `com.clickhouse.client.api.observability`) that observes client operations. Every operation - a query, a command or an insert, including the `ping` and `getTableSchema` calls, which run a query - starts one operation span, and every transport request made for it, including each retry, starts a child request span. `SpanRecorder` and `Span` are plain interfaces; an implementation extends the `DefaultSpanRecorder` base class and overrides only what it wants to record, so a recorder keeps working when the client starts a kind of span it does not know about. The registered recorder is the first thing the client calls, and it is called with everything the client knows about the operation - its settings object, the statement, the target table, the batch size, the endpoint, the metrics of the completed operation and the failure - so an implementation is free to record whatever it needs and in whatever form. Deriving the standard span names and attribute values from those structures is done by `SpanSupport`, which a recorder implementation calls if it wants them; using it is opt-in, and its methods may be overridden to report other values. A recorder opts in through `DefaultSpanRecorder#getSpanSupport()` (or `SpanSupport.DEFAULT`). Span names and attribute keys follow the OpenTelemetry semantic conventions for database and HTTP client spans, the keys are defined by the `SpanAttribute` enum, and the values are derived by `SpanSupport`, so every recorder that uses it reports the same information. An operation span is named `query `, or `insert .` for an insert, and carries `db.system.name`, `db.namespace`, `clickhouse.query_id`, `db.query.text` (query/command), `db.query.parameter.` (parameterized query), `db.operation.name` (insert), `db.collection.name` (insert), `db.operation.batch.size` (POJO insert), `server.address`/`server.port` of the first configured endpoint (each attempt reports its own on the request span), the metrics of the completed operation on success, and `error.type` plus `db.response.status_code` on failure. Success is reported per operation kind, because the metrics that describe a read are not the ones that describe a write: `SpanRecorder#recordQuerySuccess` is called for a read operation and `SpanRecorder#recordInsertSuccess` for an insert, and each records only the metrics of its own kind - a query reports `db.response.returned_rows`, `clickhouse.response.read_rows` and `clickhouse.response.read_bytes`, an insert reports `clickhouse.response.written_rows` and `clickhouse.response.written_bytes`, and both report `clickhouse.query_id`. These values come from the server's progress summary, which is not always available (for example a query reports them with `QuerySettings#waitEndOfQuery(true)`); a metric the server did not report is left out. The same distinction is on the metrics themselves: `OperationMetrics#getOperationType()` returns `OperationType.QUERY` or `OperationType.INSERT`. It reports the kind of the call the application made, not the kind of work the server did, so a command that writes - `INSERT INTO ... SELECT` run through `execute` - is reported as a query. A request span is named `POST` and carries `http.request.method`, the `server.address`/`server.port` of that attempt, `http.response.status_code` once a response is received, and `error.type`/`db.response.status_code` when the attempt fails. An operation span is started on the calling thread, so it joins the caller's ambient trace even when `async_operations` runs the operation on the client's executor, and it is ended when the operation returns its response to the caller - so it covers sending the request and receiving the response head, not streaming the response body afterwards. Each span of an operation that started is ended exactly once, also when the operation failed; an operation that could not be started at all - a closed client, for example - does not report a span. When no recorder is registered nothing is recorded and no span-related work is done.
- Metrics recording (metrics SPI): `Client.Builder.setMetricsRecorder(MetricsRecorder)` registers a backend-agnostic recorder (package `com.clickhouse.client.api.observability`) that receives the metrics of client operations, so an application can export them to any metrics backend. It follows the same pattern as the span SPI: `MetricsRecorder` is a plain interface, an implementation extends the `DefaultMetricsRecorder` base class and overrides only what it wants to record, so a recorder keeps working when the client starts reporting an event it does not know about, and the reusable `MetricsSupport` class derives the standard values from the same structures (opt-in through `DefaultMetricsRecorder#getMetricsSupport()`, and overridable). Every completed operation reports exactly one event - `recordQuerySuccess`/`recordInsertSuccess` or `recordQueryFailure`/`recordInsertFailure` - so counting those events gives the number of operations by outcome, and every retried attempt reports `recordQueryRetry`/`recordInsertRetry`, so an operation that succeeds on its third attempt reports two retries. The durations of a successful operation are read from its `OperationMetrics`; a failed operation has no metrics, so the client measures its duration itself and passes it in. Metric names, units and attribute keys follow the OpenTelemetry semantic conventions for database clients where a convention exists and are placed under `clickhouse.` where it does not: the `MetricName` enum defines `db.client.operation.duration` (unit `s`), `clickhouse.client.operation.serialization.duration` (unit `s`), `clickhouse.client.operation.count` and `clickhouse.client.operation.retries`, each with the unit and description an exporter registers its instrument with. Durations are reported in **seconds**, while `ClientMetrics` values are milliseconds - `MetricsSupport` converts them and returns `MetricsSupport.DURATION_UNKNOWN` for a duration the client did not measure (the serialization duration is measured for a POJO insert only), so a recorder never reports a made-up value. The attribute keys are the `MetricAttribute` enum - `db.system.name`, `db.namespace`, `db.operation.name` (`query` or `insert`), `db.collection.name` (insert), and `error.type` plus `db.response.status_code` on a failure. That is deliberately a smaller set than `SpanAttribute`, because an attribute of a metric becomes a time series: the statement text, the query id and the statement parameters stay on spans. A successful operation has no `error.type` attribute, so the successful time series is the one without it. When no recorder is registered nothing is recorded and no metrics-related work is done. The recorder is registered per client instance and must be thread-safe.
- Configuration surface: Supports arbitrary client options, cookies, custom headers, server-setting prefixes, client naming, query id suppliers, and buffer sizing.
+- Configuration property descriptions: Each `ClientConfigProperties` constant has a short description in its `@com.clickhouse.client.api.internal.ConfigDescription` annotation. At build time, an annotation processor generates `ClientConfigPropertiesDescriptions`; its `getDescriptions()` returns an unmodifiable map from each constant to its description, in the order of the constants. A constant without a description, or with a blank description, fails the build.
- `User-Agent` header and client metadata: Every request sends a `User-Agent` header in the standard ClickHouse client format, ` clickhouse-java-v2/ (:; ...; lv:java/; os:; arch:; hc:ahc_)`, where `` is a custom `User-Agent` header value if one is set and the client name otherwise, with leading and trailing whitespace removed (omitted when both are blank). A blank client name or `User-Agent` value set for one operation counts as not set: the request uses the value of the client configuration. The client name is the documented way to identify the application; a custom `User-Agent` header replaces it. The `arch` entry is the CPU architecture that the JVM reports (`os.arch`, for example `amd64` or `aarch64`). The `hc` entry is the HTTP client: `ahc_` (Apache HttpClient) and the version of the library that the client is built with (also in the shaded jar). `Client.Builder.setClientName(String, Map)` (or the `client_id_metadata` property, written as `key1=value1,key2=value2`, where a `,` or `\` in a value is escaped with `\`) adds key/value pairs to the comment group in the given order, then `lv`, `os`, `arch` and `hc` if the metadata does not set these keys, ignoring case (so an application can replace them); keys and values are trimmed and entries with a `null` or empty key or value are ignored. Keys and values must be printable ASCII, a key must not contain spaces or any of `:;(),=`, and a value must not contain any of `;()`: an invalid entry is rejected with `ClientMisconfigurationException` when the client is built. Client metadata is a client-level setting: it is not read from operation settings, and it is kept when the client name changes (`Client.Builder.setClientName(String)`, `Client#updateClientName`). The client logs a warning when the `User-Agent` value of the client configuration is longer than 200 characters.
- SQL helpers: Includes SQL quoting and temporal formatting helpers used by callers building SQL text safely.
@@ -74,7 +75,7 @@ Compatibility-sensitive traits:
- JDBC URL parsing: Accepts `jdbc:clickhouse:` and `jdbc:ch:` URLs with host, port, optional HTTP path, optional database, and query parameters.
- SSL URL support: Supports HTTPS connections through URL and property configuration, including default protocol and port handling. The `ssl_mode` property selects the verification strictness (`disabled`, `trust`, `verify_ca`, `strict`); values are case-insensitive and the traditional JDBC value `none` is accepted as an alias for `trust`. Root CA and client certificate/key may be supplied as a file path or as inline PEM content. The `ssl_cipher_suites` property (a comma-separated list) restricts the negotiated TLS cipher suites and is forwarded to the underlying `client-v2` transport.
- Custom SSL context via properties: A fully pre-built `javax.net.ssl.SSLContext` may be passed as a live object in the connection `Properties` under the `ssl_context` key (added with `Properties.put`, since it is not a string). It is forwarded to the underlying `client-v2` transport and used as is; trust/key material properties (e.g. `sslrootcert`, `sslcert`) cannot be combined with it and are rejected, while `ssl_mode` then only controls hostname verification. This supports diskless, in-memory TLS material behind connection pools that only expose `java.util.Properties`.
-- Driver and client properties: Separates JDBC-specific properties from passthrough client options used by the underlying `client-v2` transport. A passthrough client option that has no default value is reported with a `null` default by `Driver#getPropertyInfo` and is not sent to the transport unless the connection sets it — this is the case for the socket buffer properties `socket_rcvbuf` and `socket_sndbuf`, which are left to the operating system.
+- Driver and client properties: Separates JDBC-specific properties from passthrough client options used by the underlying `client-v2` transport. A passthrough client option that has no default value is reported with a `null` default by `Driver#getPropertyInfo` and is not sent to the transport unless the connection sets it — this is the case for the socket buffer properties `socket_rcvbuf` and `socket_sndbuf`, which are left to the operating system. `Driver#getPropertyInfo` returns a description for each client and driver property, whether the connection sets the property or not; a property that is neither a client nor a driver property, for example a `clickhouse_setting_*` or `http_header_*` key, has the description `(User Defined)`. The descriptions are the `@ConfigDescription` annotations of the `ClientConfigProperties` and `DriverProperties` constants. `DriverPropertiesDescriptions.getDescriptions()`, a class that the build generates, returns an unmodifiable map from each `DriverProperties` constant to its description.
- Metrics recording: The `jdbc_metrics_recorder` property names the `client-v2` `MetricsRecorder` implementation the connection reports the metrics of its operations to. A JDBC URL carries strings only, so the value is the fully-qualified class name of a recorder with a public no-argument constructor, and each connection creates its own instance and registers it with its own client. A class that is not on the classpath, does not implement `MetricsRecorder`, or cannot be instantiated is rejected when the connection is created. When the property is not set, nothing is recorded.
- DataSource support: Provides a JDBC `DataSource` implementation backed by the same driver configuration model.
- Connection lifecycle: Supports connection close, validity checks, ping-based health checks, and network timeout management. `Connection#getNetworkTimeout()` returns the underlying client's current network timeout, initially configured by `socket_timeout`, and `setNetworkTimeout` updates that client-level value so subsequent requests from existing as well as new statements use it. When a connection pool saves the timeout, sets another one, and restores the saved one, the configured `socket_timeout` stays in effect. `setNetworkTimeout(executor, 0)` disables the socket timeout.
diff --git a/docs/integration-jdbc.md b/docs/integration-jdbc.md
index 889bff903..868df2141 100644
--- a/docs/integration-jdbc.md
+++ b/docs/integration-jdbc.md
@@ -22,6 +22,7 @@ This guide names only the properties relevant to each step. The exhaustive lists
- **Operation configuration** — set per statement or as connection defaults: fetch size, timeouts, batch behavior, dedup tokens. Covered in Steps 4–6.
- Property routing (see [`DriverProperties`](../jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java)): if a property is a JDBC-specific driver property it is handled by the driver; **all other properties are forwarded to `ClientConfigProperties`**.
+- Property descriptions: `Driver#getPropertyInfo` returns each client and driver property with its default value and a description. Each constant of `DriverProperties` and `ClientConfigProperties` has its description in a `@com.clickhouse.client.api.internal.ConfigDescription` annotation. At build time, the annotation processor in `clickhouse-annotation-processor` generates `DriverPropertiesDescriptions` and `ClientConfigPropertiesDescriptions` with the maps of these descriptions. The build fails when a constant has no description.
### Maven Artifacts
diff --git a/history/latest/3255.md b/history/latest/3255.md
new file mode 100644
index 000000000..356f2ded7
--- /dev/null
+++ b/history/latest/3255.md
@@ -0,0 +1,11 @@
+- **[jdbc-v2]** `Driver#getPropertyInfo` now returns a description for each client and driver property. Before, the
+ description was `null`, or `(User Defined)` when the property had a value. A property that is neither a client nor a
+ driver property, for example a `clickhouse_setting_*` key, keeps the description `(User Defined)`. Property names,
+ values, and defaults are not changed. The new generated class `DriverPropertiesDescriptions` returns the descriptions
+ of the `DriverProperties` constants as a map.
+ (https://github.com/ClickHouse/clickhouse-java/issues/3255)
+- **[client-v2]** New internal annotation `com.clickhouse.client.api.internal.ConfigDescription`: each
+ `ClientConfigProperties` constant has a short description in it. The new generated class
+ `ClientConfigPropertiesDescriptions` returns the descriptions as a map. A configuration property constant without a
+ description fails the build.
+ (https://github.com/ClickHouse/clickhouse-java/issues/3255)
diff --git a/jdbc-v2/pom.xml b/jdbc-v2/pom.xml
index d47fbbf14..4a8356272 100644
--- a/jdbc-v2/pom.xml
+++ b/jdbc-v2/pom.xml
@@ -139,6 +139,35 @@
+
+ org.apache.maven.plugins
+ maven-compiler-plugin
+
+
+
+ default-compile
+
+
+
+
+ ${project.parent.groupId}
+ clickhouse-annotation-processor
+ ${revision}
+
+
+
+
+
+
+
+
+ ${project.parent.groupId}
+ clickhouse-annotation-processor
+ ${revision}
+
+
+
org.apache.maven.plugins
maven-failsafe-plugin
diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java
index 8f986e1fe..8bbcfd10b 100644
--- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java
+++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java
@@ -1,6 +1,7 @@
package com.clickhouse.jdbc;
import com.clickhouse.client.api.ClientConfigProperties;
+import com.clickhouse.client.api.internal.ConfigDescription;
import com.clickhouse.client.api.internal.ServerSettings;
import java.util.Arrays;
@@ -21,22 +22,27 @@ public enum DriverProperties {
* JDBC allows throwing SQLException for unsupported values and methods.
* But driver can ignore them and continue execution. Driver will do no operation in such case.
*/
+ @ConfigDescription("Ignores unsupported JDBC methods and values. When it is false, the driver throws "
+ + "SQLFeatureNotSupportedException.")
IGNORE_UNSUPPORTED_VALUES("jdbc_ignore_unsupported_values", String.valueOf(Boolean.FALSE)),
/**
* Schema term to be used in the connection URL. Only `schema` is supported right now.
*/
+ @ConfigDescription("Value that DatabaseMetaData.getSchemaTerm() returns. Only schema is supported.")
SCHEMA_TERM("jdbc_schema_term", "schema"),
/**
* Indicates if driver should create a secure connection over SSL/TLS
*/
+ @ConfigDescription("Uses HTTPS for the connection. It is not necessary when the URL has the https protocol.")
SECURE_CONNECTION("ssl", String.valueOf(Boolean.FALSE)),
/**
* Query settings to be passed along with query operation.
* {@see com.clickhouse.client.api.query.QuerySettings}
*/
+ @ConfigDescription("Comma-separated key=value server settings that the driver sends with each query.")
DEFAULT_QUERY_SETTINGS("default_query_settings", null),
/**
@@ -44,11 +50,14 @@ public enum DriverProperties {
* PreparedStatement is used. Has limitation and can be used with a simple form of insert like;
* {@code INSERT INTO t VALUES (?, ?, ?...)}
*/
+ @ConfigDescription("Beta. Uses the RowBinary writer for a PreparedStatement with a simple "
+ + "INSERT INTO table VALUES (?, ?, ...) statement.")
BETA_ROW_BINARY_WRITER("beta.row_binary_for_simple_insert", String.valueOf(Boolean.FALSE)),
/**
* Enables closing result set before
*/
+ @ConfigDescription("Closes the current ResultSet of a Statement before the Statement runs the next query.")
RESULTSET_AUTO_CLOSE("jdbc_resultset_auto_close", String.valueOf(Boolean.TRUE)),
/**
@@ -59,6 +68,8 @@ public enum DriverProperties {
* this is fine. It is recommended to set limit in SQL query.
*
*/
+ @ConfigDescription("Makes Statement.setMaxRows() and setLargeMaxRows() send the limit as the server setting "
+ + "max_result_rows with result_overflow_mode=break. This overrides the overflow mode that the user sets.")
USE_MAX_RESULT_ROWS("jdbc_use_max_result_rows", String.valueOf(Boolean.FALSE)),
/**
@@ -69,6 +80,7 @@ public enum DriverProperties {
* JAVACC - parser extracts required information but PreparedStatement parameters parsed separately.
*
*/
+ @ConfigDescription("SQL parser of the driver. Choices: ANTLR4, ANTLR4_PARAMS_PARSER, JAVACC.")
SQL_PARSER("jdbc_sql_parser", "JAVACC", Arrays.asList("ANTLR4", "ANTLR4_PARAMS_PARSER", "JAVACC")),
/**
@@ -76,12 +88,16 @@ public enum DriverProperties {
* before sending request with client.
* When no set - queryID is generated by using {@link UUID#randomUUID()}.
*/
+ @ConfigDescription("A java.util.function.Supplier object that generates query IDs. Set it with "
+ + "Properties.put(). When it is not set, the driver uses random UUIDs.")
QUERY_ID_GENERATOR("jdbc_query_id_generator", null),
/**
* Controls logic of saving roles that were set using {@code SET } statement.
* Default: true - save roles
*/
+ @ConfigDescription("Keeps the roles of the last SET ROLE statement and applies them to the next queries of the "
+ + "connection.")
REMEMBER_LAST_SET_ROLES("remember_last_set_roles", String.valueOf(Boolean.TRUE)),
/**
@@ -94,6 +110,8 @@ public enum DriverProperties {
*
*/
@Deprecated
+ @ConfigDescription("Deprecated. Comma-separated key=value server settings. Use properties with the clickhouse_setting_ "
+ + "prefix.")
CUSTOM_HTTP_PARAMS("custom_http_params", null),
@@ -106,6 +124,8 @@ public enum DriverProperties {
*
*/
@Deprecated
+ @ConfigDescription("Deprecated. Comma-separated key=value server settings. Use properties with the clickhouse_setting_ "
+ + "prefix.")
CUSTOM_SETTINGS("custom_settings", null),
/**
@@ -115,6 +135,7 @@ public enum DriverProperties {
* Driver ignores this setting but will throw exception when it is completely removed.
*/
@Deprecated
+ @ConfigDescription("Deprecated. The driver ignores this property.")
USE_TZ_FOR_DATES("use_server_time_zone_for_dates", null),
/**
@@ -122,11 +143,13 @@ public enum DriverProperties {
* Deprecated will be removed soon
*/
@Deprecated
+ @ConfigDescription("Deprecated. The driver ignores this property.")
HTTP_CONNECTION_PROVIDER("http_connection_provider", null),
/**
* Define cluster name for statement executions like KILL
*/
+ @ConfigDescription("Cluster name. When it is set, the driver cancels a statement with KILL QUERY ON CLUSTER.")
CLUSTER_NAME("jdbc_cluster_name", null),
/**
@@ -136,6 +159,7 @@ public enum DriverProperties {
* Value is the Java class name.
* Example: 'UInt64=java.lang.String'
*/
+ @ConfigDescription("Comma-separated type=class mappings for ResultSet.getObject(). Example: UInt64=java.lang.String.")
JDBC_TYPE_MAPPINGS("jdbc_type_mappings", null),
/**
@@ -144,6 +168,7 @@ public enum DriverProperties {
* Use `jdbc_type_mappings` instead
*/
@Deprecated
+ @ConfigDescription("Deprecated. Use jdbc_type_mappings.")
TYPE_MAPPINGS("typeMappings", null),
/**
@@ -151,6 +176,7 @@ public enum DriverProperties {
* should use when the response is in {@code JSONEachRow} format. Value is the fully-qualified class name of
* the factory class.
*/
+ @ConfigDescription("Fully qualified class name of the JsonParserFactory for JSONEachRow responses.")
JSON_PARSER_FACTORY("jdbc_json_parser_factory", null),
/**
@@ -158,6 +184,8 @@ public enum DriverProperties {
* should report the metrics of its operations to. Value is the fully-qualified class name of a recorder that has
* a public no-argument constructor; each connection creates its own instance. When not set, nothing is recorded.
*/
+ @ConfigDescription("Fully qualified class name of the MetricsRecorder for the metrics of the connection. The class must "
+ + "have a public constructor without arguments.")
METRICS_RECORDER("jdbc_metrics_recorder", null),
/**
@@ -169,12 +197,15 @@ public enum DriverProperties {
* {@code getTables()} returns {@code null} in {@code REMARKS} and {@code TYPE_SCHEM}.
* Default: true
*/
+ @ConfigDescription("Reads database metadata with SHOW DATABASES, SHOW TABLES and DESCRIBE TABLE instead of the system "
+ + "tables.")
METADATA_USE_SHOW_STATEMENTS("jdbc_metadata_use_show_statements", String.valueOf(Boolean.TRUE)),
/**
* Disables detection of application frameworks (for example Apache Spark) for the {@code User-Agent} header.
* Default: false
*/
+ @ConfigDescription("Disables the detection of application frameworks for the User-Agent header.")
DISABLE_FRAMEWORKS_DETECTION("disable_frameworks_detection", String.valueOf(Boolean.FALSE)),
/**
@@ -186,6 +217,8 @@ public enum DriverProperties {
* level and is not affected.
* Default: true
*/
+ @ConfigDescription("Makes Array.getBaseType() and Array.getBaseTypeName() of a multi-dimensional array return the next "
+ + "array level. Set to false to return the innermost type that is not an array.")
MULTI_DIMENSIONAL_ARRAY_ELEMENT_TYPE("jdbc_multi_dimensional_array_element_type", String.valueOf(Boolean.TRUE)),
;
diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/JdbcConfiguration.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/JdbcConfiguration.java
index 9bbb82c2f..509ec8008 100644
--- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/JdbcConfiguration.java
+++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/internal/JdbcConfiguration.java
@@ -2,11 +2,13 @@
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.ClientConfigProperties;
+import com.clickhouse.client.api.ClientConfigPropertiesDescriptions;
import com.clickhouse.client.api.enums.SSLMode;
import com.clickhouse.client.api.http.ClickHouseHttpProto;
import com.clickhouse.data.ClickHouseDataType;
import com.clickhouse.jdbc.Driver;
import com.clickhouse.jdbc.DriverProperties;
+import com.clickhouse.jdbc.DriverPropertiesDescriptions;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.slf4j.Logger;
@@ -46,6 +48,9 @@ public class JdbcConfiguration {
private static final Pattern PATTERN_HTTP_TOKEN = Pattern.compile(
"[A-Za-z0-9!#$%&'*+\\.\\^_`\\|~-]+");
+ static final String USER_DEFINED_PROPERTY_DESCRIPTION = "(User Defined)";
+ private static final Map PROPERTY_DESCRIPTIONS = propertyDescriptions();
+
private final boolean disableFrameworkDetection;
private final Map> typeMap;
private static final Map> COMMON_CLASSES;
@@ -382,7 +387,7 @@ private void buildFinalProperties(Map urlProperties, Properties
// create initial list of properties that will be passed to a client
for (Map.Entry prop : props.entrySet()) {
DriverPropertyInfo propertyInfo = new DriverPropertyInfo(prop.getKey(), prop.getValue());
- propertyInfo.description = "(User Defined)";
+ propertyInfo.description = PROPERTY_DESCRIPTIONS.getOrDefault(prop.getKey(), USER_DEFINED_PROPERTY_DESCRIPTION);
propertyInfos.put(prop.getKey(), propertyInfo);
if (DRIVER_PROP_KEYS.contains(prop.getKey())) {
@@ -428,7 +433,7 @@ private void buildFinalProperties(Map urlProperties, Properties
DriverPropertyInfo propertyInfo = propertyInfos.get(clientProp.getKey());
if (propertyInfo == null) {
propertyInfo = new DriverPropertyInfo(clientProp.getKey(), clientProp.getDefaultValue());
- // TODO: read description from resource file
+ propertyInfo.description = PROPERTY_DESCRIPTIONS.get(clientProp.getKey());
propertyInfos.put(clientProp.getKey(), propertyInfo);
}
}
@@ -439,6 +444,7 @@ private void buildFinalProperties(Map urlProperties, Properties
DriverPropertyInfo propertyInfo = propertyInfos.get(driverProp.getKey());
if (propertyInfo == null) {
propertyInfo = new DriverPropertyInfo(driverProp.getKey(), driverProp.getDefaultValue());
+ propertyInfo.description = PROPERTY_DESCRIPTIONS.get(driverProp.getKey());
propertyInfos.put(driverProp.getKey(), propertyInfo);
}
}
@@ -446,6 +452,17 @@ private void buildFinalProperties(Map urlProperties, Properties
listOfProperties = propertyInfos.values().stream().sorted(Comparator.comparing(o -> o.name)).collect(Collectors.toList());
}
+ /**
+ * Returns the descriptions of the client and driver properties by property key. The descriptions come from the
+ * {@code @ConfigDescription} annotations of {@link ClientConfigProperties} and {@link DriverProperties}.
+ */
+ private static Map propertyDescriptions() {
+ Map descriptions = new HashMap<>();
+ ClientConfigPropertiesDescriptions.getDescriptions().forEach((p, d) -> descriptions.put(p.getKey(), d));
+ DriverPropertiesDescriptions.getDescriptions().forEach((p, d) -> descriptions.put(p.getKey(), d));
+ return Collections.unmodifiableMap(descriptions);
+ }
+
/**
* Returns a list of driver property information.
* @return a list of driver property information for the driver
diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/JdbcConfigurationTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/JdbcConfigurationTest.java
index c59b5e89a..ea486fad5 100644
--- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/JdbcConfigurationTest.java
+++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/internal/JdbcConfigurationTest.java
@@ -2,11 +2,14 @@
import com.clickhouse.client.api.Client;
import com.clickhouse.client.api.ClientConfigProperties;
+import com.clickhouse.client.api.ClientConfigPropertiesDescriptions;
import com.clickhouse.client.api.ClientMisconfigurationException;
import com.clickhouse.client.api.enums.SSLMode;
import com.clickhouse.data.ClickHouseDataType;
+import com.clickhouse.jdbc.Driver;
import com.clickhouse.jdbc.DriverProperties;
+import com.clickhouse.jdbc.DriverPropertiesDescriptions;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
@@ -15,6 +18,7 @@
import java.lang.reflect.Field;
import java.sql.DriverPropertyInfo;
import java.sql.SQLException;
+import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.LinkedHashMap;
@@ -176,6 +180,66 @@ public void testConfigurationProperties() throws Exception {
assertEquals(p.value, "default1");
}
+ @Test
+ public void testDriverPropertiesDescriptions() {
+ Map descriptions = DriverPropertiesDescriptions.getDescriptions();
+ assertEquals(new ArrayList<>(descriptions.keySet()), Arrays.asList(DriverProperties.values()));
+ descriptions.forEach((p, d) -> assertFalse(d.trim().isEmpty(), "Description of " + p));
+ assertThrows(UnsupportedOperationException.class, () -> descriptions.put(DriverProperties.SQL_PARSER, "a"));
+
+ Set driverKeys = Arrays.stream(DriverProperties.values()).map(DriverProperties::getKey)
+ .collect(Collectors.toSet());
+ Set sharedKeys = Arrays.stream(ClientConfigProperties.values()).map(ClientConfigProperties::getKey)
+ .filter(driverKeys::contains).collect(Collectors.toSet());
+ assertTrue(sharedKeys.isEmpty(), "Keys of both a client and a driver property: " + sharedKeys);
+ }
+
+ @DataProvider(name = "propertyInfoDescriptions")
+ public Object[][] propertyInfoDescriptions() {
+ Properties properties = new Properties();
+ properties.setProperty(ClientConfigProperties.SOCKET_OPERATION_TIMEOUT.getKey(), "1000");
+ properties.setProperty(DriverProperties.SQL_PARSER.getKey(), "ANTLR4");
+ properties.setProperty("custom_property", "a");
+ return new Object[][] {
+ { "jdbc:clickhouse://localhost:8123", new Properties(), Map.of() },
+ { "jdbc:clickhouse://localhost:8123/db1?async=true&jdbc_resultset_auto_close=false"
+ + "&clickhouse_setting_max_threads=2", null,
+ Map.of(ClientConfigProperties.DATABASE.getKey(), "db1",
+ ClientConfigProperties.ASYNC_OPERATIONS.getKey(), "true",
+ DriverProperties.RESULTSET_AUTO_CLOSE.getKey(), "false",
+ ClientConfigProperties.serverSetting("max_threads"), "2") },
+ { "jdbc:clickhouse://localhost:8123", properties,
+ Map.of(ClientConfigProperties.SOCKET_OPERATION_TIMEOUT.getKey(), "1000",
+ DriverProperties.SQL_PARSER.getKey(), "ANTLR4",
+ "custom_property", "a") },
+ };
+ }
+
+ @Test(dataProvider = "propertyInfoDescriptions")
+ public void testGetPropertyInfoDescriptions(String url, Properties properties, Map setValues)
+ throws Exception {
+ Map descriptions = new HashMap<>();
+ ClientConfigPropertiesDescriptions.getDescriptions().forEach((p, d) -> descriptions.put(p.getKey(), d));
+ DriverPropertiesDescriptions.getDescriptions().forEach((p, d) -> descriptions.put(p.getKey(), d));
+ Map infos = new HashMap<>();
+ for (DriverPropertyInfo info : new Driver().getPropertyInfo(url, properties)) {
+ assertNotNull(info.description, "Description of " + info.name);
+ assertFalse(info.description.trim().isEmpty(), "Description of " + info.name);
+ infos.put(info.name, info);
+ }
+
+ Arrays.stream(ClientConfigProperties.values()).forEach(p -> assertTrue(infos.containsKey(p.getKey()), p.getKey()));
+ Arrays.stream(DriverProperties.values()).forEach(p -> assertTrue(infos.containsKey(p.getKey()), p.getKey()));
+ for (DriverPropertyInfo info : infos.values()) {
+ String expected = descriptions.getOrDefault(info.name, JdbcConfiguration.USER_DEFINED_PROPERTY_DESCRIPTION);
+ assertEquals(info.description, expected, "Description of " + info.name);
+ }
+ assertEquals(infos.get(ClientConfigProperties.USER.getKey()).description, "User name for authentication.");
+ assertEquals(infos.get(DriverProperties.SQL_PARSER.getKey()).description,
+ "SQL parser of the driver. Choices: ANTLR4, ANTLR4_PARAMS_PARSER, JAVACC.");
+ setValues.forEach((key, value) -> assertEquals(infos.get(key).value, value, "Value of " + key));
+ }
+
@DataProvider(name = "sslModeValues")
public Object[][] sslModeValues() {
return new Object[][] {
diff --git a/pom.xml b/pom.xml
index 551a7b24b..fbcc3ce00 100644
--- a/pom.xml
+++ b/pom.xml
@@ -46,6 +46,8 @@
clickhouse-client
clickhouse-http-client
+
+ clickhouse-annotation-processor
client-v2
@@ -580,6 +582,9 @@
${project.basedir}/src/main/java11
true
+
+ ${project.build.directory}/generated-sources/annotations-java11
@@ -597,6 +602,7 @@
${project.basedir}/src/main/java17
true
+ ${project.build.directory}/generated-sources/annotations-java17
@@ -953,6 +959,10 @@
true
central
+
+
+ clickhouse-annotation-processor
+