stankiewicz commented on code in PR #41753: URL: https://github.com/apache/beam/pull/41753#discussion_r4737395433
########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHousePartitionValidator.java: ########## @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import static org.apache.beam.sdk.io.clickhouse.ClickHouseReadValidationException.check; + +import com.clickhouse.client.api.Client; +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.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; +import com.clickhouse.data.ClickHouseFormat; +import java.io.IOException; + +/** Worker-side validation of the actual database partition column, independent of output schema. */ +final class ClickHousePartitionValidator { + private ClickHousePartitionValidator() {} + + static void validate(Client client, ClickHouseReadConfiguration configuration) + throws IOException { + String table = configuration.table(); + String partitionColumn = configuration.partitionColumn(); + if (table == null || partitionColumn == null) { + throw new IllegalArgumentException( + "Table and partition column are required for metadata validation"); + } + QuerySettings settings = + new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes); + try { + ClickHouseReadResources.checkInterrupted(); + try (QueryResponse response = + ClickHouseReadResources.await( + client.query(ClickHouseReadSql.describeTable(table), settings)); + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response)) { + boolean found = false; + while (true) { + ClickHouseReadResources.checkInterrupted(); + if (!reader.hasNext()) { + break; + } + reader.next(); + String name = reader.getString("name"); + if (partitionColumn.equals(name)) { + ClickHouseColumn actual = ClickHouseColumn.of(name, reader.getString("type")); + validateColumn(actual); + found = true; + } + } + if (!found) { + throw new ClickHouseReadValidationException( + "Partition column '" + partitionColumn + "' is missing from ClickHouse table"); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new IOException("ClickHouse partition metadata validation interrupted", e); + } catch (Exception e) { + throw new IOException("Unable to read ClickHouse partition metadata", e); + } Review Comment: this will also catch and rewrap ClickHouseReadValidationException. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHousePartitionValidator.java: ########## @@ -0,0 +1,92 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import static org.apache.beam.sdk.io.clickhouse.ClickHouseReadValidationException.check; + +import com.clickhouse.client.api.Client; +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.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; +import com.clickhouse.data.ClickHouseFormat; +import java.io.IOException; + +/** Worker-side validation of the actual database partition column, independent of output schema. */ +final class ClickHousePartitionValidator { + private ClickHousePartitionValidator() {} + + static void validate(Client client, ClickHouseReadConfiguration configuration) + throws IOException { + String table = configuration.table(); + String partitionColumn = configuration.partitionColumn(); + if (table == null || partitionColumn == null) { + throw new IllegalArgumentException( + "Table and partition column are required for metadata validation"); + } + QuerySettings settings = + new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes); + try { + ClickHouseReadResources.checkInterrupted(); + try (QueryResponse response = + ClickHouseReadResources.await( + client.query(ClickHouseReadSql.describeTable(table), settings)); + ClickHouseBinaryFormatReader reader = client.newBinaryFormatReader(response)) { + boolean found = false; + while (true) { + ClickHouseReadResources.checkInterrupted(); + if (!reader.hasNext()) { + break; + } + reader.next(); + String name = reader.getString("name"); + if (partitionColumn.equals(name)) { + ClickHouseColumn actual = ClickHouseColumn.of(name, reader.getString("type")); + validateColumn(actual); + found = true; Review Comment: break missing? ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { + Client activeClient = client; + Schema schema = configuration.schema(); + if (activeClient == null || schema == null) { Review Comment: use Precondititions checks ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadSql.java: ########## @@ -0,0 +1,96 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; + +/** Worker-local SQL and bound values; never included in descriptor or diagnostic strings. */ +final class ClickHouseReadSql { + private final String sql; + private final Map<String, Object> parameters; + + private ClickHouseReadSql(String sql, Map<String, Object> parameters) { + this.sql = sql; + this.parameters = Collections.unmodifiableMap(new LinkedHashMap<>(parameters)); + } + + String sql() { + return sql; + } + + Map<String, Object> parameters() { + return parameters; + } + + static ClickHouseReadSql forPartition( + ClickHouseReadConfiguration configuration, ClickHouseReadPartition partition) { + ClickHouseReadRange range = partition.range(); + String query = configuration.query(); + if (query != null) { + checkArgument(range == null, "Query mode requires a single-query work item"); + return new ClickHouseReadSql(query, Collections.emptyMap()); + } + String table = configuration.table(); + String column = configuration.partitionColumn(); + Schema schema = configuration.schema(); + if (range == null || table == null || column == null || schema == null) { Review Comment: schema check is dead code. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseIO.java: ########## @@ -234,6 +241,360 @@ public static <T> Write<T> write(String clickHouseUrl, String database, String t .withInsertDistributedSync(true); } + /** + * Creates a bounded read configured with a JDBC URL. + * + * <p>Call {@link Read#withSchema(Schema)} and exactly one of {@link Read#withQuery(String)} or + * {@link Read#withTable(String)}. Additional connection properties can be supplied using {@link + * Read#withProperties(Properties)}. This method does not connect to ClickHouse. + */ + public static Read read(String jdbcUrl) { + ClickHouseJdbcUrlParser.ParsedJdbcUrl parsed; + try { + parsed = ClickHouseJdbcUrlParser.parse(jdbcUrl); Review Comment: ClickHouseJdbcUrlParser.parse is deprecated and suggest forcing developer/user to use read(jdbcUrl, database, properties) ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); Review Comment: catches ClickHousePartitionValidator.validate IOException and wraps it again in IOException. Original ClickHouseReadValidationException remains in the cause chain, it is buried under two generic IOException layers. catch ClickHouseReadValidationException, IOException, close client and rethrow. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseRowReader.java: ########## @@ -0,0 +1,207 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import static org.apache.beam.sdk.io.clickhouse.ClickHouseReadValidationException.check; + +import com.clickhouse.data.ClickHouseColumn; +import com.clickhouse.data.ClickHouseDataType; +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.function.IntFunction; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.values.Row; +import org.joda.time.Instant; + +/** Worker-side binding of result metadata and conversion to the caller's output schema. */ +final class ClickHouseRowReader { + private final Schema schema; + private final List<Binding> bindings; + + private ClickHouseRowReader(Schema schema, List<Binding> bindings) { + this.schema = schema; + this.bindings = bindings; + } + + /** Reject unsupported Beam output types without requiring database metadata. */ + static void validateSchema(Schema schema) { + for (Schema.Field field : schema.getFields()) { + switch (field.getType().getTypeName()) { + case BYTE: + case INT16: + case INT32: + case INT64: + case FLOAT: + case DOUBLE: + case STRING: + case BOOLEAN: + case DATETIME: + break; + default: + throw new ClickHouseReadValidationException( + "Unsupported Beam output type for ClickHouse read: " + field.getType().getTypeName()); + } + } + } + + /** Bind before iterating, so metadata errors are also detected for an empty result. */ + static ClickHouseRowReader bind( + Schema schema, com.clickhouse.client.api.metadata.TableSchema resultSchema) { + validateSchema(schema); + Map<String, Integer> indices = new HashMap<>(); + List<ClickHouseColumn> columns = resultSchema.getColumns(); + for (int i = 0; i < columns.size(); i++) { + String name = columns.get(i).getColumnName(); + check(indices.put(name, i) == null, "Duplicate result column name '%s'", name); Review Comment: The Javadoc does not mention that duplicate column names in the SQL result fail the read regardless of whether they are projected. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { + Client activeClient = client; + Schema schema = configuration.schema(); Review Comment: schema is not null, you shouldn't check for null here. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadPartitions.java: ########## @@ -0,0 +1,60 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import java.util.List; +import java.util.stream.Collectors; +import org.apache.beam.sdk.transforms.Create; +import org.apache.beam.sdk.transforms.PTransform; +import org.apache.beam.sdk.transforms.Reshuffle; +import org.apache.beam.sdk.values.PBegin; +import org.apache.beam.sdk.values.PCollection; + +/** Creates explicitly coded work items and a shuffle boundary for partitioned reads. */ +final class ClickHouseReadPartitions + extends PTransform<PBegin, PCollection<ClickHouseReadPartition>> { + private final ClickHouseIO.Read configuration; + + ClickHouseReadPartitions(ClickHouseIO.Read configuration) { + this.configuration = configuration; + } + + @Override + public PCollection<ClickHouseReadPartition> expand(PBegin input) { + if (configuration.query() != null) { + return input.apply( + "QueryWorkItem", + Create.of(ClickHouseReadPartition.singleQuery()) + .withCoder(ClickHouseReadPartitionCoder.of())); + } + Long lower = configuration.lowerBound(); + Long upper = configuration.upperBound(); + Integer count = configuration.numPartitions(); + if (lower == null || upper == null || count == null) { + throw new IllegalArgumentException("Missing partition bounds or count"); + } + List<ClickHouseReadPartition> partitions = + ClickHouseRangePartitioner.partition(lower, upper, count).stream() + .map(ClickHouseReadPartition::forRange) + .collect(Collectors.toList()); + // Create materializes work items in the graph. Scheduling/concurrency remain runner-dependent. + return input + .apply("RangeWorkItems", Create.of(partitions).withCoder(ClickHouseReadPartitionCoder.of())) + .apply("DistributeRanges", Reshuffle.viaRandomKey()); Review Comment: similarly to JdbcIO.ReadWithPartitions: Impulse.create() (or Create.of((Void) null).withCoder(VoidCoder.of())) Plan & Validate (ParDo on 1 element): ClickHousePlanAndValidateFn(configuration) that will: 1. validate connection and schema from 1 cpu and not from every worker. 2. create partitions, while keeping graph size small. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseRangePartitioner.java: ########## @@ -0,0 +1,71 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import static org.apache.beam.vendor.guava.v32_1_2_jre.com.google.common.base.Preconditions.checkArgument; + +import java.util.ArrayList; +import java.util.List; + +/** Generates non-overlapping ranges covering an inclusive numeric interval. */ +final class ClickHouseRangePartitioner { + private ClickHouseRangePartitioner() {} + + static long inclusiveCardinality(long lower, long upper) { + checkArgument(lower <= upper, "Lower bound must be less than or equal to upper bound"); + try { + return Math.addExact(Math.subtractExact(upper, lower), 1L); + } catch (ArithmeticException e) { + throw new IllegalArgumentException( + "Inclusive range cardinality must fit in a signed long; this is a v1 implementation restriction"); + } + } + + static final int MAX_PARTITIONS = 10_000; + + static int effectivePartitionCount(long cardinality, int requestedPartitions) { + checkArgument(requestedPartitions >= 1, "Partition count must be at least 1"); + int count = (int) Math.min(requestedPartitions, cardinality); + checkArgument( + count <= MAX_PARTITIONS, + "Effective partition count must not exceed %s; partitions are materialized in the pipeline graph", + MAX_PARTITIONS); + return count; + } Review Comment: max partition check won't be needed if you split in dofn. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadConfiguration.java: ########## @@ -0,0 +1,83 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import java.io.Serializable; +import java.util.Properties; +import org.apache.beam.sdk.schemas.Schema; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Only the immutable settings needed by read workers, without the enclosing transform. */ +final class ClickHouseReadConfiguration implements Serializable { + private final String url; + private final String database; + private final Properties properties; + private final @Nullable String query; + private final @Nullable String table; + private final Schema schema; + private final @Nullable String partitionColumn; + + ClickHouseReadConfiguration(ClickHouseIO.Read read) { + url = read.clickHouseUrl(); + database = read.database(); + properties = read.properties(); + query = read.query(); + table = read.table(); + Schema suppliedSchema = read.schema(); + if (suppliedSchema == null) { + throw new IllegalArgumentException("An output schema is required"); Review Comment: dead code ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { + Client activeClient = client; + Schema schema = configuration.schema(); + if (activeClient == null || schema == null) { + throw new IllegalStateException("ClickHouse query reader has not been initialized"); + } + ClickHouseReadSql statement = ClickHouseReadSql.forPartition(configuration, partition); + RuntimeException downstreamFailure = null; + QuerySettings settings = + new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes); + try { + ClickHouseReadResources.checkInterrupted(); + try (QueryResponse response = + ClickHouseReadResources.await( + activeClient.query(statement.sql(), statement.parameters(), settings)); + ClickHouseBinaryFormatReader reader = activeClient.newBinaryFormatReader(response)) { + ClickHouseRowReader rowReader = ClickHouseRowReader.bind(schema, reader.getSchema()); + while (true) { + ClickHouseReadResources.checkInterrupted(); Review Comment: I'm not sure if we need this. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseIO.java: ########## @@ -234,6 +241,360 @@ public static <T> Write<T> write(String clickHouseUrl, String database, String t .withInsertDistributedSync(true); } + /** + * Creates a bounded read configured with a JDBC URL. + * + * <p>Call {@link Read#withSchema(Schema)} and exactly one of {@link Read#withQuery(String)} or + * {@link Read#withTable(String)}. Additional connection properties can be supplied using {@link + * Read#withProperties(Properties)}. This method does not connect to ClickHouse. + */ + public static Read read(String jdbcUrl) { + ClickHouseJdbcUrlParser.ParsedJdbcUrl parsed; + try { + parsed = ClickHouseJdbcUrlParser.parse(jdbcUrl); + } catch (IllegalArgumentException e) { + // The existing parser includes the URL in some errors. It may contain credentials. + String detail = + "expected a ClickHouse JDBC URL with a valid HTTP(S) host and parameter encoding"; + Throwable cause = e.getCause(); + if (cause instanceof URISyntaxException) { + // getReason() describes the syntax violation without including the original URL. + detail = ((URISyntaxException) cause).getReason(); + } + throw new IllegalArgumentException("Invalid ClickHouse connection URL: " + detail); + } + return new AutoValue_ClickHouseIO_Read.Builder() + .clickHouseUrl(parsed.getClickHouseUrl()) + .database(parsed.getDatabase()) + .connectionProperties(copyReadProperties(parsed.getProperties())) + .build(); + } + + private static Properties copyReadProperties(Properties source) { + Properties copy = new Properties(); + for (String name : source.stringPropertyNames()) { + copy.setProperty(name, source.getProperty(name)); + } + return copy; + } + + /** + * A bounded read producing {@link Row}s with a caller-supplied schema. + * + * <p>Query mode executes caller-supplied SQL as a single read. Table mode selects the schema's + * fields in schema order and partitions the configured inclusive interval. The partition column + * need not appear in the output schema. A schema is required in both modes; pipeline construction + * does not connect to ClickHouse. Result metadata and values are validated when workers read + * them. Table mode also validates the partition column against database metadata on workers. + * + * <h3>Single-query reads</h3> + * + * <p>Supply the expected output schema and SQL. Query mode executes the SQL unchanged and does + * not split it into parallel queries. Result columns bind by exact name, rather than position; + * extra result columns are ignored. + * + * <pre>{@code + * Schema eventSchema = Schema.builder() + * .addInt64Field("id") + * .addStringField("event_type") + * .build(); + * Properties properties = new Properties(); + * properties.setProperty("user", "beam_reader"); + * + * PCollection<Row> events = pipeline.apply( + * ClickHouseIO.read("jdbc:clickhouse://localhost:8123/default") + * .withProperties(properties) + * .withQuery("SELECT id, event_type FROM events WHERE id >= 0 AND id <= 100") + * .withSchema(eventSchema)); + * }</pre> + * + * <h3>Partitioned table reads</h3> + * + * <p>The schema selects the retrieved columns and their expected types, without SQL casts. Table + * and column names are quoted as identifiers, not interpreted as SQL expressions. For example, + * the following reads only {@code event_type}, using {@code id} to partition the inclusive + * interval {@code [0, 100]}: + * + * <pre>{@code + * Schema projectedSchema = Schema.builder().addStringField("event_type").build(); + * PCollection<Row> events = pipeline.apply( + * ClickHouseIO.read("jdbc:clickhouse://localhost:8123/default") + * .withProperties(properties) + * .withTable("events") + * .withSchema(projectedSchema) + * .withPartitionColumn("id") + * .withLowerBound(0L) + * .withUpperBound(100L) + * .withNumPartitions(4)); + * }</pre> + * + * <p>Only non-nullable ClickHouse {@code Int32} and {@code Int64} partition columns are + * supported. Both bounds restrict the rows read, even with one partition. Equal bounds select one + * key. Rows outside the bounds are excluded; callers reading a whole table must choose bounds + * covering the intended data. The final partition includes the upper bound; intermediate upper + * bounds are exclusive. For the example above the predicates are {@code id >= 0 AND id < 25}, + * {@code id >= 25 AND id < 50}, {@code id >= 50 AND id < 75}, and {@code id >= 75 AND id <= 100}. + * + * <p>Partition count must be positive and is capped at the interval's integer cardinality. As a + * v1 implementation restriction, inclusive cardinality must fit in a signed Java {@code long}. + * The effective partition count is limited to 10,000 because descriptors are materialized in the + * pipeline graph. Automatic bounds discovery and dynamic splitting are not supported. Partitions + * use equal-width key ranges, which may contain uneven numbers of rows. Concurrent execution + * depends on the runner, and database scan efficiency depends on the table's sorting key and + * query planning. + * + * <h3>Supported output types</h3> + * + * <table> + * <caption>ClickHouse read type mappings</caption> + * <tr><th scope="col">ClickHouse type</th><th scope="col">Beam field type</th></tr> + * <tr><td>Int8</td><td>BYTE</td></tr> + * <tr><td>Int16, UInt8</td><td>INT16</td></tr> + * <tr><td>Int32, UInt16</td><td>INT32</td></tr> + * <tr><td>Int64, UInt32</td><td>INT64</td></tr> + * <tr><td>Float32</td><td>FLOAT</td></tr> + * <tr><td>Float64</td><td>DOUBLE</td></tr> + * <tr><td>String</td><td>STRING</td></tr> + * <tr><td>Bool</td><td>BOOLEAN</td></tr> + * <tr><td>Date</td><td>DATETIME: calendar date at midnight UTC</td></tr> + * <tr><td>DateTime</td><td>DATETIME: the corresponding instant, at second precision</td></tr> + * </table> + * + * <p>Nullable source columns require nullable Beam fields; non-nullable sources may bind to + * either nullable or non-nullable fields. Missing columns, incompatible types, unexpected nulls, + * and unsupported selected types fail the read, including metadata validation for empty results. + * There is no implicit numeric widening. FixedString, UInt64, Decimal, DateTime64, complex types, + * DateTime32, and LowCardinality or aggregate wrappers are unsupported. FixedString is deferred + * because the client decoder does not preserve arbitrary bytes. Read type support is narrower + * than write type support. + * + * <h3>Consistency and connection settings</h3> + * + * <p>On a stable dataset, partitions cover the configured interval without gaps or overlaps and + * preserve duplicate rows. Independently executed partition queries do not share a globally + * consistent snapshot. Concurrent inserts, deletes, or partition-key changes may cause omissions + * or duplicate observations. Output order is unspecified. + * + * <p>Directly supplied credentials may be serialized into the pipeline graph. Display data omits + * raw SQL and connection properties. Worker failures preserve original client/server causes, + * which may contain SQL or configuration values; avoid embedding secrets in SQL literals and + * restrict access to pipeline graphs and error logs. URL parsing and property-conflict errors + * omit supplied values. + * + * <p>The connector does not restart queries internally. Client request retries, if configured, + * occur before a query response is returned. Failures after row emission propagate to Beam's + * bundle retry mechanism; mutable data may yield different results when a query is re-executed. + */ + @AutoValue + public abstract static class Read extends PTransform<PBegin, PCollection<Row>> { + abstract String clickHouseUrl(); + + abstract String database(); + + abstract Properties connectionProperties(); + + abstract @Nullable String query(); + + abstract @Nullable String table(); + + abstract @Nullable Schema schema(); + + abstract @Nullable String partitionColumn(); + + abstract @Nullable Long lowerBound(); + + abstract @Nullable Long upperBound(); + + abstract @Nullable Integer numPartitions(); + + abstract Builder toBuilder(); + + /** + * Adds connection properties, retaining a defensive copy including inherited string properties. + * Conflicting values for an existing key (including a URL property) are rejected, following the + * write API's convention. Repeating the same value is allowed. Error messages omit values. + */ + public Read withProperties(Properties properties) { + checkArgument(properties != null, "Connection properties must not be null"); + Properties merged = copyReadProperties(connectionProperties()); + for (String key : properties.stringPropertyNames()) { + String existing = merged.getProperty(key); + String supplied = properties.getProperty(key); + checkArgument( + existing == null || existing.equals(supplied), + "Connection property conflict for key '%s'; use one consistent value", + key); + merged.setProperty(key, supplied); + } + return toBuilder().connectionProperties(merged).build(); + } + + /** Returns a defensive copy of the configured connection properties. */ + public final Properties properties() { + return copyReadProperties(connectionProperties()); + } + + /** Sets caller-supplied SQL for a single read. Mutually exclusive with table mode. */ + public Read withQuery(String query) { + return toBuilder().query(query).build(); + } + + /** + * Sets an unqualified table name; the database comes from the connection URL. All partition + * options must be supplied together in table mode. + */ + public Read withTable(String table) { + return toBuilder().table(table).build(); + } + + /** + * Sets the required output schema. In table mode, its fields also select the columns to + * retrieve in schema order. Types describe expected values rather than requesting SQL casts. + * FixedString is unsupported for reads in v1 because the client decoder does not preserve + * arbitrary bytes. + */ + public Read withSchema(Schema schema) { + return toBuilder().schema(schema).build(); + } + + /** Sets a non-nullable Int32 or Int64 partition column, independently of the output schema. */ + public Read withPartitionColumn(String column) { + return toBuilder().partitionColumn(column).build(); + } + + /** + * Sets the inclusive lower read bound; valid only in table mode. Equal bounds select one key. + * Inclusive range cardinality must fit in a signed long in v1. + */ + public Read withLowerBound(long lowerBound) { + return toBuilder().lowerBound(lowerBound).build(); + } + + /** Sets the inclusive upper read bound, including when only one partition is requested. */ + public Read withUpperBound(long upperBound) { + return toBuilder().upperBound(upperBound).build(); + } + + /** + * Sets a positive requested partition count, capped at the inclusive range cardinality. Actual + * concurrent execution depends on the runner; equal-width ranges need not have equal row + * counts. + */ + public Read withNumPartitions(int numPartitions) { + return toBuilder().numPartitions(numPartitions).build(); + } Review Comment: I know we have discussed that, but current implementation will be problematic to change once you decide to support new types as it will be instantly breaking change. Consider: `.withPartitioning( ClickHouseIO.PartitionStrategy.longRange("id", 0L, 100L).withNumPartitions(4)` or generic like in JDBC: Read<PartitionColumnT>), which is generic over PartitionColumnT so withLowerBound(PartitionColumnT) / withUpperBound(PartitionColumnT) aren't fixed to long. ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { + Client activeClient = client; + Schema schema = configuration.schema(); + if (activeClient == null || schema == null) { + throw new IllegalStateException("ClickHouse query reader has not been initialized"); + } + ClickHouseReadSql statement = ClickHouseReadSql.forPartition(configuration, partition); + RuntimeException downstreamFailure = null; + QuerySettings settings = + new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes); + try { + ClickHouseReadResources.checkInterrupted(); Review Comment: it's a bit defensive to check here, do we need this? ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { + Client activeClient = client; + Schema schema = configuration.schema(); + if (activeClient == null || schema == null) { + throw new IllegalStateException("ClickHouse query reader has not been initialized"); + } + ClickHouseReadSql statement = ClickHouseReadSql.forPartition(configuration, partition); + RuntimeException downstreamFailure = null; + QuerySettings settings = + new QuerySettings().setFormat(ClickHouseFormat.RowBinaryWithNamesAndTypes); + try { + ClickHouseReadResources.checkInterrupted(); + try (QueryResponse response = + ClickHouseReadResources.await( + activeClient.query(statement.sql(), statement.parameters(), settings)); + ClickHouseBinaryFormatReader reader = activeClient.newBinaryFormatReader(response)) { + ClickHouseRowReader rowReader = ClickHouseRowReader.bind(schema, reader.getSchema()); + while (true) { + ClickHouseReadResources.checkInterrupted(); + if (!reader.hasNext()) { + break; + } + reader.next(); + Row row = rowReader.readRow(reader::readValue); + try { + output.output(row); + } catch (RuntimeException e) { + // Fused downstream transforms execute here. Preserve their exception identity and + // stack, while try-with-resources still closes this query's response. + downstreamFailure = e; + throw e; + } Review Comment: I don't think this is needed ########## sdks/java/io/clickhouse/src/main/java/org/apache/beam/sdk/io/clickhouse/ClickHouseReadFn.java: ########## @@ -0,0 +1,143 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you 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 + * + * http://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. + */ +package org.apache.beam.sdk.io.clickhouse; + +import com.clickhouse.client.api.Client; +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 java.io.IOException; +import java.util.Map; +import java.util.Properties; +import java.util.stream.Collectors; +import org.apache.beam.sdk.schemas.Schema; +import org.apache.beam.sdk.transforms.DoFn; +import org.apache.beam.sdk.values.Row; +import org.checkerframework.checker.nullness.qual.Nullable; + +/** Executes bounded read work items on a worker without replaying partially emitted results. */ +final class ClickHouseReadFn extends DoFn<ClickHouseReadPartition, Row> { + private final ClickHouseReadConfiguration configuration; + private transient @Nullable Client client; + + ClickHouseReadFn(ClickHouseIO.Read configuration) { + this.configuration = new ClickHouseReadConfiguration(configuration); + } + + @Setup + public void setup() throws IOException { + Properties properties = configuration.properties(); + Map<String, String> options = + properties.stringPropertyNames().stream() + .filter(key -> !key.equals("user") && !key.equals("password")) + .collect(Collectors.toMap(key -> key, key -> properties.getProperty(key, ""))); + Client created; + try { + Client.Builder builder = + new Client.Builder() + .addEndpoint(configuration.clickHouseUrl()) + .setDefaultDatabase(configuration.database()) + .setUsername(properties.getProperty("user", "default")) + .setPassword(properties.getProperty("password", "")) + .setOptions(options) + .setClientName(ClickHouseIO.buildClientName(properties)); + if (Boolean.parseBoolean(properties.getProperty("compress", "false"))) { + builder.compressServerResponse(true).compressClientRequest(true); + } + created = builder.build(); + } catch (Exception e) { + throw new IOException("Unable to create ClickHouse read client", e); + } + try { + if (configuration.table() != null) { + ClickHousePartitionValidator.validate(created, configuration); + } + client = created; + } catch (Exception e) { + // Beam need not invoke @Teardown when @Setup fails, so close this client immediately. + try { + created.close(); + } catch (Exception closeFailure) { + e.addSuppressed(closeFailure); + } + throw new IOException("Unable to validate ClickHouse partition metadata", e); + } + } + + @ProcessElement + public void process(@Element ClickHouseReadPartition partition, OutputReceiver<Row> output) + throws IOException { Review Comment: ClickHouseBinaryFormatReader autocloseable throws Exception, consider changing throws IOException to Exception here -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected]
