This is an automated email from the ASF dual-hosted git repository.
JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git
The following commit(s) were added to refs/heads/master by this push:
new 48336684281 Support compatible type promotion in INSERT INTO ... SELECT
48336684281 is described below
commit 48336684281624f98295a1b186cdff902b7d2e69
Author: max <[email protected]>
AuthorDate: Sat Dec 5 15:17:40 2026 +0800
Support compatible type promotion in INSERT INTO ... SELECT
---
.../it/insertquery/IoTDBInsertQueryIT.java | 547 +++++++++-
.../iotdb/db/i18n/DataNodeQueryMessages.java | 3 +
.../iotdb/db/i18n/DataNodeQueryMessages.java | 3 +
.../TableInsertTabletStatementGenerator.java | 226 ++++-
.../operator/process/TableIntoOperator.java | 6 +-
.../planner/DataNodeTableOperatorGenerator.java | 55 +-
.../relational/analyzer/StatementAnalyzer.java | 58 +-
.../relational/planner/TableLogicalPlanner.java | 22 +-
.../TableInsertTabletStatementGeneratorTest.java | 1060 ++++++++++++++++++++
.../relational/analyzer/InsertIntoQueryTest.java | 569 +++++++++++
10 files changed, 2460 insertions(+), 89 deletions(-)
diff --git
a/integration-test/src/test/java/org/apache/iotdb/relational/it/insertquery/IoTDBInsertQueryIT.java
b/integration-test/src/test/java/org/apache/iotdb/relational/it/insertquery/IoTDBInsertQueryIT.java
index 69fa8f483e6..97dd1f3aedd 100644
---
a/integration-test/src/test/java/org/apache/iotdb/relational/it/insertquery/IoTDBInsertQueryIT.java
+++
b/integration-test/src/test/java/org/apache/iotdb/relational/it/insertquery/IoTDBInsertQueryIT.java
@@ -40,16 +40,19 @@ import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
+import java.nio.charset.StandardCharsets;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
+import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import static
org.apache.iotdb.itbase.runtime.ClusterTestResultSet.getNodeResultSets;
+import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
@@ -86,7 +89,8 @@ public class IoTDBInsertQueryIT {
.getConfig()
.getCommonConfig()
.setPartitionInterval(1000)
- .setMemtableSizeThreshold(10000);
+ .setMemtableSizeThreshold(10000)
+ .setSelectIntoInsertTabletPlanRowLimit(200);
EnvFactory.getEnv().initClusterEnvironment();
}
@@ -464,25 +468,544 @@ public class IoTDBInsertQueryIT {
}
}
- /** Reject a copy when the target field type is incompatible with the source
column type. */
+ /** Promote compatible source values instead of rejecting the INSERT SELECT.
*/
@Test
- public void testColumnTypeMismatch1() throws SQLException {
- String errMsg =
- "701: Insert query has mismatched column types: Table: [TIMESTAMP,
STRING, STRING, INT64, INT64, FLOAT, TEXT, BOOLEAN], Query: [TIMESTAMP, STRING,
STRING, INT32, INT64, FLOAT, TEXT, BOOLEAN]";
- Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
- Statement statement = connection.createStatement();
+ public void testCompatibleTypePromotion() throws SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE vehicle1(deviceId STRING TAG, manufacturer STRING TAG,
s0 INT64 FIELD, s1 INT64 FIELD, s2 FLOAT FIELD, s3 TEXT FIELD, s4 BOOLEAN
FIELD)");
+ statement.execute(String.format(insertIntoQuery, 1));
+
+ List<String> expectedHeader = new ArrayList<>();
+ List<String> expectedRetArray = new ArrayList<>();
+ try (ResultSet source =
+ statement.executeQuery("SELECT s0 FROM vehicle0 ORDER BY time,
deviceId, manufacturer")) {
+ buildExpectedResult(source, expectedHeader, expectedRetArray);
+ }
+ try (ResultSet target =
+ statement.executeQuery("SELECT s0 FROM vehicle1 ORDER BY time,
deviceId, manufacturer")) {
+ resultSetEqualTest(target, expectedHeader, expectedRetArray);
+ }
+ }
+ }
+
+ /** Convert numeric and DATE values to text and preserve null rows. */
+ @Test
+ public void testCompatibleTextConversionAndNull() throws SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE type_source(deviceId STRING TAG, intValue INT32 FIELD,
otherInt INT32 FIELD, dateValue DATE FIELD)");
+ statement.execute(
+ "CREATE TABLE type_target(deviceId STRING TAG, intText TEXT FIELD,
dateString STRING FIELD, doubleValue DOUBLE FIELD)");
+ statement.execute(
+ "INSERT INTO type_source(time, deviceId, intValue, otherInt,
dateValue) VALUES(1, 'd1', 123, 456, '2024-01-01'), (2, 'd1', NULL, NULL,
NULL)");
+
+ statement.execute(
+ "INSERT INTO type_target SELECT time, deviceId, intValue, dateValue,
otherInt FROM type_source");
+
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT intText, dateString, doubleValue FROM type_target ORDER
BY time")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals("123", resultSet.getString("intText"));
+ assertEquals("2024-01-01", resultSet.getString("dateString"));
+ assertEquals(456.0, resultSet.getDouble("doubleValue"), 0.0);
+ Assert.assertTrue(resultSet.next());
+ assertNull(resultSet.getString("intText"));
+ assertNull(resultSet.getString("dateString"));
+ resultSet.getDouble("doubleValue");
+ Assert.assertTrue(resultSet.wasNull());
+ assertFalse(resultSet.next());
+ }
+ }
+ }
+
+ /**
+ * Preserve YYYY-MM-DD formatting for DATE columns across exchanges,
literals, casts, and shared
+ * channels.
+ */
+ @Test
+ public void testDateToTextPreservesFormatAcrossExchangeAndExpressions()
throws SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE date_src(device_id STRING TAG, d DATE FIELD, raw_date
STRING FIELD)");
+ statement.execute(
+ "CREATE TABLE date_dst(device_id STRING TAG, d_str STRING FIELD,
d_text TEXT FIELD, lit_str STRING FIELD, cast_str TEXT FIELD)");
+ statement.execute(
+ "CREATE TABLE date_null_dst(device_id STRING TAG, d_str STRING
FIELD, d_text TEXT FIELD, lit_str STRING FIELD)");
+
+ StringBuilder batchInsert =
+ new StringBuilder("INSERT INTO date_src(time, device_id, d,
raw_date) VALUES ");
+ int rowNum = 0;
+ for (int day = 1; day <= 12; day++) {
+ for (int dev = 0; dev < 6; dev++) {
+ if (rowNum > 0) {
+ batchInsert.append(',');
+ }
+ long ts = day * 1000L + dev;
+ batchInsert.append(
+ String.format(
+ Locale.ENGLISH,
+ "(%d, 'd%d', '2024-01-%02d', '2024-03-%02d')",
+ ts,
+ dev,
+ day,
+ day));
+ rowNum++;
+ }
+ }
+ statement.execute(batchInsert.toString());
+ statement.execute("FLUSH");
+
+ // Non-device LIMIT over multiple devices/regions exercises ExchangeNode
+ shared channels +
+ // CAST/literal folding.
+ statement.execute(
+ "INSERT INTO date_dst SELECT time, device_id, d, d,
CAST('2024-02-29' AS DATE), CAST(raw_date AS DATE) FROM date_src LIMIT 72");
+
+ int count = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, device_id, d_str, d_text, lit_str, cast_str FROM
date_dst ORDER BY time, device_id")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ int day = (int) (ts / 1000L);
+ String expectedDate = String.format(Locale.ENGLISH, "2024-01-%02d",
day);
+ String expectedCast = String.format(Locale.ENGLISH, "2024-03-%02d",
day);
+ assertEquals(expectedDate, resultSet.getString("d_str"));
+ assertEquals(expectedDate, resultSet.getString("d_text"));
+ assertEquals("2024-02-29", resultSet.getString("lit_str"));
+ assertEquals(expectedCast, resultSet.getString("cast_str"));
+ count++;
+ }
+ }
+ assertEquals(72, count);
+
+ statement.execute(
+ "INSERT INTO date_src(time, device_id, d, raw_date) VALUES (99999,
'd0', NULL, NULL)");
+ statement.execute(
+ "INSERT INTO date_null_dst SELECT time, device_id, d, d,
CAST('2024-02-29' AS DATE) FROM date_src WHERE time = 99999");
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT d_str, d_text, lit_str FROM
date_null_dst")) {
+ Assert.assertTrue(resultSet.next());
+ assertNull(resultSet.getString("d_str"));
+ assertNull(resultSet.getString("d_text"));
+ assertEquals("2024-02-29", resultSet.getString("lit_str"));
+ assertFalse(resultSet.next());
+ }
+ }
+ }
+
+ /**
+ * Reject NULL and out-of-precision integer timestamps when promoted to the
target time column.
+ */
+ @Test
+ public void testIntegerTimePromotionNullAndPrecisionValidation() throws
SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE time_src(device_id STRING TAG, tick INT32 FIELD,
micro_tick INT64 FIELD, v INT32 FIELD)");
+ statement.execute("CREATE TABLE time_dst(device_id STRING TAG, v INT32
FIELD)");
+
+ // Sentinel row at time=0 ensures NULL timestamp coercion cannot
overwrite existing data.
+ statement.execute("INSERT INTO time_dst(time, device_id, v) VALUES (0,
'd1', 999)");
+ statement.execute(
+ "INSERT INTO time_src(time, device_id, tick, micro_tick, v) VALUES
(1, 'd1', NULL, 100, 22), (2, 'd1', 500, 1700000000000000, 33)");
+
+ try {
+ statement.execute(
+ "INSERT INTO time_dst(time, device_id, v) SELECT tick, device_id,
v FROM time_src WHERE time = 1");
+ fail("Expected NULL timestamp failure");
+ } catch (Exception e) {
+ Assert.assertTrue(e.getMessage(), e.getMessage().contains("701:
Timestamp cannot be null"));
+ }
+
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT time, device_id, v FROM time_dst
ORDER BY time")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals(0L, resultSet.getLong(1));
+ assertEquals(999, resultSet.getInt(3));
+ assertFalse(resultSet.next());
+ }
+
+ try {
+ statement.execute(
+ "INSERT INTO time_dst(time, device_id, v) SELECT micro_tick,
device_id, v FROM time_src WHERE time = 2");
+ fail("Expected timestamp precision failure");
+ } catch (Exception e) {
+ Assert.assertTrue(
+ e.getMessage(),
+ e.getMessage().contains("701:") &&
e.getMessage().contains("1700000000000000"));
+ }
+
+ statement.execute(
+ "INSERT INTO time_dst(time, device_id, v) SELECT tick, device_id, v
FROM time_src WHERE time = 2");
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT time, device_id, v FROM time_dst
ORDER BY time")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals(0L, resultSet.getLong(1));
+ assertEquals(999, resultSet.getInt(3));
+ Assert.assertTrue(resultSet.next());
+ assertEquals(500L, resultSet.getLong(1));
+ assertEquals(33, resultSet.getInt(3));
+ assertFalse(resultSet.next());
+ }
+ }
+ }
+
+ /**
+ * Preserve exact TIMESTAMP-to-TIMESTAMP copies when timestamp precision
checking is re-enabled,
+ * while continuing to reject out-of-precision promoted integer constants.
+ */
+ @Test
+ public void testNativeTimestampCopyPreservedWhenPrecisionCheckReEnabled()
throws SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ try {
+ statement.execute("CREATE TABLE native_time_src (v INT32 FIELD)");
+ statement.execute("CREATE TABLE native_time_dst (v INT32 FIELD)");
+ statement.execute(
+ "CREATE TABLE native_time_dist_src (device_id STRING TAG, v INT32
FIELD)");
+ statement.execute(
+ "CREATE TABLE native_time_dist_dst (device_id STRING TAG, v INT32
FIELD)");
+ statement.execute("CREATE TABLE native_time_rle_dst (v INT32 FIELD)");
+ statement.execute("CREATE TABLE native_time_rle_reject_dst (v INT32
FIELD)");
+
+ setTimestampPrecisionCheckEnabled(statement, false);
+ statement.execute("INSERT INTO native_time_src (time, v) VALUES
(1700000000000000, 42)");
+
+ StringBuilder distInsert =
+ new StringBuilder("INSERT INTO native_time_dist_src (time,
device_id, v) VALUES ");
+ int rowIdx = 0;
+ for (int dev = 0; dev < 6; dev++) {
+ for (int i = 0; i < 2; i++) {
+ if (rowIdx > 0) {
+ distInsert.append(',');
+ }
+ long ts = 1_700_000_000_000_000L + dev * 10L + i;
+ distInsert.append(String.format(Locale.ENGLISH, "(%d, 'd%d', %d)",
ts, dev, rowIdx));
+ rowIdx++;
+ }
+ }
+ statement.execute(distInsert.toString());
+ statement.execute("FLUSH");
+
+ setTimestampPrecisionCheckEnabled(statement, true);
+
+ // 1. Plain TIMESTAMP -> TIMESTAMP copy succeeds even when precision
check is re-enabled.
+ statement.execute("INSERT INTO native_time_dst SELECT time, v FROM
native_time_src");
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT time, v FROM native_time_dst ORDER
BY time")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals(1_700_000_000_000_000L, resultSet.getLong(1));
+ assertEquals(42, resultSet.getInt(2));
+ assertFalse(resultSet.next());
+ }
+
+ // 2. Distributed ExchangeNode copy across devices preserves logical
TIMESTAMP type.
+ statement.execute(
+ "INSERT INTO native_time_dist_dst SELECT time, device_id, v FROM
native_time_dist_src LIMIT 12");
+ int distCount = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, device_id, v FROM native_time_dist_dst ORDER BY
time, device_id")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ long offset = ts - 1_700_000_000_000_000L;
+ int dev = (int) (offset / 10L);
+ int i = (int) (offset % 10L);
+ assertEquals("d" + dev, resultSet.getString(2));
+ assertEquals(dev * 2 + i, resultSet.getInt(3));
+ distCount++;
+ }
+ }
+ assertEquals(12, distCount);
+
+ // 3. RLE TIMESTAMP constant path succeeds when precision check is
enabled.
+ statement.execute(
+ "INSERT INTO native_time_rle_dst SELECT CAST(1700000000000000 AS
TIMESTAMP), v FROM native_time_src");
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT time, v FROM native_time_rle_dst
ORDER BY time")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals(1_700_000_000_000_000L, resultSet.getLong(1));
+ assertEquals(42, resultSet.getInt(2));
+ assertFalse(resultSet.next());
+ }
+
+ // 4. RLE INT64 constant path is still rejected when precision check
is enabled.
+ try {
+ statement.execute(
+ "INSERT INTO native_time_rle_reject_dst SELECT 1700000000000000,
v FROM native_time_src");
+ fail("Expected out-of-precision INT64 RLE timestamp to be rejected");
+ } catch (Exception e) {
+ Assert.assertTrue(
+ e.getMessage(),
+ e.getMessage().contains("701:") &&
e.getMessage().contains("1700000000000000"));
+ }
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT count(*) FROM
native_time_rle_reject_dst")) {
+ Assert.assertTrue(resultSet.next());
+ assertEquals(0L, resultSet.getLong(1));
+ }
+ } finally {
+ setTimestampPrecisionCheckEnabled(statement, true);
+ }
+ }
+ }
+
+ private static void setTimestampPrecisionCheckEnabled(Statement statement,
boolean enabled)
+ throws SQLException {
try {
+ statement.execute(
+ String.format("SET CONFIGURATION
timestamp_precision_check_enabled='%s'", enabled));
+ } catch (SQLException e) {
+ // run in IDE will trigger this, ignore it
+ if (e.getMessage() == null
+ || !e.getMessage().contains("Unable to find the configuration
file")) {
+ throw e;
+ }
+ }
+ }
+
+ /**
+ * Support multiple destination columns (including time) reading one source
column across batches.
+ */
+ @Test
+ public void testSharedSourceColumnAndMultiBatchPromotion() throws
SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
statement.execute("USE test");
- // create table
statement.execute(
- "CREATE TABLE IF NOT EXISTS vehicle1(deviceId STRING TAG,
manufacturer STRING TAG, s0 INT64 FIELD, s1 INT64 FIELD, s2 FLOAT FIELD, s3
TEXT FIELD, s4 BOOLEAN FIELD)");
- // insert into vehicle1 select * from vehicle0
+ "CREATE TABLE dup_dst(device_id STRING TAG, wide INT64 FIELD,
formatted STRING FIELD, text_copy TEXT FIELD)");
+ statement.execute(
+ "INSERT INTO dup_dst(time, device_id, wide, formatted, text_copy)
SELECT time, deviceId, s0, s0, s0 FROM vehicle0");
+
+ int count = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, wide, formatted, text_copy FROM dup_dst ORDER BY
time, device_id")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ assertEquals(ts, resultSet.getLong(2));
+ assertEquals(Long.toString(ts), resultSet.getString(3));
+ assertEquals(Long.toString(ts), resultSet.getString(4));
+ count++;
+ }
+ }
+ assertEquals(1200, count);
+
+ statement.execute(
+ "CREATE TABLE time_and_val_dst(device_id STRING TAG, formatted
STRING FIELD)");
+ statement.execute(
+ "INSERT INTO time_and_val_dst(time, device_id, formatted) SELECT s0,
deviceId, s0 FROM vehicle0 WHERE deviceId = 'd0' LIMIT 50");
+
+ int promotedCount = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery("SELECT time, formatted FROM time_and_val_dst
ORDER BY time")) {
+ while (resultSet.next()) {
+ assertEquals(Long.toString(resultSet.getLong(1)),
resultSet.getString(2));
+ promotedCount++;
+ }
+ }
+ assertEquals(50, promotedCount);
+ }
+ }
+
+ /**
+ * Verify multi-batch tablet splitting (> rowLimit) with DATE promotion
across ExchangeNode and
+ * out-of-order TAG columns triggering downstream swapColumn().
+ */
+ @Test
+ public void testMultiBatchDatePromotionWithTagReordering() throws
SQLException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE mb_date_src(device_id STRING TAG, region_tag STRING
TAG, d DATE FIELD, tag_num INT32 FIELD)");
+ statement.execute(
+ "CREATE TABLE mb_date_dst(device_id STRING TAG, d_str STRING FIELD,
d_text TEXT FIELD)");
+ statement.execute("CREATE TABLE mb_int_tag_dst(tag_id STRING TAG, d_str
STRING FIELD)");
+ statement.execute(
+ "CREATE TABLE mb_multi_tag_dst(t1 STRING TAG, t2 STRING TAG, d_str
STRING FIELD)");
+
+ // 450 rows > selectIntoInsertTabletPlanRowLimit(200) -> 3 tablets
across 6 devices.
+ LocalDate startDate = LocalDate.of(2024, 1, 1);
+ for (int batch = 0; batch < 5; batch++) {
+ StringBuilder insertSql =
+ new StringBuilder(
+ "INSERT INTO mb_date_src(time, device_id, region_tag, d,
tag_num) VALUES ");
+ int batchRows = 0;
+ for (int dayOffset = batch * 15; dayOffset < (batch + 1) * 15;
dayOffset++) {
+ String dateLiteral = startDate.plusDays(dayOffset).toString();
+ for (int dev = 0; dev < 6; dev++) {
+ if (batchRows > 0) {
+ insertSql.append(',');
+ }
+ long ts = (dayOffset + 1L) * 1000L + dev;
+ insertSql.append(
+ String.format(
+ Locale.ENGLISH,
+ "(%d, 'd%d', 'r%d', '%s', %d)",
+ ts,
+ dev,
+ dev % 2,
+ dateLiteral,
+ dev));
+ batchRows++;
+ }
+ }
+ statement.execute(insertSql.toString());
+ }
+ statement.execute("FLUSH");
+
+ // Scenario 1: DATE FIELD before STRING TAG + LIMIT over multi-device
regions (ExchangeNode).
+ statement.execute(
+ "INSERT INTO mb_date_dst(time, d_str, d_text, device_id) SELECT
time, d, d, device_id FROM mb_date_src LIMIT 450");
+ int count1 = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, device_id, d_str, d_text FROM mb_date_dst ORDER BY
time, device_id")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ int dayOffset = (int) (ts / 1000L) - 1;
+ int dev = (int) (ts % 1000L);
+ String expectedDate = startDate.plusDays(dayOffset).toString();
+ assertEquals("d" + dev, resultSet.getString("device_id"));
+ assertEquals(expectedDate, resultSet.getString("d_str"));
+ assertEquals(expectedDate, resultSet.getString("d_text"));
+ count1++;
+ }
+ }
+ assertEquals(450, count1);
+
+ // Scenario 2: DATE FIELD before non-string (INT32 -> STRING) TAG across
3 tablets.
+ statement.execute(
+ "INSERT INTO mb_int_tag_dst(time, d_str, tag_id) SELECT time, d,
tag_num FROM mb_date_src LIMIT 450");
+ int count2 = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, tag_id, d_str FROM mb_int_tag_dst ORDER BY time,
tag_id")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ int dayOffset = (int) (ts / 1000L) - 1;
+ int dev = (int) (ts % 1000L);
+ assertEquals(Integer.toString(dev), resultSet.getString("tag_id"));
+ assertEquals(startDate.plusDays(dayOffset).toString(),
resultSet.getString("d_str"));
+ count2++;
+ }
+ }
+ assertEquals(450, count2);
+
+ // Scenario 3: Multi-TAG reversed order with DATE FIELD in between
across 3 tablets.
+ statement.execute(
+ "INSERT INTO mb_multi_tag_dst(time, t2, d_str, t1) SELECT time,
region_tag, d, device_id FROM mb_date_src LIMIT 450");
+ int count3 = 0;
+ try (ResultSet resultSet =
+ statement.executeQuery(
+ "SELECT time, t1, t2, d_str FROM mb_multi_tag_dst ORDER BY time,
t1, t2")) {
+ while (resultSet.next()) {
+ long ts = resultSet.getLong(1);
+ int dayOffset = (int) (ts / 1000L) - 1;
+ int dev = (int) (ts % 1000L);
+ assertEquals("d" + dev, resultSet.getString("t1"));
+ assertEquals("r" + (dev % 2), resultSet.getString("t2"));
+ assertEquals(startDate.plusDays(dayOffset).toString(),
resultSet.getString("d_str"));
+ count3++;
+ }
+ }
+ assertEquals(450, count3);
+ }
+ }
+
+ /**
+ * Lock storage-aligned conversion contracts for TIMESTAMP -> STRING/TEXT,
BLOB <-> STRING/TEXT,
+ * and non-string values promoted into TAG/ATTRIBUTE columns.
+ */
+ @Test
+ public void testCompatibleEdgeTypeConversions()
+ throws SQLException, IoTDBConnectionException,
StatementExecutionException {
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE edge_src(device_id STRING TAG, ts TIMESTAMP FIELD,
utf8_blob BLOB FIELD, raw_blob BLOB FIELD, raw_str STRING FIELD, raw_text TEXT
FIELD, int_val INT32 FIELD, d DATE FIELD)");
+ statement.execute(
+ "CREATE TABLE edge_dst(tag_from_int STRING TAG, attr_from_date
STRING ATTRIBUTE, ts_str STRING FIELD, ts_text TEXT FIELD, utf8_blob_str STRING
FIELD, raw_blob_text TEXT FIELD, str_to_blob BLOB FIELD, text_to_blob BLOB
FIELD)");
+
+ statement.execute(
+ "INSERT INTO edge_src(time, device_id, ts, utf8_blob, raw_blob,
raw_str, raw_text, int_val, d) VALUES "
+ + "(10, 'd1', 1704067200000, X'68656c6c6f', X'cafebabe',
'hello', 'world', 42, '2024-02-29'), "
+ + "(20, 'd2', NULL, NULL, NULL, NULL, NULL, 43, NULL)");
+
+ statement.execute(
+ "INSERT INTO edge_dst(time, tag_from_int, attr_from_date, ts_str,
ts_text, utf8_blob_str, raw_blob_text, str_to_blob, text_to_blob) "
+ + "SELECT time, int_val, d, ts, ts, utf8_blob, raw_blob,
raw_str, raw_text FROM edge_src");
+
+ // BLOB must not promote into a TAG column because invalid UTF-8 bytes
collide via
+ // Binary.toString() during device ID construction.
+ try {
+ statement.execute(
+ "INSERT INTO edge_dst(time, tag_from_int, ts_str) SELECT time,
raw_blob, ts FROM edge_src");
+ fail("Expected BLOB -> STRING TAG promotion to be rejected");
+ } catch (Exception e) {
+ Assert.assertTrue(
+ e.getMessage(),
+ e.getMessage().contains("701: Insert query has mismatched column
types"));
+ }
+
+ byte[] expectedRawBlob = new byte[] {(byte) 0xCA, (byte) 0xFE, (byte)
0xBA, (byte) 0xBE};
+ byte[] expectedHelloBytes = "hello".getBytes(StandardCharsets.UTF_8);
+ byte[] expectedWorldBytes = "world".getBytes(StandardCharsets.UTF_8);
+
+ try (ITableSession session =
EnvFactory.getEnv().getTableSessionConnection();
+ SessionDataSet dataSet =
+ session.executeQueryStatement(
+ "SELECT time, tag_from_int, attr_from_date, ts_str, ts_text,
utf8_blob_str, raw_blob_text, str_to_blob, text_to_blob FROM test.edge_dst
ORDER BY time")) {
+ Assert.assertTrue(dataSet.hasNext());
+ RowRecord row1 = dataSet.next();
+ assertEquals(10L, row1.getFields().get(0).getLongV());
+ assertEquals("42", row1.getFields().get(1).getStringValue());
+ assertEquals("2024-02-29", row1.getFields().get(2).getStringValue());
+ assertEquals("1704067200000",
row1.getFields().get(3).getStringValue());
+ assertEquals("1704067200000",
row1.getFields().get(4).getStringValue());
+ assertEquals("hello", row1.getFields().get(5).getStringValue());
+ assertArrayEquals(expectedRawBlob,
row1.getFields().get(6).getBinaryV().getValues());
+ assertArrayEquals(expectedHelloBytes,
row1.getFields().get(7).getBinaryV().getValues());
+ assertArrayEquals(expectedWorldBytes,
row1.getFields().get(8).getBinaryV().getValues());
+
+ Assert.assertTrue(dataSet.hasNext());
+ RowRecord row2 = dataSet.next();
+ assertEquals(20L, row2.getFields().get(0).getLongV());
+ assertEquals("43", row2.getFields().get(1).getStringValue());
+ for (int col = 2; col <= 8; col++) {
+ assertNull(row2.getFields().get(col).getDataType());
+ }
+ assertFalse(dataSet.hasNext());
+ }
+ }
+ }
+
+ /** Reject source and target types that are not in the compatibility table.
*/
+ @Test
+ public void testIncompatibleTypePromotionRejected() throws SQLException {
+ String errMsg =
+ "701: Insert query has mismatched column types: Table: [TIMESTAMP,
STRING, STRING, INT64, INT64, INT64, TEXT, BOOLEAN], Query: [TIMESTAMP, STRING,
STRING, INT32, INT64, FLOAT, TEXT, BOOLEAN]";
+ try (Connection connection =
EnvFactory.getEnv().getConnection(BaseEnv.TABLE_SQL_DIALECT);
+ Statement statement = connection.createStatement()) {
+ statement.execute("USE test");
+ statement.execute(
+ "CREATE TABLE vehicle1(deviceId STRING TAG, manufacturer STRING TAG,
s0 INT64 FIELD, s1 INT64 FIELD, s2 INT64 FIELD, s3 TEXT FIELD, s4 BOOLEAN
FIELD)");
statement.execute(String.format(insertIntoQuery, 1));
fail("No exception!");
} catch (Exception e) {
Assert.assertTrue(e.getMessage(), e.getMessage().contains(errMsg));
- } finally {
- statement.execute(String.format(dropTableTemplate, 1));
}
}
diff --git
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
index a3a76b8e827..2d0d9147371 100644
---
a/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/en/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
@@ -5036,4 +5036,7 @@ public final class DataNodeQueryMessages {
public static final String LOG_QUERYFAILED_QUERYID_ARG_SQL_ARG_249264E9 =
"[QueryFailed] queryId: {}, sql: {}";
+
+ public static final String
EXCEPTION_ROWLIMIT_MUST_BE_POSITIVE_BUT_WAS_ARG_E10AF0CD =
+ "rowLimit must be positive, but was: %d";
}
diff --git
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
index 9efab6b8879..c40d6a7d900 100644
---
a/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
+++
b/iotdb-core/datanode/src/main/i18n/zh/org/apache/iotdb/db/i18n/DataNodeQueryMessages.java
@@ -5735,4 +5735,7 @@ public final class DataNodeQueryMessages {
public static final String LOG_QUERYFAILED_QUERYID_ARG_SQL_ARG_249264E9 =
"[QueryFailed] queryId: {}, SQL:{}";
+
+ public static final String
EXCEPTION_ROWLIMIT_MUST_BE_POSITIVE_BUT_WAS_ARG_E10AF0CD =
+ "rowLimit 必须为正数,但实际值为:%d";
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGenerator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGenerator.java
index 08a15eaddb5..1773cb427f1 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGenerator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGenerator.java
@@ -19,31 +19,44 @@
package org.apache.iotdb.db.queryengine.execution.operator.process;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
import org.apache.iotdb.commons.path.PartialPath;
import
org.apache.iotdb.commons.queryengine.plan.planner.plan.parameter.InputLocation;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
import
org.apache.iotdb.db.queryengine.plan.statement.crud.InsertTabletStatement;
+import org.apache.iotdb.db.utils.TypeServices;
+import org.apache.iotdb.db.utils.TypeServices.SourceColumnToTabletValueWriter;
import org.apache.tsfile.block.column.Column;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.read.common.block.TsBlock;
+import org.apache.tsfile.read.common.block.column.NullColumn;
+import org.apache.tsfile.read.common.block.column.RunLengthEncodedColumn;
import org.apache.tsfile.read.common.type.Type;
import org.apache.tsfile.read.common.type.TypeFactory;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.BitMap;
import org.apache.tsfile.utils.RamUsageEstimator;
+import java.nio.charset.StandardCharsets;
+import java.util.Arrays;
import java.util.List;
import java.util.Map;
-import java.util.concurrent.atomic.AtomicLong;
public class TableInsertTabletStatementGenerator extends
InsertTabletStatementGenerator {
private static final long INSTANCE_SIZE =
RamUsageEstimator.shallowSizeOfInstance(TableInsertTabletStatementGenerator.class);
private final String databaseName;
- private final AtomicLong writtenCounter;
+ private long writtenCount;
private final int timeColumnIndex;
+ private final TSDataType timeSourceDataType;
+ private final TSDataType[] sourceDataTypes;
private final TsTableColumnCategory[] columnCategories;
+ private final SourceColumnToTabletValueWriter[] writers;
public TableInsertTabletStatementGenerator(
String databaseName,
@@ -54,7 +67,8 @@ public class TableInsertTabletStatementGenerator extends
InsertTabletStatementGe
List<TsTableColumnCategory> tsTableColumnCategories,
boolean isAligned,
int rowLimit,
- String timeColumnName) {
+ String timeColumnName,
+ TSDataType timeSourceDataType) {
super(
targetTable,
measurementToDataTypeMap.keySet().toArray(new String[0]),
@@ -63,47 +77,208 @@ public class TableInsertTabletStatementGenerator extends
InsertTabletStatementGe
.filter(entry -> !entry.getKey().equalsIgnoreCase(timeColumnName))
.map(Map.Entry::getValue)
.toArray(InputLocation[]::new),
-
inputColumnTypes.stream().map(TypeFactory::getType).toArray(Type[]::new),
+
measurementToDataTypeMap.values().stream().map(TypeFactory::getType).toArray(Type[]::new),
isAligned,
rowLimit);
+ if (rowLimit <= 0) {
+ throw new IllegalArgumentException(
+ String.format(
+
DataNodeQueryMessages.EXCEPTION_ROWLIMIT_MUST_BE_POSITIVE_BUT_WAS_ARG_E10AF0CD,
+ rowLimit));
+ }
this.databaseName = databaseName;
- this.writtenCounter = new AtomicLong(0);
+ this.writtenCount = 0L;
+ this.sourceDataTypes = inputColumnTypes.toArray(new TSDataType[0]);
this.columnCategories = tsTableColumnCategories.toArray(new
TsTableColumnCategory[0]);
this.timeColumnIndex =
measurementToInputLocationMap.get(timeColumnName).getValueColumnIndex();
+ this.timeSourceDataType = timeSourceDataType;
+ this.writers = new SourceColumnToTabletValueWriter[dataTypes.length];
+ for (int i = 0; i < dataTypes.length; i++) {
+ if (!dataTypes[i].isBinary()) {
+ this.writers[i] =
+
TypeServices.StorageEngine.SOURCE_COLUMN_TO_TABLET_VALUE_WRITER_SERVICE.call(
+ Type.fromTsDataType(dataTypes[i]));
+ }
+ }
this.reset();
}
+ @Override
public int processTsBlock(TsBlock tsBlock, int lastReadIndex) {
- while (lastReadIndex < tsBlock.getPositionCount()) {
- times[rowCount] =
tsBlock.getValueColumns()[timeColumnIndex].getLong(lastReadIndex);
+ int rowsToProcess = Math.min(tsBlock.getPositionCount() - lastReadIndex,
rowLimit - rowCount);
+ if (rowsToProcess <= 0) {
+ return lastReadIndex;
+ }
+
+ Column[] valueColumns = tsBlock.getValueColumns();
+ populateTimestamps(valueColumns[timeColumnIndex], lastReadIndex,
rowsToProcess);
+
+ for (int i = 0; i < measurements.length; i++) {
+ Column valueColumn =
valueColumns[inputLocations[i].getValueColumnIndex()];
+ if (isAllNullColumn(valueColumn)) {
+ // bitMaps[i] is marked NULL by default on reset().
+ continue;
+ }
+ if (dataTypes[i].isBinary()) {
+ processBinaryTargetColumn(
+ valueColumn,
+ sourceDataTypes[i],
+ (Binary[]) columns[i],
+ bitMaps[i],
+ lastReadIndex,
+ rowsToProcess);
+ } else {
+ processPrimitiveTargetColumn(
+ valueColumn,
+ writers[i],
+ typeConvertors[i],
+ columns[i],
+ bitMaps[i],
+ lastReadIndex,
+ rowsToProcess);
+ }
+ }
+
+ rowCount += rowsToProcess;
+ writtenCount += rowsToProcess;
+ return lastReadIndex + rowsToProcess;
+ }
+
+ private void populateTimestamps(Column timeColumn, int lastReadIndex, int
rowsToProcess) {
+ if (timeColumn instanceof NullColumn) {
+ throw new
SemanticException(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL);
+ }
+ boolean shouldCheckPrecision =
+ (timeSourceDataType == TSDataType.INT32 || timeSourceDataType ==
TSDataType.INT64)
+ &&
CommonDescriptor.getInstance().getConfig().isTimestampPrecisionCheckEnabled();
+ if (timeColumn instanceof RunLengthEncodedColumn) {
+ Column value = ((RunLengthEncodedColumn) timeColumn).getValue();
+ if (value.isNull(0)) {
+ throw new
SemanticException(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL);
+ }
+ long timestamp = value.getLong(0);
+ if (shouldCheckPrecision) {
+ TimestampPrecisionUtils.checkTimestampPrecision(timestamp);
+ }
+ Arrays.fill(times, rowCount, rowCount + rowsToProcess, timestamp);
+ return;
+ }
- for (int i = 0; i < measurements.length; ++i) {
- int valueColumnIndex = inputLocations[i].getValueColumnIndex();
- Column valueColumn = tsBlock.getValueColumns()[valueColumnIndex];
+ boolean mayHaveNull = timeColumn.mayHaveNull();
+ for (int rowOffset = 0; rowOffset < rowsToProcess; rowOffset++) {
+ int sourceRowIndex = lastReadIndex + rowOffset;
+ if (mayHaveNull && timeColumn.isNull(sourceRowIndex)) {
+ throw new
SemanticException(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL);
+ }
+ long timestamp = timeColumn.getLong(sourceRowIndex);
+ if (shouldCheckPrecision) {
+ TimestampPrecisionUtils.checkTimestampPrecision(timestamp);
+ }
+ times[rowCount + rowOffset] = timestamp;
+ }
+ }
- // if the value is NULL
- if (valueColumn.isNull(lastReadIndex)) {
- // bit in bitMaps are marked as 1 (NULL) by default
- continue;
- }
+ private void processBinaryTargetColumn(
+ Column valueColumn,
+ TSDataType sourceType,
+ Binary[] targetBinaries,
+ BitMap bitMap,
+ int lastReadIndex,
+ int rowsToProcess) {
+ // IntColumn.getBinary(int) formats raw integers without checking DATE;
always format by
+ // logical sourceType when DATE flows into a binary target.
+ boolean isLogicalDate = (sourceType == TSDataType.DATE);
- bitMaps[i].unmark(rowCount);
- processColumn(valueColumn, columns[i], dataTypes[i],
typeConvertors[i], lastReadIndex);
+ if (valueColumn instanceof RunLengthEncodedColumn) {
+ Column rleValue = ((RunLengthEncodedColumn) valueColumn).getValue();
+ Binary value = isLogicalDate ? formatDateToBinary(rleValue.getInt(0)) :
rleValue.getBinary(0);
+ Arrays.fill(targetBinaries, rowCount, rowCount + rowsToProcess, value);
+ bitMap.unmarkRange(rowCount, rowsToProcess);
+ return;
+ }
+
+ boolean mayHaveNull = valueColumn.mayHaveNull();
+ for (int rowOffset = 0; rowOffset < rowsToProcess; rowOffset++) {
+ int sourceRowIndex = lastReadIndex + rowOffset;
+ if (mayHaveNull && valueColumn.isNull(sourceRowIndex)) {
+ continue;
+ }
+ int targetRowIndex = rowCount + rowOffset;
+ targetBinaries[targetRowIndex] =
+ isLogicalDate
+ ? formatDateToBinary(valueColumn.getInt(sourceRowIndex))
+ : valueColumn.getBinary(sourceRowIndex);
+ if (mayHaveNull) {
+ bitMap.unmark(targetRowIndex);
}
+ }
+ if (!mayHaveNull) {
+ bitMap.unmarkRange(rowCount, rowsToProcess);
+ }
+ }
- writtenCounter.getAndIncrement();
- ++rowCount;
- ++lastReadIndex;
- if (rowCount == rowLimit) {
- break;
+ private void processPrimitiveTargetColumn(
+ Column valueColumn,
+ SourceColumnToTabletValueWriter writer,
+ Type typeConvertor,
+ Object targetColumn,
+ BitMap bitMap,
+ int lastReadIndex,
+ int rowsToProcess) {
+ boolean mayHaveNull = valueColumn.mayHaveNull();
+ for (int rowOffset = 0; rowOffset < rowsToProcess; rowOffset++) {
+ int sourceRowIndex = lastReadIndex + rowOffset;
+ if (mayHaveNull && valueColumn.isNull(sourceRowIndex)) {
+ continue;
+ }
+ int targetRowIndex = rowCount + rowOffset;
+ writer.write(typeConvertor, valueColumn, sourceRowIndex, targetColumn,
targetRowIndex);
+ if (mayHaveNull) {
+ bitMap.unmark(targetRowIndex);
}
}
- return lastReadIndex;
+ if (!mayHaveNull) {
+ bitMap.unmarkRange(rowCount, rowsToProcess);
+ }
+ }
+
+ private static Binary formatDateToBinary(int date) {
+ if (date >= 0 && date <= 99_999_999) {
+ int year = date / 10000;
+ int monthDay = date % 10000;
+ int month = monthDay / 100;
+ int day = monthDay % 100;
+ byte[] bytes = new byte[10];
+ bytes[0] = (byte) ('0' + (year / 1000));
+ bytes[1] = (byte) ('0' + ((year / 100) % 10));
+ bytes[2] = (byte) ('0' + ((year / 10) % 10));
+ bytes[3] = (byte) ('0' + (year % 10));
+ bytes[4] = '-';
+ bytes[5] = (byte) ('0' + (month / 10));
+ bytes[6] = (byte) ('0' + (month % 10));
+ bytes[7] = '-';
+ bytes[8] = (byte) ('0' + (day / 10));
+ bytes[9] = (byte) ('0' + (day % 10));
+ return new Binary(bytes);
+ }
+ return new Binary(TSDataType.getDateStringValue(date),
StandardCharsets.UTF_8);
+ }
+
+ private static boolean isAllNullColumn(Column column) {
+ // All-null builders may expose a typed INT32 null block even for a
different logical type.
+ return column instanceof NullColumn
+ || (column instanceof RunLengthEncodedColumn
+ && ((RunLengthEncodedColumn) column).getValue().isNull(0));
}
@Override
public InsertTabletStatement constructInsertTabletStatement() {
InsertTabletStatement insertTabletStatement =
super.constructInsertTabletStatement();
+ // Isolate per-statement metadata arrays from downstream in-place TAG
reordering (swapColumn).
+ insertTabletStatement.setMeasurements(measurements.clone());
+ insertTabletStatement.setDataTypes(dataTypes.clone());
+ insertTabletStatement.setTypeConvertors(typeConvertors.clone());
+ insertTabletStatement.setInputLocations(inputLocations.clone());
insertTabletStatement.setDatabaseName(databaseName);
insertTabletStatement.setWriteToTable(true);
return insertTabletStatement;
@@ -111,7 +286,7 @@ public class TableInsertTabletStatementGenerator extends
InsertTabletStatementGe
@Override
public long getWrittenCount() {
- return writtenCounter.get();
+ return writtenCount;
}
@Override
@@ -128,7 +303,8 @@ public class TableInsertTabletStatementGenerator extends
InsertTabletStatementGe
+ sizeOf(dataTypes, TSDataType.class)
+ sizeOf(inputLocations, InputLocation.class)
+ sizeOf(typeConvertors, Type.class)
+ + sizeOf(sourceDataTypes, TSDataType.class)
+ sizeOf(columnCategories, TsTableColumnCategory.class)
- + RamUsageEstimator.shallowSizeOfInstance(AtomicLong.class);
+ + RamUsageEstimator.shallowSizeOf(writers);
}
}
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableIntoOperator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableIntoOperator.java
index b4a3c4380ea..b2a96524879 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableIntoOperator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableIntoOperator.java
@@ -69,7 +69,8 @@ public class TableIntoOperator extends AbstractIntoOperator {
boolean isAligned,
ExecutorService intoOperationExecutor,
long statementSizePerLine,
- ColumnSchema timeColumnOfTargetTable) {
+ ColumnSchema timeColumnOfTargetTable,
+ TSDataType timeSourceDataType) {
super(operatorContext, child, inputColumnTypes, intoOperationExecutor,
statementSizePerLine);
this.maxReturnSize = MAX_RETURN_SIZE;
insertTabletStatementGenerator =
@@ -82,7 +83,8 @@ public class TableIntoOperator extends AbstractIntoOperator {
inputColumnCategories,
isAligned,
maxRowNumberInStatement,
- timeColumnOfTargetTable.getName());
+ timeColumnOfTargetTable.getName(),
+ timeSourceDataType);
}
@Override
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
index 7c6c2d2234e..a1df09a55fa 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/planner/DataNodeTableOperatorGenerator.java
@@ -2270,33 +2270,35 @@ public class DataNodeTableOperatorGenerator
Map<String, TSDataType> tsDataTypeMap = new LinkedHashMap<>();
Map<String, InputLocation> inputLocationMap = new LinkedHashMap<>();
- List<TSDataType> inputColumnTypes = new ArrayList<>();
+ List<TSDataType> sourceColumnTypes = new ArrayList<>();
+ List<TSDataType> targetColumnTypes = new ArrayList<>();
List<TsTableColumnCategory> inputColumnCategories = new ArrayList<>();
List<ColumnSchema> originColumns = node.getColumns();
List<Symbol> originInputColumnNames = node.getNeededInputColumnNames();
- int size = originColumns.size();
- List<ColumnSchema> inputColumns = new ArrayList<>(size);
-
- List<Symbol> childOutputName = node.getChild().getOutputSymbols();
- Map<Symbol, Integer> map = new HashMap<>(childOutputName.size());
- for (int i = 0; i < size; i++) {
- map.put(childOutputName.get(i), i);
- inputColumns.add(null);
- }
- for (int i = 0; i < size; i++) {
- int index = map.get(originInputColumnNames.get(i));
- inputColumns.set(index, originColumns.get(i));
+ List<Symbol> childOutputSymbols = node.getChild().getOutputSymbols();
+ Map<Symbol, Integer> childOutputSymbolIndexMap = new
HashMap<>(childOutputSymbols.size());
+ for (int i = 0; i < childOutputSymbols.size(); i++) {
+ childOutputSymbolIndexMap.putIfAbsent(childOutputSymbols.get(i), i);
}
+
ColumnSchema timeColumnOfTargetTable = null;
- for (int i = 0; i < inputColumns.size(); i++) {
- String columnName = inputColumns.get(i).getName();
- inputLocationMap.put(columnName, new InputLocation(0, i));
+ TSDataType timeSourceDataType = null;
+ for (int i = 0; i < originColumns.size(); i++) {
+ ColumnSchema targetColumn = originColumns.get(i);
+ Symbol inputSymbol = originInputColumnNames.get(i);
+ int childOutputIndex = childOutputSymbolIndexMap.get(inputSymbol);
+
+ String columnName = targetColumn.getName();
+ inputLocationMap.put(columnName, new InputLocation(0, childOutputIndex));
- TsTableColumnCategory columnCategory =
inputColumns.get(i).getColumnCategory();
+ TsTableColumnCategory columnCategory = targetColumn.getColumnCategory();
if (columnCategory == TIME) {
if (timeColumnOfTargetTable == null) {
- timeColumnOfTargetTable = inputColumns.get(i);
+ timeColumnOfTargetTable = targetColumn;
+ timeSourceDataType =
+ InternalTypeManager.getTSDataType(
+ context.getTypeProvider().getTableModelType(inputSymbol));
} else {
throw new SemanticException(
DataNodeQueryMessages.MULTIPLE_COLUMNS_WITH_TIME_CATEGORY_FOUND);
@@ -2304,9 +2306,13 @@ public class DataNodeTableOperatorGenerator
continue;
}
- TSDataType columnType =
InternalTypeManager.getTSDataType(inputColumns.get(i).getType());
- tsDataTypeMap.put(columnName, columnType);
- inputColumnTypes.add(columnType);
+ TSDataType targetColumnType =
InternalTypeManager.getTSDataType(targetColumn.getType());
+ TSDataType sourceColumnType =
+ InternalTypeManager.getTSDataType(
+ context.getTypeProvider().getTableModelType(inputSymbol));
+ tsDataTypeMap.put(columnName, targetColumnType);
+ targetColumnTypes.add(targetColumnType);
+ sourceColumnTypes.add(sourceColumnType);
inputColumnCategories.add(columnCategory);
}
if (timeColumnOfTargetTable == null) {
@@ -2314,21 +2320,22 @@ public class DataNodeTableOperatorGenerator
}
long statementSizePerLine =
- OperatorGeneratorUtil.calculateStatementSizePerLine(inputColumnTypes);
+ OperatorGeneratorUtil.calculateStatementSizePerLine(targetColumnTypes);
return new TableIntoOperator(
operatorContext,
child,
node.getDatabase(),
targetTable,
- inputColumnTypes,
+ sourceColumnTypes,
inputColumnCategories,
inputLocationMap,
tsDataTypeMap,
true,
FragmentInstanceManager.getInstance().getIntoOperationExecutor(),
statementSizePerLine,
- timeColumnOfTargetTable);
+ timeColumnOfTargetTable,
+ timeSourceDataType);
}
private boolean[] checkStatisticAndScanOrder(
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java
index 61c1f38f7d7..515f8629bfc 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/StatementAnalyzer.java
@@ -247,6 +247,7 @@ import
org.apache.ratis.thirdparty.com.google.common.collect.Iterables;
import org.apache.ratis.thirdparty.com.google.common.collect.ListMultimap;
import org.apache.ratis.thirdparty.com.google.common.collect.Streams;
import org.apache.tsfile.common.conf.TSFileConfig;
+import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.read.common.type.BinaryType;
import org.apache.tsfile.read.common.type.ObjectType;
import org.apache.tsfile.read.common.type.RowType;
@@ -296,6 +297,7 @@ import static
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.
import static
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.Type.LEFT;
import static
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.Join.Type.RIGHT;
import static
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.PatternRecognitionRelation.RowsPerMatch.ONE;
+import static
org.apache.iotdb.commons.queryengine.plan.relational.type.InternalTypeManager.getTSDataType;
import static
org.apache.iotdb.commons.schema.table.TsTable.TABLE_ALLOWED_PROPERTIES;
import static
org.apache.iotdb.commons.udf.builtin.relational.TableBuiltinScalarFunction.DATE_BIN;
import static
org.apache.iotdb.db.queryengine.execution.warnings.StandardWarningCode.REDUNDANT_ORDER_BY;
@@ -1251,14 +1253,19 @@ public class StatementAnalyzer {
return false;
}
- // Do not consider type coercion at the moment
- private boolean typesMatchForInsert(List<Type> tableTypes, List<Type>
queryTypes) {
- if (tableTypes.size() != queryTypes.size()) {
+ private boolean typesMatchForInsert(List<ColumnSchema> targetColumns,
List<Type> queryTypes) {
+ if (targetColumns.size() != queryTypes.size()) {
return false;
}
- for (int i = 0; i < tableTypes.size(); i++) {
- if (!tableTypes.get(i).equals(queryTypes.get(i))) {
+ for (int i = 0; i < targetColumns.size(); i++) {
+ ColumnSchema targetColumn = targetColumns.get(i);
+ Type tableType = targetColumn.getType();
+ Type queryType = queryTypes.get(i);
+ if (tableType.equals(queryType)) {
+ continue;
+ }
+ if (!isCompatibleSinkType(targetColumn, queryType)) {
return false;
}
}
@@ -1266,6 +1273,30 @@ public class StatementAnalyzer {
return true;
}
+ private static boolean isCompatibleSinkType(ColumnSchema targetColumn,
Type queryType) {
+ TSDataType sink = toScalarTsDataType(targetColumn.getType());
+ TSDataType source = toScalarTsDataType(queryType);
+ if (sink == null || source == null || !sink.isCompatible(source)) {
+ return false;
+ }
+ // TAG segments are converted to UTF-8 strings via Binary.toString() for
IDeviceID; raw BLOB
+ // bytes containing invalid UTF-8 would decode to '\uFFFD' and collide
distinct devices.
+ return !(targetColumn.getColumnCategory() == TsTableColumnCategory.TAG
+ && source == TSDataType.BLOB);
+ }
+
+ private static TSDataType toScalarTsDataType(Type type) {
+ switch (type.getTypeEnum()) {
+ case ROW:
+ case VECTOR:
+ case OBJECT:
+ case UNKNOWN:
+ return null;
+ default:
+ return getTSDataType(type);
+ }
+ }
+
@Override
public Scope visitInsert(Insert insert, Optional<Scope> scope) {
queryContext.setQueryType(QueryType.READ_WRITE);
@@ -1350,20 +1381,17 @@ public class StatementAnalyzer {
}
// set Insert in analysis
- analysis.setInsert(
- new Analysis.Insert(
- insert.getTable(),
-
insertColumns.stream().map(columnSchemaMap::get).collect(toImmutableList())));
-
- List<Type> tableTypes =
- insertColumns.stream()
- .map(insertColumn ->
tableSchema.get().getColumn(insertColumn).getType())
- .collect(toImmutableList());
+ List<ColumnSchema> targetColumns =
+
insertColumns.stream().map(columnSchemaMap::get).collect(toImmutableList());
+ analysis.setInsert(new Analysis.Insert(insert.getTable(),
targetColumns));
+
List<Type> queryTypes =
queryScope.getRelationType().getVisibleFields().stream()
.map(Field::getType)
.collect(toImmutableList());
- if (!typesMatchForInsert(tableTypes, queryTypes)) {
+ if (!typesMatchForInsert(targetColumns, queryTypes)) {
+ List<Type> tableTypes =
+
targetColumns.stream().map(ColumnSchema::getType).collect(toImmutableList());
throw new SemanticException(
String.format(
DataNodeQueryMessages.INSERT_QUERY_HAS_MISMATCHED_COLUMN_TYPES_TABLE_S_QUERY_S,
diff --git
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableLogicalPlanner.java
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableLogicalPlanner.java
index 9406aaa7237..ef65592f0a1 100644
---
a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableLogicalPlanner.java
+++
b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/plan/relational/planner/TableLogicalPlanner.java
@@ -99,6 +99,7 @@ import
org.apache.ratis.thirdparty.com.google.common.collect.ImmutableMap;
import org.apache.tsfile.enums.TSDataType;
import org.apache.tsfile.read.common.type.LongType;
import org.apache.tsfile.read.common.type.StringType;
+import org.apache.tsfile.read.common.type.Type;
import org.apache.tsfile.read.common.type.TypeFactory;
import java.util.ArrayList;
@@ -118,7 +119,6 @@ import static
org.apache.iotdb.db.queryengine.metric.QueryPlanCostMetricSet.LOGI
import static
org.apache.iotdb.db.queryengine.plan.relational.planner.QueryPlanner.visibleFields;
import static
org.apache.iotdb.db.queryengine.plan.relational.sql.ast.CountDevice.COUNT_DEVICE_HEADER_STRING;
import static
org.apache.iotdb.db.queryengine.plan.relational.sql.ast.ShowDevice.getDeviceColumnHeaderList;
-import static
org.apache.ratis.thirdparty.com.google.common.collect.ImmutableList.toImmutableList;
public class TableLogicalPlanner {
private final MPPQueryContext queryContext;
@@ -304,28 +304,28 @@ public class TableLogicalPlanner {
Assignments.Builder assignments = Assignments.builder();
List<Symbol> neededInputColumnNames = new
ArrayList<>(insertColumns.size());
+ ImmutableList.Builder<Field> fields = ImmutableList.builder();
for (int i = 0, size = insertColumns.size(); i < size; i++) {
- Symbol output =
- symbolAllocator.newSymbol(insertColumns.get(i).getName(),
insertColumns.get(i).getType());
+ ColumnSchema insertColumn = insertColumns.get(i);
Symbol input = visibleFieldMappings.get(i);
+ Type inputType = symbolAllocator.getTypes().getTableModelType(input);
+ Symbol output = symbolAllocator.newSymbol(insertColumn.getName(),
inputType);
neededInputColumnNames.add(output);
assignments.put(output, input.toSymbolReference());
+ fields.add(
+ Field.newUnqualified(
+ insertColumn.getName(), inputType,
insertColumn.getColumnCategory()));
}
// Project Node
ProjectNode projectNode =
new ProjectNode(
queryContext.getQueryId().genPlanNodeId(), plan.getRoot(),
assignments.build());
- List<Field> fields =
- insertColumns.stream()
- .map(
- column ->
- Field.newUnqualified(
- column.getName(), column.getType(),
column.getColumnCategory()))
- .collect(toImmutableList());
Scope scope =
- Scope.builder().withRelationType(RelationId.anonymous(), new
RelationType(fields)).build();
+ Scope.builder()
+ .withRelationType(RelationId.anonymous(), new
RelationType(fields.build()))
+ .build();
plan = new RelationPlan(projectNode, scope,
projectNode.getOutputSymbols(), Optional.empty());
// Into Node
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGeneratorTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGeneratorTest.java
new file mode 100644
index 00000000000..39c031f6195
--- /dev/null
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/process/TableInsertTabletStatementGeneratorTest.java
@@ -0,0 +1,1060 @@
+/*
+ * 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.iotdb.db.queryengine.execution.operator.process;
+
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.path.PartialPath;
+import
org.apache.iotdb.commons.queryengine.plan.planner.plan.parameter.InputLocation;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
+import org.apache.iotdb.db.i18n.DataNodeQueryMessages;
+import
org.apache.iotdb.db.queryengine.plan.statement.crud.InsertTabletStatement;
+
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.block.TsBlock;
+import org.apache.tsfile.read.common.block.column.BinaryColumn;
+import org.apache.tsfile.read.common.block.column.BooleanColumn;
+import org.apache.tsfile.read.common.block.column.DictionaryColumn;
+import org.apache.tsfile.read.common.block.column.DoubleColumn;
+import org.apache.tsfile.read.common.block.column.FloatColumn;
+import org.apache.tsfile.read.common.block.column.IntColumn;
+import org.apache.tsfile.read.common.block.column.LongColumn;
+import org.apache.tsfile.read.common.block.column.NullColumn;
+import org.apache.tsfile.read.common.block.column.RunLengthEncodedColumn;
+import org.apache.tsfile.utils.Binary;
+import org.apache.tsfile.utils.DateUtils;
+import org.junit.Test;
+
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDate;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static org.junit.Assert.assertArrayEquals;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertThrows;
+import static org.junit.Assert.assertTrue;
+
+public class TableInsertTabletStatementGeneratorTest {
+
+ @Test
+ public void testProcessTsBlockConvertsCompatibleColumns() throws Exception {
+ List<TSDataType> sourceTypes =
+ Arrays.asList(
+ TSDataType.INT32,
+ TSDataType.TIMESTAMP,
+ TSDataType.INT32,
+ TSDataType.INT32,
+ TSDataType.DATE);
+ List<TSDataType> targetTypes =
+ Arrays.asList(
+ TSDataType.INT64,
+ TSDataType.INT64,
+ TSDataType.DOUBLE,
+ TSDataType.TEXT,
+ TSDataType.STRING);
+ TableInsertTabletStatementGenerator generator =
createGenerator(sourceTypes, targetTypes);
+ int date = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 1, 1));
+
+ assertEquals(
+ 1,
+ generator.processTsBlock(
+ createTsBlock(
+ new IntColumn(1, Optional.empty(), new int[] {123}),
+ new LongColumn(1, Optional.empty(), new long[] {456L}),
+ new IntColumn(1, Optional.empty(), new int[] {789}),
+ new IntColumn(1, Optional.empty(), new int[] {123}),
+ new IntColumn(1, Optional.empty(), new int[] {date},
TSDataType.DATE)),
+ 0));
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(1, statement.getRowCount());
+ assertArrayEquals(new long[] {1L}, statement.getTimes());
+ assertArrayEquals(new long[] {123L}, (long[]) statement.getColumns()[0]);
+ assertArrayEquals(new long[] {456L}, (long[]) statement.getColumns()[1]);
+ assertArrayEquals(new double[] {789.0}, (double[])
statement.getColumns()[2], 0.0);
+ assertEquals("123", ((Binary[]) statement.getColumns()[3])[0].toString());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[4])[0].toString());
+ assertFalse(statement.getBitMaps()[3].isMarked(0));
+ assertFalse(statement.getBitMaps()[4].isMarked(0));
+ }
+
+ @Test
+ public void testAllNullColumnsRemainNullWithoutConversion() throws Exception
{
+ List<TSDataType> sourceTypes = Arrays.asList(TSDataType.DATE,
TSDataType.DATE);
+ List<TSDataType> targetTypes = Arrays.asList(TSDataType.TEXT,
TSDataType.STRING);
+ TableInsertTabletStatementGenerator generator =
createGenerator(sourceTypes, targetTypes);
+
+ assertEquals(
+ 1,
+ generator.processTsBlock(
+ createTsBlock(
+ new NullColumn(1),
+ new RunLengthEncodedColumn(
+ new IntColumn(1, Optional.of(new boolean[] {true}), new
int[] {0}), 1)),
+ 0));
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(1, statement.getRowCount());
+ assertTrue(statement.getBitMaps()[0].isMarked(0));
+ assertTrue(statement.getBitMaps()[1].isMarked(0));
+ }
+
+ @Test
+ public void testLogicalDateConvertedToTextWhenPhysicalColumnIsInt32() throws
Exception {
+ List<TSDataType> sourceTypes = Arrays.asList(TSDataType.DATE,
TSDataType.DATE, TSDataType.DATE);
+ List<TSDataType> targetTypes =
+ Arrays.asList(TSDataType.STRING, TSDataType.TEXT, TSDataType.STRING);
+ TableInsertTabletStatementGenerator generator =
createGenerator(sourceTypes, targetTypes);
+
+ int date1 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 1, 1));
+ int date2 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 2, 29));
+ // Simulate upstream exchange / cast / literal columns whose runtime
Column type is INT32.
+ IntColumn plainInt32Date =
+ new IntColumn(
+ 3, Optional.of(new boolean[] {false, true, false}), new int[]
{date1, 0, date2});
+ Column rleInt32Date =
+ new RunLengthEncodedColumn(new IntColumn(1, Optional.empty(), new
int[] {date1}), 3);
+ Column dictInt32Date =
+ new IntColumn(2, Optional.empty(), new int[] {date1, date2})
+ .getPositions(new int[] {0, 1, 0}, 0, 3);
+ Column timeColumn = new LongColumn(3, Optional.empty(), new long[] {1L,
2L, 3L});
+ TsBlock block =
+ new TsBlock(
+ timeColumn, new Column[] {timeColumn, plainInt32Date,
rleInt32Date, dictInt32Date});
+
+ assertEquals(3, generator.processTsBlock(block, 0));
+ // Conversion must not mutate the source column in place.
+ assertEquals(TSDataType.INT32, plainInt32Date.getDataType());
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(3, statement.getRowCount());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[0])[0].toString());
+ assertTrue(statement.getBitMaps()[0].isMarked(1));
+ assertEquals("2024-02-29", ((Binary[])
statement.getColumns()[0])[2].toString());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[1])[0].toString());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[1])[1].toString());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[2])[0].toString());
+ assertEquals("2024-02-29", ((Binary[])
statement.getColumns()[2])[1].toString());
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[2])[2].toString());
+ }
+
+ @Test
+ public void testNullTimestampRejectedBeforeWritingRow() throws Exception {
+ TableInsertTabletStatementGenerator generator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64));
+
+ Column nullLongTime = new LongColumn(1, Optional.of(new boolean[] {true}),
new long[] {0L});
+ TsBlock longNullBlock =
+ new TsBlock(
+ nullLongTime,
+ new Column[] {nullLongTime, new IntColumn(1, Optional.empty(), new
int[] {42})});
+ SemanticException longEx =
+ assertThrows(SemanticException.class, () ->
generator.processTsBlock(longNullBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
longEx.getMessage());
+ assertEquals(0, generator.getRowCount());
+ assertEquals(0, generator.getWrittenCount());
+
+ Column nullIntTime = new IntColumn(1, Optional.of(new boolean[] {true}),
new int[] {0});
+ TsBlock intNullBlock =
+ new TsBlock(
+ new LongColumn(1, Optional.empty(), new long[] {0L}),
+ new Column[] {nullIntTime, new IntColumn(1, Optional.empty(), new
int[] {42})});
+ SemanticException intEx =
+ assertThrows(SemanticException.class, () ->
generator.processTsBlock(intNullBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
intEx.getMessage());
+ assertEquals(0, generator.getRowCount());
+ assertEquals(0, generator.getWrittenCount());
+ }
+
+ @Test
+ public void testOutOfPrecisionTimestampRejected() throws Exception {
+ String previousPrecision = TimestampPrecisionUtils.TIMESTAMP_PRECISION;
+ boolean previousCheckEnabled =
+
CommonDescriptor.getInstance().getConfig().isTimestampPrecisionCheckEnabled();
+ TimestampPrecisionUtils.TIMESTAMP_PRECISION = "ms";
+
CommonDescriptor.getInstance().getConfig().setTimestampPrecisionCheckEnabled(true);
+ try {
+ long[] outOfRangeValues = new long[] {1_700_000_000_000_000L,
-1_700_000_000_000_000L};
+ for (long outOfRangeValue : outOfRangeValues) {
+ TableInsertTabletStatementGenerator int64Generator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ 10,
+ TSDataType.INT64);
+ Column plainInt64Time = new LongColumn(1, Optional.empty(), new long[]
{outOfRangeValue});
+ TsBlock plainInt64Block =
+ new TsBlock(
+ plainInt64Time,
+ new Column[] {plainInt64Time, new IntColumn(1,
Optional.empty(), new int[] {7})});
+ SemanticException plainException =
+ assertThrows(
+ SemanticException.class, () ->
int64Generator.processTsBlock(plainInt64Block, 0));
+ assertTrue(
+ plainException.getMessage(),
+
plainException.getMessage().contains(Long.toString(outOfRangeValue)));
+ assertEquals(0, int64Generator.getRowCount());
+ assertEquals(0, int64Generator.getWrittenCount());
+
+ Column rleInt64Time =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.empty(), new long[]
{outOfRangeValue}), 2);
+ TsBlock rleInt64Block =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {rleInt64Time, new IntColumn(2, Optional.empty(),
new int[] {7, 8})});
+ SemanticException rleException =
+ assertThrows(
+ SemanticException.class, () ->
int64Generator.processTsBlock(rleInt64Block, 0));
+ assertTrue(
+ rleException.getMessage(),
+
rleException.getMessage().contains(Long.toString(outOfRangeValue)));
+ assertEquals(0, int64Generator.getRowCount());
+ assertEquals(0, int64Generator.getWrittenCount());
+ }
+
+ // Native TIMESTAMP source bypasses precision check even when precision
check is enabled.
+ TableInsertTabletStatementGenerator tsGenerator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ 10,
+ TSDataType.TIMESTAMP);
+ Column plainTsTime =
+ new LongColumn(
+ 2, Optional.empty(), new long[] {1_700_000_000_000_000L,
-1_700_000_000_000_000L});
+ TsBlock plainTsBlock =
+ new TsBlock(
+ plainTsTime,
+ new Column[] {plainTsTime, new IntColumn(2, Optional.empty(),
new int[] {42, 43})});
+ assertEquals(2, tsGenerator.processTsBlock(plainTsBlock, 0));
+ Column rleTsTime =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.empty(), new long[]
{1_700_000_000_000_000L}), 3);
+ TsBlock rleTsBlock =
+ new TsBlock(
+ new LongColumn(3, Optional.empty(), new long[] {1L, 2L, 3L}),
+ new Column[] {rleTsTime, new IntColumn(3, Optional.empty(), new
int[] {44, 45, 46})});
+ assertEquals(3, tsGenerator.processTsBlock(rleTsBlock, 0));
+ InsertTabletStatement tsStatement =
tsGenerator.constructInsertTabletStatement();
+ assertEquals(5, tsStatement.getRowCount());
+ assertEquals(5L, tsGenerator.getWrittenCount());
+ assertArrayEquals(
+ new long[] {
+ 1_700_000_000_000_000L,
+ -1_700_000_000_000_000L,
+ 1_700_000_000_000_000L,
+ 1_700_000_000_000_000L,
+ 1_700_000_000_000_000L
+ },
+ tsStatement.getTimes());
+
+ // Promoted INT32 source (plain and RLE) checks precision and succeeds
for valid int32 values.
+ TableInsertTabletStatementGenerator int32Generator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ 10,
+ TSDataType.INT32);
+ Column plainInt32Time =
+ new IntColumn(2, Optional.empty(), new int[] {500,
Integer.MAX_VALUE});
+ TsBlock plainInt32Block =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {plainInt32Time, new IntColumn(2, Optional.empty(),
new int[] {1, 2})});
+ assertEquals(2, int32Generator.processTsBlock(plainInt32Block, 0));
+ Column rleInt32Time =
+ new RunLengthEncodedColumn(new IntColumn(1, Optional.empty(), new
int[] {600}), 2);
+ TsBlock rleInt32Block =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {rleInt32Time, new IntColumn(2, Optional.empty(),
new int[] {3, 4})});
+ assertEquals(2, int32Generator.processTsBlock(rleInt32Block, 0));
+ InsertTabletStatement int32Statement =
int32Generator.constructInsertTabletStatement();
+ assertEquals(4, int32Statement.getRowCount());
+ assertArrayEquals(
+ new long[] {500L, Integer.MAX_VALUE, 600L, 600L},
int32Statement.getTimes());
+
+ // Native TIMESTAMP source must still reject NULL timestamps in plain,
NullColumn, and RLE
+ // paths.
+ TableInsertTabletStatementGenerator nullCheckGenerator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ 10,
+ TSDataType.TIMESTAMP);
+ Column nullableTsTime =
+ new LongColumn(
+ 2, Optional.of(new boolean[] {false, true}), new long[]
{1_700_000_000_000_000L, 0L});
+ TsBlock nullableTsBlock =
+ new TsBlock(
+ nullableTsTime,
+ new Column[] {
+ nullableTsTime, new IntColumn(2, Optional.empty(), new int[]
{10, 20})
+ });
+ SemanticException nullableEx =
+ assertThrows(
+ SemanticException.class, () ->
nullCheckGenerator.processTsBlock(nullableTsBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
nullableEx.getMessage());
+ assertEquals(0, nullCheckGenerator.getRowCount());
+ assertEquals(0, nullCheckGenerator.getWrittenCount());
+
+ TsBlock nullColBlock =
+ new TsBlock(
+ new LongColumn(1, Optional.empty(), new long[] {1L}),
+ new Column[] {new NullColumn(1), new IntColumn(1,
Optional.empty(), new int[] {10})});
+ SemanticException nullColEx =
+ assertThrows(
+ SemanticException.class, () ->
nullCheckGenerator.processTsBlock(nullColBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
nullColEx.getMessage());
+ assertEquals(0, nullCheckGenerator.getRowCount());
+ assertEquals(0, nullCheckGenerator.getWrittenCount());
+
+ Column nullRleTsTime =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.of(new boolean[] {true}), new long[]
{0L}), 2);
+ TsBlock nullRleTsBlock =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {nullRleTsTime, new IntColumn(2, Optional.empty(),
new int[] {10, 20})});
+ SemanticException nullRleEx =
+ assertThrows(
+ SemanticException.class, () ->
nullCheckGenerator.processTsBlock(nullRleTsBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
nullRleEx.getMessage());
+ assertEquals(0, nullCheckGenerator.getRowCount());
+ assertEquals(0, nullCheckGenerator.getWrittenCount());
+
+ // When precision checking is disabled, promoted INT64 (plain and RLE)
succeeds.
+
CommonDescriptor.getInstance().getConfig().setTimestampPrecisionCheckEnabled(false);
+ TableInsertTabletStatementGenerator disabledCheckGenerator =
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ 10,
+ TSDataType.INT64);
+ Column plainOutOfRange =
+ new LongColumn(1, Optional.empty(), new long[]
{1_700_000_000_000_000L});
+ assertEquals(
+ 1,
+ disabledCheckGenerator.processTsBlock(
+ new TsBlock(
+ plainOutOfRange,
+ new Column[] {
+ plainOutOfRange, new IntColumn(1, Optional.empty(), new
int[] {1})
+ }),
+ 0));
+ Column rleOutOfRange =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.empty(), new long[]
{-1_700_000_000_000_000L}), 2);
+ assertEquals(
+ 2,
+ disabledCheckGenerator.processTsBlock(
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {
+ rleOutOfRange, new IntColumn(2, Optional.empty(), new
int[] {2, 3})
+ }),
+ 0));
+ InsertTabletStatement disabledStatement =
+ disabledCheckGenerator.constructInsertTabletStatement();
+ assertEquals(3, disabledStatement.getRowCount());
+ assertEquals(3L, disabledCheckGenerator.getWrittenCount());
+ assertArrayEquals(
+ new long[] {1_700_000_000_000_000L, -1_700_000_000_000_000L,
-1_700_000_000_000_000L},
+ disabledStatement.getTimes());
+ } finally {
+ TimestampPrecisionUtils.TIMESTAMP_PRECISION = previousPrecision;
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setTimestampPrecisionCheckEnabled(previousCheckEnabled);
+ }
+ }
+
+ @Test
+ public void testMultipleTargetsReadSameInputChannel() throws Exception {
+ Map<String, InputLocation> locations = new LinkedHashMap<>();
+ locations.put("time", new InputLocation(0, 0));
+ locations.put("wide", new InputLocation(0, 1));
+ locations.put("formatted", new InputLocation(0, 1));
+
+ Map<String, TSDataType> targets = new LinkedHashMap<>();
+ targets.put("wide", TSDataType.INT64);
+ targets.put("formatted", TSDataType.STRING);
+
+ TableInsertTabletStatementGenerator generator =
+ new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("target_table"),
+ locations,
+ targets,
+ Arrays.asList(TSDataType.INT32, TSDataType.INT32),
+ Arrays.asList(TsTableColumnCategory.FIELD,
TsTableColumnCategory.FIELD),
+ true,
+ 10,
+ "time",
+ TSDataType.TIMESTAMP);
+
+ Column timeColumn = new LongColumn(2, Optional.empty(), new long[] {10L,
20L});
+ Column sharedInt = new IntColumn(2, Optional.empty(), new int[] {123,
456});
+ TsBlock block = new TsBlock(timeColumn, new Column[] {timeColumn,
sharedInt});
+
+ assertEquals(2, generator.processTsBlock(block, 0));
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(2, statement.getRowCount());
+ assertArrayEquals(new long[] {10L, 20L}, statement.getTimes());
+ assertArrayEquals(new long[] {123L, 456L}, (long[])
statement.getColumns()[0]);
+ assertEquals("123", ((Binary[]) statement.getColumns()[1])[0].toString());
+ assertEquals("456", ((Binary[]) statement.getColumns()[1])[1].toString());
+ }
+
+ @Test
+ public void testMultiTabletBatchConvertsEachRowOnce() throws Exception {
+ int totalRows = 1000;
+ int rowLimit = 100;
+ Map<String, InputLocation> locations = new LinkedHashMap<>();
+ locations.put("time", new InputLocation(0, 0));
+ locations.put("s0", new InputLocation(0, 1));
+ Map<String, TSDataType> targets = new LinkedHashMap<>();
+ targets.put("s0", TSDataType.STRING);
+
+ TableInsertTabletStatementGenerator generator =
+ new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("target_table"),
+ locations,
+ targets,
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TsTableColumnCategory.FIELD),
+ true,
+ rowLimit,
+ "time",
+ TSDataType.TIMESTAMP);
+
+ long[] timestamps = new long[totalRows];
+ int[] values = new int[totalRows];
+ for (int i = 0; i < totalRows; i++) {
+ timestamps[i] = i + 1L;
+ values[i] = i * 10;
+ }
+ Column timeColumn = new LongColumn(totalRows, Optional.empty(),
timestamps);
+ AtomicInteger intReadCount = new AtomicInteger(0);
+ AtomicInteger binaryConvertCount = new AtomicInteger(0);
+ CountingIntColumn countingValues =
+ new CountingIntColumn(values, null, TSDataType.INT32, intReadCount,
binaryConvertCount);
+ TsBlock remaining = new TsBlock(timeColumn, new Column[] {timeColumn,
countingValues});
+
+ int batchCount = 0;
+ int verifiedRows = 0;
+ while (!remaining.isEmpty()) {
+ int nextIndex = generator.processTsBlock(remaining, 0);
+ assertEquals(rowLimit, nextIndex);
+ assertTrue(generator.isFull());
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(rowLimit, statement.getRowCount());
+ Binary[] binaries = (Binary[]) statement.getColumns()[0];
+ for (int i = 0; i < rowLimit; i++) {
+ int globalRow = batchCount * rowLimit + i;
+ assertEquals(globalRow + 1L, statement.getTimes()[i]);
+ assertEquals(Integer.toString(globalRow * 10), binaries[i].toString());
+ }
+ verifiedRows += rowLimit;
+ batchCount++;
+ generator.reset();
+ remaining = remaining.subTsBlock(nextIndex);
+ }
+
+ assertEquals(10, batchCount);
+ assertEquals(totalRows, verifiedRows);
+ assertEquals(totalRows, generator.getWrittenCount());
+ // Each row must be converted only for the tablet that consumes it (1000
instead of 5500).
+ assertEquals(totalRows, binaryConvertCount.get());
+ }
+
+ @Test
+ public void testRleAndDictionaryEncodings() throws Exception {
+ int rows = 100;
+ int date1 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 1, 1));
+ int date2 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 2, 29));
+
+ List<TSDataType> sourceTypes =
+ Arrays.asList(
+ TSDataType.DATE,
+ TSDataType.DATE,
+ TSDataType.INT32,
+ TSDataType.INT32,
+ TSDataType.INT32,
+ TSDataType.STRING);
+ List<TSDataType> targetTypes =
+ Arrays.asList(
+ TSDataType.STRING,
+ TSDataType.STRING,
+ TSDataType.STRING,
+ TSDataType.STRING,
+ TSDataType.INT64,
+ TSDataType.STRING);
+ TableInsertTabletStatementGenerator generator =
createGenerator(sourceTypes, targetTypes, rows);
+
+ AtomicInteger rleDateReads = new AtomicInteger(0);
+ Column rleDate =
+ new RunLengthEncodedColumn(
+ new CountingIntColumn(
+ new int[] {date1}, null, TSDataType.INT32, rleDateReads, new
AtomicInteger(0)),
+ rows);
+
+ int[] ids = new int[rows];
+ for (int i = 0; i < rows; i++) {
+ ids[i] = i % 3;
+ }
+ Column dictDate =
+ DictionaryColumn.create(
+ rows,
+ new IntColumn(
+ 3, Optional.of(new boolean[] {false, false, true}), new int[]
{date1, date2, 0}),
+ ids);
+
+ AtomicInteger rleIntBinaryReads = new AtomicInteger(0);
+ Column rleInt =
+ new RunLengthEncodedColumn(
+ new CountingIntColumn(
+ new int[] {77}, null, TSDataType.INT32, new AtomicInteger(0),
rleIntBinaryReads),
+ rows);
+
+ Column dictInt =
+ DictionaryColumn.create(
+ rows,
+ new IntColumn(
+ 3, Optional.of(new boolean[] {false, false, true}), new int[]
{10, 20, 0}),
+ ids);
+
+ Column rleWide =
+ new RunLengthEncodedColumn(new IntColumn(1, Optional.empty(), new
int[] {55}), rows);
+ Column dictNullWrapped = DictionaryColumn.create(rows, new NullColumn(1),
new int[rows]);
+ Column rleTime =
+ new RunLengthEncodedColumn(new LongColumn(1, Optional.empty(), new
long[] {999L}), rows);
+
+ TsBlock block =
+ new TsBlock(
+ rleTime,
+ new Column[] {rleTime, rleDate, dictDate, rleInt, dictInt,
rleWide, dictNullWrapped});
+ assertEquals(rows, generator.processTsBlock(block, 0));
+
+ // RLE converts once per batch rather than once per row.
+ assertEquals(1, rleDateReads.get());
+ assertEquals(1, rleIntBinaryReads.get());
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(rows, statement.getRowCount());
+ assertTrue(generator.ramBytesUsed() > 0);
+ for (int i = 0; i < rows; i++) {
+ assertEquals(999L, statement.getTimes()[i]);
+ assertFalse(statement.getBitMaps()[0].isMarked(i));
+ assertEquals("2024-01-01", ((Binary[])
statement.getColumns()[0])[i].toString());
+ if (i % 3 == 2) {
+ assertTrue(statement.getBitMaps()[1].isMarked(i));
+ assertTrue(statement.getBitMaps()[3].isMarked(i));
+ } else {
+ assertFalse(statement.getBitMaps()[1].isMarked(i));
+ assertEquals(
+ i % 3 == 0 ? "2024-01-01" : "2024-02-29",
+ ((Binary[]) statement.getColumns()[1])[i].toString());
+ assertFalse(statement.getBitMaps()[3].isMarked(i));
+ assertEquals(
+ i % 3 == 0 ? "10" : "20", ((Binary[])
statement.getColumns()[3])[i].toString());
+ }
+ assertFalse(statement.getBitMaps()[2].isMarked(i));
+ assertEquals("77", ((Binary[]) statement.getColumns()[2])[i].toString());
+ assertFalse(statement.getBitMaps()[4].isMarked(i));
+ assertEquals(55L, ((long[]) statement.getColumns()[4])[i]);
+ assertTrue(statement.getBitMaps()[5].isMarked(i));
+ }
+
+ // NullColumn and null RLE timestamps must also be rejected cleanly.
+ generator.reset();
+ Column nullTime = new NullColumn(2);
+ TsBlock nullTimeBlock =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {
+ nullTime,
+ rleDate.getRegion(0, 2),
+ dictDate.getRegion(0, 2),
+ rleInt.getRegion(0, 2),
+ dictInt.getRegion(0, 2),
+ rleWide.getRegion(0, 2),
+ dictNullWrapped.getRegion(0, 2)
+ });
+ SemanticException nullColEx =
+ assertThrows(SemanticException.class, () ->
generator.processTsBlock(nullTimeBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
nullColEx.getMessage());
+
+ Column nullRleTime =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.of(new boolean[] {true}), new long[]
{0L}), 2);
+ TsBlock nullRleTimeBlock =
+ new TsBlock(
+ new LongColumn(2, Optional.empty(), new long[] {1L, 2L}),
+ new Column[] {
+ nullRleTime,
+ rleDate.getRegion(0, 2),
+ dictDate.getRegion(0, 2),
+ rleInt.getRegion(0, 2),
+ dictInt.getRegion(0, 2),
+ rleWide.getRegion(0, 2),
+ dictNullWrapped.getRegion(0, 2)
+ });
+ SemanticException nullRleEx =
+ assertThrows(SemanticException.class, () ->
generator.processTsBlock(nullRleTimeBlock, 0));
+ assertEquals(DataNodeQueryMessages.TIMESTAMP_CANNOT_BE_NULL,
nullRleEx.getMessage());
+ }
+
+ @Test
+ public void testEdgeCompatibleConversionsAndDateBoundaries() throws
Exception {
+ // Contract verification for TIMESTAMP -> STRING/TEXT, BLOB <->
STRING/TEXT, non-string ->
+ // TAG/ATTRIBUTE, DATE formatting edge cases, and non-zero lastReadIndex /
rowCount offsets.
+ Map<String, InputLocation> locations = new LinkedHashMap<>();
+ locations.put("time", new InputLocation(0, 0));
+ locations.put("tag_from_int", new InputLocation(0, 1));
+ locations.put("attr_from_date", new InputLocation(0, 2));
+ locations.put("ts_str", new InputLocation(0, 3));
+ locations.put("ts_text", new InputLocation(0, 3));
+ locations.put("blob_to_str", new InputLocation(0, 4));
+ locations.put("str_to_blob", new InputLocation(0, 5));
+ locations.put("bool_str", new InputLocation(0, 6));
+ locations.put("float_str", new InputLocation(0, 7));
+ locations.put("double_str", new InputLocation(0, 8));
+ locations.put("local_date_str", new InputLocation(0, 9));
+
+ Map<String, TSDataType> targets = new LinkedHashMap<>();
+ targets.put("tag_from_int", TSDataType.STRING);
+ targets.put("attr_from_date", TSDataType.STRING);
+ targets.put("ts_str", TSDataType.STRING);
+ targets.put("ts_text", TSDataType.TEXT);
+ targets.put("blob_to_str", TSDataType.STRING);
+ targets.put("str_to_blob", TSDataType.BLOB);
+ targets.put("bool_str", TSDataType.STRING);
+ targets.put("float_str", TSDataType.STRING);
+ targets.put("double_str", TSDataType.STRING);
+ targets.put("local_date_str", TSDataType.STRING);
+
+ TableInsertTabletStatementGenerator generator =
+ new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("edge_table"),
+ locations,
+ targets,
+ Arrays.asList(
+ TSDataType.INT32,
+ TSDataType.DATE,
+ TSDataType.TIMESTAMP,
+ TSDataType.TIMESTAMP,
+ TSDataType.BLOB,
+ TSDataType.STRING,
+ TSDataType.BOOLEAN,
+ TSDataType.FLOAT,
+ TSDataType.DOUBLE,
+ TSDataType.DATE),
+ Arrays.asList(
+ TsTableColumnCategory.TAG,
+ TsTableColumnCategory.ATTRIBUTE,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD,
+ TsTableColumnCategory.FIELD),
+ true,
+ 10,
+ "time",
+ TSDataType.TIMESTAMP);
+
+ byte[] rawNonUtf8 = new byte[] {(byte) 0xDE, (byte) 0xAD, (byte) 0xBE,
(byte) 0xEF};
+ byte[] utf8Bytes = "hello".getBytes(StandardCharsets.UTF_8);
+ int yearMin = DateUtils.parseDateExpressionToInt(LocalDate.of(1000, 1, 1));
+ int yearMax = DateUtils.parseDateExpressionToInt(LocalDate.of(9999, 12,
31));
+ int leapDay = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 2,
29));
+ int negativeFallbackDate = -10101;
+
+ Column times = new LongColumn(4, Optional.empty(), new long[] {10L, 20L,
30L, 40L});
+ Column intTags = new IntColumn(4, Optional.empty(), new int[] {1, 2, 3,
4});
+ Column erasedDates =
+ new IntColumn(
+ 4, Optional.empty(), new int[] {yearMin, yearMax, leapDay,
negativeFallbackDate});
+ Column tsCol =
+ new LongColumn(
+ 4, Optional.empty(), new long[] {1704067200000L, 1704067200001L,
0L, 1704067200003L});
+ Column blobCol =
+ new BinaryColumn(
+ 4,
+ Optional.empty(),
+ new Binary[] {
+ new Binary(rawNonUtf8),
+ new Binary(rawNonUtf8),
+ new Binary(rawNonUtf8),
+ new Binary(rawNonUtf8)
+ });
+ Column strCol =
+ new BinaryColumn(
+ 4,
+ Optional.empty(),
+ new Binary[] {
+ new Binary(utf8Bytes),
+ new Binary(utf8Bytes),
+ new Binary(utf8Bytes),
+ new Binary(utf8Bytes)
+ });
+ Column boolCol =
+ new BooleanColumn(4, Optional.empty(), new boolean[] {true, false,
true, false});
+ Column floatCol = new FloatColumn(4, Optional.empty(), new float[] {1.5f,
2.5f, 3.5f, 4.5f});
+ Column doubleCol = new DoubleColumn(4, Optional.empty(), new double[]
{1.25, 2.25, 3.25, 4.25});
+ // Local IntColumn carrying TSDataType.DATE tag must also format as
YYYY-MM-DD directly.
+ Column localDates =
+ new IntColumn(
+ 4,
+ Optional.empty(),
+ new int[] {yearMin, yearMax, leapDay, negativeFallbackDate},
+ TSDataType.DATE);
+
+ TsBlock block =
+ new TsBlock(
+ times,
+ new Column[] {
+ times,
+ intTags,
+ erasedDates,
+ tsCol,
+ blobCol,
+ strCol,
+ boolCol,
+ floatCol,
+ doubleCol,
+ localDates
+ });
+
+ // Feed in two slices (first 1 row, then remaining 3 rows starting at
lastReadIndex=1) to verify
+ // non-zero rowCount and lastReadIndex offsets.
+ assertEquals(1, generator.processTsBlock(block.getRegion(0, 1), 0));
+ assertEquals(4, generator.processTsBlock(block, 1));
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(4, statement.getRowCount());
+ assertArrayEquals(new long[] {10L, 20L, 30L, 40L}, statement.getTimes());
+ assertEquals("1", ((Binary[]) statement.getColumns()[0])[0].toString());
+ assertEquals("4", ((Binary[]) statement.getColumns()[0])[3].toString());
+ assertEquals("1000-01-01", ((Binary[])
statement.getColumns()[1])[0].toString());
+ assertEquals("9999-12-31", ((Binary[])
statement.getColumns()[1])[1].toString());
+ assertEquals("2024-02-29", ((Binary[])
statement.getColumns()[1])[2].toString());
+ assertEquals(
+ TSDataType.getDateStringValue(negativeFallbackDate),
+ ((Binary[]) statement.getColumns()[1])[3].toString());
+ // TIMESTAMP -> STRING / TEXT follows TSDataType storage promotion (epoch
numeric string).
+ assertEquals("1704067200000", ((Binary[])
statement.getColumns()[2])[0].toString());
+ assertEquals("1704067200000", ((Binary[])
statement.getColumns()[3])[0].toString());
+ // BLOB <-> STRING preserves raw bytes identically.
+ assertArrayEquals(rawNonUtf8, ((Binary[])
statement.getColumns()[4])[0].getValues());
+ assertArrayEquals(utf8Bytes, ((Binary[])
statement.getColumns()[5])[0].getValues());
+ assertEquals("true", ((Binary[]) statement.getColumns()[6])[0].toString());
+ assertEquals("false", ((Binary[])
statement.getColumns()[6])[1].toString());
+ assertEquals("1.5", ((Binary[]) statement.getColumns()[7])[0].toString());
+ assertEquals("1.25", ((Binary[]) statement.getColumns()[8])[0].toString());
+ assertEquals("1000-01-01", ((Binary[])
statement.getColumns()[9])[0].toString());
+ assertEquals("9999-12-31", ((Binary[])
statement.getColumns()[9])[1].toString());
+ assertEquals("2024-02-29", ((Binary[])
statement.getColumns()[9])[2].toString());
+ assertEquals(
+ TSDataType.getDateStringValue(negativeFallbackDate),
+ ((Binary[]) statement.getColumns()[9])[3].toString());
+ }
+
+ @Test
+ public void testCrossBatchTagSwapDoesNotCorruptSourceDataTypes() throws
Exception {
+ int date1 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 1, 1));
+ int date2 = DateUtils.parseDateExpressionToInt(LocalDate.of(2024, 1, 2));
+
+ // Scenario 1: FIELD (DATE -> STRING, physical INT32 after Exchange/CAST)
before STRING TAG.
+ Map<String, InputLocation> stringTagLocations = new LinkedHashMap<>();
+ stringTagLocations.put("time", new InputLocation(0, 0));
+ stringTagLocations.put("d_str", new InputLocation(0, 1));
+ stringTagLocations.put("device_id", new InputLocation(0, 2));
+ Map<String, TSDataType> stringTagTargets = new LinkedHashMap<>();
+ stringTagTargets.put("d_str", TSDataType.STRING);
+ stringTagTargets.put("device_id", TSDataType.STRING);
+
+ TableInsertTabletStatementGenerator stringTagGenerator =
+ new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("target_table"),
+ stringTagLocations,
+ stringTagTargets,
+ Arrays.asList(TSDataType.DATE, TSDataType.STRING),
+ Arrays.asList(TsTableColumnCategory.FIELD,
TsTableColumnCategory.TAG),
+ true,
+ 1,
+ "time",
+ TSDataType.TIMESTAMP);
+
+ Column time1 = new LongColumn(1, Optional.empty(), new long[] {1L});
+ Column erasedDate1 = new IntColumn(1, Optional.empty(), new int[] {date1});
+ Column dev1 =
+ new BinaryColumn(
+ 1, Optional.empty(), new Binary[] {new Binary("d1",
StandardCharsets.UTF_8)});
+ assertEquals(
+ 1,
+ stringTagGenerator.processTsBlock(
+ new TsBlock(time1, new Column[] {time1, erasedDate1, dev1}), 0));
+ InsertTabletStatement batch1 =
stringTagGenerator.constructInsertTabletStatement();
+ assertEquals("2024-01-01", ((Binary[])
batch1.getColumns()[0])[0].toString());
+ assertEquals("d1", ((Binary[]) batch1.getColumns()[1])[0].toString());
+ // Simulate WrappedInsertStatement.reorderTagColumnsWithSwap() moving TAG
to index 0.
+ batch1.swapColumn(1, 0);
+
+ stringTagGenerator.reset();
+ Column time2 = new LongColumn(1, Optional.empty(), new long[] {2L});
+ Column erasedDate2 = new IntColumn(1, Optional.empty(), new int[] {date2});
+ Column dev2 =
+ new BinaryColumn(
+ 1, Optional.empty(), new Binary[] {new Binary("d2",
StandardCharsets.UTF_8)});
+ assertEquals(
+ 1,
+ stringTagGenerator.processTsBlock(
+ new TsBlock(time2, new Column[] {time2, erasedDate2, dev2}), 0));
+ InsertTabletStatement batch2 =
stringTagGenerator.constructInsertTabletStatement();
+ assertArrayEquals(new String[] {"d_str", "device_id"},
batch2.getMeasurements());
+ assertEquals("2024-01-02", ((Binary[])
batch2.getColumns()[0])[0].toString());
+ assertEquals("d2", ((Binary[]) batch2.getColumns()[1])[0].toString());
+
+ // Scenario 2: FIELD (DATE -> STRING) before non-string TAG (INT32 ->
STRING).
+ TableInsertTabletStatementGenerator intTagGenerator =
+ new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("target_table"),
+ stringTagLocations,
+ stringTagTargets,
+ Arrays.asList(TSDataType.DATE, TSDataType.INT32),
+ Arrays.asList(TsTableColumnCategory.FIELD,
TsTableColumnCategory.TAG),
+ true,
+ 1,
+ "time",
+ TSDataType.TIMESTAMP);
+
+ Column intTag1 = new IntColumn(1, Optional.empty(), new int[] {7});
+ assertEquals(
+ 1,
+ intTagGenerator.processTsBlock(
+ new TsBlock(
+ time1,
+ new Column[] {
+ time1,
+ new IntColumn(1, Optional.empty(), new int[] {date1},
TSDataType.DATE),
+ intTag1
+ }),
+ 0));
+ InsertTabletStatement intTagBatch1 =
intTagGenerator.constructInsertTabletStatement();
+ assertEquals("2024-01-01", ((Binary[])
intTagBatch1.getColumns()[0])[0].toString());
+ assertEquals("7", ((Binary[]) intTagBatch1.getColumns()[1])[0].toString());
+ intTagBatch1.swapColumn(1, 0);
+
+ intTagGenerator.reset();
+ Column intTag2 = new IntColumn(1, Optional.empty(), new int[] {42});
+ assertEquals(
+ 1,
+ intTagGenerator.processTsBlock(
+ new TsBlock(time2, new Column[] {time2, erasedDate2, intTag2}),
0));
+ InsertTabletStatement intTagBatch2 =
intTagGenerator.constructInsertTabletStatement();
+ assertArrayEquals(new String[] {"d_str", "device_id"},
intTagBatch2.getMeasurements());
+ assertEquals("2024-01-02", ((Binary[])
intTagBatch2.getColumns()[0])[0].toString());
+ assertEquals("42", ((Binary[])
intTagBatch2.getColumns()[1])[0].toString());
+ }
+
+ @Test
+ public void testNonPositiveRowLimitRejected() {
+ for (int invalidRowLimit : new int[] {0, -1}) {
+ IllegalArgumentException exception =
+ assertThrows(
+ IllegalArgumentException.class,
+ () ->
+ createGenerator(
+ Collections.singletonList(TSDataType.INT32),
+ Collections.singletonList(TSDataType.INT64),
+ invalidRowLimit));
+ assertEquals(
+ String.format(
+
DataNodeQueryMessages.EXCEPTION_ROWLIMIT_MUST_BE_POSITIVE_BUT_WAS_ARG_E10AF0CD,
+ invalidRowLimit),
+ exception.getMessage());
+ }
+ }
+
+ @Test
+ public void testLossyIntegerToFloatingPointPromotions() throws Exception {
+ TableInsertTabletStatementGenerator generator =
+ createGenerator(
+ Arrays.asList(TSDataType.INT64, TSDataType.TIMESTAMP,
TSDataType.INT32),
+ Arrays.asList(TSDataType.DOUBLE, TSDataType.DOUBLE,
TSDataType.FLOAT));
+
+ boolean[] rowNulls = new boolean[] {false, false, false, true};
+ LongColumn timeColumn = new LongColumn(4, Optional.empty(), new long[]
{1L, 2L, 3L, 4L});
+ LongColumn int64Column =
+ new LongColumn(
+ 4,
+ Optional.of(rowNulls),
+ new long[] {9007199254740992L, 9007199254740993L,
-9007199254740993L, 0L});
+ LongColumn timestampColumn =
+ new LongColumn(
+ 4, Optional.of(rowNulls), new long[] {9007199254740992L,
9007199254740993L, 0L, 0L});
+ IntColumn int32Column =
+ new IntColumn(4, Optional.of(rowNulls), new int[] {16777216, 16777217,
-16777217, 0});
+ TsBlock block =
+ new TsBlock(
+ timeColumn, new Column[] {timeColumn, int64Column,
timestampColumn, int32Column});
+
+ int nextIndex = generator.processTsBlock(block, 0);
+ assertEquals(4, nextIndex);
+
+ InsertTabletStatement statement =
generator.constructInsertTabletStatement();
+ assertEquals(4, statement.getRowCount());
+ assertEquals(4L, generator.getWrittenCount());
+
+ double[] int64ToDouble = (double[]) statement.getColumns()[0];
+ assertEquals(9007199254740992.0d, int64ToDouble[0], 0.0d);
+ assertEquals(9007199254740992.0d, int64ToDouble[1], 0.0d);
+ assertEquals(-9007199254740992.0d, int64ToDouble[2], 0.0d);
+ assertFalse(statement.getBitMaps()[0].isMarked(0));
+ assertTrue(statement.getBitMaps()[0].isMarked(3));
+
+ double[] timestampToDouble = (double[]) statement.getColumns()[1];
+ assertEquals(9007199254740992.0d, timestampToDouble[0], 0.0d);
+ assertEquals(9007199254740992.0d, timestampToDouble[1], 0.0d);
+ assertEquals(0.0d, timestampToDouble[2], 0.0d);
+ assertFalse(statement.getBitMaps()[1].isMarked(0));
+ assertTrue(statement.getBitMaps()[1].isMarked(3));
+
+ float[] int32ToFloat = (float[]) statement.getColumns()[2];
+ assertEquals(16777216.0f, int32ToFloat[0], 0.0f);
+ assertEquals(16777216.0f, int32ToFloat[1], 0.0f);
+ assertEquals(-16777216.0f, int32ToFloat[2], 0.0f);
+ assertFalse(statement.getBitMaps()[2].isMarked(0));
+ assertTrue(statement.getBitMaps()[2].isMarked(3));
+ }
+
+ private static TableInsertTabletStatementGenerator createGenerator(
+ List<TSDataType> sourceTypes, List<TSDataType> targetTypes) throws
Exception {
+ return createGenerator(sourceTypes, targetTypes, 10);
+ }
+
+ private static TableInsertTabletStatementGenerator createGenerator(
+ List<TSDataType> sourceTypes, List<TSDataType> targetTypes, int
rowLimit) throws Exception {
+ return createGenerator(sourceTypes, targetTypes, rowLimit,
TSDataType.TIMESTAMP);
+ }
+
+ private static TableInsertTabletStatementGenerator createGenerator(
+ List<TSDataType> sourceTypes,
+ List<TSDataType> targetTypes,
+ int rowLimit,
+ TSDataType timeSourceDataType)
+ throws Exception {
+ Map<String, InputLocation> locations = new LinkedHashMap<>();
+ Map<String, TSDataType> targets = new LinkedHashMap<>();
+ List<TSDataType> inputTypes = new ArrayList<>();
+ List<TsTableColumnCategory> categories = new ArrayList<>();
+ locations.put("time", new InputLocation(0, 0));
+ for (int i = 0; i < sourceTypes.size(); i++) {
+ String measurement = "s" + i;
+ locations.put(measurement, new InputLocation(0, i + 1));
+ targets.put(measurement, targetTypes.get(i));
+ inputTypes.add(sourceTypes.get(i));
+ categories.add(TsTableColumnCategory.FIELD);
+ }
+ return new TableInsertTabletStatementGenerator(
+ "testdb",
+ new PartialPath("target_table"),
+ locations,
+ targets,
+ inputTypes,
+ categories,
+ true,
+ rowLimit,
+ "time",
+ timeSourceDataType);
+ }
+
+ private static TsBlock createTsBlock(Column... sourceColumns) {
+ LongColumn timeColumn = new LongColumn(1, Optional.empty(), new long[]
{1L});
+ Column[] valueColumns = new Column[sourceColumns.length + 1];
+ valueColumns[0] = timeColumn;
+ System.arraycopy(sourceColumns, 0, valueColumns, 1, sourceColumns.length);
+ return new TsBlock(timeColumn, valueColumns);
+ }
+
+ private static final class CountingIntColumn extends IntColumn {
+ private final int[] backingValues;
+ private final boolean[] backingNulls;
+ private final AtomicInteger intReadCount;
+ private final AtomicInteger binaryReadCount;
+
+ private CountingIntColumn(
+ int[] values,
+ boolean[] valueIsNull,
+ TSDataType dataType,
+ AtomicInteger intReadCount,
+ AtomicInteger binaryReadCount) {
+ super(values.length, Optional.ofNullable(valueIsNull), values, dataType);
+ this.backingValues = values;
+ this.backingNulls = valueIsNull;
+ this.intReadCount = intReadCount;
+ this.binaryReadCount = binaryReadCount;
+ }
+
+ @Override
+ public int getInt(int position) {
+ intReadCount.incrementAndGet();
+ return super.getInt(position);
+ }
+
+ @Override
+ public Binary getBinary(int position) {
+ binaryReadCount.incrementAndGet();
+ return super.getBinary(position);
+ }
+
+ @Override
+ public Column subColumn(int fromIndex) {
+ int[] slicedValues = Arrays.copyOfRange(backingValues, fromIndex,
backingValues.length);
+ boolean[] slicedNulls =
+ backingNulls == null
+ ? null
+ : Arrays.copyOfRange(backingNulls, fromIndex,
backingNulls.length);
+ return new CountingIntColumn(
+ slicedValues, slicedNulls, getDataType(), intReadCount,
binaryReadCount);
+ }
+ }
+}
diff --git
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/InsertIntoQueryTest.java
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/InsertIntoQueryTest.java
index 3dfd85ebbbd..3d126848205 100644
---
a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/InsertIntoQueryTest.java
+++
b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/plan/relational/analyzer/InsertIntoQueryTest.java
@@ -19,29 +19,73 @@
package org.apache.iotdb.db.queryengine.plan.relational.analyzer;
+import org.apache.iotdb.calc.execution.operator.Operator;
+import org.apache.iotdb.calc.plan.planner.memory.MemoryReservationManager;
+import org.apache.iotdb.commons.conf.CommonDescriptor;
+import org.apache.iotdb.commons.exception.SemanticException;
+import org.apache.iotdb.commons.queryengine.common.SessionInfo;
import org.apache.iotdb.commons.queryengine.plan.planner.plan.node.PlanNode;
+import
org.apache.iotdb.commons.queryengine.plan.relational.metadata.ColumnSchema;
+import
org.apache.iotdb.commons.queryengine.plan.relational.metadata.QualifiedObjectName;
+import
org.apache.iotdb.commons.queryengine.plan.relational.metadata.TableSchema;
+import org.apache.iotdb.commons.queryengine.plan.relational.planner.Symbol;
import
org.apache.iotdb.commons.queryengine.plan.relational.planner.node.LimitNode;
import
org.apache.iotdb.commons.queryengine.plan.relational.planner.node.OutputNode;
+import
org.apache.iotdb.commons.queryengine.plan.relational.planner.node.ProjectNode;
import
org.apache.iotdb.commons.queryengine.plan.relational.planner.node.StreamSortNode;
import
org.apache.iotdb.commons.queryengine.plan.relational.planner.node.TopKNode;
+import
org.apache.iotdb.commons.queryengine.plan.relational.sql.ast.SymbolReference;
+import org.apache.iotdb.commons.queryengine.utils.TimestampPrecisionUtils;
+import org.apache.iotdb.commons.schema.table.column.TsTableColumnCategory;
import org.apache.iotdb.db.conf.IoTDBDescriptor;
+import org.apache.iotdb.db.queryengine.common.FragmentInstanceId;
+import org.apache.iotdb.db.queryengine.common.MPPQueryContext;
+import org.apache.iotdb.db.queryengine.common.PlanFragmentId;
+import org.apache.iotdb.db.queryengine.execution.fragment.DataNodeQueryContext;
+import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceContext;
+import
org.apache.iotdb.db.queryengine.execution.fragment.FragmentInstanceStateMachine;
+import
org.apache.iotdb.db.queryengine.execution.operator.process.TableIntoOperator;
+import org.apache.iotdb.db.queryengine.plan.analyze.TypeProvider;
+import
org.apache.iotdb.db.queryengine.plan.planner.DataNodeTableOperatorGenerator;
+import org.apache.iotdb.db.queryengine.plan.planner.LocalExecutionPlanContext;
import org.apache.iotdb.db.queryengine.plan.planner.plan.DistributedQueryPlan;
import org.apache.iotdb.db.queryengine.plan.planner.plan.LogicalQueryPlan;
+import org.apache.iotdb.db.queryengine.plan.planner.plan.PlanFragment;
import
org.apache.iotdb.db.queryengine.plan.planner.plan.node.sink.IdentitySinkNode;
import org.apache.iotdb.db.queryengine.plan.relational.planner.SymbolAllocator;
import
org.apache.iotdb.db.queryengine.plan.relational.planner.TableLogicalPlanner;
import
org.apache.iotdb.db.queryengine.plan.relational.planner.distribute.TableDistributedPlanner;
+import
org.apache.iotdb.db.queryengine.plan.relational.planner.distribute.TableModelTypeProviderExtractor;
import
org.apache.iotdb.db.queryengine.plan.relational.planner.node.DeviceTableScanNode;
import
org.apache.iotdb.db.queryengine.plan.relational.planner.node.ExchangeNode;
import org.apache.iotdb.db.queryengine.plan.relational.planner.node.IntoNode;
+import org.apache.tsfile.block.column.Column;
+import org.apache.tsfile.enums.TSDataType;
+import org.apache.tsfile.read.common.block.TsBlock;
+import org.apache.tsfile.read.common.block.column.IntColumn;
+import org.apache.tsfile.read.common.block.column.LongColumn;
+import org.apache.tsfile.read.common.block.column.NullColumn;
+import org.apache.tsfile.read.common.block.column.RunLengthEncodedColumn;
+import org.apache.tsfile.read.common.type.DateType;
+import org.apache.tsfile.read.common.type.IntType;
+import org.apache.tsfile.read.common.type.LongType;
+import org.apache.tsfile.read.common.type.StringType;
+import org.apache.tsfile.read.common.type.TimestampType;
+import org.apache.tsfile.read.common.type.Type;
+import org.apache.tsfile.read.common.type.TypeFactory;
import org.junit.BeforeClass;
import org.junit.Test;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Optional;
+
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.AnalyzerTest.analyzeSQL;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.MockTableModelDataPartition.DEVICES_REGION_GROUP;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.DEFAULT_WARNING;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.QUERY_CONTEXT;
+import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.QUERY_ID;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.SESSION_INFO;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.TEST_MATADATA;
import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils.assertTableScan;
@@ -49,7 +93,15 @@ import static
org.apache.iotdb.db.queryengine.plan.relational.analyzer.TestUtils
import static
org.apache.iotdb.db.queryengine.plan.statement.component.Ordering.ASC;
import static
org.apache.iotdb.db.queryengine.plan.statement.component.Ordering.DESC;
import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertNull;
+import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
+import static org.mockito.ArgumentMatchers.any;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
public class InsertIntoQueryTest {
String sql;
@@ -126,4 +178,521 @@ public class InsertIntoQueryTest {
assertTableScan(deviceTableScanNode, DEVICES_REGION_GROUP.get(i - 1),
DESC, 10, 0, true, "");
}
}
+
+ @Test
+ public void compatibleInsertTypesAreAcceptedWithoutCast() {
+ TestMetadata metadata = metadataForInsert(TSDataType.INT32,
TSDataType.INT64);
+ String insertSql = "INSERT INTO testdb.compat_target SELECT * FROM
testdb.compat_source";
+
+ Analysis compatibleAnalysis = analyzeSQL(insertSql, metadata,
QUERY_CONTEXT);
+ assertNotNull(compatibleAnalysis.getInsert());
+
+ SymbolAllocator symbolAllocator = new SymbolAllocator();
+ LogicalQueryPlan compatiblePlan =
+ new TableLogicalPlanner(
+ QUERY_CONTEXT, metadata, SESSION_INFO, symbolAllocator,
DEFAULT_WARNING)
+ .plan(compatibleAnalysis);
+ PlanNode inputNode = getChildrenNode(compatiblePlan.getRootNode(), 2);
+ if (inputNode instanceof ProjectNode) {
+ assertTrue(
+ ((ProjectNode) inputNode)
+ .getAssignments().getMap().values().stream()
+ .allMatch(SymbolReference.class::isInstance));
+ } else {
+ assertTrue(inputNode instanceof DeviceTableScanNode);
+ }
+ }
+
+ @Test
+ public void incompatibleInsertTypesAreRejected() {
+ assertIncompatibleInsert(TSDataType.FLOAT, TSDataType.INT64);
+ assertIncompatibleInsert(TSDataType.DATE, TSDataType.INT32);
+ assertIncompatibleInsert(TSDataType.INT32, TSDataType.DATE);
+ }
+
+ @Test
+ public void lossyNumericPromotionsAreAcceptedWithoutCast() {
+ TSDataType[][] pairs = {
+ {TSDataType.INT64, TSDataType.DOUBLE},
+ {TSDataType.TIMESTAMP, TSDataType.DOUBLE},
+ {TSDataType.INT32, TSDataType.FLOAT},
+ };
+ String insertSql = "INSERT INTO testdb.compat_target SELECT * FROM
testdb.compat_source";
+ for (TSDataType[] pair : pairs) {
+ TSDataType sourceType = pair[0];
+ TSDataType targetType = pair[1];
+ TestMetadata metadata = metadataForInsert(sourceType, targetType);
+ MPPQueryContext localQueryContext =
+ new MPPQueryContext(insertSql, QUERY_ID, SESSION_INFO, null, null);
+ Analysis localAnalysis = analyzeSQL(insertSql, metadata,
localQueryContext);
+ assertNotNull(localAnalysis.getInsert());
+
+ SymbolAllocator symbolAllocator = new SymbolAllocator();
+ LogicalQueryPlan plan =
+ new TableLogicalPlanner(
+ localQueryContext, metadata, SESSION_INFO, symbolAllocator,
DEFAULT_WARNING)
+ .plan(localAnalysis);
+ IntoNode plannedInto = (IntoNode) getChildrenNode(plan.getRootNode(), 1);
+ Symbol valueInputSymbol = plannedInto.getNeededInputColumnNames().get(1);
+ assertEquals(TypeFactory.getType(targetType),
plannedInto.getColumns().get(1).getType());
+ assertEquals(
+ TypeFactory.getType(sourceType),
+ symbolAllocator.getTypes().getTableModelType(valueInputSymbol));
+ }
+ }
+
+ @Test
+ public void blobPromotionToTagColumnIsRejectedWhileFieldIsAllowed() {
+ TableSchema blobSource =
+ new TableSchema(
+ "blob_source",
+ Arrays.asList(
+ new ColumnSchema(
+ "time",
+ TypeFactory.getType(TSDataType.TIMESTAMP),
+ false,
+ TsTableColumnCategory.TIME),
+ new ColumnSchema(
+ "raw_blob",
+ TypeFactory.getType(TSDataType.BLOB),
+ false,
+ TsTableColumnCategory.FIELD),
+ new ColumnSchema(
+ "val",
+ TypeFactory.getType(TSDataType.INT32),
+ false,
+ TsTableColumnCategory.FIELD)));
+ TableSchema blobTagTarget =
+ new TableSchema(
+ "blob_tag_target",
+ Arrays.asList(
+ new ColumnSchema(
+ "time",
+ TypeFactory.getType(TSDataType.TIMESTAMP),
+ false,
+ TsTableColumnCategory.TIME),
+ new ColumnSchema("tag_id", StringType.STRING, false,
TsTableColumnCategory.TAG),
+ new ColumnSchema(
+ "val",
+ TypeFactory.getType(TSDataType.INT32),
+ false,
+ TsTableColumnCategory.FIELD)));
+ TableSchema blobFieldTarget =
+ new TableSchema(
+ "blob_field_target",
+ Arrays.asList(
+ new ColumnSchema(
+ "time",
+ TypeFactory.getType(TSDataType.TIMESTAMP),
+ false,
+ TsTableColumnCategory.TIME),
+ new ColumnSchema(
+ "str_field", StringType.STRING, false,
TsTableColumnCategory.FIELD)));
+
+ TestMetadata metadata =
+ new TestMetadata() {
+ @Override
+ public boolean tableExists(QualifiedObjectName name) {
+ String objectName = name.getObjectName();
+ return objectName.equalsIgnoreCase("blob_source")
+ || objectName.equalsIgnoreCase("blob_tag_target")
+ || objectName.equalsIgnoreCase("blob_field_target")
+ || super.tableExists(name);
+ }
+
+ @Override
+ public Optional<TableSchema> getTableSchema(
+ SessionInfo session, QualifiedObjectName name) {
+ if (name.getObjectName().equalsIgnoreCase("blob_source")) {
+ return Optional.of(blobSource);
+ }
+ if (name.getObjectName().equalsIgnoreCase("blob_tag_target")) {
+ return Optional.of(blobTagTarget);
+ }
+ if (name.getObjectName().equalsIgnoreCase("blob_field_target")) {
+ return Optional.of(blobFieldTarget);
+ }
+ return super.getTableSchema(session, name);
+ }
+ };
+
+ SemanticException exception =
+ assertThrows(
+ SemanticException.class,
+ () ->
+ analyzeSQL(
+ "INSERT INTO testdb.blob_tag_target(time, tag_id, val)
SELECT time, raw_blob, val FROM testdb.blob_source",
+ metadata,
+ QUERY_CONTEXT));
+ assertTrue(
+ exception.getMessage(),
+ exception.getMessage().contains("Insert query has mismatched column
types"));
+
+ Analysis fieldAnalysis =
+ analyzeSQL(
+ "INSERT INTO testdb.blob_field_target(time, str_field) SELECT
time, raw_blob FROM testdb.blob_source",
+ metadata,
+ QUERY_CONTEXT);
+ assertNotNull(fieldAnalysis.getInsert());
+ }
+
+ @Test
+ public void logicalDateTypeIsPreservedThroughIntoPlanning() {
+ TestMetadata metadata = metadataForInsert(TSDataType.DATE,
TSDataType.STRING);
+ for (String insertSql :
+ Arrays.asList(
+ "INSERT INTO testdb.compat_target SELECT time, value FROM
testdb.compat_source",
+ "INSERT INTO testdb.compat_target SELECT time, CAST('2024-01-01'
AS DATE) FROM testdb.compat_source")) {
+ MPPQueryContext localQueryContext =
+ new MPPQueryContext(insertSql, QUERY_ID, SESSION_INFO, null, null);
+ Analysis localAnalysis = analyzeSQL(insertSql, metadata,
localQueryContext);
+ SymbolAllocator symbolAllocator = new SymbolAllocator();
+ LogicalQueryPlan plan =
+ new TableLogicalPlanner(
+ localQueryContext, metadata, SESSION_INFO, symbolAllocator,
DEFAULT_WARNING)
+ .plan(localAnalysis);
+
+ IntoNode plannedInto = (IntoNode) getChildrenNode(plan.getRootNode(), 1);
+ Symbol valueInputSymbol = plannedInto.getNeededInputColumnNames().get(1);
+ assertEquals(StringType.STRING,
plannedInto.getColumns().get(1).getType());
+ assertEquals(DateType.DATE,
symbolAllocator.getTypes().getTableModelType(valueInputSymbol));
+
+ DistributedQueryPlan distributedPlan =
+ new TableDistributedPlanner(localAnalysis, symbolAllocator, plan,
metadata, null).plan();
+ int verifiedIntoFragments = 0;
+ for (PlanFragment fragment : distributedPlan.getFragments()) {
+ PlanNode fragmentTree = fragment.getPlanNodeTree();
+ IntoNode distributedInto = findIntoNode(fragmentTree);
+ if (distributedInto != null) {
+ TypeProvider extractedTypes =
+ TableModelTypeProviderExtractor.extractor(
+ fragmentTree, localQueryContext.getTypeProvider());
+ assertEquals(
+ DateType.DATE,
+
extractedTypes.getTableModelType(distributedInto.getNeededInputColumnNames().get(1)));
+ verifiedIntoFragments++;
+ }
+ }
+ assertTrue(verifiedIntoFragments > 0);
+ }
+ }
+
+ private static IntoNode findIntoNode(PlanNode node) {
+ if (node instanceof IntoNode) {
+ return (IntoNode) node;
+ }
+ for (PlanNode child : node.getChildren()) {
+ IntoNode found = findIntoNode(child);
+ if (found != null) {
+ return found;
+ }
+ }
+ return null;
+ }
+
+ @Test
+ public void sharedSourceChannelPlansAndBuildsIntoOperator() {
+ TestMetadata metadata = metadataForDuplicateTargets();
+ for (String insertSql :
+ Arrays.asList(
+ "INSERT INTO testdb.dup_target SELECT time, value, value FROM
testdb.compat_source",
+ "INSERT INTO testdb.dup_target SELECT value, value, value FROM
testdb.compat_source")) {
+ MPPQueryContext localQueryContext =
+ new MPPQueryContext(insertSql, QUERY_ID, SESSION_INFO, null, null);
+ Analysis localAnalysis = analyzeSQL(insertSql, metadata,
localQueryContext);
+ SymbolAllocator symbolAllocator = new SymbolAllocator();
+ LogicalQueryPlan plan =
+ new TableLogicalPlanner(
+ localQueryContext, metadata, SESSION_INFO, symbolAllocator,
DEFAULT_WARNING)
+ .plan(localAnalysis);
+
+ IntoNode plannedInto = (IntoNode) getChildrenNode(plan.getRootNode(), 1);
+ assertEquals(3, plannedInto.getColumns().size());
+ assertEquals(3, plannedInto.getNeededInputColumnNames().size());
+
+ TypeProvider typeProvider = new TypeProvider();
+
symbolAllocator.getTypes().allTableModelTypes().forEach(typeProvider::putTableModelType);
+
+ PlanNode mockChild = mock(PlanNode.class);
+
when(mockChild.getOutputSymbols()).thenReturn(plannedInto.getChild().getOutputSymbols());
+ doReturn(mock(Operator.class)).when(mockChild).accept(any(), any());
+ IntoNode operatorInto =
+ new IntoNode(
+ plannedInto.getPlanNodeId(),
+ mockChild,
+ plannedInto.getDatabase(),
+ plannedInto.getTable(),
+ plannedInto.getColumns(),
+ plannedInto.getNeededInputColumnNames(),
+ plannedInto.getRowCountSymbol());
+
+ FragmentInstanceContext fragmentContext =
+ FragmentInstanceContext.createFragmentInstanceContext(
+ new FragmentInstanceId(new PlanFragmentId(QUERY_ID, 0), "0"),
+ mock(FragmentInstanceStateMachine.class),
+ mock(MemoryReservationManager.class));
+ LocalExecutionPlanContext executionContext =
+ new LocalExecutionPlanContext(typeProvider, fragmentContext,
(DataNodeQueryContext) null);
+
+ Operator operator =
+ new DataNodeTableOperatorGenerator(metadata).visitInto(operatorInto,
executionContext);
+ assertTrue(operator instanceof TableIntoOperator);
+ }
+ }
+
+ @Test
+ public void
timeSourceLogicalTypeIsPreservedAndControlsIntoOperatorPrecisionCheck()
+ throws Exception {
+ TableSchema timeTypeSrc =
+ new TableSchema(
+ "time_type_src",
+ Arrays.asList(
+ new ColumnSchema(
+ "time", TimestampType.TIMESTAMP, false,
TsTableColumnCategory.TIME),
+ new ColumnSchema("tick", IntType.INT32, false,
TsTableColumnCategory.FIELD),
+ new ColumnSchema("micro_tick", LongType.INT64, false,
TsTableColumnCategory.FIELD),
+ new ColumnSchema("v", IntType.INT32, false,
TsTableColumnCategory.FIELD)));
+ TableSchema timeTypeDst =
+ new TableSchema(
+ "time_type_dst",
+ Arrays.asList(
+ new ColumnSchema(
+ "time", TimestampType.TIMESTAMP, false,
TsTableColumnCategory.TIME),
+ new ColumnSchema("v", IntType.INT32, false,
TsTableColumnCategory.FIELD)));
+
+ TestMetadata metadata =
+ new TestMetadata() {
+ @Override
+ public boolean tableExists(QualifiedObjectName name) {
+ String objectName = name.getObjectName();
+ return objectName.equalsIgnoreCase("time_type_src")
+ || objectName.equalsIgnoreCase("time_type_dst")
+ || super.tableExists(name);
+ }
+
+ @Override
+ public Optional<TableSchema> getTableSchema(
+ SessionInfo session, QualifiedObjectName name) {
+ if (name.getObjectName().equalsIgnoreCase("time_type_src")) {
+ return Optional.of(timeTypeSrc);
+ }
+ if (name.getObjectName().equalsIgnoreCase("time_type_dst")) {
+ return Optional.of(timeTypeDst);
+ }
+ return super.getTableSchema(session, name);
+ }
+ };
+
+ List<String> sqls =
+ Arrays.asList(
+ "INSERT INTO testdb.time_type_dst(time, v) SELECT time, v FROM
testdb.time_type_src",
+ "INSERT INTO testdb.time_type_dst(time, v) SELECT tick, v FROM
testdb.time_type_src",
+ "INSERT INTO testdb.time_type_dst(time, v) SELECT micro_tick, v
FROM testdb.time_type_src");
+ List<Type> expectedTypes =
+ Arrays.asList(TimestampType.TIMESTAMP, IntType.INT32, LongType.INT64);
+
+ String previousPrecision = TimestampPrecisionUtils.TIMESTAMP_PRECISION;
+ boolean previousCheckEnabled =
+
CommonDescriptor.getInstance().getConfig().isTimestampPrecisionCheckEnabled();
+ TimestampPrecisionUtils.TIMESTAMP_PRECISION = "ms";
+
CommonDescriptor.getInstance().getConfig().setTimestampPrecisionCheckEnabled(true);
+ try {
+ for (int i = 0; i < sqls.size(); i++) {
+ String insertSql = sqls.get(i);
+ Type expectedTimeSourceType = expectedTypes.get(i);
+ MPPQueryContext localQueryContext =
+ new MPPQueryContext(insertSql, QUERY_ID, SESSION_INFO, null, null);
+ Analysis localAnalysis = analyzeSQL(insertSql, metadata,
localQueryContext);
+ SymbolAllocator symbolAllocator = new SymbolAllocator();
+ LogicalQueryPlan plan =
+ new TableLogicalPlanner(
+ localQueryContext, metadata, SESSION_INFO,
symbolAllocator, DEFAULT_WARNING)
+ .plan(localAnalysis);
+
+ IntoNode plannedInto = (IntoNode) getChildrenNode(plan.getRootNode(),
1);
+ Symbol timeInputSymbol =
plannedInto.getNeededInputColumnNames().get(0);
+ assertEquals(
+ expectedTimeSourceType,
symbolAllocator.getTypes().getTableModelType(timeInputSymbol));
+
+ DistributedQueryPlan distributedPlan =
+ new TableDistributedPlanner(localAnalysis, symbolAllocator, plan,
metadata, null)
+ .plan();
+ int verifiedIntoFragments = 0;
+ for (PlanFragment fragment : distributedPlan.getFragments()) {
+ PlanNode fragmentTree = fragment.getPlanNodeTree();
+ IntoNode distributedInto = findIntoNode(fragmentTree);
+ if (distributedInto != null) {
+ TypeProvider extractedTypes =
+ TableModelTypeProviderExtractor.extractor(
+ fragmentTree, localQueryContext.getTypeProvider());
+ assertEquals(
+ expectedTimeSourceType,
+ extractedTypes.getTableModelType(
+ distributedInto.getNeededInputColumnNames().get(0)));
+ verifiedIntoFragments++;
+ }
+ }
+ assertTrue(verifiedIntoFragments > 0);
+
+ if (expectedTimeSourceType == TimestampType.TIMESTAMP
+ || expectedTimeSourceType == LongType.INT64) {
+ Column plainTimeCol =
+ new LongColumn(1, Optional.empty(), new long[]
{1_700_000_000_000_000L});
+ Column rleTimeCol =
+ new RunLengthEncodedColumn(
+ new LongColumn(1, Optional.empty(), new long[]
{1_700_000_000_000_000L}), 1);
+ for (Column timeCol : Arrays.asList(plainTimeCol, rleTimeCol)) {
+ TypeProvider typeProvider = new TypeProvider();
+ symbolAllocator
+ .getTypes()
+ .allTableModelTypes()
+ .forEach(typeProvider::putTableModelType);
+
+ List<Symbol> childOutputSymbols =
plannedInto.getChild().getOutputSymbols();
+ int timeIdx =
+
childOutputSymbols.indexOf(plannedInto.getNeededInputColumnNames().get(0));
+ int valIdx =
childOutputSymbols.indexOf(plannedInto.getNeededInputColumnNames().get(1));
+ Column[] valueColumns = new Column[childOutputSymbols.size()];
+ Arrays.fill(valueColumns, new NullColumn(1));
+ valueColumns[timeIdx] = timeCol;
+ valueColumns[valIdx] = new IntColumn(1, Optional.empty(), new
int[] {42});
+ TsBlock inputBlock =
+ new TsBlock(
+ new LongColumn(1, Optional.empty(), new long[]
{1_700_000_000_000_000L}),
+ valueColumns);
+
+ Operator mockChildOp = mock(Operator.class);
+ when(mockChildOp.hasNextWithTimer()).thenReturn(true);
+ when(mockChildOp.nextWithTimer()).thenReturn(inputBlock);
+
+ PlanNode mockChild = mock(PlanNode.class);
+ when(mockChild.getOutputSymbols()).thenReturn(childOutputSymbols);
+ doReturn(mockChildOp).when(mockChild).accept(any(), any());
+ IntoNode operatorInto =
+ new IntoNode(
+ plannedInto.getPlanNodeId(),
+ mockChild,
+ plannedInto.getDatabase(),
+ plannedInto.getTable(),
+ plannedInto.getColumns(),
+ plannedInto.getNeededInputColumnNames(),
+ plannedInto.getRowCountSymbol());
+
+ FragmentInstanceContext fragmentContext =
+ FragmentInstanceContext.createFragmentInstanceContext(
+ new FragmentInstanceId(new PlanFragmentId(QUERY_ID, 0),
"0"),
+ mock(FragmentInstanceStateMachine.class),
+ mock(MemoryReservationManager.class));
+ LocalExecutionPlanContext executionContext =
+ new LocalExecutionPlanContext(
+ typeProvider, fragmentContext, (DataNodeQueryContext)
null);
+
+ Operator operator =
+ new DataNodeTableOperatorGenerator(metadata)
+ .visitInto(operatorInto, executionContext);
+ assertTrue(operator instanceof TableIntoOperator);
+
+ // Call next() at most once so buffered rows (<
maxRowNumberInStatement) do not trigger
+ // DataNodeInternalClient submission.
+ if (expectedTimeSourceType == TimestampType.TIMESTAMP) {
+ assertNull(operator.next());
+ } else {
+ SemanticException ex = assertThrows(SemanticException.class,
operator::next);
+ assertTrue(ex.getMessage(),
ex.getMessage().contains("1700000000000000"));
+ }
+ verify(mockChildOp).nextWithTimer();
+ }
+ }
+ }
+ } finally {
+ TimestampPrecisionUtils.TIMESTAMP_PRECISION = previousPrecision;
+ CommonDescriptor.getInstance()
+ .getConfig()
+ .setTimestampPrecisionCheckEnabled(previousCheckEnabled);
+ }
+ }
+
+ private static TestMetadata metadataForDuplicateTargets() {
+ TableSchema dupTarget =
+ new TableSchema(
+ "dup_target",
+ Arrays.asList(
+ new ColumnSchema(
+ "time",
+ TypeFactory.getType(TSDataType.TIMESTAMP),
+ false,
+ TsTableColumnCategory.TIME),
+ new ColumnSchema("wide", LongType.INT64, false,
TsTableColumnCategory.FIELD),
+ new ColumnSchema(
+ "formatted", StringType.STRING, false,
TsTableColumnCategory.FIELD)));
+ return new TestMetadata() {
+ @Override
+ public boolean tableExists(QualifiedObjectName name) {
+ return name.getObjectName().equalsIgnoreCase("compat_source")
+ || name.getObjectName().equalsIgnoreCase("dup_target")
+ || super.tableExists(name);
+ }
+
+ @Override
+ public Optional<TableSchema> getTableSchema(SessionInfo session,
QualifiedObjectName name) {
+ if (name.getObjectName().equalsIgnoreCase("compat_source")) {
+ return Optional.of(tableSchema("compat_source", TSDataType.INT32));
+ }
+ if (name.getObjectName().equalsIgnoreCase("dup_target")) {
+ return Optional.of(dupTarget);
+ }
+ return super.getTableSchema(session, name);
+ }
+ };
+ }
+
+ private static void assertIncompatibleInsert(TSDataType sourceType,
TSDataType targetType) {
+ TestMetadata metadata = metadataForInsert(sourceType, targetType);
+ SemanticException exception =
+ assertThrows(
+ SemanticException.class,
+ () ->
+ analyzeSQL(
+ "INSERT INTO testdb.compat_target SELECT * FROM
testdb.compat_source",
+ metadata,
+ QUERY_CONTEXT));
+ assertTrue(
+ exception.getMessage(),
+ exception.getMessage().contains("Insert query has mismatched column
types"));
+ }
+
+ private static TestMetadata metadataForInsert(TSDataType sourceType,
TSDataType targetType) {
+ return new TestMetadata() {
+ @Override
+ public boolean tableExists(QualifiedObjectName name) {
+ return name.getObjectName().equalsIgnoreCase("compat_source")
+ || name.getObjectName().equalsIgnoreCase("compat_target")
+ || super.tableExists(name);
+ }
+
+ @Override
+ public Optional<TableSchema> getTableSchema(SessionInfo session,
QualifiedObjectName name) {
+ if (name.getObjectName().equalsIgnoreCase("compat_source")) {
+ return Optional.of(tableSchema("compat_source", sourceType));
+ }
+ if (name.getObjectName().equalsIgnoreCase("compat_target")) {
+ return Optional.of(tableSchema("compat_target", targetType));
+ }
+ return super.getTableSchema(session, name);
+ }
+ };
+ }
+
+ private static TableSchema tableSchema(String tableName, TSDataType
fieldType) {
+ return new TableSchema(
+ tableName,
+ Arrays.asList(
+ new ColumnSchema(
+ "time",
+ TypeFactory.getType(TSDataType.TIMESTAMP),
+ false,
+ TsTableColumnCategory.TIME),
+ new ColumnSchema(
+ "value", TypeFactory.getType(fieldType), false,
TsTableColumnCategory.FIELD)));
+ }
}