This is an automated email from the ASF dual-hosted git repository. github-merge-queue[bot] pushed a commit to branch gh-readonly-queue/dev/pr-13288-520ced47bb82397bbda2296647f0b60f51ead83f in repository https://gitbox.apache.org/repos/asf/seatunnel.git
commit ea25d55a0819ab13ca40fe37b89e8e2310826cfe Author: Sepuri Sai Krishna <[email protected]> AuthorDate: Sun Nov 29 10:28:59 2026 +0000 [Fix][Connector-V2][Cassandra] Fail the job when a row cannot be written (#13288) --- docs/en/connectors/sink/Cassandra.md | 22 +- .../introduction/concepts/incompatible-changes.md | 31 ++ docs/zh/connectors/sink/Cassandra.md | 15 +- .../introduction/concepts/incompatible-changes.md | 21 ++ .../exception/CassandraConnectorErrorCode.java | 4 +- .../seatunnel/cassandra/sink/CassandraSink.java | 7 +- .../cassandra/sink/CassandraSinkWriter.java | 266 +++++++++++-- .../seatunnel/cassandra/util/TypeConvertUtil.java | 8 + .../cassandra/sink/CassandraSinkWriterTest.java | 412 +++++++++++++++++++++ .../cassandra/util/TypeConvertUtilTest.java | 143 +++++++ .../seatunnel/cassandra/CassandraIT.java | 115 +++++- .../fake_null_primary_key_to_cassandra.conf | 53 +++ .../resources/fake_oversized_row_to_cassandra.conf | 50 +++ 13 files changed, 1084 insertions(+), 63 deletions(-) diff --git a/docs/en/connectors/sink/Cassandra.md b/docs/en/connectors/sink/Cassandra.md index 02f1d2dd81..8d9d8abef1 100644 --- a/docs/en/connectors/sink/Cassandra.md +++ b/docs/en/connectors/sink/Cassandra.md @@ -93,7 +93,9 @@ Use this option when the upstream row has extra fields that should not be writte ### batch_size [int] The number of rows written through [Cassandra-Java-Driver](https://github.com/datastax/java-driver) each time, -default is `5000`. +default is `5000`. With `async_write = false`, the sink sends the buffered rows as one batch once +this many rows have arrived. With `async_write = true`, it waits for the asynchronous writes in +flight once this many rows have been sent, so no more than this many writes are in flight. ### batch_type [String] @@ -101,7 +103,9 @@ The `Cassandra` batch processing mode, default is `UNLOGGED`. ### async_write [boolean] -Whether `cassandra` writes in asynchronous mode, default is `true`. +Whether `cassandra` writes in asynchronous mode, default is `true`. In both modes, a row that +Cassandra rejects fails the job, and every row received before a checkpoint is written before the +checkpoint completes. ### common-options @@ -111,7 +115,19 @@ Sink plugin common parameters. For details, see [Sink Common Options](../common- - The target keyspace and table must already exist before the job starts. - `fields` is useful when the upstream row has extra columns. It is not a schema creation option. -- `async_write = true` (default) sends each row as an individual async statement, while `batch_size` controls how often the buffer is flushed. With `async_write = false`, rows are grouped into one `batch_type` batch that is flushed once it holds `batch_size + 1` statements, because the size check runs after each row is already appended to the batch. +- `async_write = true` (default) sends each row as an individual async statement, and the sink waits for the writes in flight once `batch_size` rows have been sent. With `async_write = false`, rows are grouped into one `batch_type` batch of at most `batch_size` statements per flush. + At each checkpoint the sink writes the buffered rows and waits for the writes in flight, so the + sink gives at-least-once delivery: a restored job may write some rows again. +- The sink drops the rows it still holds, without sending them, only when the engine aborts the + writer: Spark does so after a failed write or checkpoint preparation, and Zeta after a failed + checkpoint preparation. In other cases a failed task closes the sink normally, and closing writes + the buffered rows first, so rows received before the failure can reach the table. Either way the + engine writes the rows after the last checkpoint again when it retries the task or restores the + job, as the at-least-once note above says. +- When it starts, the sink reads the primary key of the target table from the driver schema + metadata, and reads the schema from the server once more if the table is missing there. A NULL + key then fails the job with the table and column before anything is sent. If the primary key + still cannot be read, the job fails with error `CASSANDRA-06`. - The sink uses the Cassandra Java driver. Authentication options match the driver's terminology. Note that `consistency_level` is currently accepted but not applied to write statements; to change the write consistency level, adjust the driver default in your cluster/client setup. diff --git a/docs/en/introduction/concepts/incompatible-changes.md b/docs/en/introduction/concepts/incompatible-changes.md index 49da318fd9..c924194e59 100644 --- a/docs/en/introduction/concepts/incompatible-changes.md +++ b/docs/en/introduction/concepts/incompatible-changes.md @@ -63,6 +63,37 @@ for connector requirements and the restrictions on shared physical destinations. - **Impact**: An endpoint that rejected the old body with an error now accepts it. A receiver written for the old body, which decodes each element as a JSON string, now receives objects and has to be changed. - **Migration Guide**: No configuration change is needed. If a receiver decodes each array element from a string, change it to use the element directly. +### Cassandra: a NULL cell stays NULL + +- **Affected jobs**: jobs that read NULL cells with the Cassandra source or write NULL values with + the Cassandra sink. +- **Behavior change**: the source used to read a NULL `tinyint`, `smallint`, `int`, `bigint`, + `float`, `double` or `boolean` as `0` or `false`, and a NULL `list`, `set` or `map` as empty. A + NULL `decimal`, `varint`, `uuid`, `timeuuid`, `inet` or `blob` failed the job. The source now emits + NULL for all of them. The sink now writes a NULL value as NULL, which replaces any value the target + row already has in that column. It used to fail the job for most types and to write a NULL `inet` as + `127.0.0.1`. A NULL in a primary key column now fails the job with the table and column name. For a + `text`, `ascii`, `time` or `date` key this replaces a job that succeeded while losing rows. To do + this, the sink reads the primary key of the target table from the driver schema metadata when it + starts, and fails if it cannot read it. +- **Migration**: no configuration change is required. Transforms, sinks and queries that relied on + `0`, `false` or an empty collection for a NULL cell must handle NULL, and a target column declared + `NOT NULL` will now reject these rows. Filter out rows with a NULL key before the Cassandra sink. + +### Cassandra sink: a row that cannot be written fails the job + +- **Affected jobs**: jobs with the Cassandra sink, with either value of `async_write`. +- **Behavior change**: with `async_write = true`, the default, a write that Cassandra rejected or + that timed out was only logged, and the job finished without the row. With `async_write = false`, + the rows buffered for the next batch were sent only after the next checkpoint had completed, so a + failure there made the job restore from that checkpoint and skip those rows. Now the sink writes + the buffered rows and waits for the writes in flight at every checkpoint, after `batch_size` rows + and when it closes, and a row that cannot be written fails the job with error `CASSANDRA-07`, + the table name and the error of Cassandra. +- **Migration**: no configuration change is required. A job that finished while losing rows now + fails; fix the rows or the table that Cassandra rejects, for example values above its mutation + size limit. A restored job may write the rows since the last checkpoint again. + ### Doris source: `case_sensitive = false` now lowercases a single-table `database`/`table` - **Behavior change: a single-table Doris source configured with `case_sensitive = false` resolves the `database` and `table` names in lowercase** diff --git a/docs/zh/connectors/sink/Cassandra.md b/docs/zh/connectors/sink/Cassandra.md index cf59985795..225c1d8c8f 100644 --- a/docs/zh/connectors/sink/Cassandra.md +++ b/docs/zh/connectors/sink/Cassandra.md @@ -89,7 +89,8 @@ sink 会把数据写入已经存在的 Cassandra 表。如果不配置 `fields` ### batch_size [int] 通过 [Cassandra-Java-Driver](https://github.com/datastax/java-driver) 每次写入的行数, -默认值 `5000`. +默认值 `5000`. 当 `async_write = false` 时,缓冲的行达到这个数量后,Sink 会把它们作为一个批次发送。当 `async_write = true` 时, +每发送这么多行,Sink 会等待正在进行的异步写入完成,因此同时进行的写入不会超过这个数量。 ### batch_type [String] @@ -97,7 +98,8 @@ sink 会把数据写入已经存在的 Cassandra 表。如果不配置 `fields` ### async_write [boolean] -`cassandra` 是否以异步模式写入, 默认值 `true`. +`cassandra` 是否以异步模式写入, 默认值 `true`. 两种模式下,被 Cassandra 拒绝的行都会导致作业失败,并且 +在 checkpoint 完成前,该 checkpoint 之前收到的每一行都会写入。 ### common-options @@ -107,7 +109,14 @@ Sink 插件通用参数,详情请参考 [Sink 常用选项](../common-options/ - 任务启动前,目标 keyspace 和表必须已经存在。 - `fields` 适合上游数据有额外字段、只想写入其中一部分字段的场景;它不是建表配置。 -- `async_write = true`(默认)下每行都会作为独立的异步语句发送,`batch_size` 只控制 flush 频率;`async_write = false` 时,行才会按 `batch_type` 聚合成一个批次。由于先追加行、再检查大小阈值,实际每次 flush 发送的批次包含 `batch_size + 1` 条。 +- `async_write = true`(默认)下每行都会作为独立的异步语句发送,每发送 `batch_size` 行,Sink 会等待正在进行的写入完成;`async_write = false` 时,行才会按 `batch_type` 聚合成一个批次,每次 flush 最多包含 `batch_size` 条。 + 每次 checkpoint 时,Sink 会写入缓冲的行并等待正在进行的写入完成,因此 Sink 提供至少一次(at-least-once)语义:恢复后的作业可能会再次写入部分行。 +- 只有引擎中止 writer 时,Sink 才会丢弃仍在缓冲中的行而不发送:Spark 在写入或准备 checkpoint 失败后中止, + Zeta 在准备 checkpoint 失败后中止。其他情况下,失败的任务会正常关闭 Sink,关闭时会先写入缓冲的行, + 因此失败前收到的行可能已经写入表中。无论哪种情况,引擎在重试任务或恢复作业时都会再次写入最后一个 + checkpoint 之后的行,即上文所述的至少一次语义。 +- 启动时,Sink 会从 Driver 的 schema 元数据中读取目标表的主键;如果元数据中没有该表,会再从服务端读取一次 schema。 + 这样,主键为 NULL 的行会在发送任何数据之前使作业失败,并给出表名和列名。如果仍然无法读取主键,作业会以错误 `CASSANDRA-06` 失败。 - 连接器底层使用 Cassandra Java Driver;认证相关参数与 Driver 保持一致。注意:`consistency_level` 当前 仅被接受、不会应用到写入语句;如需调整写入一致性级别,请调整集群/客户端的 Driver 默认配置。 - `batch_type = "UNLOGGED"` 是常见默认值;当正确性优先于吞吐时使用 `LOGGED`,counter 表使用 `COUNTER`。 diff --git a/docs/zh/introduction/concepts/incompatible-changes.md b/docs/zh/introduction/concepts/incompatible-changes.md index 70910428fa..9ad2cb20b1 100644 --- a/docs/zh/introduction/concepts/incompatible-changes.md +++ b/docs/zh/introduction/concepts/incompatible-changes.md @@ -49,6 +49,27 @@ - **影响**:此前因请求体格式报错的接口现在可以正常接收。专门适配旧格式、把每个元素再按 JSON 字符串解码的接收方,现在收到的是对象,需要修改。 - **迁移指南**:无需修改配置。如果接收方会把数组的每个元素从字符串解码,请改为直接使用该元素。 +### Cassandra:NULL 单元格保持为 NULL + +- **影响范围**:使用 Cassandra Source 读取 NULL 单元格,或使用 Cassandra Sink 写入 NULL 值的作业。 +- **行为变化**:Source 以前会把 NULL 的 `tinyint`、`smallint`、`int`、`bigint`、`float`、`double`、 + `boolean` 读取为 `0` 或 `false`,把 NULL 的 `list`、`set`、`map` 读取为空集合;NULL 的 `decimal`、 + `varint`、`uuid`、`timeuuid`、`inet`、`blob` 会导致作业失败。现在 Source 对以上类型都输出 NULL。Sink + 现在把 NULL 值写为 NULL,并覆盖目标行该列已有的值;以前大多数类型会导致作业失败,NULL 的 `inet` 会被写为 + `127.0.0.1`。主键列为 NULL 时,作业现在会失败并给出表名和列名;对于 `text`、`ascii`、`time` 或 `date` 主键,以前作业会成功但丢失数据行。为此,Sink 在启动时从驱动的 schema 元数据中读取目标表的主键,读取不到时作业失败。 +- **迁移方式**:无需修改配置。依赖 NULL 单元格读取为 `0`、`false` 或空集合的 Transform、Sink 和查询需要 + 改为处理 NULL;目标列声明为 `NOT NULL` 时,这些行现在会被拒绝。请在 Cassandra Sink 之前过滤掉主键为 NULL 的行。 + +### Cassandra Sink:无法写入的行会导致作业失败 + +- **影响范围**:使用 Cassandra Sink 的作业,`async_write` 取任意值。 +- **行为变化**:`async_write = true`(默认值)时,被 Cassandra 拒绝或超时的写入以前只会记录日志,作业会在缺少该行的情况下 + 正常结束。`async_write = false` 时,为下一批缓冲的行以前要等下一次 checkpoint 完成后才发送,因此此时的失败会让作业从该 + checkpoint 恢复并跳过这些行。现在 Sink 在每次 checkpoint、每写入 `batch_size` 行以及关闭时,都会写入缓冲的行并等待正在进行的 + 写入完成;无法写入的行会使作业失败,错误码为 `CASSANDRA-07`,并给出表名和 Cassandra 返回的错误。 +- **迁移方式**:无需修改配置。以前在丢失数据行的情况下仍成功结束的作业,现在会失败;请修正被 Cassandra 拒绝的行或表,例如超过其 + mutation 大小上限的值。恢复后的作业可能会再次写入上次 checkpoint 之后的行。 + ### Doris Source:`case_sensitive = false` 现在会将单表 `database`/`table` 转为小写 - **行为变更:单表 Doris Source 配置 `case_sensitive = false` 时,`database` 与 `table` 名称按小写解析** diff --git a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/exception/CassandraConnectorErrorCode.java b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/exception/CassandraConnectorErrorCode.java index fa8db0c0d0..746a4082b2 100644 --- a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/exception/CassandraConnectorErrorCode.java +++ b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/exception/CassandraConnectorErrorCode.java @@ -24,7 +24,9 @@ public enum CassandraConnectorErrorCode implements SeaTunnelErrorCode { ADD_BATCH_DATA_FAILED("CASSANDRA-02", "Add batch SeaTunnelRow data into a batch failed"), CLOSE_CQL_SESSION_FAILED("CASSANDRA-03", "Close cql session of cassandra failed"), NO_DATA_IN_SOURCE_TABLE("CASSANDRA-04", "No data in source table"), - PARSE_IP_ADDRESS_FAILED("CASSANDRA-05", "Parse ip address from string field"); + PARSE_IP_ADDRESS_FAILED("CASSANDRA-05", "Parse ip address from string field"), + READ_PRIMARY_KEY_FAILED("CASSANDRA-06", "Read the primary key of the target table failed"), + WRITE_FAILED("CASSANDRA-07", "Write rows into the target table failed"); private final String code; private final String description; diff --git a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSink.java b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSink.java index ed92ff6067..0d73c0cbc3 100644 --- a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSink.java +++ b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSink.java @@ -19,6 +19,7 @@ package org.apache.seatunnel.connectors.seatunnel.cassandra.sink; import org.apache.seatunnel.api.common.SeaTunnelAPIErrorCode; import org.apache.seatunnel.api.configuration.ReadonlyConfig; +import org.apache.seatunnel.api.sink.SeaTunnelSink; import org.apache.seatunnel.api.sink.SinkWriter; import org.apache.seatunnel.api.table.catalog.CatalogTable; import org.apache.seatunnel.api.table.type.SeaTunnelRow; @@ -28,8 +29,6 @@ import org.apache.seatunnel.connectors.seatunnel.cassandra.client.CassandraClien import org.apache.seatunnel.connectors.seatunnel.cassandra.config.CassandraParameters; import org.apache.seatunnel.connectors.seatunnel.cassandra.exception.CassandraConnectorErrorCode; import org.apache.seatunnel.connectors.seatunnel.cassandra.exception.CassandraConnectorException; -import org.apache.seatunnel.connectors.seatunnel.common.sink.AbstractSimpleSink; -import org.apache.seatunnel.connectors.seatunnel.common.sink.AbstractSinkWriter; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; @@ -41,7 +40,7 @@ import java.util.Optional; import static org.apache.seatunnel.connectors.seatunnel.cassandra.config.CassandraSinkOptions.TABLE; -public class CassandraSink extends AbstractSimpleSink<SeaTunnelRow, Void> { +public class CassandraSink implements SeaTunnelSink<SeaTunnelRow, Void, Void, Void> { private final CassandraParameters cassandraParameters; private final CatalogTable catalogTable; @@ -96,7 +95,7 @@ public class CassandraSink extends AbstractSimpleSink<SeaTunnelRow, Void> { } @Override - public AbstractSinkWriter<SeaTunnelRow, Void> createWriter(SinkWriter.Context context) + public SinkWriter<SeaTunnelRow, Void, Void> createWriter(SinkWriter.Context context) throws IOException { return new CassandraSinkWriter( cassandraParameters, catalogTable.getSeaTunnelRowType(), tableSchema); diff --git a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriter.java b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriter.java index 394b2b46be..db9504f447 100644 --- a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriter.java +++ b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriter.java @@ -17,34 +17,46 @@ package org.apache.seatunnel.connectors.seatunnel.cassandra.sink; +import org.apache.seatunnel.api.sink.SinkWriter; import org.apache.seatunnel.api.table.type.SeaTunnelRow; import org.apache.seatunnel.api.table.type.SeaTunnelRowType; -import org.apache.seatunnel.common.utils.ExceptionUtils; import org.apache.seatunnel.connectors.seatunnel.cassandra.client.CassandraClient; import org.apache.seatunnel.connectors.seatunnel.cassandra.config.CassandraParameters; import org.apache.seatunnel.connectors.seatunnel.cassandra.exception.CassandraConnectorErrorCode; import org.apache.seatunnel.connectors.seatunnel.cassandra.exception.CassandraConnectorException; import org.apache.seatunnel.connectors.seatunnel.cassandra.util.TypeConvertUtil; -import org.apache.seatunnel.connectors.seatunnel.common.sink.AbstractSinkWriter; +import com.datastax.oss.driver.api.core.CqlIdentifier; import com.datastax.oss.driver.api.core.CqlSession; import com.datastax.oss.driver.api.core.cql.AsyncResultSet; import com.datastax.oss.driver.api.core.cql.BatchStatement; import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.ColumnDefinition; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.metadata.Metadata; +import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata; import com.datastax.oss.driver.api.core.type.DataType; import lombok.extern.slf4j.Slf4j; import java.io.IOException; import java.util.ArrayList; import java.util.Arrays; +import java.util.Collections; import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.concurrent.CancellationException; import java.util.concurrent.CompletionStage; +import java.util.concurrent.ExecutionException; import java.util.concurrent.atomic.AtomicInteger; +import java.util.stream.Collectors; @Slf4j -public class CassandraSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> { +public class CassandraSinkWriter implements SinkWriter<SeaTunnelRow, Void, Void> { + + /** Failed writes added as suppressed to the error, after the first one, its cause. */ + static final int MAX_SUPPRESSED_WRITE_FAILURES = 9; private final CassandraParameters cassandraParameters; private final SeaTunnelRowType seaTunnelRowType; @@ -56,60 +68,200 @@ public class CassandraSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> private final PreparedStatement preparedStatement; private final AtomicInteger counter = new AtomicInteger(0); + /** Set once the session is closed, by {@link #close()} or {@link #abortPrepare()}. */ + private boolean sessionClosed; + + /** + * The primary key columns of the target table, never empty. A NULL value for one of them is + * rejected before anything is sent, with the table and column in the error. + */ + private final Set<CqlIdentifier> primaryKeyColumns; + public CassandraSinkWriter( CassandraParameters cassandraParameters, SeaTunnelRowType seaTunnelRowType, ColumnDefinitions tableSchema) { - this.cassandraParameters = cassandraParameters; - this.seaTunnelRowType = seaTunnelRowType; - this.tableSchema = tableSchema; - this.session = + this( + cassandraParameters, + seaTunnelRowType, + tableSchema, CassandraClient.getCqlSessionBuilder( cassandraParameters.getHost(), cassandraParameters.getKeyspace(), cassandraParameters.getUsername(), cassandraParameters.getPassword(), cassandraParameters.getDatacenter()) - .build(); + .build()); + } + + /** + * Creates a writer that owns {@code session}: {@link #close()} closes it, and so does this + * constructor when it fails. It fails when the primary key of the target table cannot be read + * from the driver schema metadata, also after one refresh, because a NULL key could then not be + * rejected before the write. + */ + CassandraSinkWriter( + CassandraParameters cassandraParameters, + SeaTunnelRowType seaTunnelRowType, + ColumnDefinitions tableSchema, + CqlSession session) { + this.cassandraParameters = cassandraParameters; + this.seaTunnelRowType = seaTunnelRowType; + this.tableSchema = tableSchema; + this.session = session; this.batchStatement = BatchStatement.builder(cassandraParameters.getBatchType()).build(); this.boundStatementList = new ArrayList<>(); this.completionStages = new ArrayList<>(); - this.preparedStatement = session.prepare(initPrepareCQL()); + try { + this.preparedStatement = session.prepare(initPrepareCQL()); + this.primaryKeyColumns = readPrimaryKeyColumns(); + } catch (RuntimeException e) { + try { + session.close(); + } catch (RuntimeException closeFailure) { + e.addSuppressed(closeFailure); + } + throw e; + } + } + + private Set<CqlIdentifier> readPrimaryKeyColumns() { + // The prepared statement names the table as the server resolved it, so a configured name + // such as keyspace.table needs no parsing here. + ColumnDefinition insertedColumn = preparedStatement.getVariableDefinitions().get(0); + CqlIdentifier keyspace = insertedColumn.getKeyspace(); + CqlIdentifier table = insertedColumn.getTable(); + Set<CqlIdentifier> primaryKey = primaryKeyColumns(session.getMetadata(), keyspace, table); + if (primaryKey.isEmpty()) { + // The driver may not have loaded the table yet, for example right after it was + // created. A refresh reads the schema from the server, even if schema metadata is + // disabled in the driver configuration. + primaryKey = primaryKeyColumns(session.refreshSchema(), keyspace, table); + } + if (primaryKey.isEmpty()) { + throw new CassandraConnectorException( + CassandraConnectorErrorCode.READ_PRIMARY_KEY_FAILED, + String.format( + "Cannot read the primary key of table %s.%s from the driver schema" + + " metadata. It is needed to reject a NULL key before the" + + " write.", + keyspace.asCql(true), table.asCql(true))); + } + return primaryKey; + } + + private static Set<CqlIdentifier> primaryKeyColumns( + Metadata metadata, CqlIdentifier keyspace, CqlIdentifier table) { + return metadata.getKeyspace(keyspace) + .flatMap(keyspaceMetadata -> keyspaceMetadata.getTable(table)) + .map( + tableMetadata -> + tableMetadata.getPrimaryKey().stream() + .map(ColumnMetadata::getName) + .collect(Collectors.toSet())) + .orElse(Collections.emptySet()); } @Override public void write(SeaTunnelRow row) throws IOException { BoundStatement boundStatement = this.preparedStatement.bind(); addIntoBatch(row, boundStatement); - if (counter.getAndIncrement() >= cassandraParameters.getBatchSize()) { + // The row that reaches batch_size is flushed with the others, so that no more than + // batch_size rows are buffered or in flight. + if (counter.incrementAndGet() >= cassandraParameters.getBatchSize()) { flush(); - counter.set(0); } } + /** + * Called at each checkpoint. Writes the rows buffered for the next batch and waits for the + * asynchronous writes in flight, so that the checkpoint completes only when every row received + * before it is in Cassandra, and fails when one of them could not be written. + */ + @Override + public Optional<Void> prepareCommit() { + flush(); + return Optional.empty(); + } + + /** + * Writes the buffered batch, or waits for the asynchronous writes in flight, and throws when a + * row could not be written. Called after {@code batch_size} rows, at each checkpoint and in + * {@link #close()}. + */ private void flush() { + counter.set(0); if (cassandraParameters.getAsyncWrite()) { - completionStages.forEach( - resultStage -> - resultStage.whenComplete( - (resultSet, error) -> { - if (error != null) { - log.error(ExceptionUtils.getMessage(error)); - } - })); - completionStages.clear(); + waitForAsyncWrites(); } else { - try { - this.session.execute(this.batchStatement.addAll(boundStatementList)); - } catch (Exception e) { - log.error("Batch insert error,Try inserting one by one!", e); - for (BoundStatement statement : boundStatementList) { + writeBatch(); + } + } + + private void waitForAsyncWrites() { + if (completionStages.isEmpty()) { + return; + } + int writes = completionStages.size(); + List<Throwable> failures = new ArrayList<>(); + try { + for (CompletionStage<AsyncResultSet> write : completionStages) { + try { + write.toCompletableFuture().get(); + } catch (ExecutionException e) { + failures.add(e.getCause()); + } catch (CancellationException e) { + failures.add(e); + } + } + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new CassandraConnectorException( + CassandraConnectorErrorCode.WRITE_FAILED, + "Interrupted while waiting for the writes to table " + + cassandraParameters.getTable(), + e); + } finally { + completionStages.clear(); + } + if (!failures.isEmpty()) { + CassandraConnectorException failure = + new CassandraConnectorException( + CassandraConnectorErrorCode.WRITE_FAILED, + String.format( + "%d of %d writes to table %s failed; the first failure is the" + + " cause", + failures.size(), writes, cassandraParameters.getTable()), + failures.get(0)); + failures.stream() + .skip(1) + .limit(MAX_SUPPRESSED_WRITE_FAILURES) + .forEach(failure::addSuppressed); + throw failure; + } + } + + private void writeBatch() { + if (boundStatementList.isEmpty()) { + return; + } + try { + this.session.execute(this.batchStatement.addAll(boundStatementList)); + } catch (Exception e) { + log.error("Batch insert error,Try inserting one by one!", e); + for (BoundStatement statement : boundStatementList) { + try { this.session.execute(statement); + } catch (RuntimeException rowFailure) { + throw new CassandraConnectorException( + CassandraConnectorErrorCode.WRITE_FAILED, + "Cannot write a row to table " + cassandraParameters.getTable(), + rowFailure); } - } finally { - this.batchStatement.clear(); - this.boundStatementList.clear(); } + } finally { + this.batchStatement.clear(); + this.boundStatementList.clear(); } } @@ -119,6 +271,15 @@ public class CassandraSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> String fieldName = cassandraParameters.getFields().get(i); DataType dataType = tableSchema.get(i).getType(); Object fieldValue = row.getField(seaTunnelRowType.indexOf(fieldName)); + // Reject a NULL key before anything is sent, with the table and the column. + if (fieldValue == null + && primaryKeyColumns.contains( + preparedStatement.getVariableDefinitions().get(i).getName())) { + throw new IllegalArgumentException( + String.format( + "Primary key column %s of table %s is NULL", + fieldName, cassandraParameters.getTable())); + } boundStatement = TypeConvertUtil.reconvertAndInject(boundStatement, i, dataType, fieldValue); } @@ -143,14 +304,55 @@ public class CassandraSinkWriter extends AbstractSinkWriter<SeaTunnelRow, Void> String.join(",", placeholder)); } + /** + * Called on a failed writer: by Spark when a write or {@link #prepareCommit()} throws, and by + * Zeta when preparing a checkpoint fails. Drops the buffered rows and the writes in flight + * without sending anything, because the engine writes them again when it retries or restores, + * and closes the session. Spark does not call {@link #close()} after it, so the session would + * otherwise keep its driver threads running. + */ + @Override + public void abortPrepare() { + counter.set(0); + completionStages.clear(); + boundStatementList.clear(); + closeSession(); + } + + /** + * Writes what is left, as {@link #prepareCommit()} does, and closes the session in any case. + * After {@link #abortPrepare()} there is nothing left to write and the session is closed. + */ @Override public void close() throws IOException { - flush(); + RuntimeException failure = null; try { - if (this.session != null) { - this.session.close(); + flush(); + } catch (RuntimeException e) { + failure = e; + } + try { + closeSession(); + } catch (RuntimeException e) { + if (failure == null) { + failure = e; + } else { + failure.addSuppressed(e); } - } catch (Exception e) { + } + if (failure != null) { + throw failure; + } + } + + private void closeSession() { + if (sessionClosed) { + return; + } + sessionClosed = true; + try { + session.close(); + } catch (RuntimeException e) { throw new CassandraConnectorException( CassandraConnectorErrorCode.CLOSE_CQL_SESSION_FAILED, e); } diff --git a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtil.java b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtil.java index 1753c97df2..861763a38f 100644 --- a/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtil.java +++ b/seatunnel-connectors-v2/connector-cassandra/src/main/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtil.java @@ -136,6 +136,10 @@ public class TypeConvertUtil { Object[] fields = new Object[row.size()]; ColumnDefinitions metaData = row.getColumnDefinitions(); for (int i = 0; i < row.size(); i++) { + // The driver's primitive getters read a CQL NULL as 0 or false, so check it first. + if (row.isNull(i)) { + continue; + } switch (metaData.get(i).getType().getProtocolCode()) { case ProtocolConstants.DataType.ASCII: case ProtocolConstants.DataType.VARCHAR: @@ -292,6 +296,10 @@ public class TypeConvertUtil { public static BoundStatement reconvertAndInject( BoundStatement statement, int index, DataType type, Object fileValue) { + // The typed setters below would unbox a null, or resolve a null inet to the loopback. + if (fileValue == null) { + return statement.setToNull(index); + } switch (type.getProtocolCode()) { case ProtocolConstants.DataType.VARCHAR: case ProtocolConstants.DataType.ASCII: diff --git a/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriterTest.java b/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriterTest.java new file mode 100644 index 0000000000..044a19639c --- /dev/null +++ b/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/sink/CassandraSinkWriterTest.java @@ -0,0 +1,412 @@ +/* + * 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.seatunnel.connectors.seatunnel.cassandra.sink; + +import org.apache.seatunnel.api.table.type.BasicType; +import org.apache.seatunnel.api.table.type.SeaTunnelDataType; +import org.apache.seatunnel.api.table.type.SeaTunnelRow; +import org.apache.seatunnel.api.table.type.SeaTunnelRowType; +import org.apache.seatunnel.connectors.seatunnel.cassandra.config.CassandraParameters; +import org.apache.seatunnel.connectors.seatunnel.cassandra.exception.CassandraConnectorException; + +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; + +import com.datastax.oss.driver.api.core.CqlIdentifier; +import com.datastax.oss.driver.api.core.CqlSession; +import com.datastax.oss.driver.api.core.cql.AsyncResultSet; +import com.datastax.oss.driver.api.core.cql.BoundStatement; +import com.datastax.oss.driver.api.core.cql.ColumnDefinition; +import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; +import com.datastax.oss.driver.api.core.cql.DefaultBatchType; +import com.datastax.oss.driver.api.core.cql.PreparedStatement; +import com.datastax.oss.driver.api.core.cql.Statement; +import com.datastax.oss.driver.api.core.metadata.Metadata; +import com.datastax.oss.driver.api.core.metadata.schema.ColumnMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.KeyspaceMetadata; +import com.datastax.oss.driver.api.core.metadata.schema.TableMetadata; +import com.datastax.oss.driver.api.core.type.DataType; +import com.datastax.oss.driver.api.core.type.DataTypes; + +import java.io.IOException; +import java.time.Duration; +import java.util.Arrays; +import java.util.Collections; +import java.util.Optional; +import java.util.concurrent.CompletableFuture; +import java.util.concurrent.CompletionStage; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.RETURNS_SELF; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class CassandraSinkWriterTest { + + private final CqlSession session = mock(CqlSession.class); + private final BoundStatement statement = mock(BoundStatement.class, RETURNS_SELF); + private boolean tableInMetadata = true; + private boolean tableInRefreshedMetadata = true; + private int batchSize = 100; + + @Test + void nullPrimaryKeyFailsTheWriteWithAsyncWrite() { + assertNullPrimaryKeyFailsTheWrite(true, "t"); + } + + @Test + void nullPrimaryKeyFailsTheWriteWithSyncWrite() { + assertNullPrimaryKeyFailsTheWrite(false, "t"); + } + + @Test + void nullPrimaryKeyFailsTheWriteWithATableNameIncludingTheKeyspace() { + assertNullPrimaryKeyFailsTheWrite(true, "ks.t"); + } + + @Test + void nullInAnotherColumnIsWritten() throws IOException { + writer(true, "t").write(new SeaTunnelRow(new Object[] {1L, null})); + + verify(statement).setLong(0, 1L); + verify(statement).setToNull(1); + verify(session).executeAsync(statement); + } + + @Test + void primaryKeyMissingFromTheMetadataIsReadAfterARefresh() { + tableInMetadata = false; + + assertNullPrimaryKeyFailsTheWrite(true, "t"); + verify(session).refreshSchema(); + } + + @Test + void writerFailsAndClosesTheSessionWhenThePrimaryKeyCannotBeRead() { + tableInMetadata = false; + tableInRefreshedMetadata = false; + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, () -> writer(true, "t")); + + Assertions.assertTrue( + e.getMessage().contains("Cannot read the primary key of table ks.t"), + e.getMessage()); + verify(session).close(); + verify(session, never()).executeAsync(any(Statement.class)); + } + + @Test + void writerClosesTheSessionWhenThePrepareFails() { + IllegalStateException prepareFailure = new IllegalStateException("prepare failed"); + when(session.prepare(anyString())).thenThrow(prepareFailure); + + CassandraParameters parameters = parameters(true, "t"); + IllegalStateException e = + Assertions.assertThrows( + IllegalStateException.class, + () -> + new CassandraSinkWriter( + parameters, + rowType(), + mock(ColumnDefinitions.class), + session)); + + Assertions.assertSame(prepareFailure, e); + verify(session).close(); + } + + @Test + void failedAsyncWriteFailsTheCheckpoint() throws IOException { + RuntimeException rejected = new RuntimeException("rejected"); + when(session.executeAsync(any(Statement.class))).thenReturn(written(), failed(rejected)); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + writer.write(row(2L)); + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, writer::prepareCommit); + + Assertions.assertTrue( + e.getMessage().contains("1 of 2 writes to table t failed"), e.getMessage()); + Assertions.assertSame(rejected, e.getCause()); + } + + @Test + void everyFailedAsyncWriteIsReported() throws IOException { + RuntimeException first = new RuntimeException("first"); + RuntimeException second = new RuntimeException("second"); + when(session.executeAsync(any(Statement.class))) + .thenReturn(failed(first), written(), failed(second)); + CassandraSinkWriter writer = writer(true, "t"); + for (long id = 1; id <= 3; id++) { + writer.write(row(id)); + } + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, writer::prepareCommit); + + Assertions.assertTrue( + e.getMessage().contains("2 of 3 writes to table t failed"), e.getMessage()); + Assertions.assertSame(first, e.getCause()); + Assertions.assertArrayEquals(new Throwable[] {second}, e.getSuppressed()); + } + + @Test + void failedAsyncWriteFailsTheWriteThatReachesTheBatchSize() throws IOException { + batchSize = 2; + RuntimeException rejected = new RuntimeException("rejected"); + when(session.executeAsync(any(Statement.class))).thenReturn(failed(rejected), written()); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + + CassandraConnectorException e = + Assertions.assertThrows( + CassandraConnectorException.class, () -> writer.write(row(2L))); + + Assertions.assertTrue( + e.getMessage().contains("1 of 2 writes to table t failed"), e.getMessage()); + Assertions.assertSame(rejected, e.getCause()); + } + + @Test + void batchSizeOfOneWaitsForEachAsyncWrite() { + batchSize = 1; + RuntimeException rejected = new RuntimeException("rejected"); + when(session.executeAsync(any(Statement.class))).thenReturn(failed(rejected)); + CassandraSinkWriter writer = writer(true, "t"); + + CassandraConnectorException e = + Assertions.assertThrows( + CassandraConnectorException.class, () -> writer.write(row(1L))); + + Assertions.assertSame(rejected, e.getCause()); + verify(session, times(1)).executeAsync(any(Statement.class)); + } + + @Test + void batchIsSentWhenItReachesTheBatchSize() throws IOException { + batchSize = 2; + CassandraSinkWriter writer = writer(false, "t"); + writer.write(row(1L)); + verify(session, never()).execute(any(Statement.class)); + + writer.write(row(2L)); + verify(session, times(1)).execute(any(Statement.class)); + } + + @Test + void checkpointPassesWhenEveryAsyncWriteSucceeded() throws IOException { + when(session.executeAsync(any(Statement.class))).thenReturn(written()); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + + Assertions.assertEquals(Optional.empty(), writer.prepareCommit()); + Assertions.assertEquals(Optional.empty(), writer.prepareCommit()); + } + + @Test + void checkpointWritesTheBufferedBatch() throws IOException { + CassandraSinkWriter writer = writer(false, "t"); + writer.write(row(1L)); + writer.write(row(2L)); + verify(session, never()).execute(any(Statement.class)); + + writer.prepareCommit(); + verify(session, times(1)).execute(any(Statement.class)); + + writer.prepareCommit(); + verify(session, times(1)).execute(any(Statement.class)); + } + + @Test + void rejectedRowOfTheBatchFailsTheCheckpoint() throws IOException { + RuntimeException rejected = new RuntimeException("rejected"); + when(session.execute(any(Statement.class))).thenThrow(rejected); + CassandraSinkWriter writer = writer(false, "t"); + writer.write(row(1L)); + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, writer::prepareCommit); + + Assertions.assertTrue( + e.getMessage().contains("Cannot write a row to table t"), e.getMessage()); + Assertions.assertSame(rejected, e.getCause()); + } + + @Test + void closeFailsAndClosesTheSessionWhenTheLastWritesFail() throws IOException { + RuntimeException rejected = new RuntimeException("rejected"); + when(session.executeAsync(any(Statement.class))).thenReturn(failed(rejected)); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, writer::close); + + Assertions.assertSame(rejected, e.getCause()); + verify(session).close(); + } + + @Test + void abortClosesTheSessionWithoutWritingTheBufferedBatch() throws IOException { + CassandraSinkWriter writer = writer(false, "t"); + writer.write(row(1L)); + + writer.abortPrepare(); + verify(session).close(); + + writer.close(); + verify(session, never()).execute(any(Statement.class)); + verify(session, times(1)).close(); + } + + @Test + void abortAfterAFailedCheckpointClosesTheSessionOnce() throws IOException { + when(session.executeAsync(any(Statement.class))) + .thenReturn(failed(new RuntimeException("rejected"))); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + Assertions.assertThrows(CassandraConnectorException.class, writer::prepareCommit); + + writer.abortPrepare(); + writer.close(); + + verify(session, times(1)).executeAsync(any(Statement.class)); + verify(session, times(1)).close(); + } + + @Test + void abortDoesNotWaitForTheWritesInFlight() throws IOException { + when(session.executeAsync(any(Statement.class))).thenReturn(new CompletableFuture<>()); + CassandraSinkWriter writer = writer(true, "t"); + writer.write(row(1L)); + + Assertions.assertTimeoutPreemptively(Duration.ofSeconds(10), writer::abortPrepare); + Assertions.assertTimeoutPreemptively(Duration.ofSeconds(10), writer::close); + verify(session, times(1)).close(); + } + + @Test + void abortFailsWhenTheSessionCannotBeClosed() { + RuntimeException closeFailure = new RuntimeException("close"); + doThrow(closeFailure).when(session).close(); + CassandraSinkWriter writer = writer(true, "t"); + + CassandraConnectorException e = + Assertions.assertThrows(CassandraConnectorException.class, writer::abortPrepare); + + Assertions.assertSame(closeFailure, e.getCause()); + } + + private static SeaTunnelRow row(long id) { + return new SeaTunnelRow(new Object[] {id, "a"}); + } + + private static CompletionStage<AsyncResultSet> written() { + return CompletableFuture.completedFuture(mock(AsyncResultSet.class)); + } + + private static CompletionStage<AsyncResultSet> failed(Throwable error) { + CompletableFuture<AsyncResultSet> write = new CompletableFuture<>(); + write.completeExceptionally(error); + return write; + } + + private void assertNullPrimaryKeyFailsTheWrite(boolean asyncWrite, String configuredTable) { + CassandraSinkWriter writer = writer(asyncWrite, configuredTable); + + CassandraConnectorException e = + Assertions.assertThrows( + CassandraConnectorException.class, + () -> writer.write(new SeaTunnelRow(new Object[] {null, "a"}))); + + Assertions.assertEquals( + "Primary key column id of table " + configuredTable + " is NULL", + e.getCause().getMessage()); + verify(session, never()).executeAsync(any(Statement.class)); + verify(session, never()).execute(any(Statement.class)); + } + + private CassandraSinkWriter writer(boolean asyncWrite, String configuredTable) { + CassandraParameters parameters = parameters(asyncWrite, configuredTable); + + ColumnDefinitions schema = mock(ColumnDefinitions.class); + ColumnDefinition idColumn = column("id", DataTypes.BIGINT); + ColumnDefinition textColumn = column("c", DataTypes.TEXT); + when(schema.get(0)).thenReturn(idColumn); + when(schema.get(1)).thenReturn(textColumn); + + PreparedStatement prepared = mock(PreparedStatement.class); + when(session.prepare(anyString())).thenReturn(prepared); + when(prepared.bind()).thenReturn(statement); + when(prepared.getVariableDefinitions()).thenReturn(schema); + + ColumnMetadata key = mock(ColumnMetadata.class); + when(key.getName()).thenReturn(CqlIdentifier.fromCql("id")); + TableMetadata table = mock(TableMetadata.class); + when(table.getPrimaryKey()).thenReturn(Collections.singletonList(key)); + Metadata metadata = metadata(tableInMetadata ? table : null); + Metadata refreshedMetadata = metadata(tableInRefreshedMetadata ? table : null); + when(session.getMetadata()).thenReturn(metadata); + when(session.refreshSchema()).thenReturn(refreshedMetadata); + + parameters.setBatchSize(batchSize); + return new CassandraSinkWriter(parameters, rowType(), schema, session); + } + + private static CassandraParameters parameters(boolean asyncWrite, String configuredTable) { + CassandraParameters parameters = new CassandraParameters(); + parameters.setKeyspace("ks"); + parameters.setTable(configuredTable); + parameters.setFields(Arrays.asList("id", "c")); + parameters.setBatchSize(100); + parameters.setBatchType(DefaultBatchType.UNLOGGED); + parameters.setAsyncWrite(asyncWrite); + return parameters; + } + + private static SeaTunnelRowType rowType() { + return new SeaTunnelRowType( + new String[] {"id", "c"}, + new SeaTunnelDataType[] {BasicType.LONG_TYPE, BasicType.STRING_TYPE}); + } + + /** Driver metadata whose keyspace {@code ks} holds {@code table} as {@code t}, if not null. */ + private static Metadata metadata(TableMetadata table) { + KeyspaceMetadata keyspace = mock(KeyspaceMetadata.class); + when(keyspace.getTable(CqlIdentifier.fromCql("t"))).thenReturn(Optional.ofNullable(table)); + Metadata metadata = mock(Metadata.class); + when(metadata.getKeyspace(CqlIdentifier.fromCql("ks"))).thenReturn(Optional.of(keyspace)); + return metadata; + } + + private static ColumnDefinition column(String name, DataType type) { + ColumnDefinition column = mock(ColumnDefinition.class); + when(column.getName()).thenReturn(CqlIdentifier.fromCql(name)); + when(column.getKeyspace()).thenReturn(CqlIdentifier.fromCql("ks")); + when(column.getTable()).thenReturn(CqlIdentifier.fromCql("t")); + when(column.getType()).thenReturn(type); + return column; + } +} diff --git a/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtilTest.java b/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtilTest.java index 1490877828..50369406b5 100644 --- a/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtilTest.java +++ b/seatunnel-connectors-v2/connector-cassandra/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/util/TypeConvertUtilTest.java @@ -22,12 +22,32 @@ import org.apache.seatunnel.api.table.type.SeaTunnelRow; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; +import com.datastax.oss.driver.api.core.ProtocolVersion; +import com.datastax.oss.driver.api.core.cql.BoundStatement; import com.datastax.oss.driver.api.core.cql.ColumnDefinition; import com.datastax.oss.driver.api.core.cql.ColumnDefinitions; import com.datastax.oss.driver.api.core.cql.Row; +import com.datastax.oss.driver.api.core.detach.AttachmentPoint; +import com.datastax.oss.driver.api.core.type.DataType; import com.datastax.oss.driver.api.core.type.DataTypes; +import com.datastax.oss.driver.api.core.type.codec.TypeCodecs; +import com.datastax.oss.driver.internal.core.cql.DefaultColumnDefinition; +import com.datastax.oss.driver.internal.core.cql.DefaultColumnDefinitions; +import com.datastax.oss.driver.internal.core.cql.DefaultRow; +import com.datastax.oss.protocol.internal.ProtocolConstants; +import com.datastax.oss.protocol.internal.response.result.ColumnSpec; +import com.datastax.oss.protocol.internal.response.result.RawType; +import java.nio.ByteBuffer; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; + +import static org.mockito.Mockito.RETURNS_SELF; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; class TypeConvertUtilTest { @@ -48,4 +68,127 @@ class TypeConvertUtilTest { Assertions.assertNull(seaTunnelRow.getField(0)); } + + @Test + void nullCellsBecomeNullFieldsForEveryType() { + RawType text = RawType.PRIMITIVES.get(ProtocolConstants.DataType.VARCHAR); + RawType integer = RawType.PRIMITIVES.get(ProtocolConstants.DataType.INT); + List<RawType> types = + new ArrayList<>( + Arrays.asList( + new RawType.RawList(text), + new RawType.RawList(integer), + new RawType.RawSet(text), + new RawType.RawMap(text, integer))); + for (int code : + new int[] { + ProtocolConstants.DataType.ASCII, + ProtocolConstants.DataType.VARCHAR, + ProtocolConstants.DataType.VARINT, + ProtocolConstants.DataType.TIMEUUID, + ProtocolConstants.DataType.UUID, + ProtocolConstants.DataType.INET, + ProtocolConstants.DataType.TINYINT, + ProtocolConstants.DataType.SMALLINT, + ProtocolConstants.DataType.INT, + ProtocolConstants.DataType.BIGINT, + ProtocolConstants.DataType.FLOAT, + ProtocolConstants.DataType.DOUBLE, + ProtocolConstants.DataType.DECIMAL, + ProtocolConstants.DataType.BOOLEAN, + ProtocolConstants.DataType.TIME, + ProtocolConstants.DataType.DATE, + ProtocolConstants.DataType.TIMESTAMP, + ProtocolConstants.DataType.BLOB + }) { + types.add(RawType.PRIMITIVES.get(code)); + } + + for (RawType type : types) { + SeaTunnelRow seaTunnelRow = TypeConvertUtil.buildSeaTunnelRow(driverRow(type, null)); + + Assertions.assertNull(seaTunnelRow.getField(0), "protocol type " + type.id); + } + } + + @Test + void storedZeroAndFalseAreStillRead() { + RawType integer = RawType.PRIMITIVES.get(ProtocolConstants.DataType.INT); + RawType bool = RawType.PRIMITIVES.get(ProtocolConstants.DataType.BOOLEAN); + + Assertions.assertEquals( + 0, + TypeConvertUtil.buildSeaTunnelRow( + driverRow( + integer, TypeCodecs.INT.encode(0, ProtocolVersion.DEFAULT))) + .getField(0)); + Assertions.assertEquals( + false, + TypeConvertUtil.buildSeaTunnelRow( + driverRow( + bool, + TypeCodecs.BOOLEAN.encode(false, ProtocolVersion.DEFAULT))) + .getField(0)); + } + + @Test + void nullValuesAreBoundAsNullForEveryType() { + List<DataType> types = + Arrays.asList( + DataTypes.ASCII, + DataTypes.TEXT, + DataTypes.VARINT, + DataTypes.TIMEUUID, + DataTypes.UUID, + DataTypes.INET, + DataTypes.TINYINT, + DataTypes.SMALLINT, + DataTypes.INT, + DataTypes.BIGINT, + DataTypes.COUNTER, + DataTypes.FLOAT, + DataTypes.DOUBLE, + DataTypes.DECIMAL, + DataTypes.BOOLEAN, + DataTypes.TIME, + DataTypes.DATE, + DataTypes.TIMESTAMP, + DataTypes.BLOB, + DataTypes.listOf(DataTypes.TEXT), + DataTypes.setOf(DataTypes.TEXT), + DataTypes.mapOf(DataTypes.TEXT, DataTypes.INT)); + + for (DataType type : types) { + BoundStatement statement = mock(BoundStatement.class, RETURNS_SELF); + + Assertions.assertSame( + statement, + TypeConvertUtil.reconvertAndInject(statement, 3, type, null), + type.toString()); + + verify(statement).setToNull(3); + verifyNoMoreInteractions(statement); + } + } + + @Test + void nonNullValuesAreStillBound() { + BoundStatement statement = mock(BoundStatement.class, RETURNS_SELF); + + TypeConvertUtil.reconvertAndInject(statement, 0, DataTypes.INT, 0); + + verify(statement).setInt(0, 0); + verifyNoMoreInteractions(statement); + } + + /** Builds a real driver row, whose getters decode a null value the way a CQL NULL is read. */ + private static Row driverRow(RawType type, ByteBuffer value) { + ColumnDefinition definition = + new DefaultColumnDefinition( + new ColumnSpec("test", "t", "c", 0, type), AttachmentPoint.NONE); + return new DefaultRow( + DefaultColumnDefinitions.valueOf(Collections.singletonList(definition)), + Collections.singletonList(value), + AttachmentPoint.NONE); + } } diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/CassandraIT.java b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/CassandraIT.java index d10695010d..788bdd167e 100644 --- a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/CassandraIT.java +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/java/org/apache/seatunnel/connectors/seatunnel/cassandra/CassandraIT.java @@ -112,6 +112,9 @@ public class CassandraIT extends TestSuiteBase implements TestResource { private static final String CASSANDRA_JOB_CONFIG = "/cassandra_to_cassandra.conf"; private static final String CASSANDRA_MULTI_TABLE_JOB_CONFIG = "/cassandra_multitable_source.conf"; + private static final String NULL_PRIMARY_KEY_JOB_CONFIG = + "/fake_null_primary_key_to_cassandra.conf"; + private static final String OVERSIZED_ROW_JOB_CONFIG = "/fake_oversized_row_to_cassandra.conf"; private static final String CASSANDRA_DRIVER_CONFIG = "/application.conf"; private static final String DATACENTER = "datacenter1"; private static final String KEYSPACE = "test"; @@ -124,6 +127,7 @@ public class CassandraIT extends TestSuiteBase implements TestResource { private static final String MT_INSERT_A = "mt_insert_a"; private static final String MT_INSERT_B = "mt_insert_b"; private static final int MT_ROWS_PER_TABLE = 5; + private static final long NULL_CELLS_ROW_ID = -1L; private static final Pair<SeaTunnelRowType, List<SeaTunnelRow>> TEST_DATASET = generateTestDataSet(); private Config config; @@ -375,14 +379,59 @@ public class CassandraIT extends TestSuiteBase implements TestResource { @TestTemplate public void testCassandra(TestContainer container) throws Exception { + // The job must clear these values: a NULL cell is written as NULL, not left unset + session.execute( + SimpleStatement.builder( + String.format( + "insert into %s (id, c_text, c_int, c_list_int)" + + " values (%d, 'old value', 7, [1, 2])", + SINK_TABLE, NULL_CELLS_ROW_ID)) + .setKeyspace(KEYSPACE) + .build()); Container.ExecResult execResult = container.executeJob(CASSANDRA_JOB_CONFIG); Assertions.assertEquals(0, execResult.getExitCode()); Assertions.assertNotNull(getRow()); + assertNullCellsStayNull(); compareResult(); clearSinkTable(); Assertions.assertNull(getRow()); } + @TestTemplate + public void testNullPrimaryKeyFailsTheJob(TestContainer container) throws Exception { + Container.ExecResult execResult = container.executeJob(NULL_PRIMARY_KEY_JOB_CONFIG); + Assertions.assertNotEquals(0, execResult.getExitCode()); + Assertions.assertTrue( + (execResult.getStdout() + execResult.getStderr()) + .contains("Primary key column id of table sink_table is NULL")); + Assertions.assertNull(getRow()); + } + + /** + * The server rejects the only row, which is larger than its mutation limit. The job has to fail + * with either write mode and the default restarts: an asynchronous write used to be only + * logged, and a synchronous batch used to be sent only after the final checkpoint, so the + * restored job finished without the row (#13286). + */ + @TestTemplate + public void testRejectedRowFailsTheJob(TestContainer container) throws Exception { + Map<Boolean, String> expectedErrors = new HashMap<>(); + expectedErrors.put(true, "1 of 1 writes to table sink_table failed"); + expectedErrors.put(false, "Cannot write a row to table sink_table"); + for (Map.Entry<Boolean, String> expected : expectedErrors.entrySet()) { + Container.ExecResult execResult = + container.executeJob( + OVERSIZED_ROW_JOB_CONFIG, + Collections.singletonList("async_write=" + expected.getKey())); + String output = execResult.getStdout() + execResult.getStderr(); + Assertions.assertNotEquals( + 0, execResult.getExitCode(), "async_write = " + expected.getKey()); + Assertions.assertTrue( + output.contains(expected.getValue()), "async_write = " + expected.getKey()); + Assertions.assertNull(getRow()); + } + } + @TestTemplate public void testCassandraMultiTableSource(TestContainer container) throws Exception { Container.ExecResult execResult = container.executeJob(CASSANDRA_MULTI_TABLE_JOB_CONFIG); @@ -502,11 +551,37 @@ public class CassandraIT extends TestSuiteBase implements TestResource { } session.execute(batchStatement); batchStatement.clear(); + // Every column of this row except the key is NULL. + session.execute( + SimpleStatement.builder( + String.format( + "insert into %s (id) values (%d)", + SOURCE_TABLE, NULL_CELLS_ROW_ID)) + .setKeyspace(KEYSPACE) + .build()); } catch (Exception e) { throw new RuntimeException("Batch insert data failed!", e); } } + private void assertNullCellsStayNull() { + Row row = + session.execute( + SimpleStatement.builder( + String.format( + "select * from %s where id = %d", + SINK_TABLE, NULL_CELLS_ROW_ID)) + .setKeyspace(KEYSPACE) + .build()) + .one(); + Assertions.assertNotNull(row, "The sink table has no row with id " + NULL_CELLS_ROW_ID); + for (String column : TEST_DATASET.getKey().getFieldNames()) { + if (!"id".equals(column)) { + Assertions.assertTrue(row.isNull(column), column); + } + } + } + private void compareResult() throws IOException { String sourceCql = "select * from " + SOURCE_TABLE; String sinkCql = "select * from " + SINK_TABLE; @@ -524,29 +599,29 @@ public class CassandraIT extends TestSuiteBase implements TestResource { Iterator<Row> sourceIterator = sourceResultSet.iterator(); Iterator<Row> sinkIterator = sinkResultSet.iterator(); while (sourceIterator.hasNext()) { - if (sinkIterator.hasNext()) { - Row sourceNext = sourceIterator.next(); - Row sinkNext = sinkIterator.next(); - for (String column : columnList) { - Object source = sourceNext.getObject(column); - Object sink = sinkNext.getObject(column); - if (!Objects.deepEquals(source, sink)) { - InputStream sourceAsciiStream = - sourceNext.get(column, ByteArrayInputStream.class); - InputStream sinkAsciiStream = - sinkNext.get(column, ByteArrayInputStream.class); - Assertions.assertNotNull(sourceAsciiStream); - Assertions.assertNotNull(sinkAsciiStream); - String sourceValue = - IOUtils.toString(sourceAsciiStream, StandardCharsets.UTF_8); - String sinkValue = - IOUtils.toString(sinkAsciiStream, StandardCharsets.UTF_8); - Assertions.assertEquals(sourceValue, sinkValue); - } - Assertions.assertTrue(true); + Row sourceNext = sourceIterator.next(); + Assertions.assertTrue( + sinkIterator.hasNext(), + "The sink table has no row for source row id " + sourceNext.getLong("id")); + Row sinkNext = sinkIterator.next(); + for (String column : columnList) { + Object source = sourceNext.getObject(column); + Object sink = sinkNext.getObject(column); + if (!Objects.deepEquals(source, sink)) { + InputStream sourceAsciiStream = + sourceNext.get(column, ByteArrayInputStream.class); + InputStream sinkAsciiStream = sinkNext.get(column, ByteArrayInputStream.class); + Assertions.assertNotNull(sourceAsciiStream); + Assertions.assertNotNull(sinkAsciiStream); + String sourceValue = + IOUtils.toString(sourceAsciiStream, StandardCharsets.UTF_8); + String sinkValue = IOUtils.toString(sinkAsciiStream, StandardCharsets.UTF_8); + Assertions.assertEquals(sourceValue, sinkValue); } } } + Assertions.assertFalse( + sinkIterator.hasNext(), "The sink table has more rows than the source table"); } private void createKeyspace() { diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_null_primary_key_to_cassandra.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_null_primary_key_to_cassandra.conf new file mode 100644 index 0000000000..caf5c9a56c --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_null_primary_key_to_cassandra.conf @@ -0,0 +1,53 @@ +# +# 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. +# + +env { + parallelism = 1 + job.mode = "BATCH" + # This job fails on purpose, so a restart can only repeat the failure. + job.retry.times = 0 +} + +source { + FakeSource { + plugin_output = "fake" + schema = { + fields { + id = bigint + } + } + rows = [ + { + kind = INSERT + fields = [null] + } + ] + } +} + +sink { + Cassandra { + plugin_input = "fake" + host = "cassandra:9042" + username = "" + password = "" + datacenter = "datacenter1" + keyspace = "test" + table = "sink_table" + fields = ["id"] + } +} diff --git a/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_oversized_row_to_cassandra.conf b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_oversized_row_to_cassandra.conf new file mode 100644 index 0000000000..d8bc409bb4 --- /dev/null +++ b/seatunnel-e2e/seatunnel-connector-v2-e2e/connector-cassandra-e2e/src/test/resources/fake_oversized_row_to_cassandra.conf @@ -0,0 +1,50 @@ +# +# 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. +# + +env { + parallelism = 1 + job.mode = "BATCH" +} + +source { + FakeSource { + plugin_output = "fake" + row.num = 1 + # 17 MiB, above the 16 MiB mutation limit of Cassandra 4.1, so the server rejects the row. + string.length = 17825792 + schema = { + fields { + id = bigint + c_text = string + } + } + } +} + +sink { + Cassandra { + plugin_input = "fake" + host = "cassandra:9042" + username = "" + password = "" + datacenter = "datacenter1" + keyspace = "test" + table = "sink_table" + fields = ["id", "c_text"] + async_write = ${async_write} + } +}
