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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,9 @@
/**
* Class designed to convert different data types to Java objects.
* First use-case is to convert ClickHouse data types to String representation.
* Note: class is not thread-safe to avoid extra object creation.
* Note: this class is thread-safe. It keeps no conversion state in fields: each array conversion uses
* a new writer, so one instance (for example, {@link #INSTANCE}) can be used by many threads at the same time.
* A subclass that is shared in the same way must not keep per-call state in fields.
*/
public class DataTypeConverter {

Expand All @@ -43,10 +45,6 @@ public class DataTypeConverter {

public static final DataTypeConverter INSTANCE = new DataTypeConverter();

private final ListAsStringWriter listAsStringWriter = new ListAsStringWriter();

private final ArrayAsStringWriter arrayAsStringWriter = new ArrayAsStringWriter();

public String convertToString(Object value, ClickHouseColumn column) {
if (value == null) {
return null;
Expand Down Expand Up @@ -234,11 +232,11 @@ public String ipvToString(Object value, ClickHouseColumn column) {

public String arrayToString(Object value, ClickHouseColumn column) {
if (value instanceof BinaryStreamReader.ArrayValue) {
return listAsStringWriter.convertAndReset(((BinaryStreamReader.ArrayValue) value).asList(), new StringBuilder(), column);
return new ListAsStringWriter(column).convert(((BinaryStreamReader.ArrayValue) value).asList(), new StringBuilder());
} else if (value.getClass().isArray()) {
return arrayAsStringWriter.convertAndReset(value, new StringBuilder(), column);
return new ArrayAsStringWriter(column).convert(value, new StringBuilder());
} else if (value instanceof List<?>) {
return listAsStringWriter.convertAndReset((List<?>) value, new StringBuilder(), column);
return new ListAsStringWriter(column).convert((List<?>) value, new StringBuilder());
}
return value.toString();
}
Expand Down Expand Up @@ -575,18 +573,15 @@ private static void appendEnquotedArrayElement(String value, ClickHouseColumn el
}
}

/** Keeps the state of one conversion: create a new writer for each value. */
private final class ArrayAsStringWriter extends BaseCollectionConverter.BaseArrayWriter {
private ClickHouseColumn column;
private final ClickHouseColumn column;

ArrayAsStringWriter() {
ArrayAsStringWriter(ClickHouseColumn column) {
super();
}

public void setColumn(ClickHouseColumn column) {
this.column = column;
}


@Override
protected void onItem(Object item, ListConversionState<Object> state) {
if (item == null) {
Expand All @@ -597,27 +592,13 @@ protected void onItem(Object item, ListConversionState<Object> state) {
String str = DataTypeConverter.this.convertToString(item, elementColumn);
appendEnquotedArrayElement(str, elementColumn, appendable);
}

public String convertAndReset(Object list, Appendable acc, ClickHouseColumn column) {
// Save current state to handle re-entrancy (nested array conversion)
ClickHouseColumn prevColumn = this.column;
Appendable prevAppendable = this.appendable;
try {
setColumn(column);
return super.convert(list, acc);
} finally {
// Restore previous state for re-entrant calls
this.column = prevColumn;
setAccumulator(prevAppendable);
}
}
}

/** Keeps the state of one conversion: create a new writer for each value. */
private final class ListAsStringWriter extends BaseCollectionConverter.BaseListWriter {
private final ClickHouseColumn column;

private ClickHouseColumn column;

public void setColumn(ClickHouseColumn column) {
ListAsStringWriter(ClickHouseColumn column) {
this.column = column;
}

Expand All @@ -632,19 +613,5 @@ protected void onItem(Object item, ListConversionState<List<?>> state) {
appendEnquotedArrayElement(str, elementColumn, appendable);

}

public String convertAndReset(List<?> list, Appendable acc, ClickHouseColumn column) {
// Save current state to handle re-entrancy (nested array conversion)
ClickHouseColumn prevColumn = this.column;
Appendable prevAppendable = this.appendable;
try {
setColumn(column);
return super.convert(list, acc);
} finally {
// Restore previous state for re-entrant calls
this.column = prevColumn;
setAccumulator(prevAppendable);
}
}
}
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.clickhouse.client.api.internal;

import com.clickhouse.client.api.data_formats.internal.BinaryStreamReader;
import com.clickhouse.data.ClickHouseColumn;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
Expand All @@ -13,9 +14,16 @@
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNull;
import static org.testng.Assert.assertTrue;

@Test(groups = {"unit"})
public class DataTypeConverterTest {
Expand Down Expand Up @@ -195,6 +203,77 @@ public void testVariantTwoDimensionalGeoToString() {
"[[1.0, 2.0], [3.0, 4.0]]");
}

@DataProvider(name = "arrayContainers")
public static Object[][] arrayContainers() {
return new Object[][] {
{(Function<Object[], Object>) Arrays::asList},
{(Function<Object[], Object>) items -> items},
{(Function<Object[], Object>) items -> {
BinaryStreamReader.ArrayValue array = new BinaryStreamReader.ArrayValue(Object.class, items.length);
for (int i = 0; i < items.length; i++) {
array.set(i, items[i]);
}
return array;
}},
};
}

@Test(dataProvider = "arrayContainers")
public void testArrayToStringWithSharedInstanceInParallel(Function<Object[], Object> container) throws Exception {
DataTypeConverter converter = DataTypeConverter.INSTANCE;
BlockingValue first = new BlockingValue("1");
BlockingValue second = new BlockingValue("b");
ExecutorService executor = Executors.newFixedThreadPool(2);
try {
Future<String> intArray = executor.submit(() -> converter.convertToString(
container.apply(new Object[] {first, 2}), ClickHouseColumn.of("v", "Array(Int32)")));
first.awaitEntered();
Future<String> strArray = executor.submit(() -> converter.convertToString(
container.apply(new Object[] {second, "c"}), ClickHouseColumn.of("v", "Array(String)")));
second.awaitEntered();

first.release();
assertEquals(intArray.get(10, TimeUnit.SECONDS), "[1, 2]");
second.release();
assertEquals(strArray.get(10, TimeUnit.SECONDS), "['b', 'c']");
} finally {
executor.shutdownNow();
}
}

/** Array element whose conversion waits until the test releases it, to interleave two conversions. */
private static final class BlockingValue {
private final String text;
private final CountDownLatch entered = new CountDownLatch(1);
private final CountDownLatch released = new CountDownLatch(1);

BlockingValue(String text) {
this.text = text;
}

void awaitEntered() throws InterruptedException {
assertTrue(entered.await(10, TimeUnit.SECONDS), "conversion did not start");
}

void release() {
released.countDown();
}

@Override
public String toString() {
entered.countDown();
try {
if (!released.await(10, TimeUnit.SECONDS)) {
throw new IllegalStateException("value was not released");
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IllegalStateException(e);
}
return text;
}
}

@DataProvider(name = "queryParameters")
public static Object[][] queryParameters() {
return new Object[][] {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2127,6 +2127,38 @@ public void testConcurrentQueries() throws Exception{
Assert.assertEquals(latch.getCount(), 0);
}

@Test(groups = {"integration"})
public void testGetStringOfArraysInParallelReaders() throws Exception {
final int concurrency = 4;
final int rows = 10_000;
final String sql = "SELECT number, [toString(number), 'x'] AS s, [number, number + 1] AS n FROM numbers(" + rows + ")";
ExecutorService executor = Executors.newFixedThreadPool(concurrency);
try {
List<Future<Integer>> futures = new ArrayList<>();
for (int i = 0; i < concurrency; i++) {
futures.add(executor.submit(() -> {
int count = 0;
try (QueryResponse response = client.query(sql).get();
ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response)) {
while (reader.hasNext()) {
reader.next();
long number = reader.getLong("number");
Assert.assertEquals(reader.getString("s"), "['" + number + "', 'x']");
Assert.assertEquals(reader.getString("n"), "[" + number + ", " + (number + 1) + "]");
count++;
}
}
return count;
}));
}
for (Future<Integer> future : futures) {
Assert.assertEquals(future.get(30, TimeUnit.SECONDS).intValue(), rows);
}
} finally {
executor.shutdownNow();
}
}

@Test(groups = {"integration"})
public void testQueryReadToPOJO() {
int limit = 10;
Expand Down
7 changes: 7 additions & 0 deletions history/latest/2728.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
- **[client-v2, jdbc-v2]** Fixed `getString()` on array values (`Array`, `QBit`, and arrays in `Variant` or `Dynamic`)
when readers, `GenericRecord` or `ResultSet` objects in different threads convert them at the same time. All of them
share one `DataTypeConverter`, and its array writers kept the current column and output buffer in fields. Parallel
conversions changed each other's state: a result had wrong quotes or values from another thread, or the call failed
with a `NullPointerException`. `DataTypeConverter` now creates a new array writer for each conversion, so it keeps
no conversion state and is thread-safe.
(https://github.com/ClickHouse/clickhouse-java/issues/2728)
Loading