diff --git a/client-v2/pom.xml b/client-v2/pom.xml index 0c6409cdf..57ff943a8 100644 --- a/client-v2/pom.xml +++ b/client-v2/pom.xml @@ -88,8 +88,26 @@ com.fasterxml.jackson.core jackson-databind - test ${jackson.version} + provided + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + provided + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + provided + + + com.google.code.gson + gson + ${gson.version} + provided ${project.parent.groupId} diff --git a/client-v2/src/main/java/com/clickhouse/client/api/Client.java b/client-v2/src/main/java/com/clickhouse/client/api/Client.java index c32095e78..9cc857ee6 100644 --- a/client-v2/src/main/java/com/clickhouse/client/api/Client.java +++ b/client-v2/src/main/java/com/clickhouse/client/api/Client.java @@ -3,11 +3,14 @@ import com.clickhouse.client.api.command.CommandResponse; import com.clickhouse.client.api.command.CommandSettings; import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader; +import com.clickhouse.client.api.data_formats.JSONEachRowFormatReader; import com.clickhouse.client.api.data_formats.NativeFormatReader; import com.clickhouse.client.api.data_formats.RowBinaryFormatReader; import com.clickhouse.client.api.data_formats.RowBinaryWithNamesAndTypesFormatReader; import com.clickhouse.client.api.data_formats.RowBinaryWithNamesFormatReader; import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader; +import com.clickhouse.client.api.data_formats.internal.JsonParser; +import com.clickhouse.client.api.data_formats.internal.JsonParserFactory; import com.clickhouse.client.api.data_formats.internal.MapBackedRecord; import com.clickhouse.client.api.data_formats.internal.ProcessParser; import com.clickhouse.client.api.enums.Protocol; @@ -1663,6 +1666,7 @@ public CompletableFuture query(String sqlQuery, Map buildRequestSettings(Map opSettings) return requestSettings; } + /** + * Applies format-specific server-side settings to the already merged request settings. + * Must be called after {@link #buildRequestSettings(Map)} and after the request format has been resolved + * (either provided by the caller or defaulted), so that the inspected format reflects the final value. + * + *

For {@link ClickHouseFormat#JSONEachRow} the JSON output flags below are forced to {@code 0} so that the + * stream contains plain JSON numbers (and not quoted strings or non-standard tokens), which is what + * {@link com.clickhouse.client.api.data_formats.JSONEachRowFormatReader} expects:

+ *
    + *
  • {@code output_format_json_quote_64bit_integers}
  • + *
  • {@code output_format_json_quote_64bit_floats}
  • + *
  • {@code output_format_json_quote_denormals}
  • + *
  • {@code output_format_json_quote_decimals}
  • + *
+ */ + private static void applyFormatSpecificSettings(QuerySettings requestSettings) { + if (requestSettings.getFormat() == ClickHouseFormat.JSONEachRow) { + requestSettings.serverSetting("output_format_json_quote_64bit_integers", "0"); + requestSettings.serverSetting("output_format_json_quote_64bit_floats", "0"); + requestSettings.serverSetting("output_format_json_quote_denormals", "0"); + requestSettings.serverSetting("output_format_json_quote_decimals", "0"); + } + } + private Duration durationSince(long sinceNanos) { return Duration.ofNanos(System.nanoTime() - sinceNanos); } 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 e548a90f9..9c40e48dd 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 @@ -196,6 +196,15 @@ public Object parseValue(String value) { * See ClickHouse Docs */ CUSTOM_SETTINGS_PREFIX("custom_settings_prefix", String.class, "custom_"), + + /** + * Configures what JSON processor will be used for JSON formats. Choices: + *
    + *
  • JACKSON - uses Jackson library.
  • + *
  • GSON - uses Gson library.
  • + *
+ */ + JSON_PROCESSOR("json_processor", String.class, "JACKSON"), ; private static final Logger LOG = LoggerFactory.getLogger(ClientConfigProperties.class); diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/JSONEachRowFormatReader.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/JSONEachRowFormatReader.java new file mode 100644 index 000000000..d0615e526 --- /dev/null +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/JSONEachRowFormatReader.java @@ -0,0 +1,528 @@ +package com.clickhouse.client.api.data_formats; + +import com.clickhouse.client.api.data_formats.internal.JsonParser; +import com.clickhouse.client.api.metadata.TableSchema; +import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; +import com.clickhouse.data.value.ClickHouseBitmap; +import com.clickhouse.data.value.ClickHouseGeoMultiPolygonValue; +import com.clickhouse.data.value.ClickHouseGeoPointValue; +import com.clickhouse.data.value.ClickHouseGeoPolygonValue; +import com.clickhouse.data.value.ClickHouseGeoRingValue; + +import java.math.BigDecimal; +import java.math.BigInteger; +import java.net.Inet4Address; +import java.net.Inet6Address; +import java.time.Duration; +import java.time.Instant; +import java.time.LocalDate; +import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.OffsetDateTime; +import java.time.ZonedDateTime; +import java.time.temporal.TemporalAmount; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.UUID; + +public class JSONEachRowFormatReader implements ClickHouseBinaryFormatReader { + private final JsonParser parser; + private TableSchema schema; + private Map currentRow; + private Map firstRow; + private boolean firstRowRead = false; + + public JSONEachRowFormatReader(JsonParser parser) { + this.parser = parser; + try { + this.firstRow = parser.nextRow(); + if (firstRow != null) { + List columns = new ArrayList<>(); + for (String key : firstRow.keySet()) { + // For JSONEachRow we don't know the exact ClickHouse type, so we use a reasonable default. + // We can try to guess based on the value type in the first row. + columns.add(ClickHouseColumn.of(key, guessDataType(firstRow.get(key)), false)); + } + this.schema = new TableSchema(columns); + } else { + this.schema = new TableSchema(new ArrayList<>()); + } + } catch (Exception e) { + throw new RuntimeException("Failed to initialize JSON reader", e); + } + } + + private ClickHouseDataType guessDataType(Object value) { + if (value instanceof Number) { + if (value instanceof Integer || value instanceof Long || value instanceof BigInteger) { + return ClickHouseDataType.Int64; + } else if (value instanceof Double || value instanceof Float || value instanceof BigDecimal) { + double d = ((Number) value).doubleValue(); + if (d == Math.floor(d) && !Double.isInfinite(d) && d <= Long.MAX_VALUE && d >= Long.MIN_VALUE) { + return ClickHouseDataType.Int64; + } + return ClickHouseDataType.Float64; + } else { + return ClickHouseDataType.Float64; + } + } else if (value instanceof Boolean) { + return ClickHouseDataType.Bool; + } else { + return ClickHouseDataType.String; + } + } + + @Override + public T readValue(int colIndex) { + return (T) currentRow.get(schema.columnIndexToName(colIndex)); + } + + @Override + public T readValue(String colName) { + return (T) currentRow.get(colName); + } + + @Override + public boolean hasValue(String colName) { + return currentRow.containsKey(colName) && currentRow.get(colName) != null; + } + + @Override + public boolean hasValue(int colIndex) { + return hasValue(schema.columnIndexToName(colIndex)); + } + + @Override + public boolean hasNext() { + if (!firstRowRead) { + return firstRow != null; + } + return true; // We'll find out in next() + } + + @Override + public Map next() { + if (!firstRowRead) { + firstRowRead = true; + currentRow = firstRow; + return currentRow; + } + try { + currentRow = parser.nextRow(); + return currentRow; + } catch (Exception e) { + throw new RuntimeException("Failed to read next JSON row", e); + } + } + + @Override + public String getString(String colName) { + Object val = currentRow.get(colName); + return val == null ? null : val.toString(); + } + + @Override + public byte getByte(String colName) { + return ((Number) currentRow.get(colName)).byteValue(); + } + + @Override + public short getShort(String colName) { + return ((Number) currentRow.get(colName)).shortValue(); + } + + @Override + public int getInteger(String colName) { + return ((Number) currentRow.get(colName)).intValue(); + } + + @Override + public long getLong(String colName) { + return ((Number) currentRow.get(colName)).longValue(); + } + + @Override + public float getFloat(String colName) { + return ((Number) currentRow.get(colName)).floatValue(); + } + + @Override + public double getDouble(String colName) { + return ((Number) currentRow.get(colName)).doubleValue(); + } + + @Override + public boolean getBoolean(String colName) { + Object val = currentRow.get(colName); + if (val instanceof Boolean) return (Boolean) val; + if (val instanceof Number) return ((Number) val).intValue() != 0; + return Boolean.parseBoolean(val.toString()); + } + + @Override + public BigInteger getBigInteger(String colName) { + Object val = currentRow.get(colName); + if (val == null) return null; + if (val instanceof BigInteger) return (BigInteger) val; + return new BigDecimal(val.toString()).toBigInteger(); + } + + @Override + public BigDecimal getBigDecimal(String colName) { + Object val = currentRow.get(colName); + if (val instanceof BigDecimal) return (BigDecimal) val; + return new BigDecimal(val.toString()); + } + + @Override + public Instant getInstant(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public ZonedDateTime getZonedDateTime(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public Duration getDuration(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public Inet4Address getInet4Address(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public Inet6Address getInet6Address(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public UUID getUUID(String colName) { + return UUID.fromString(currentRow.get(colName).toString()); + } + + @Override + public ClickHouseGeoPointValue getGeoPoint(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public ClickHouseGeoRingValue getGeoRing(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public ClickHouseGeoPolygonValue getGeoPolygon(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public ClickHouseGeoMultiPolygonValue getGeoMultiPolygon(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public List getList(String colName) { + return (List) currentRow.get(colName); + } + + @Override + public byte[] getByteArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public int[] getIntArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public long[] getLongArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public float[] getFloatArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public double[] getDoubleArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public boolean[] getBooleanArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public short[] getShortArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public String[] getStringArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public Object[] getObjectArray(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public String getString(int index) { + return getString(schema.columnIndexToName(index)); + } + + @Override + public byte getByte(int index) { + return getByte(schema.columnIndexToName(index)); + } + + @Override + public short getShort(int index) { + return getShort(schema.columnIndexToName(index)); + } + + @Override + public int getInteger(int index) { + return getInteger(schema.columnIndexToName(index)); + } + + @Override + public long getLong(int index) { + return getLong(schema.columnIndexToName(index)); + } + + @Override + public float getFloat(int index) { + return getFloat(schema.columnIndexToName(index)); + } + + @Override + public double getDouble(int index) { + return getDouble(schema.columnIndexToName(index)); + } + + @Override + public boolean getBoolean(int index) { + return getBoolean(schema.columnIndexToName(index)); + } + + @Override + public BigInteger getBigInteger(int index) { + return getBigInteger(schema.columnIndexToName(index)); + } + + @Override + public BigDecimal getBigDecimal(int index) { + return getBigDecimal(schema.columnIndexToName(index)); + } + + @Override + public Instant getInstant(int index) { + return getInstant(schema.columnIndexToName(index)); + } + + @Override + public ZonedDateTime getZonedDateTime(int index) { + return getZonedDateTime(schema.columnIndexToName(index)); + } + + @Override + public Duration getDuration(int index) { + return getDuration(schema.columnIndexToName(index)); + } + + @Override + public Inet4Address getInet4Address(int index) { + return getInet4Address(schema.columnIndexToName(index)); + } + + @Override + public Inet6Address getInet6Address(int index) { + return getInet6Address(schema.columnIndexToName(index)); + } + + @Override + public UUID getUUID(int index) { + return getUUID(schema.columnIndexToName(index)); + } + + @Override + public ClickHouseGeoPointValue getGeoPoint(int index) { + return getGeoPoint(schema.columnIndexToName(index)); + } + + @Override + public ClickHouseGeoRingValue getGeoRing(int index) { + return getGeoRing(schema.columnIndexToName(index)); + } + + @Override + public ClickHouseGeoPolygonValue getGeoPolygon(int index) { + return getGeoPolygon(schema.columnIndexToName(index)); + } + + @Override + public ClickHouseGeoMultiPolygonValue getGeoMultiPolygon(int index) { + return getGeoMultiPolygon(schema.columnIndexToName(index)); + } + + @Override + public List getList(int index) { + return getList(schema.columnIndexToName(index)); + } + + @Override + public byte[] getByteArray(int index) { + return getByteArray(schema.columnIndexToName(index)); + } + + @Override + public int[] getIntArray(int index) { + return getIntArray(schema.columnIndexToName(index)); + } + + @Override + public long[] getLongArray(int index) { + return getLongArray(schema.columnIndexToName(index)); + } + + @Override + public float[] getFloatArray(int index) { + return getFloatArray(schema.columnIndexToName(index)); + } + + @Override + public double[] getDoubleArray(int index) { + return getDoubleArray(schema.columnIndexToName(index)); + } + + @Override + public boolean[] getBooleanArray(int index) { + return getBooleanArray(schema.columnIndexToName(index)); + } + + @Override + public short[] getShortArray(int index) { + return getShortArray(schema.columnIndexToName(index)); + } + + @Override + public String[] getStringArray(int index) { + return getStringArray(schema.columnIndexToName(index)); + } + + @Override + public Object[] getObjectArray(int index) { + return getObjectArray(schema.columnIndexToName(index)); + } + + @Override + public Object[] getTuple(int index) { + return getTuple(schema.columnIndexToName(index)); + } + + @Override + public Object[] getTuple(String colName) { + return (Object[]) currentRow.get(colName); + } + + @Override + public byte getEnum8(String colName) { + return getByte(colName); + } + + @Override + public byte getEnum8(int index) { + return getByte(index); + } + + @Override + public short getEnum16(String colName) { + return getShort(colName); + } + + @Override + public short getEnum16(int index) { + return getShort(index); + } + + @Override + public LocalDate getLocalDate(String colName) { + return LocalDate.parse(currentRow.get(colName).toString()); + } + + @Override + public LocalDate getLocalDate(int index) { + return getLocalDate(schema.columnIndexToName(index)); + } + + @Override + public LocalTime getLocalTime(String colName) { + return LocalTime.parse(currentRow.get(colName).toString()); + } + + @Override + public LocalTime getLocalTime(int index) { + return getLocalTime(schema.columnIndexToName(index)); + } + + @Override + public LocalDateTime getLocalDateTime(String colName) { + return LocalDateTime.parse(currentRow.get(colName).toString()); + } + + @Override + public LocalDateTime getLocalDateTime(int index) { + return getLocalDateTime(schema.columnIndexToName(index)); + } + + @Override + public OffsetDateTime getOffsetDateTime(String colName) { + return OffsetDateTime.parse(currentRow.get(colName).toString()); + } + + @Override + public OffsetDateTime getOffsetDateTime(int index) { + return getOffsetDateTime(schema.columnIndexToName(index)); + } + + @Override + public TableSchema getSchema() { + return schema; + } + + @Override + public ClickHouseBitmap getClickHouseBitmap(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public ClickHouseBitmap getClickHouseBitmap(int index) { + throw new UnsupportedOperationException(); + } + + @Override + public TemporalAmount getTemporalAmount(int index) { + throw new UnsupportedOperationException(); + } + + @Override + public TemporalAmount getTemporalAmount(String colName) { + throw new UnsupportedOperationException(); + } + + @Override + public void close() throws Exception { + parser.close(); + } +} diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/GsonJsonParser.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/GsonJsonParser.java new file mode 100644 index 000000000..fe70ec93f --- /dev/null +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/GsonJsonParser.java @@ -0,0 +1,39 @@ +package com.clickhouse.client.api.data_formats.internal; + +import com.google.gson.Gson; +import com.google.gson.reflect.TypeToken; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonToken; + +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.Map; + +public class GsonJsonParser implements JsonParser { + private final Gson gson; + private final JsonReader reader; + + public GsonJsonParser(InputStream inputStream) { + this.gson = new Gson(); + this.reader = new JsonReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8)); + this.reader.setLenient(true); // JSONEachRow needs lenient reader for multiple root objects + } + + @Override + public Map nextRow() throws Exception { + try { + if (reader.peek() == JsonToken.END_DOCUMENT) { + return null; + } + } catch (java.io.EOFException e) { + return null; + } + return gson.fromJson(reader, new TypeToken>() {}.getType()); + } + + @Override + public void close() throws Exception { + reader.close(); + } +} diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JacksonJsonParser.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JacksonJsonParser.java new file mode 100644 index 000000000..e406ba5cc --- /dev/null +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JacksonJsonParser.java @@ -0,0 +1,49 @@ +package com.clickhouse.client.api.data_formats.internal; + +import com.fasterxml.jackson.core.JsonFactory; +import com.fasterxml.jackson.core.JsonToken; +import com.fasterxml.jackson.databind.ObjectMapper; + +import java.io.InputStream; +import java.util.Map; + +public class JacksonJsonParser implements com.clickhouse.client.api.data_formats.internal.JsonParser { + private final ObjectMapper mapper; + private final JsonFactory factory; + private com.fasterxml.jackson.core.JsonParser parser; + + public JacksonJsonParser(InputStream inputStream) { + this.mapper = new ObjectMapper(); + this.factory = new JsonFactory(); + try { + this.parser = factory.createParser(inputStream); + } catch (Exception e) { + throw new RuntimeException("Failed to create Jackson parser", e); + } + } + + @Override + public Map nextRow() throws Exception { + if (parser.nextToken() == null) { + return null; + } + if (parser.currentToken() != JsonToken.START_OBJECT) { + // Handle cases where there might be extra characters between objects, + // like newlines in JSONEachRow. + while (parser.nextToken() != null && parser.currentToken() != JsonToken.START_OBJECT) { + // skip + } + if (parser.currentToken() == null) { + return null; + } + } + return mapper.readValue(parser, Map.class); + } + + @Override + public void close() throws Exception { + if (parser != null) { + parser.close(); + } + } +} diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParser.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParser.java new file mode 100644 index 000000000..2d02dabb3 --- /dev/null +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParser.java @@ -0,0 +1,15 @@ +package com.clickhouse.client.api.data_formats.internal; + +import java.util.Map; + +/** + * Interface for JSON row processors. + */ +public interface JsonParser extends AutoCloseable { + /** + * Reads next row from the input stream. + * @return map of column names to values, or null if no more rows + * @throws Exception if an error occurs during parsing + */ + Map nextRow() throws Exception; +} diff --git a/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParserFactory.java b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParserFactory.java new file mode 100644 index 000000000..0e86fd70a --- /dev/null +++ b/client-v2/src/main/java/com/clickhouse/client/api/data_formats/internal/JsonParserFactory.java @@ -0,0 +1,27 @@ +package com.clickhouse.client.api.data_formats.internal; + +import java.io.InputStream; +import java.lang.reflect.Constructor; + +public class JsonParserFactory { + public static JsonParser createParser(String type, InputStream inputStream) { + String className; + if ("JACKSON".equalsIgnoreCase(type)) { + className = "com.clickhouse.client.api.data_formats.internal.JacksonJsonParser"; + } else if ("GSON".equalsIgnoreCase(type)) { + className = "com.clickhouse.client.api.data_formats.internal.GsonJsonParser"; + } else { + throw new IllegalArgumentException("Unsupported JSON processor: " + type + ". Supported: JACKSON, GSON"); + } + + try { + Class clazz = Class.forName(className); + Constructor constructor = clazz.getConstructor(InputStream.class); + return (JsonParser) constructor.newInstance(inputStream); + } catch (ClassNotFoundException e) { + throw new RuntimeException("JSON processor class not found: " + className + ". Make sure you have the required library (Jackson or Gson) on your classpath.", e); + } catch (Exception e) { + throw new RuntimeException("Failed to instantiate JSON processor: " + type, e); + } + } +} diff --git a/client-v2/src/test/java/com/clickhouse/client/ClientTests.java b/client-v2/src/test/java/com/clickhouse/client/ClientTests.java index 0508d9e58..07154058c 100644 --- a/client-v2/src/test/java/com/clickhouse/client/ClientTests.java +++ b/client-v2/src/test/java/com/clickhouse/client/ClientTests.java @@ -329,7 +329,7 @@ public void testDefaultSettings() { Assert.assertEquals(config.get(p.getKey()), p.getDefaultValue(), "Default value doesn't match"); } } - Assert.assertEquals(config.size(), 34); // to check everything is set. Increment when new added. + Assert.assertEquals(config.size(), 35); // to check everything is set. Increment when new added. } try (Client client = new Client.Builder() @@ -362,7 +362,7 @@ public void testDefaultSettings() { .setSocketSndbuf(100000) .build()) { Map config = client.getConfiguration(); - Assert.assertEquals(config.size(), 35); // to check everything is set. Increment when new added. + Assert.assertEquals(config.size(), 36); // to check everything is set. Increment when new added. Assert.assertEquals(config.get(ClientConfigProperties.DATABASE.getKey()), "mydb"); Assert.assertEquals(config.get(ClientConfigProperties.MAX_EXECUTION_TIME.getKey()), "10"); Assert.assertEquals(config.get(ClientConfigProperties.COMPRESSION_LZ4_UNCOMPRESSED_BUF_SIZE.getKey()), "300000"); @@ -429,7 +429,7 @@ public void testWithOldDefaults() { Assert.assertEquals(config.get(p.getKey()), p.getDefaultValue(), "Default value doesn't match"); } } - Assert.assertEquals(config.size(), 34); // to check everything is set. Increment when new added. + Assert.assertEquals(config.size(), 35); // to check everything is set. Increment when new added. } } diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/AbstractJSONEachRowFormatReaderTests.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/AbstractJSONEachRowFormatReaderTests.java new file mode 100644 index 000000000..1a760c334 --- /dev/null +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/AbstractJSONEachRowFormatReaderTests.java @@ -0,0 +1,130 @@ +package com.clickhouse.client.api.data_formats; + +import com.clickhouse.client.BaseIntegrationTest; +import com.clickhouse.client.ClickHouseNode; +import com.clickhouse.client.ClickHouseProtocol; +import com.clickhouse.client.ClickHouseServerForTest; +import com.clickhouse.client.api.Client; +import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.client.api.enums.Protocol; +import com.clickhouse.client.api.query.QueryResponse; +import com.clickhouse.client.api.query.QuerySettings; +import com.clickhouse.data.ClickHouseDataType; +import com.clickhouse.data.ClickHouseFormat; +import org.testng.Assert; +import org.testng.annotations.AfterMethod; +import org.testng.annotations.BeforeMethod; +import org.testng.annotations.Test; + +import java.util.Map; + +public abstract class AbstractJSONEachRowFormatReaderTests extends BaseIntegrationTest { + + protected Client client; + + protected abstract String getProcessor(); + + @BeforeMethod(groups = {"integration"}) + public void setUp() { + ClickHouseNode node = getServer(ClickHouseProtocol.HTTP); + client = new Client.Builder() + .addEndpoint(Protocol.HTTP, node.getHost(), node.getPort(), isCloud()) + .setUsername("default") + .setPassword(ClickHouseServerForTest.getPassword()) + .setOption(ClientConfigProperties.JSON_PROCESSOR.getKey(), getProcessor()) + .build(); + } + + @AfterMethod(groups = {"integration"}) + public void tearDown() { + if (client != null) { + client.close(); + } + } + + private QuerySettings newJsonEachRowSettings() { + return new QuerySettings() + .setFormat(ClickHouseFormat.JSONEachRow); + } + + @Test(groups = {"integration"}) + public void testBasicParsing() throws Exception { + String sql = "SELECT 1 as id, 'test' as name, true as active " + + "UNION ALL SELECT 2, 'clickhouse', false"; + + try (QueryResponse response = client.query(sql, newJsonEachRowSettings()).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + + // First row + Assert.assertTrue(reader.hasNext()); + Map row1 = reader.next(); + Assert.assertNotNull(row1); + Assert.assertEquals(reader.getInteger("id"), 1); + Assert.assertEquals(reader.getString("name"), "test"); + Assert.assertEquals(reader.getBoolean("active"), true); + + // Second row + Assert.assertTrue(reader.hasNext()); + Map row2 = reader.next(); + Assert.assertNotNull(row2); + Assert.assertEquals(reader.getInteger("id"), 2); + Assert.assertEquals(reader.getString("name"), "clickhouse"); + Assert.assertEquals(reader.getBoolean("active"), false); + + // No more rows + Assert.assertNull(reader.next()); + } + } + + @Test(groups = {"integration"}) + public void testSchemaInference() throws Exception { + String sql = "SELECT toInt64(42) as col_int, toFloat64(3.14) as col_float, " + + "true as col_bool, 'val' as col_str"; + + try (QueryResponse response = client.query(sql, newJsonEachRowSettings()).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + + Assert.assertNotNull(reader.getSchema()); + Assert.assertEquals(reader.getSchema().getColumns().size(), 4); + + Assert.assertEquals(reader.getSchema().getColumnByIndex(1).getDataType(), ClickHouseDataType.Int64); + Assert.assertEquals(reader.getSchema().getColumnByIndex(2).getDataType(), ClickHouseDataType.Float64); + Assert.assertEquals(reader.getSchema().getColumnByIndex(3).getDataType(), ClickHouseDataType.Bool); + Assert.assertEquals(reader.getSchema().getColumnByIndex(4).getDataType(), ClickHouseDataType.String); + } + } + + @Test(groups = {"integration"}) + public void testDataTypes() throws Exception { + String sql = "SELECT toInt8(120) as b, toInt16(30000) as s, toInt32(1000000) as i, " + + "toInt64(10000000000) as l, toFloat32(1.23) as f, toFloat64(1.23456789) as d, " + + "true as bool, 'hello' as str"; + + try (QueryResponse response = client.query(sql, newJsonEachRowSettings()).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + + reader.next(); + Assert.assertEquals(reader.getByte("b"), (byte) 120); + Assert.assertEquals(reader.getShort("s"), (short) 30000); + Assert.assertEquals(reader.getInteger("i"), 1000000); + Assert.assertEquals(reader.getLong("l"), 10000000000L); + Assert.assertEquals(reader.getFloat("f"), 1.23f, 0.001f); + Assert.assertEquals(reader.getDouble("d"), 1.23456789d, 0.00000001d); + Assert.assertEquals(reader.getBoolean("bool"), true); + Assert.assertEquals(reader.getString("str"), "hello"); + } + } + + @Test(groups = {"integration"}) + public void testEmptyData() throws Exception { + String sql = "SELECT * FROM remote('127.0.0.1', system.one) WHERE dummy > 1"; + + try (QueryResponse response = client.query(sql, newJsonEachRowSettings()).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + + Assert.assertFalse(reader.hasNext()); + Assert.assertNull(reader.next()); + Assert.assertEquals(reader.getSchema().getColumns().size(), 0); + } + } +} diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/GsonJSONEachRowFormatReaderTests.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/GsonJSONEachRowFormatReaderTests.java new file mode 100644 index 000000000..58573da0c --- /dev/null +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/GsonJSONEachRowFormatReaderTests.java @@ -0,0 +1,11 @@ +package com.clickhouse.client.api.data_formats; + +import org.testng.annotations.Test; + +@Test(groups = {"integration"}) +public class GsonJSONEachRowFormatReaderTests extends AbstractJSONEachRowFormatReaderTests { + @Override + protected String getProcessor() { + return "GSON"; + } +} diff --git a/client-v2/src/test/java/com/clickhouse/client/api/data_formats/JacksonJSONEachRowFormatReaderTests.java b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/JacksonJSONEachRowFormatReaderTests.java new file mode 100644 index 000000000..8689504bb --- /dev/null +++ b/client-v2/src/test/java/com/clickhouse/client/api/data_formats/JacksonJSONEachRowFormatReaderTests.java @@ -0,0 +1,13 @@ +package com.clickhouse.client.api.data_formats; + +import org.testng.Assert; +import org.testng.annotations.Test; + +@Test(groups = {"integration"}) +public class JacksonJSONEachRowFormatReaderTests extends AbstractJSONEachRowFormatReaderTests { + + @Override + protected String getProcessor() { + return "JACKSON"; + } +} diff --git a/examples/client-v2-json-processors/.gitignore b/examples/client-v2-json-processors/.gitignore new file mode 100644 index 000000000..f8b92c3aa --- /dev/null +++ b/examples/client-v2-json-processors/.gitignore @@ -0,0 +1,2 @@ +.gradle +build diff --git a/examples/client-v2-json-processors/README.md b/examples/client-v2-json-processors/README.md new file mode 100644 index 000000000..f8cd7dbe5 --- /dev/null +++ b/examples/client-v2-json-processors/README.md @@ -0,0 +1,58 @@ +# Client V2 JSON Processors Example + +## Overview + +This standalone example shows how to configure `client-v2` to read `JSONEachRow` +responses with both supported JSON processors using one shared table and one +shared dataset: + +- `JACKSON` +- `GSON` + +## Requirements + +- JDK 17 or newer +- A running ClickHouse server reachable from the machine running the example +- A locally installed `client-v2` snapshot from this repository + +## How to Run + +From this directory: + +```shell +gradle run +``` + +Connection properties can be supplied as system properties: + +- `-DchEndpoint` - Endpoint to connect to (default: `http://localhost:8123`) +- `-DchUser` - ClickHouse user name (default: `default`) +- `-DchPassword` - ClickHouse user password (default: empty) +- `-DchDatabase` - ClickHouse database name (default: `default`) + +Example with custom connection properties: + +```shell +gradle run \ + -DchEndpoint=http://localhost:8123 \ + -DchUser=default \ + -DchPassword= \ + -DchDatabase=default +``` + +## Executable Example + +`com.clickhouse.examples.client_v2.json_processors.ClientV2JsonProcessorsExample` + +- Runs the following steps in order: + 1. defines table `client_v2_json_processors_example` with primitive columns + and one `payload JSON` column; + 2. loads sample rows from `src/main/resources/sample_data.csv` into that table; + 3. reads the same rows with `runGsonExample(...)`; + 4. reads the same rows again with `runJacksonExample(...)`. +- Reads rows back through `client.newBinaryFormatReader(response)` and logs the + primitive columns together with the parsed JSON object from `payload`. + +The build keeps both `jackson-databind` and `gson` on the classpath so the +example can switch between processors at runtime. Production applications only +need to keep the processor they actually use. diff --git a/examples/client-v2-json-processors/build.gradle.kts b/examples/client-v2-json-processors/build.gradle.kts new file mode 100644 index 000000000..59ec03181 --- /dev/null +++ b/examples/client-v2-json-processors/build.gradle.kts @@ -0,0 +1,37 @@ +plugins { + application +} + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation(libs.clickhouseClient) + + // Keep both processors on the classpath so the example can switch between them. + implementation(libs.jacksonDatabind) + implementation(libs.gson) + + implementation(libs.slf4jApi) + runtimeOnly(libs.slf4jSimple) +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +application { + mainClass = "com.clickhouse.examples.client_v2.json_processors.ClientV2JsonProcessorsExample" +} + +tasks.named("run") { + listOf("chEndpoint", "chUser", "chPassword", "chDatabase", "jsonProcessor").forEach { key -> + System.getProperty(key)?.let { value -> + systemProperty(key, value) + } + } +} diff --git a/examples/client-v2-json-processors/gradle.properties b/examples/client-v2-json-processors/gradle.properties new file mode 100644 index 000000000..5ad69748c --- /dev/null +++ b/examples/client-v2-json-processors/gradle.properties @@ -0,0 +1 @@ +org.gradle.configuration-cache=true diff --git a/examples/client-v2-json-processors/gradle/libs.versions.toml b/examples/client-v2-json-processors/gradle/libs.versions.toml new file mode 100644 index 000000000..7379edc0e --- /dev/null +++ b/examples/client-v2-json-processors/gradle/libs.versions.toml @@ -0,0 +1,12 @@ +[versions] +clickhouseClient = "0.9.8-SNAPSHOT" +jackson = "2.18.6" +gson = "2.10.1" +slf4j = "2.0.17" + +[libraries] +clickhouseClient = { module = "com.clickhouse:client-v2", version.ref = "clickhouseClient" } +jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } +slf4jApi = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4jSimple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } diff --git a/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.jar b/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..d997cfc60 Binary files /dev/null and b/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.properties b/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..c61a118f7 --- /dev/null +++ b/examples/client-v2-json-processors/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/examples/client-v2-json-processors/gradlew b/examples/client-v2-json-processors/gradlew new file mode 100755 index 000000000..739907dfd --- /dev/null +++ b/examples/client-v2-json-processors/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/examples/client-v2-json-processors/gradlew.bat b/examples/client-v2-json-processors/gradlew.bat new file mode 100644 index 000000000..e509b2dd8 --- /dev/null +++ b/examples/client-v2-json-processors/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/client-v2-json-processors/settings.gradle.kts b/examples/client-v2-json-processors/settings.gradle.kts new file mode 100644 index 000000000..8b35c469e --- /dev/null +++ b/examples/client-v2-json-processors/settings.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "ch-java-client-v2-json-processors" diff --git a/examples/client-v2-json-processors/src/main/java/com/clickhouse/examples/client_v2/json_processors/ClientV2JsonProcessorsExample.java b/examples/client-v2-json-processors/src/main/java/com/clickhouse/examples/client_v2/json_processors/ClientV2JsonProcessorsExample.java new file mode 100644 index 000000000..2f91afa38 --- /dev/null +++ b/examples/client-v2-json-processors/src/main/java/com/clickhouse/examples/client_v2/json_processors/ClientV2JsonProcessorsExample.java @@ -0,0 +1,240 @@ +package com.clickhouse.examples.client_v2.json_processors; + +import com.clickhouse.client.api.Client; +import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.client.api.command.CommandResponse; +import com.clickhouse.client.api.data_formats.ClickHouseBinaryFormatReader; +import com.clickhouse.client.api.query.QueryResponse; +import com.clickhouse.client.api.query.QuerySettings; +import com.clickhouse.data.ClickHouseFormat; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class ClientV2JsonProcessorsExample { + private static final Logger LOG = LoggerFactory.getLogger(ClientV2JsonProcessorsExample.class); + private static final String TABLE_NAME = "client_v2_json_processors_example"; + private static final String SAMPLE_DATA_RESOURCE = "/sample_data.csv"; + private static final String CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + + "id UInt32, " + + "name String, " + + "active Bool, " + + "score Float64, " + + "payload JSON" + + ") ENGINE = MergeTree ORDER BY id"; + private static final String SELECT_DATA_SQL = "SELECT id, name, active, score, payload " + + "FROM " + TABLE_NAME + " ORDER BY id"; + + public static void main(String[] args) throws Exception { + ConnectionConfig config = ConnectionConfig.load(); + defineTableStructure(config); + loadData(config); + + runGsonExample(config); + runJacksonExample(config); + } + + private static void defineTableStructure(ConnectionConfig config) throws Exception { + LOG.info("Step 1. Defining table structure: {}", TABLE_NAME); + try (Client client = createClient(config, "GSON")) { + executeStatement(client, "DROP TABLE IF EXISTS " + TABLE_NAME); + executeStatement(client, CREATE_TABLE_SQL); + } + } + + private static void loadData(ConnectionConfig config) throws Exception { + List rows = readSampleRows(); + LOG.info("Step 2. Loading {} sample rows from {} into {}", rows.size(), SAMPLE_DATA_RESOURCE, TABLE_NAME); + try (Client client = createClient(config, "GSON")) { + executeStatement(client, "TRUNCATE TABLE " + TABLE_NAME); + executeStatement(client, buildInsertSql(rows)); + } + } + + private static void runJacksonExample(ConnectionConfig config) throws Exception { + LOG.info("Step 4. Running client-v2 example with Jackson"); + try (Client client = createClient(config, "JACKSON")) { + readRows(client, "JACKSON"); + } + } + + private static void runGsonExample(ConnectionConfig config) throws Exception { + LOG.info("Step 3. Running client-v2 example with Gson"); + try (Client client = createClient(config, "GSON")) { + readRows(client, "GSON"); + } + } + + private static void readRows(Client client, String processor) throws Exception { + try (QueryResponse response = client.query(SELECT_DATA_SQL, new QuerySettings().setFormat(ClickHouseFormat.JSONEachRow)).get()) { + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response); + while (reader.next() != null) { + Map payload = reader.readValue("payload"); + LOG.info("[{}] id={}, name={}, active={}, score={}, payload={}({})", + processor, + reader.getInteger("id"), + reader.getString("name"), + reader.getBoolean("active"), + reader.getDouble("score"), + payload.getClass().getName(), + payload); + } + } + } + + private static Client createClient(ConnectionConfig config, String processor) { + return new Client.Builder() + .addEndpoint(config.endpoint) + .setUsername(config.user) + .setPassword(config.password) + .setDefaultDatabase(config.database) + .serverSetting("allow_experimental_json_type", "1") + .setOption(ClientConfigProperties.JSON_PROCESSOR.getKey(), processor) + .build(); + } + + private static void executeStatement(Client client, String sql) throws Exception { + try (CommandResponse ignored = client.execute(sql).get()) { + LOG.debug("Executed SQL: {}", sql); + } + } + + private static List readSampleRows() throws IOException { + InputStream stream = ClientV2JsonProcessorsExample.class.getResourceAsStream(SAMPLE_DATA_RESOURCE); + if (stream == null) { + throw new IOException("Resource not found: " + SAMPLE_DATA_RESOURCE); + } + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { + String header = reader.readLine(); + if (header == null) { + throw new IOException("CSV resource is empty: " + SAMPLE_DATA_RESOURCE); + } + + List rows = new ArrayList<>(); + String line; + while ((line = reader.readLine()) != null) { + if (line.trim().isEmpty()) { + continue; + } + + List values = parseCsvLine(line); + if (values.size() != 5) { + throw new IOException("Expected 5 columns in sample CSV but found " + values.size() + ": " + line); + } + + rows.add(new SampleRow( + Integer.parseInt(values.get(0)), + values.get(1), + Boolean.parseBoolean(values.get(2)), + Double.parseDouble(values.get(3)), + values.get(4))); + } + + return rows; + } + } + + private static List parseCsvLine(String line) { + List values = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + boolean inQuotes = false; + + for (int i = 0; i < line.length(); i++) { + char ch = line.charAt(i); + if (ch == '"') { + if (inQuotes && i + 1 < line.length() && line.charAt(i + 1) == '"') { + current.append('"'); + i++; + } else { + inQuotes = !inQuotes; + } + } else if (ch == ',' && !inQuotes) { + values.add(current.toString()); + current.setLength(0); + } else { + current.append(ch); + } + } + + values.add(current.toString()); + return values; + } + + private static String buildInsertSql(List rows) { + if (rows.isEmpty()) { + throw new IllegalArgumentException("Sample CSV does not contain any rows"); + } + + StringBuilder sql = new StringBuilder("INSERT INTO ") + .append(TABLE_NAME) + .append(" (id, name, active, score, payload) VALUES "); + + for (SampleRow row : rows) { + sql.append('(') + .append(row.id) + .append(", ") + .append(quoteSqlString(row.name)) + .append(", ") + .append(row.active) + .append(", ") + .append(row.score) + .append(", ") + .append(quoteSqlString(row.payload)) + .append("), "); + } + + sql.setLength(sql.length() - 2); + return sql.toString(); + } + + private static String quoteSqlString(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + private static final class SampleRow { + private final int id; + private final String name; + private final boolean active; + private final double score; + private final String payload; + + private SampleRow(int id, String name, boolean active, double score, String payload) { + this.id = id; + this.name = name; + this.active = active; + this.score = score; + this.payload = payload; + } + } + + private static final class ConnectionConfig { + private final String endpoint; + private final String user; + private final String password; + private final String database; + + private ConnectionConfig(String endpoint, String user, String password, String database) { + this.endpoint = endpoint; + this.user = user; + this.password = password; + this.database = database; + } + + private static ConnectionConfig load() { + return new ConnectionConfig( + System.getProperty("chEndpoint", "http://localhost:8123"), + System.getProperty("chUser", "default"), + System.getProperty("chPassword", ""), + System.getProperty("chDatabase", "default")); + } + } +} diff --git a/examples/jdbc-v2-json-processors/.gitignore b/examples/jdbc-v2-json-processors/.gitignore new file mode 100644 index 000000000..f8b92c3aa --- /dev/null +++ b/examples/jdbc-v2-json-processors/.gitignore @@ -0,0 +1,2 @@ +.gradle +build diff --git a/examples/jdbc-v2-json-processors/README.md b/examples/jdbc-v2-json-processors/README.md new file mode 100644 index 000000000..c22f2e5ad --- /dev/null +++ b/examples/jdbc-v2-json-processors/README.md @@ -0,0 +1,56 @@ +# JDBC V2 JSON Processors Example + +## Overview + +This standalone example shows how to configure `jdbc-v2` to read +`FORMAT JSONEachRow` results with both supported JSON processors using one +shared table and one shared dataset: + +- `JACKSON` +- `GSON` + +## Requirements + +- JDK 17 or newer +- A running ClickHouse server reachable from the machine running the example +- A locally installed `jdbc-v2` snapshot from this repository + +## How to Run + +From this directory: + +```shell +gradle run +``` + +Connection properties can be supplied as system properties: + +- `-DchUrl` - JDBC URL (default: `jdbc:clickhouse://localhost:8123/default`) +- `-DchUser` - ClickHouse user name (default: `default`) +- `-DchPassword` - ClickHouse user password (default: empty) + +Example with custom connection properties: + +```shell +gradle run \ + -DchUrl=jdbc:clickhouse://localhost:8123/default \ + -DchUser=default \ + -DchPassword= +``` + +## Executable Example + +`com.clickhouse.examples.jdbc_v2.json_processors.JdbcV2JsonProcessorsExample` + +- Runs the following steps in order: + 1. defines table `jdbc_v2_json_processors_example` with primitive columns and + one `payload JSON` column; + 2. loads sample rows from `src/main/resources/sample_data.csv` into that table; + 3. reads the same rows with `runGsonExample(...)`; + 4. reads the same rows again with `runJacksonExample(...)`. +- Reads rows back through `ResultSet` and logs the primitive columns together + with the parsed JSON object from `payload`. + +The build keeps both `jackson-databind` and `gson` on the classpath so the +example can switch between processors at runtime. Production applications only +need to keep the processor they actually use. diff --git a/examples/jdbc-v2-json-processors/build.gradle.kts b/examples/jdbc-v2-json-processors/build.gradle.kts new file mode 100644 index 000000000..65b501e3e --- /dev/null +++ b/examples/jdbc-v2-json-processors/build.gradle.kts @@ -0,0 +1,37 @@ +plugins { + application +} + +repositories { + mavenLocal() + mavenCentral() +} + +dependencies { + implementation(libs.jdbcV2) + + // Keep both processors on the classpath so the example can switch between them. + implementation(libs.jacksonDatabind) + implementation(libs.gson) + + implementation(libs.slf4jApi) + runtimeOnly(libs.slf4jSimple) +} + +java { + toolchain { + languageVersion = JavaLanguageVersion.of(17) + } +} + +application { + mainClass = "com.clickhouse.examples.jdbc_v2.json_processors.JdbcV2JsonProcessorsExample" +} + +tasks.named("run") { + listOf("chUrl", "chUser", "chPassword", "jsonProcessor").forEach { key -> + System.getProperty(key)?.let { value -> + systemProperty(key, value) + } + } +} diff --git a/examples/jdbc-v2-json-processors/gradle.properties b/examples/jdbc-v2-json-processors/gradle.properties new file mode 100644 index 000000000..5ad69748c --- /dev/null +++ b/examples/jdbc-v2-json-processors/gradle.properties @@ -0,0 +1 @@ +org.gradle.configuration-cache=true diff --git a/examples/jdbc-v2-json-processors/gradle/libs.versions.toml b/examples/jdbc-v2-json-processors/gradle/libs.versions.toml new file mode 100644 index 000000000..6ac8a57a6 --- /dev/null +++ b/examples/jdbc-v2-json-processors/gradle/libs.versions.toml @@ -0,0 +1,12 @@ +[versions] +jdbcV2 = "0.9.8-SNAPSHOT" +jackson = "2.18.6" +gson = "2.10.1" +slf4j = "2.0.17" + +[libraries] +jdbcV2 = { module = "com.clickhouse:jdbc-v2", version.ref = "jdbcV2" } +jacksonDatabind = { module = "com.fasterxml.jackson.core:jackson-databind", version.ref = "jackson" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } +slf4jApi = { module = "org.slf4j:slf4j-api", version.ref = "slf4j" } +slf4jSimple = { module = "org.slf4j:slf4j-simple", version.ref = "slf4j" } diff --git a/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.jar b/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000..d997cfc60 Binary files /dev/null and b/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.jar differ diff --git a/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.properties b/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000..c61a118f7 --- /dev/null +++ b/examples/jdbc-v2-json-processors/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,7 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-9.4.1-bin.zip +networkTimeout=10000 +validateDistributionUrl=true +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/examples/jdbc-v2-json-processors/gradlew b/examples/jdbc-v2-json-processors/gradlew new file mode 100755 index 000000000..739907dfd --- /dev/null +++ b/examples/jdbc-v2-json-processors/gradlew @@ -0,0 +1,248 @@ +#!/bin/sh + +# +# Copyright © 2015 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/2d6327017519d23b96af35865dc997fcb544fb40/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -jar "$APP_HOME/gradle/wrapper/gradle-wrapper.jar" \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/examples/jdbc-v2-json-processors/gradlew.bat b/examples/jdbc-v2-json-processors/gradlew.bat new file mode 100644 index 000000000..e509b2dd8 --- /dev/null +++ b/examples/jdbc-v2-json-processors/gradlew.bat @@ -0,0 +1,93 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -jar "%APP_HOME%\gradle\wrapper\gradle-wrapper.jar" %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/examples/jdbc-v2-json-processors/settings.gradle.kts b/examples/jdbc-v2-json-processors/settings.gradle.kts new file mode 100644 index 000000000..4cb564e86 --- /dev/null +++ b/examples/jdbc-v2-json-processors/settings.gradle.kts @@ -0,0 +1,5 @@ +plugins { + id("org.gradle.toolchains.foojay-resolver-convention") version "1.0.0" +} + +rootProject.name = "ch-java-jdbc-v2-json-processors" diff --git a/examples/jdbc-v2-json-processors/src/main/java/com/clickhouse/examples/jdbc_v2/json_processors/JdbcV2JsonProcessorsExample.java b/examples/jdbc-v2-json-processors/src/main/java/com/clickhouse/examples/jdbc_v2/json_processors/JdbcV2JsonProcessorsExample.java new file mode 100644 index 000000000..58a465a1b --- /dev/null +++ b/examples/jdbc-v2-json-processors/src/main/java/com/clickhouse/examples/jdbc_v2/json_processors/JdbcV2JsonProcessorsExample.java @@ -0,0 +1,221 @@ +package com.clickhouse.examples.jdbc_v2.json_processors; + +import com.clickhouse.client.api.ClientConfigProperties; +import com.clickhouse.jdbc.Driver; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.ResultSet; +import java.sql.Statement; +import java.util.ArrayList; +import java.util.List; +import java.util.Properties; + +public class JdbcV2JsonProcessorsExample { + private static final Logger LOG = LoggerFactory.getLogger(JdbcV2JsonProcessorsExample.class); + private static final String TABLE_NAME = "jdbc_v2_json_processors_example"; + private static final String SAMPLE_DATA_RESOURCE = "/sample_data.csv"; + private static final String CREATE_TABLE_SQL = "CREATE TABLE " + TABLE_NAME + " (" + + "id UInt32, " + + "name String, " + + "active Bool, " + + "score Float64, " + + "payload JSON" + + ") ENGINE = MergeTree ORDER BY id"; + private static final String SELECT_DATA_SQL = "SELECT id, name, active, score, payload " + + "FROM " + TABLE_NAME + " ORDER BY id FORMAT JSONEachRow"; + + public static void main(String[] args) throws Exception { + String url = System.getProperty("chUrl", "jdbc:clickhouse://localhost:8123/default"); + String user = System.getProperty("chUser", "default"); + String password = System.getProperty("chPassword", ""); + Properties setupProperties = baseProperties(user, password); + + registerDriver(); + defineTableStructure(url, setupProperties); + loadData(url, setupProperties); + + runGsonExample(url, user, password); + runJacksonExample(url, user, password); + } + + private static void defineTableStructure(String url, Properties properties) throws Exception { + LOG.info("Step 1. Defining table structure: {}", TABLE_NAME); + try (Connection connection = DriverManager.getConnection(url, properties); + Statement statement = connection.createStatement()) { + statement.execute("DROP TABLE IF EXISTS " + TABLE_NAME); + statement.execute(CREATE_TABLE_SQL); + } + } + + private static void loadData(String url, Properties properties) throws Exception { + List rows = readSampleRows(); + LOG.info("Step 2. Loading {} sample rows from {} into {}", rows.size(), SAMPLE_DATA_RESOURCE, TABLE_NAME); + try (Connection connection = DriverManager.getConnection(url, properties); + Statement statement = connection.createStatement()) { + statement.execute("TRUNCATE TABLE " + TABLE_NAME); + statement.executeUpdate(buildInsertSql(rows)); + } + } + + private static void runJacksonExample(String url, String user, String password) throws Exception { + Properties properties = baseProperties(user, password); + properties.setProperty(ClientConfigProperties.JSON_PROCESSOR.getKey(), "JACKSON"); + LOG.info("Step 4. Running jdbc-v2 example with Jackson"); + readRows(url, properties, "JACKSON"); + } + + private static void runGsonExample(String url, String user, String password) throws Exception { + Properties properties = baseProperties(user, password); + properties.setProperty(ClientConfigProperties.JSON_PROCESSOR.getKey(), "GSON"); + LOG.info("Step 3. Running jdbc-v2 example with Gson"); + readRows(url, properties, "GSON"); + } + + private static void readRows(String url, Properties properties, String processor) throws Exception { + try (Connection connection = DriverManager.getConnection(url, properties); + Statement statement = connection.createStatement(); + ResultSet rs = statement.executeQuery(SELECT_DATA_SQL)) { + while (rs.next()) { + Object payload = rs.getObject("payload"); + LOG.info("[{}] id={}, name={}, active={}, score={}, payload={}", + processor, + rs.getInt("id"), + rs.getString("name"), + rs.getBoolean("active"), + rs.getDouble("score"), + payload); + } + } + } + + private static Properties baseProperties(String user, String password) { + Properties properties = new Properties(); + properties.setProperty("user", user); + properties.setProperty("password", password); + properties.setProperty(ClientConfigProperties.serverSetting("allow_experimental_json_type"), "1"); + return properties; + } + + private static void registerDriver() { + // `jdbc-v2` does not self-register from its static initializer, so standalone + // examples should register it explicitly before calling DriverManager. + Driver.load(); + } + + private static List readSampleRows() throws IOException { + InputStream stream = JdbcV2JsonProcessorsExample.class.getResourceAsStream(SAMPLE_DATA_RESOURCE); + if (stream == null) { + throw new IOException("Resource not found: " + SAMPLE_DATA_RESOURCE); + } + + try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) { + String header = reader.readLine(); + if (header == null) { + throw new IOException("CSV resource is empty: " + SAMPLE_DATA_RESOURCE); + } + + List rows = new ArrayList<>(); + String line; + while ((line = reader.readLine()) != null) { + if (line.trim().isEmpty()) { + continue; + } + + List values = parseCsvLine(line); + if (values.size() != 5) { + throw new IOException("Expected 5 columns in sample CSV but found " + values.size() + ": " + line); + } + + rows.add(new SampleRow( + Integer.parseInt(values.get(0)), + values.get(1), + Boolean.parseBoolean(values.get(2)), + Double.parseDouble(values.get(3)), + values.get(4))); + } + + return rows; + } + } + + private static List parseCsvLine(String line) { + List values = new ArrayList<>(); + StringBuilder current = new StringBuilder(); + boolean inQuotes = false; + + for (int i = 0; i < line.length(); i++) { + char ch = line.charAt(i); + if (ch == '"') { + if (inQuotes && i + 1 < line.length() && line.charAt(i + 1) == '"') { + current.append('"'); + i++; + } else { + inQuotes = !inQuotes; + } + } else if (ch == ',' && !inQuotes) { + values.add(current.toString()); + current.setLength(0); + } else { + current.append(ch); + } + } + + values.add(current.toString()); + return values; + } + + private static String buildInsertSql(List rows) { + if (rows.isEmpty()) { + throw new IllegalArgumentException("Sample CSV does not contain any rows"); + } + + StringBuilder sql = new StringBuilder("INSERT INTO ") + .append(TABLE_NAME) + .append(" (id, name, active, score, payload) VALUES "); + + for (SampleRow row : rows) { + sql.append('(') + .append(row.id) + .append(", ") + .append(quoteSqlString(row.name)) + .append(", ") + .append(row.active) + .append(", ") + .append(row.score) + .append(", ") + .append(quoteSqlString(row.payload)) + .append("), "); + } + + sql.setLength(sql.length() - 2); + return sql.toString(); + } + + private static String quoteSqlString(String value) { + return "'" + value.replace("'", "''") + "'"; + } + + private static final class SampleRow { + private final int id; + private final String name; + private final boolean active; + private final double score; + private final String payload; + + private SampleRow(int id, String name, boolean active, double score, String payload) { + this.id = id; + this.name = name; + this.active = active; + this.score = score; + this.payload = payload; + } + } +} diff --git a/jdbc-v2/pom.xml b/jdbc-v2/pom.xml index a8f02f2e9..05b035694 100644 --- a/jdbc-v2/pom.xml +++ b/jdbc-v2/pom.xml @@ -50,14 +50,35 @@ ${guava.version}
- com.fasterxml.jackson.core jackson-databind - test ${jackson.version} + provided + + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + provided + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + provided + + + + com.google.code.gson + gson + ${gson.version} + provided + + + ${project.parent.groupId} clickhouse-client @@ -89,18 +110,6 @@ test - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - test - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - test - com.fasterxml.jackson.dataformat jackson-dataformat-yaml @@ -211,4 +220,4 @@ - \ No newline at end of file + 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 f18071e3f..7ec1e6823 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/DriverProperties.java @@ -80,7 +80,6 @@ public enum DriverProperties { /** * Controls logic of saving roles that were set using {@code SET } statement. - * Default: true - save roles */ REMEMBER_LAST_SET_ROLES("remember_last_set_roles", String.valueOf(Boolean.TRUE)), diff --git a/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java index 2801450ed..66712f1e0 100644 --- a/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java +++ b/jdbc-v2/src/main/java/com/clickhouse/jdbc/StatementImpl.java @@ -6,6 +6,7 @@ import com.clickhouse.client.api.query.QueryResponse; import com.clickhouse.client.api.query.QuerySettings; import com.clickhouse.client.api.sql.SQLUtils; +import com.clickhouse.data.ClickHouseFormat; import com.clickhouse.jdbc.internal.ExceptionUtils; import com.clickhouse.jdbc.internal.FeatureManager; import com.clickhouse.jdbc.internal.ParsedStatement; @@ -177,11 +178,14 @@ protected ResultSetImpl executeQueryImpl(String sql, QuerySettings settings) thr response = connection.getClient().query(lastStatementSql, mergedSettings).get(queryTimeout, TimeUnit.SECONDS); } - if (response.getFormat().isText()) { - throw new SQLException("Only RowBinaryWithNameAndTypes is supported for output format. Please check your query.", + ClickHouseBinaryFormatReader reader; + if (response.getFormat() == ClickHouseFormat.JSONEachRow || !response.getFormat().isText()) { + reader = connection.getClient().newBinaryFormatReader(response); + } else { + throw new SQLException("Only RowBinaryWithNameAndTypes and JSONEachRow are supported for output format. Please check your query.", ExceptionUtils.SQL_STATE_CLIENT_ERROR); } - ClickHouseBinaryFormatReader reader = connection.getClient().newBinaryFormatReader(response); + if (reader.getSchema() == null) { long writtenRows = 0L; try { 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 3680cc32b..a508116b0 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 @@ -18,12 +18,7 @@ import java.nio.charset.StandardCharsets; import java.sql.DriverPropertyInfo; import java.sql.SQLException; -import java.util.Comparator; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Properties; -import java.util.Set; +import java.util.*; import java.util.function.Supplier; import java.util.regex.Pattern; import java.util.stream.Collectors; diff --git a/jdbc-v2/src/test/java/com/clickhouse/jdbc/StatementTest.java b/jdbc-v2/src/test/java/com/clickhouse/jdbc/StatementTest.java index ab1144071..6658a1e3e 100644 --- a/jdbc-v2/src/test/java/com/clickhouse/jdbc/StatementTest.java +++ b/jdbc-v2/src/test/java/com/clickhouse/jdbc/StatementTest.java @@ -647,6 +647,38 @@ public void testTextFormatInResponse() throws Exception { } } + @Test(groups = {"integration"}) + public void testJSONEachRowFormat() throws Exception { + Properties properties = new Properties(); + properties.setProperty(ClientConfigProperties.JSON_PROCESSOR.getKey(), "JACKSON"); + try (Connection conn = getJdbcConnection(properties)) { + try (Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT 1 AS num, 'test' AS str FORMAT JSONEachRow")) { + assertTrue(rs.next()); + assertEquals(rs.getInt("num"), 1); + assertEquals(rs.getString("str"), "test"); + assertFalse(rs.next()); + } + } + } + } + + @Test(groups = {"integration"}) + public void testJSONEachRowFormatGson() throws Exception { + Properties properties = new Properties(); + properties.setProperty(ClientConfigProperties.JSON_PROCESSOR.getKey(), "GSON"); + try (Connection conn = getJdbcConnection(properties)) { + try (Statement stmt = conn.createStatement()) { + try (ResultSet rs = stmt.executeQuery("SELECT 2 AS num, 'gson' AS str FORMAT JSONEachRow")) { + assertTrue(rs.next()); + assertEquals(rs.getInt("num"), 2); + assertEquals(rs.getString("str"), "gson"); + assertFalse(rs.next()); + } + } + } + } + @Test(groups = "integration") void testWithClause() throws Exception { int count = 0; 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 a5a3e972f..ef368524e 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 @@ -122,7 +122,8 @@ public void testParseURLValid(String jdbcURL, Properties properties, { JdbcConfiguration configuration = new JdbcConfiguration(jdbcURL, properties); assertEquals(configuration.getConnectionUrl(), connectionURL, "URL: " + jdbcURL); - assertEquals(configuration.clientProperties, expectedClientProps, "URL: " + jdbcURL); + assertEquals(configuration.clientProperties, expectedClientProps, "expected: " + expectedClientProps + + " actual: " + configuration.clientProperties); Client.Builder bob = new Client.Builder(); configuration.applyClientProperties(bob); Client client = bob.build();