From eaa49352ce69cd90c97ca79c9ee2b65173fb88f4 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 12:05:59 +0800 Subject: [PATCH 1/7] Fix timestamp fields and failure status in table CSV imports --- .../iotdb/tool/data/ImportDataTable.java | 14 +++- .../tool/data/DataToolRegressionTest.java | 74 +++++++++++++++++++ 2 files changed, 87 insertions(+), 1 deletion(-) diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java index af1541cc62985..40052b3451d0c 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java @@ -49,6 +49,7 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.time.DateTimeException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -376,7 +377,8 @@ protected boolean writeData( } type = headerTypeMap.get(headerName); if (type != null) { - Object valueTrans = typeTrans(value, type); + Object valueTrans = + type == TSDataType.TIMESTAMP ? parseTimestampField(value) : typeTrans(value, type); if (valueTrans == null) { isFail = true; ioTPrinter.printf( @@ -404,11 +406,21 @@ protected boolean writeData( } if (!failedRecords.isEmpty()) { + markFileFailed(); writeFailedLinesFile(headerNames, failedFilePath, failedRecords); + return false; } return true; } + private static Long parseTimestampField(String value) { + try { + return parseTimestamp(value); + } catch (DateTimeException | ArithmeticException e) { + return null; + } + } + private static void writeAndEmptyDataSet(Tablet tablet, int retryTime) { executeWithRetry( () -> { diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index 5ea07bf0e0547..eb3aa28708b10 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -59,6 +59,7 @@ import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; import java.util.Arrays; @@ -756,6 +757,79 @@ public void testFailedTableCsvDoesNotSkipNextFile() throws Exception { assertNull(ImportDataScanTool.pollFromQueue()); } + @Test + public void testTableCsvTimestampFieldRoundTrip() throws Exception { + long eventTime = 1796355197083L; + ITableSession session = mockTimestampFieldImport(); + SessionDataSet result = + dataSet( + List.of("time", "event_ts"), + List.of("TIMESTAMP", "TIMESTAMP"), + new Object[] {eventTime + 1000, eventTime}); + String sql = "select * from t"; + when(session.executeQueryStatement(eq(sql), anyLong())).thenReturn(result); + ExportConfig config = + ExportConfig.parse( + new String[] { + "-t", directory.toString(), "-sql_dialect", "table", "-db", "db", "-ft", "csv" + }, + ZonedDateTime.now()); + try (ExportProgressReporter progress = progress(); + ExportDataTable exporter = new ExportDataTable(config, progress, session)) { + exporter.zoneId = ZoneOffset.ofHours(8); + exporter.export(new ExportTask(sql, directory.resolve("dump"), null, "t")); + } + Path csv = directory.resolve("dump_0.csv"); + assertEquals( + "2026-12-04T11:33:18.083+08:00,2026-12-04T11:33:17.083+08:00", + Files.readAllLines(csv).get(1)); + Map imported = new HashMap<>(); + doAnswer( + invocation -> { + Tablet tablet = invocation.getArgument(0); + for (int row = 0; row < tablet.getRowSize(); row++) { + imported.put(tablet.getTimestamp(row), tablet.getValue(row, 0)); + } + return null; + }) + .when(session) + .insert(any(Tablet.class)); + Path numeric = directory.resolve("numeric.csv"); + Files.writeString(numeric, "time,event_ts\n2,1000\n"); + ImportDataScanTool.putToQueue(csv.toString()); + ImportDataScanTool.putToQueue(numeric.toString()); + assertTrue(AbstractImportData.init(new ImportDataTable())); + assertEquals(Map.of(eventTime + 1000, eventTime, 2L, 1000L), imported); + assertFalse(Files.exists(directory.resolve("dump_0.csv.failed_0"))); + assertFalse(Files.exists(directory.resolve("numeric.csv.failed_0"))); + } + + @Test + public void testTableCsvInvalidTimestampFieldFailsFile() throws Exception { + mockTimestampFieldImport(); + Path csv = directory.resolve("invalid.csv"); + Files.writeString(csv, "time,event_ts\n1,1000\n2,invalid\n"); + long failures = loadFileFailedNum.sum(); + long successes = loadFileSuccessfulNum.sum(); + ImportDataScanTool.putToQueue(csv.toString()); + assertFalse(AbstractImportData.init(new ImportDataTable())); + assertEquals(failures + 1, loadFileFailedNum.sum()); + assertEquals(successes, loadFileSuccessfulNum.sum()); + assertEquals( + List.of("time,event_ts", "2,invalid"), + Files.readAllLines(directory.resolve("invalid.csv.failed_0"))); + } + + private ITableSession mockTimestampFieldImport() throws Exception { + set(ImportDataTable.class, "dataTypes", Map.of("event_ts", TSDataType.TIMESTAMP)); + set(ImportDataTable.class, "columnCategory", Map.of("event_ts", ColumnCategory.FIELD)); + ITableSession session = mock(ITableSession.class); + ITableSessionPool pool = mock(ITableSessionPool.class); + when(pool.getSession()).thenReturn(session); + set(ImportDataTable.class, "sessionPool", pool); + return session; + } + @Test public void testTypedTableCsvUsesOriginalHeaderSpelling() throws Exception { Map types = new LinkedHashMap<>(); From 6b10760faa35c7c83405396e08f9570d88d1ae06 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 14:48:53 +0800 Subject: [PATCH 2/7] Fix CSV timestamp parsing across time zones and precision boundaries --- .../apache/iotdb/tool/data/ImportData.java | 14 +- .../tool/data/DataToolRegressionTest.java | 132 +++++++++++++++--- .../java/org/apache/iotdb/rpc/RpcUtils.java | 17 +-- .../org/apache/iotdb/rpc/RpcUtilsTest.java | 9 ++ .../iotdb/db/utils/DateTimeUtilsTest.java | 18 +-- .../queryengine/utils/DateTimeUtils.java | 94 ++++++++----- 6 files changed, 206 insertions(+), 78 deletions(-) diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportData.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportData.java index 74ef77fbf5ac6..f4929d7e7f776 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportData.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportData.java @@ -248,12 +248,16 @@ public static void main(String[] args) throws IoTDBConnectionException { Objects.toString(e.getMessage()))); System.exit(Constants.CODE_ERROR); } - int resultCode = importFromTargetPathAsync(); + int resultCode = + importFromTargetPathAsync(sqlDialectTree ? new ImportDataTree() : new ImportDataTable()); System.exit(resultCode); } private static void parseSpecialParams(CommandLine commandLine) throws ArgsErrorException { timeZoneID = commandLine.getOptionValue(Constants.TIME_ZONE_ARGS); + if (!sqlDialectTree && Constants.CSV_SUFFIXS.equalsIgnoreCase(fileType)) { + zoneId = timeZoneID == null ? ZoneId.systemDefault() : ZoneId.of(timeZoneID); + } targetPath = commandLine.getOptionValue(Constants.FILE_ARGS); if (commandLine.getOptionValue(Constants.BATCH_POINT_SIZE_ARGS) != null) { batchPointSize = @@ -460,14 +464,8 @@ private static void applyTypeInferArgs(String key, String value) throws ArgsErro Constants.TYPE_INFER_KEY_DICT.put(key, Constants.TYPE_INFER_VALUE_DICT.get(value)); } - private static int importFromTargetPathAsync() { + static int importFromTargetPathAsync(AbstractImportData importData) { try { - AbstractImportData importData; - if (sqlDialectTree) { - importData = new ImportDataTree(); - } else { - importData = new ImportDataTable(); - } importData.init(); final File file = new File(targetPath); if (!file.isFile() && !file.isDirectory()) { diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index eb3aa28708b10..23572807dbe02 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -31,9 +31,12 @@ import org.apache.iotdb.session.pool.SessionPool; import org.apache.iotdb.tool.common.Constants; import org.apache.iotdb.tool.common.ImportTsFileOperation; +import org.apache.iotdb.tool.common.OptionsUtil; import org.apache.iotdb.tool.tsfile.ImportTsFileBase; import org.apache.iotdb.tool.tsfile.ImportTsFileScanTool; +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; import org.apache.commons.csv.CSVParser; import org.apache.tsfile.enums.ColumnCategory; import org.apache.tsfile.enums.TSDataType; @@ -59,6 +62,7 @@ import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; import java.nio.file.Path; +import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -88,6 +92,7 @@ import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.never; +import static org.mockito.Mockito.spy; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -761,11 +766,77 @@ public void testFailedTableCsvDoesNotSkipNextFile() throws Exception { public void testTableCsvTimestampFieldRoundTrip() throws Exception { long eventTime = 1796355197083L; ITableSession session = mockTimestampFieldImport(); + Path csv = + exportTimestampField(session, eventTime + 1000, eventTime, ZoneOffset.ofHours(8), "ms"); + assertEquals( + "2026-12-04T11:33:18.083+08:00,2026-12-04T11:33:17.083+08:00", + Files.readAllLines(csv).get(1)); + Map imported = captureTimestampField(session); + Path numeric = directory.resolve("numeric.csv"); + Files.writeString(numeric, "time,event_ts\n2,1000\n"); + ImportDataScanTool.putToQueue(csv.toString()); + ImportDataScanTool.putToQueue(numeric.toString()); + assertTrue(AbstractImportData.init(new ImportDataTable())); + assertEquals(Map.of(eventTime + 1000, eventTime, 2L, 1000L), imported); + assertFalse(Files.exists(directory.resolve("dump_0.csv.failed_0"))); + assertFalse(Files.exists(directory.resolve("numeric.csv.failed_0"))); + } + + @Test + public void testTableCsvNanosecondTimestampFieldRoundTrip() throws Exception { + assertTimestampRoundTrip( + Long.MIN_VALUE + 1, ZoneOffset.UTC, "ns", "1677-09-21T00:12:43.145224193Z"); + } + + @Test + public void testTableCsvNegativeOffsetTimestampRoundTrip() throws Exception { + assertTimestampRoundTrip( + 1796355197083L, ZoneOffset.ofHours(-5), "ms", "2026-12-03T22:33:17.083-05:00"); + } + + private void assertTimestampRoundTrip( + long timestamp, ZoneOffset zone, String precision, String expected) throws Exception { + ITableSession session = mockTimestampFieldImport(); + Path csv = exportTimestampField(session, timestamp, timestamp, zone, precision); + assertEquals(expected + "," + expected, Files.readAllLines(csv).get(1)); + Map imported = captureTimestampField(session); + assertEquals(0, importTableCsv(csv, "-tp", precision)); + assertEquals(Map.of(timestamp, timestamp), imported); + } + + @Test + public void testTableCsvTimestampFieldUsesConfiguredTimeZone() throws Exception { + zoneId = ZoneOffset.UTC; + Map imported = captureTimestampField(mockTimestampFieldImport()); + Path csv = directory.resolve("local.csv"); + Files.writeString(csv, "time,event_ts\n1970-01-01T08:00:00,1970-01-01T08:00:00\n"); + assertEquals(0, importTableCsv(csv, "-tz", "+08:00")); + assertEquals(Map.of(0L, 0L), imported); + + imported.clear(); + Files.writeString( + csv, + "time,event_ts\n1,2026-07-01T12:00:00\n2,2026-01-01T12:00:00\n3,1970-01-01T08:00:00+08:00\n"); + assertEquals(0, importTableCsv(csv, "-tz", "America/New_York")); + assertEquals( + Map.of( + 1L, + Instant.parse("2026-07-01T16:00:00Z").toEpochMilli(), + 2L, + Instant.parse("2026-01-01T17:00:00Z").toEpochMilli(), + 3L, + 0L), + imported); + } + + private Path exportTimestampField( + ITableSession session, long rowTime, long eventTime, ZoneOffset offset, String precision) + throws Exception { SessionDataSet result = dataSet( List.of("time", "event_ts"), List.of("TIMESTAMP", "TIMESTAMP"), - new Object[] {eventTime + 1000, eventTime}); + new Object[] {rowTime, eventTime}); String sql = "select * from t"; when(session.executeQueryStatement(eq(sql), anyLong())).thenReturn(result); ExportConfig config = @@ -776,13 +847,14 @@ public void testTableCsvTimestampFieldRoundTrip() throws Exception { ZonedDateTime.now()); try (ExportProgressReporter progress = progress(); ExportDataTable exporter = new ExportDataTable(config, progress, session)) { - exporter.zoneId = ZoneOffset.ofHours(8); + exporter.zoneId = offset; + exporter.timestampPrecision = precision; exporter.export(new ExportTask(sql, directory.resolve("dump"), null, "t")); } - Path csv = directory.resolve("dump_0.csv"); - assertEquals( - "2026-12-04T11:33:18.083+08:00,2026-12-04T11:33:17.083+08:00", - Files.readAllLines(csv).get(1)); + return directory.resolve("dump_0.csv"); + } + + private Map captureTimestampField(ITableSession session) throws Exception { Map imported = new HashMap<>(); doAnswer( invocation -> { @@ -794,30 +866,50 @@ public void testTableCsvTimestampFieldRoundTrip() throws Exception { }) .when(session) .insert(any(Tablet.class)); - Path numeric = directory.resolve("numeric.csv"); - Files.writeString(numeric, "time,event_ts\n2,1000\n"); - ImportDataScanTool.putToQueue(csv.toString()); - ImportDataScanTool.putToQueue(numeric.toString()); - assertTrue(AbstractImportData.init(new ImportDataTable())); - assertEquals(Map.of(eventTime + 1000, eventTime, 2L, 1000L), imported); - assertFalse(Files.exists(directory.resolve("dump_0.csv.failed_0"))); - assertFalse(Files.exists(directory.resolve("numeric.csv.failed_0"))); + return imported; } @Test public void testTableCsvInvalidTimestampFieldFailsFile() throws Exception { mockTimestampFieldImport(); - Path csv = directory.resolve("invalid.csv"); - Files.writeString(csv, "time,event_ts\n1,1000\n2,invalid\n"); + assertTimestampFieldFailsFile("invalid.csv", "invalid"); + assertTimestampFieldFailsFile("suffix.csv", "2026-12-04T03:33:17.083Zjunk"); + assertTimestampFieldFailsFile( + "concatenated.csv", "2026-12-04T03:33:17.083Z2026-12-04T03:33:17.083Z"); + } + + private void assertTimestampFieldFailsFile(String name, String value) throws Exception { + Path csv = directory.resolve(name); + Files.writeString(csv, "time,event_ts\n1,1000\n2," + value + "\n"); long failures = loadFileFailedNum.sum(); long successes = loadFileSuccessfulNum.sum(); - ImportDataScanTool.putToQueue(csv.toString()); - assertFalse(AbstractImportData.init(new ImportDataTable())); + assertEquals(1, importTableCsv(csv)); assertEquals(failures + 1, loadFileFailedNum.sum()); assertEquals(successes, loadFileSuccessfulNum.sum()); assertEquals( - List.of("time,event_ts", "2,invalid"), - Files.readAllLines(directory.resolve("invalid.csv.failed_0"))); + List.of("time,event_ts", "2," + value), + Files.readAllLines(directory.resolve(name + ".failed_0"))); + } + + private int importTableCsv(Path csv, String... options) throws Exception { + sqlDialectTree = false; + host = "127.0.0.1"; + List args = + new ArrayList<>(List.of("-ft", "csv", "-s", csv.toString(), "-db", "db", "-table", "t")); + args.addAll(Arrays.asList(options)); + CommandLine commandLine = + new DefaultParser() + .parse(OptionsUtil.createTableImportCsvOptions(), args.toArray(new String[0])); + invoke( + ImportData.class, + "parseSpecialParams", + null, + new Class[] {CommandLine.class}, + commandLine); + ImportDataTable importer = spy(new ImportDataTable()); + doNothing().when(importer).init(); + ImportDataScanTool.putToQueue(csv.toString()); + return ImportData.importFromTargetPathAsync(importer); } private ITableSession mockTimestampFieldImport() throws Exception { diff --git a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java index 70447af257cc6..6f6a6d9cb2256 100644 --- a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java +++ b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java @@ -44,6 +44,8 @@ import java.util.List; import java.util.Map; import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; import java.util.stream.Collectors; public class RpcUtils { @@ -294,6 +296,8 @@ public static TSFetchResultsResp getTSFetchResultsResp(TSStatus status) { public static final String DEFAULT_TIME_FORMAT = "default"; public static final String DEFAULT_TIMESTAMP_PRECISION = "ms"; + private static final Pattern OFFSET_SUFFIX = + Pattern.compile("(?:Z|[+-]\\d{2}:\\d{2}(?::\\d{2})?)$"); public static String setTimeFormat(String newTimeFormat) { String timeFormat; @@ -332,16 +336,9 @@ public static String formatDatetime( } public static String formatDatetimeStr(String datetime, StringBuilder digits) { - if (datetime.contains("+")) { - String timeZoneStr = datetime.substring(datetime.length() - 6); - return datetime.substring(0, datetime.length() - 6) + "." + digits + timeZoneStr; - } else if (datetime.contains("Z")) { - String timeZoneStr = datetime.substring(datetime.length() - 1); - return datetime.substring(0, datetime.length() - 1) + "." + digits + timeZoneStr; - } else { - String timeZoneStr = ""; - return datetime + "." + digits + timeZoneStr; - } + Matcher offset = OFFSET_SUFFIX.matcher(datetime); + int endOfTime = offset.find() ? offset.start() : datetime.length(); + return datetime.substring(0, endOfTime) + "." + digits + datetime.substring(endOfTime); } @SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning diff --git a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java index 4702dd6082789..0ecebdb9357ab 100644 --- a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java +++ b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java @@ -78,6 +78,15 @@ public void parseLongToDateWithPrecision() { Assert.assertEquals( "1970-01-01T07:59:59.999+08:00", RpcUtils.parseLongToDateWithPrecision(formatter, -1, zoneId, "ms")); + + zoneId = ZoneId.of("-05:00"); + Assert.assertEquals( + "2026-12-03T22:33:17.083-05:00", + RpcUtils.formatDatetime(RpcUtils.DEFAULT_TIME_FORMAT, "ms", 1796355197083L, zoneId)); + Assert.assertEquals( + "2026-12-03T22:33:17.083", + RpcUtils.parseLongToDateWithPrecision( + DateTimeFormatter.ISO_LOCAL_DATE_TIME, 1796355197083L, zoneId, "ms")); } @Test diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java index d196bdecef6b4..b50695cf1f50b 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java @@ -33,9 +33,9 @@ import org.junit.Test; import java.time.Instant; +import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; -import java.time.ZonedDateTime; import java.util.TimeZone; import static org.junit.Assert.assertEquals; @@ -53,13 +53,9 @@ public class DateTimeUtilsTest { /** Test convertDatetimeStrToLong() method with different time precision. */ @Test public void convertDatetimeStrToLongTest1() { - zoneOffset = ZonedDateTime.now().getOffset(); zoneId = ZoneId.systemDefault(); - if (zoneOffset.toString().equals("Z")) { - delta = 8 * 3600000; - } else { - delta = (8 - Long.parseLong(zoneOffset.toString().split(":")[0])) * 3600000; - } + zoneOffset = zoneId.getRules().getOffset(LocalDateTime.of(2019, 1, 2, 15, 13, 27)); + delta = (ZoneOffset.ofHours(8).getTotalSeconds() - zoneOffset.getTotalSeconds()) * 1000L; testConvertDatetimeStrToLongWithoutMS(zoneOffset, zoneId, timestamp - 689 + delta); testConvertDatetimeStrToLongWithMS(zoneOffset, zoneId, timestamp + delta); testConvertDatetimeStrToLongWithMS2(zoneOffset, zoneId, timestamp - 9 + delta); @@ -93,7 +89,7 @@ public void convertDatetimeStrToLongTest4() { fail(); } catch (Exception e) { assertEquals( - "Text '1999-02-29T00:00:00.000+00:00' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", + "Text '1999-02-29T00:00:00.000' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", e.getMessage()); } } @@ -224,6 +220,12 @@ public void getInstantWithPrecisionTest() { Assert.assertThrows( ArithmeticException.class, () -> DateTimeUtils.getInstantWithPrecision("294247-01-10T04:00:54.775808+00:00", "us")); + assertEquals( + Long.MIN_VALUE, + DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224192Z", "ns")); + Assert.assertThrows( + ArithmeticException.class, + () -> DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224191Z", "ns")); } @Test diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java index 5102738df70d9..ca273f5c8ea29 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java @@ -539,6 +539,28 @@ public static void initTimestampPrecision() { .toFormatter() .withResolverStyle(ResolverStyle.STRICT); + private static final DateTimeFormatter DASHED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WIDTH_1_2); + private static final DateTimeFormatter ISO_TIMESTAMP = + timestampParser(DateTimeFormatter.ISO_LOCAL_DATE); + private static final DateTimeFormatter SLASHED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WITH_SLASH); + private static final DateTimeFormatter DOTTED_TIMESTAMP = + timestampParser(ISO_LOCAL_DATE_WITH_DOT); + + private static DateTimeFormatter timestampParser(DateTimeFormatter date) { + return new DateTimeFormatterBuilder() + .parseCaseInsensitive() + .append(date) + .appendLiteral('T') + .append(ISO_LOCAL_TIME_WITH_NS) + .optionalStart() + .appendOffsetId() + .optionalEnd() + .toFormatter() + .withResolverStyle(ResolverStyle.STRICT); + } + public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String timeStr) { try { return Long.parseLong(timeStr); @@ -549,38 +571,58 @@ public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String tim public static long convertDatetimeStrToLong(String str, ZoneId zoneId) { return convertDatetimeStrToLong( - str, - toZoneOffset(zoneId), - 0, - CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); + str, zoneId, CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); } public static long convertDatetimeStrToLong( String str, ZoneId zoneId, String timestampPrecision) { - return convertDatetimeStrToLong(str, toZoneOffset(zoneId), 0, timestampPrecision); + if (str.contains("[") || str.contains("]")) { + throw new DateTimeException( + String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); + } + if (str.length() == 10) { + str += "T00:00:00"; + } + return getInstantWithPrecision(parseDateTime(str, zoneId), timestampPrecision); } public static long getInstantWithPrecision(String str, String timestampPrecision) { - ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, formatter); - Instant instant = zonedDateTime.toInstant(); + return getInstantWithPrecision(parseDateTime(str, null), timestampPrecision); + } + + private static Instant parseDateTime(String str, ZoneId defaultZone) { + DateTimeFormatter parser; + int dot = str.indexOf('.'); + if (str.indexOf('/') >= 0) { + parser = SLASHED_TIMESTAMP; + } else if (dot >= 0 && dot < str.indexOf(':')) { + parser = DOTTED_TIMESTAMP; + } else { + // The space-separated ISO form also supports signed years. + parser = str.indexOf(' ') >= 0 ? ISO_TIMESTAMP : DASHED_TIMESTAMP; + } + return parser.withZone(defaultZone).parse(str.replace(' ', 'T'), Instant::from); + } + + private static long getInstantWithPrecision(Instant instant, String timestampPrecision) { if ("us".equals(timestampPrecision) || "microsecond".equals(timestampPrecision)) { - if (instant.getEpochSecond() < 0 && instant.getNano() > 0) { - // Same as Instant#toEpochMilli: multiply (epochSecond + 1) so that the product cannot - // overflow near Long.MIN_VALUE, then subtract that extra second (1_000_000 us). - long millis = Math.multiplyExact(instant.getEpochSecond() + 1, 1000_000L); - long adjustment = instant.getNano() / 1000 - 1_000_000L; - return Math.addExact(millis, adjustment); - } else { - long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000L); - return Math.addExact(millis, instant.getNano() / 1000); - } + return scaleEpochSecond(instant, 1_000_000L, instant.getNano() / 1000); } else if ("ns".equals(timestampPrecision) || "nanosecond".equals(timestampPrecision)) { - long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000_000L); - return Math.addExact(millis, instant.getNano()); + return scaleEpochSecond(instant, 1_000_000_000L, instant.getNano()); } return instant.toEpochMilli(); } + private static long scaleEpochSecond(Instant instant, long unitsPerSecond, long fraction) { + long seconds = instant.getEpochSecond(); + if (seconds < 0 && fraction > 0) { + // As in Instant.toEpochMilli(), avoid intermediate overflow near Long.MIN_VALUE. + seconds++; + fraction -= unitsPerSecond; + } + return Math.addExact(Math.multiplyExact(seconds, unitsPerSecond), fraction); + } + /** convert date time string to millisecond, microsecond or nanosecond. */ public static long convertDatetimeStrToLong( String str, ZoneOffset offset, int depth, String timestampPrecision) { @@ -588,19 +630,7 @@ public static long convertDatetimeStrToLong( throw new DateTimeException( String.format(QueryMessages.DATETIME_CONVERT_FAILED, str, offset)); } - if (str.contains("Z")) { - return convertDatetimeStrToLong( - str.substring(0, str.indexOf('Z')) + "+00:00", offset, depth, timestampPrecision); - } else if (str.length() == 10) { - return convertDatetimeStrToLong(str + "T00:00:00", offset, depth, timestampPrecision); - } else if (str.length() - str.lastIndexOf('+') != 6 - && str.length() - str.lastIndexOf('-') != 6) { - return convertDatetimeStrToLong(str + offset, offset, depth + 1, timestampPrecision); - } else if (str.contains("[") || str.contains("]")) { - throw new DateTimeException( - String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); - } - return getInstantWithPrecision(str, timestampPrecision); + return convertDatetimeStrToLong(str, offset, timestampPrecision); } public static TimeUnit timestampPrecisionStringToTimeUnit(String timestampPrecision) { From 3f9fd0ba003a100ca4247691245042aea9fa68dd Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 15:06:12 +0800 Subject: [PATCH 3/7] Continue table CSV imports after an invalid primary timestamp --- .../iotdb/tool/data/ImportDataTable.java | 13 +++++++++- .../tool/data/DataToolRegressionTest.java | 24 +++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java index 40052b3451d0c..44b06e1db7cea 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java @@ -339,9 +339,20 @@ protected boolean writeData( List columnCategorys = new LinkedList<>(columnCategory.values()); Tablet tablet = new Tablet(table, headNames, columnTypes, columnCategorys, batchPointSize); for (CSVRecord recordObj : records) { + String timeValue = recordObj.get(0); + Long rowTimeStamp = parseTimestampField(timeValue); + if (rowTimeStamp == null) { + ioTPrinter.printf( + CliMessages.LOG_LINE_ARG_COLUMN_ARG_ARG_CAN_T_CONVERT_TO_ARG_ARG_F85541A2, + recordObj.getRecordNumber(), + headerNames.get(0), + timeValue, + TSDataType.TIMESTAMP); + failedRecords.add(recordObj.stream().collect(Collectors.toList())); + continue; + } boolean isFail = false; final int rowSize = tablet.getRowSize(); - long rowTimeStamp = parseTimestamp(recordObj.get(0)); for (String headerName : headerNameMap.keySet()) { String value = recordObj.get(headerNameMap.get(headerName)); if (!"".equals(value)) { diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index 23572807dbe02..a585805ed8e90 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -71,6 +71,7 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import static org.junit.Assert.assertEquals; @@ -891,6 +892,29 @@ private void assertTimestampFieldFailsFile(String name, String value) throws Exc Files.readAllLines(directory.resolve(name + ".failed_0"))); } + @Test + public void testTableCsvInvalidPrimaryTimestampPreservesOtherRows() throws Exception { + ITableSession session = mockTimestampFieldImport(); + Map imported = captureTimestampField(session); + Path csv = directory.resolve("rows.csv"); + String invalidTimeRow = "2026-12-04T03:33:17.083Zjunk,5"; + Files.write(csv, List.of("time,event_ts", "1,4", "2,invalid", invalidTimeRow, "3,6")); + long failures = loadFileFailedNum.sum(); + long successes = loadFileSuccessfulNum.sum(); + + assertEquals(1, importTableCsv(csv, "-batch", "3")); + assertEquals(Set.of(1L, 2L, 3L), imported.keySet()); + assertEquals(4L, imported.get(1L)); + assertNull(imported.get(2L)); + assertEquals(6L, imported.get(3L)); + verify(session).insert(any(Tablet.class)); + assertEquals( + List.of("time,event_ts", "2,invalid", invalidTimeRow), + Files.readAllLines(directory.resolve("rows.csv.failed_0"))); + assertEquals(failures + 1, loadFileFailedNum.sum()); + assertEquals(successes, loadFileSuccessfulNum.sum()); + } + private int importTableCsv(Path csv, String... options) throws Exception { sqlDialectTree = false; host = "127.0.0.1"; From a06d84fbc77c93250c91bef5fb3f895d49a3a972 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 15:21:43 +0800 Subject: [PATCH 4/7] Preserve other rows when a table CSV record is missing columns --- .../org/apache/iotdb/cli/i18n/CliMessages.java | 3 +++ .../org/apache/iotdb/cli/i18n/CliMessages.java | 3 +++ .../apache/iotdb/tool/data/ImportDataTable.java | 10 ++++++++++ .../iotdb/tool/data/DataToolRegressionTest.java | 17 +++++++++++++++++ 4 files changed, 33 insertions(+) diff --git a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/CliMessages.java b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/CliMessages.java index 25ceeee707a6b..66c8af3f5a5fe 100644 --- a/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/CliMessages.java +++ b/iotdb-client/cli/src/main/i18n/en/org/apache/iotdb/cli/i18n/CliMessages.java @@ -457,6 +457,9 @@ private CliMessages() {} public static final String LOG_THE_FILE_NAME_MUST_END_WITH_CSV_OR_TXT_0C020AB3 = "The file name must end with \"csv\" or \"txt\"!"; + public static final String LOG_CSV_RECORD_ARG_HAS_ARG_COLUMNS_EXPECTED_AT_LEAST_ARG_8678387E = + "CSV record %d has %d columns, expected at least %d."; + public static final String LOG_LINE_ARG_COLUMN_ARG_ARG_UNKNOWN_TYPE_ARG_93D3B31D = "Line '%s', column '%s': '%s' unknown type%n"; diff --git a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/CliMessages.java b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/CliMessages.java index aba90733ec101..f13eb62f86264 100644 --- a/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/CliMessages.java +++ b/iotdb-client/cli/src/main/i18n/zh/org/apache/iotdb/cli/i18n/CliMessages.java @@ -431,6 +431,9 @@ private CliMessages() {} public static final String LOG_THE_FILE_NAME_MUST_END_WITH_CSV_OR_TXT_0C020AB3 = "文件名必须以 \"csv\" 或 \"txt\" 结尾!"; + public static final String LOG_CSV_RECORD_ARG_HAS_ARG_COLUMNS_EXPECTED_AT_LEAST_ARG_8678387E = + "CSV 第 %d 条记录有 %d 列,至少需要 %d 列。"; + public static final String LOG_LINE_ARG_COLUMN_ARG_ARG_UNKNOWN_TYPE_ARG_93D3B31D = "第 '%s' 行,第 '%s' 列:'%s' 类型未知%n"; diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java index 44b06e1db7cea..9ee64545c98f0 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java @@ -339,6 +339,16 @@ protected boolean writeData( List columnCategorys = new LinkedList<>(columnCategory.values()); Tablet tablet = new Tablet(table, headNames, columnTypes, columnCategorys, batchPointSize); for (CSVRecord recordObj : records) { + if (recordObj.size() < headerNames.size()) { + ioTPrinter.println( + String.format( + CliMessages.LOG_CSV_RECORD_ARG_HAS_ARG_COLUMNS_EXPECTED_AT_LEAST_ARG_8678387E, + recordObj.getRecordNumber(), + recordObj.size(), + headerNames.size())); + failedRecords.add(recordObj.stream().collect(Collectors.toList())); + continue; + } String timeValue = recordObj.get(0); Long rowTimeStamp = parseTimestampField(timeValue); if (rowTimeStamp == null) { diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index a585805ed8e90..8e46d09233431 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -915,6 +915,23 @@ public void testTableCsvInvalidPrimaryTimestampPreservesOtherRows() throws Excep assertEquals(successes, loadFileSuccessfulNum.sum()); } + @Test + public void testTableCsvMissingTrailingFieldPreservesOtherRows() throws Exception { + Map imported = captureTimestampField(mockTimestampFieldImport()); + Path csv = directory.resolve("short.csv"); + Files.write(csv, List.of("time,event_ts", "1,4", "2,invalid", "3", "4,", "5,6")); + + assertEquals(1, importTableCsv(csv, "-batch", "3")); + assertEquals(Set.of(1L, 2L, 4L, 5L), imported.keySet()); + assertEquals(4L, imported.get(1L)); + assertNull(imported.get(2L)); + assertNull(imported.get(4L)); + assertEquals(6L, imported.get(5L)); + assertEquals( + List.of("time,event_ts", "2,invalid", "3"), + Files.readAllLines(directory.resolve("short.csv.failed_0"))); + } + private int importTableCsv(Path csv, String... options) throws Exception { sqlDialectTree = false; host = "127.0.0.1"; From 476524933a9a2bae2d43bba5bcdb2451f3795df4 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 15:41:33 +0800 Subject: [PATCH 5/7] Preserve table CSV failure files and isolate DATE and BLOB errors When a directory import uses -fd, retain each source directory in the failure path so same-named CSV files can be retried independently. Keep the existing flat name for a single input file. Report invalid dates and odd-length hex fields as row failures while inserting valid fields and continuing the batch. --- .../iotdb/tool/data/ImportDataTable.java | 50 ++++++-- .../tool/data/DataToolRegressionTest.java | 118 ++++++++++++++++++ 2 files changed, 159 insertions(+), 9 deletions(-) diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java index 9ee64545c98f0..2466a8eb3a4c1 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/data/ImportDataTable.java @@ -49,7 +49,10 @@ import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; import java.time.DateTimeException; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; @@ -293,13 +296,7 @@ protected void importFromCsvFile(File file) { ioTPrinter.println(CliMessages.LOG_THE_FIRST_FIELD_OF_HEADER_MUST_BE_TIME_2D6FAABE); return; } - String failedFilePath; - if (failedFileDirectory == null) { - failedFilePath = file.getAbsolutePath() + ".failed"; - } else { - failedFilePath = failedFileDirectory + file.getName() + ".failed"; - } - if (writeData(headerNames, records.collect(Collectors.toList()), failedFilePath)) { + if (writeData(headerNames, records.collect(Collectors.toList()), failedCsvPath(file))) { processSuccessFile(); } } catch (IOException e) { @@ -315,6 +312,16 @@ protected void importFromCsvFile(File file) { } } + private static String failedCsvPath(File file) { + if (failedFileDirectory == null) { + return file.getAbsolutePath() + ".failed"; + } + Path source = file.toPath().toAbsolutePath().normalize(); + Path root = Path.of(targetPath).toAbsolutePath().normalize(); + Path relative = source.equals(root) ? source.getFileName() : root.relativize(source); + return Path.of(failedFileDirectory).resolve(relative) + ".failed"; + } + protected boolean writeData( List headerNames, List records, String failedFilePath) { Map headerTypeMap = new HashMap<>(); @@ -398,8 +405,7 @@ protected boolean writeData( } type = headerTypeMap.get(headerName); if (type != null) { - Object valueTrans = - type == TSDataType.TIMESTAMP ? parseTimestampField(value) : typeTrans(value, type); + Object valueTrans = parseField(value, type); if (valueTrans == null) { isFail = true; ioTPrinter.printf( @@ -428,12 +434,38 @@ protected boolean writeData( if (!failedRecords.isEmpty()) { markFileFailed(); + if (failedFileDirectory != null) { + try { + Files.createDirectories(Path.of(failedFilePath).toAbsolutePath().getParent()); + } catch (IOException e) { + ioTPrinter.println( + String.format( + CliMessages.EXCEPTION_CANNOT_DUMP_FAIL_RESULT_BECAUSE_ARG_5C6E82E0, + e.getMessage())); + return false; + } + } writeFailedLinesFile(headerNames, failedFilePath, failedRecords); return false; } return true; } + private static Object parseField(String value, TSDataType type) { + if (type == TSDataType.TIMESTAMP) { + return parseTimestampField(value); + } + // Each byte needs two hex digits, with or without the optional 0x prefix. + if (type == TSDataType.BLOB && value.length() % 2 != 0) { + return null; + } + try { + return typeTrans(value, type); + } catch (DateTimeParseException e) { + return null; + } + } + private static Long parseTimestampField(String value) { try { return parseTimestamp(value); diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index 8e46d09233431..54817c35b65e8 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -49,6 +49,7 @@ import org.junit.Test; import org.junit.rules.TemporaryFolder; +import java.io.File; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; @@ -63,6 +64,7 @@ import java.nio.file.Files; import java.nio.file.Path; import java.time.Instant; +import java.time.LocalDate; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.ArrayList; @@ -111,6 +113,7 @@ public void setUp() throws Exception { AbstractDataTool.class, ImportDataTree.class, ImportDataTable.class, + ImportDataScanTool.class, ImportTsFileBase.class, ImportTsFileScanTool.class)) { for (Field field : owner.getDeclaredFields()) { @@ -763,6 +766,56 @@ public void testFailedTableCsvDoesNotSkipNextFile() throws Exception { assertNull(ImportDataScanTool.pollFromQueue()); } + @Test + public void testTableCsvFailedDirectoryPreservesRelativePaths() throws Exception { + mockTimestampFieldImport(); + Path source = Files.createDirectory(directory.resolve("source")); + Path failed = Files.createDirectory(directory.resolve("failed")); + String header = "time,event_ts"; + for (String name : List.of("a", "b")) { + Path file = Files.createDirectory(source.resolve(name)).resolve("data.csv"); + Files.write(file, List.of(header, "1,bad_" + name)); + } + Files.write(source.resolve("top.csv"), List.of(header, "2,bad_top")); + Path good = Files.createDirectory(source.resolve("good")).resolve("data.csv"); + Files.write(good, List.of(header, "3,123")); + + targetPath = source.toString(); + failedFileDirectory = failed.toString() + File.separator; + threadNum = 2; + ImportDataTable importer = spy(new ImportDataTable()); + doAnswer( + invocation -> { + ImportDataScanTool.setSourceFullPath(targetPath); + ImportDataScanTool.traverseAndCollectFiles(); + return null; + }) + .when(importer) + .init(); + assertEquals(1, ImportData.importFromTargetPathAsync(importer)); + + for (String name : List.of("a", "b")) { + assertEquals( + List.of(header, "1,bad_" + name), + Files.readAllLines(failed.resolve(name).resolve("data.csv.failed_0"))); + } + assertEquals( + List.of(header, "2,bad_top"), Files.readAllLines(failed.resolve("top.csv.failed_0"))); + assertFalse(Files.exists(failed.resolve("good"))); + } + + @Test + public void testTableCsvSingleSourceUsesFlatFailedFileName() throws Exception { + mockTimestampFieldImport(); + Path csv = Files.createDirectory(directory.resolve("nested")).resolve("data.csv"); + Path failed = directory.resolve("failed"); + List lines = List.of("time,event_ts", "1,bad"); + Files.write(csv, lines); + + assertEquals(1, importTableCsv(csv, "-fd", failed.toString())); + assertEquals(lines, Files.readAllLines(failed.resolve("data.csv.failed_0"))); + } + @Test public void testTableCsvTimestampFieldRoundTrip() throws Exception { long eventTime = 1796355197083L; @@ -932,6 +985,71 @@ public void testTableCsvMissingTrailingFieldPreservesOtherRows() throws Exceptio Files.readAllLines(directory.resolve("short.csv.failed_0"))); } + @Test + public void testTableCsvInvalidDateAndBlobPreserveValidFields() throws Exception { + ITableSession session = mockTimestampFieldImport(); + Map types = new LinkedHashMap<>(); + types.put("event_ts", TSDataType.TIMESTAMP); + types.put("day", TSDataType.DATE); + types.put("payload", TSDataType.BLOB); + set(ImportDataTable.class, "dataTypes", types); + set( + ImportDataTable.class, + "columnCategory", + Map.of( + "event_ts", + ColumnCategory.FIELD, + "day", + ColumnCategory.FIELD, + "payload", + ColumnCategory.FIELD)); + Map> imported = new HashMap<>(); + doAnswer( + invocation -> { + Tablet tablet = invocation.getArgument(0); + for (int row = 0; row < tablet.getRowSize(); row++) { + imported.put( + tablet.getTimestamp(row), + Arrays.asList( + tablet.getValue(row, 0), tablet.getValue(row, 1), tablet.getValue(row, 2))); + } + return null; + }) + .when(session) + .insert(any(Tablet.class)); + Path csv = directory.resolve("fields.csv"); + String header = "time,event_ts,day,payload"; + String badTimestamp = "1,invalid,2024-02-29,0x0a"; + String badDate = "2,102,2026-02-30,FE"; + String badBlob = "3,103,2024-02-29,0xABC"; + String both = "4,104,not-a-date,0xGG"; + Files.write( + csv, + List.of( + header, + badTimestamp, + badDate, + badBlob, + both, + "5,105,2024-02-29,0x", + "6,106,2024-02-29,")); + + assertEquals(1, importTableCsv(csv, "-batch", "3")); + LocalDate leapDay = LocalDate.of(2024, 2, 29); + assertEquals( + Map.of( + 1L, Arrays.asList(null, leapDay, new Binary(new byte[] {0x0a})), + 2L, Arrays.asList(102L, null, new Binary(new byte[] {(byte) 0xfe})), + 3L, Arrays.asList(103L, leapDay, null), + 4L, Arrays.asList(104L, null, null), + 5L, List.of(105L, leapDay, new Binary(new byte[0])), + 6L, Arrays.asList(106L, leapDay, null)), + imported); + assertEquals( + List.of(header, badTimestamp, badDate, badBlob, both), + Files.readAllLines(directory.resolve("fields.csv.failed_0"))); + } + private int importTableCsv(Path csv, String... options) throws Exception { sqlDialectTree = false; host = "127.0.0.1"; From d663b5bfe068f102fa13545e25b6768e6a0da83d Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 16:12:22 +0800 Subject: [PATCH 6/7] Check microsecond CSV round trips and valid rows on import failure --- .../apache/iotdb/tool/data/DataToolRegressionTest.java | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java index 54817c35b65e8..25d16efb1e2af 100644 --- a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/data/DataToolRegressionTest.java @@ -836,6 +836,12 @@ public void testTableCsvTimestampFieldRoundTrip() throws Exception { assertFalse(Files.exists(directory.resolve("numeric.csv.failed_0"))); } + @Test + public void testTableCsvMicrosecondTimestampFieldRoundTrip() throws Exception { + assertTimestampRoundTrip( + 1796355197083123L, ZoneOffset.UTC, "us", "2026-12-04T03:33:17.083123Z"); + } + @Test public void testTableCsvNanosecondTimestampFieldRoundTrip() throws Exception { assertTimestampRoundTrip( @@ -925,7 +931,6 @@ private Map captureTimestampField(ITableSession session) throws Ex @Test public void testTableCsvInvalidTimestampFieldFailsFile() throws Exception { - mockTimestampFieldImport(); assertTimestampFieldFailsFile("invalid.csv", "invalid"); assertTimestampFieldFailsFile("suffix.csv", "2026-12-04T03:33:17.083Zjunk"); assertTimestampFieldFailsFile( @@ -933,11 +938,13 @@ public void testTableCsvInvalidTimestampFieldFailsFile() throws Exception { } private void assertTimestampFieldFailsFile(String name, String value) throws Exception { + Map imported = captureTimestampField(mockTimestampFieldImport()); Path csv = directory.resolve(name); Files.writeString(csv, "time,event_ts\n1,1000\n2," + value + "\n"); long failures = loadFileFailedNum.sum(); long successes = loadFileSuccessfulNum.sum(); assertEquals(1, importTableCsv(csv)); + assertEquals(1000L, imported.get(1L)); assertEquals(failures + 1, loadFileFailedNum.sum()); assertEquals(successes, loadFileSuccessfulNum.sum()); assertEquals( From 87fe2eebeeea42c0bb2074c7467636294aeb93f6 Mon Sep 17 00:00:00 2001 From: DaZuiZui Date: Fri, 4 Dec 2026 17:46:37 +0800 Subject: [PATCH 7/7] Keep the parser in its own change and preserve custom timestamp formats --- .../java/org/apache/iotdb/rpc/RpcUtils.java | 37 +++++--- .../org/apache/iotdb/rpc/RpcUtilsTest.java | 14 +++ .../iotdb/db/utils/DateTimeUtilsTest.java | 18 ++-- .../queryengine/utils/DateTimeUtils.java | 94 +++++++------------ 4 files changed, 78 insertions(+), 85 deletions(-) diff --git a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java index 6f6a6d9cb2256..3d7fe41a01e67 100644 --- a/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java +++ b/iotdb-client/service-rpc/src/main/java/org/apache/iotdb/rpc/RpcUtils.java @@ -44,8 +44,6 @@ import java.util.List; import java.util.Map; import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; import java.util.stream.Collectors; public class RpcUtils { @@ -296,8 +294,6 @@ public static TSFetchResultsResp getTSFetchResultsResp(TSStatus status) { public static final String DEFAULT_TIME_FORMAT = "default"; public static final String DEFAULT_TIMESTAMP_PRECISION = "ms"; - private static final Pattern OFFSET_SUFFIX = - Pattern.compile("(?:Z|[+-]\\d{2}:\\d{2}(?::\\d{2})?)$"); public static String setTimeFormat(String newTimeFormat) { String timeFormat; @@ -336,9 +332,27 @@ public static String formatDatetime( } public static String formatDatetimeStr(String datetime, StringBuilder digits) { - Matcher offset = OFFSET_SUFFIX.matcher(datetime); - int endOfTime = offset.find() ? offset.start() : datetime.length(); - return datetime.substring(0, endOfTime) + "." + digits + datetime.substring(endOfTime); + if (datetime.contains("+")) { + String timeZoneStr = datetime.substring(datetime.length() - 6); + return datetime.substring(0, datetime.length() - 6) + "." + digits + timeZoneStr; + } else if (datetime.contains("Z")) { + String timeZoneStr = datetime.substring(datetime.length() - 1); + return datetime.substring(0, datetime.length() - 1) + "." + digits + timeZoneStr; + } else { + String timeZoneStr = ""; + return datetime + "." + digits + timeZoneStr; + } + } + + private static String formatDatetimeWithFraction( + ZonedDateTime dateTime, DateTimeFormatter formatter, StringBuilder digits) { + if (formatter == DateTimeFormatter.ISO_OFFSET_DATE_TIME) { + return dateTime.format(DateTimeFormatter.ISO_LOCAL_DATE_TIME) + + "." + + digits + + dateTime.getOffset().getId(); + } + return formatDatetimeStr(dateTime.format(formatter), digits); } @SuppressWarnings("squid:S3776") // Suppress high Cognitive Complexity warning @@ -356,14 +370,13 @@ public static String parseLongToDateWithPrecision( } ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(integerOfDate), zoneid); - String datetime = dateTime.format(formatter); int length = digits.length(); if (length != 3) { for (int i = 0; i < 3 - length; i++) { digits.insert(0, "0"); } } - return formatDatetimeStr(datetime, digits); + return formatDatetimeWithFraction(dateTime, formatter, digits); } else if (MICROSECOND.equals(timestampPrecision)) { if (timestamp > 0 || timestamp % 1000_000 == 0) { integerOfDate = timestamp / 1000_000; @@ -374,14 +387,13 @@ public static String parseLongToDateWithPrecision( } ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(integerOfDate), zoneid); - String datetime = dateTime.format(formatter); int length = digits.length(); if (length != 6) { for (int i = 0; i < 6 - length; i++) { digits.insert(0, "0"); } } - return formatDatetimeStr(datetime, digits); + return formatDatetimeWithFraction(dateTime, formatter, digits); } else { if (timestamp > 0 || timestamp % 1000_000_000L == 0) { integerOfDate = timestamp / 1000_000_000L; @@ -392,14 +404,13 @@ public static String parseLongToDateWithPrecision( } ZonedDateTime dateTime = ZonedDateTime.ofInstant(Instant.ofEpochSecond(integerOfDate), zoneid); - String datetime = dateTime.format(formatter); int length = digits.length(); if (length != 9) { for (int i = 0; i < 9 - length; i++) { digits.insert(0, "0"); } } - return formatDatetimeStr(datetime, digits); + return formatDatetimeWithFraction(dateTime, formatter, digits); } } diff --git a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java index 0ecebdb9357ab..10fde450eb86c 100644 --- a/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java +++ b/iotdb-client/service-rpc/src/test/java/org/apache/iotdb/rpc/RpcUtilsTest.java @@ -87,6 +87,20 @@ public void parseLongToDateWithPrecision() { "2026-12-03T22:33:17.083", RpcUtils.parseLongToDateWithPrecision( DateTimeFormatter.ISO_LOCAL_DATE_TIME, 1796355197083L, zoneId, "ms")); + Assert.assertEquals( + "1969-12-31T18:59:30.000-05:00:30", + RpcUtils.formatDatetime("iso8601", "ms", 0, ZoneId.of("-05:00:30"))); + } + + @Test + public void customFormatEndingInHourAndMinuteKeepsFractionAtEnd() { + Assert.assertEquals( + "2026-12-04-11:33.083", + RpcUtils.parseLongToDateWithPrecision( + DateTimeFormatter.ofPattern("yyyy-MM-dd-HH:mm"), + 1796355197083L, + ZoneId.of("Asia/Shanghai"), + "ms")); } @Test diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java index b50695cf1f50b..d196bdecef6b4 100644 --- a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/utils/DateTimeUtilsTest.java @@ -33,9 +33,9 @@ import org.junit.Test; import java.time.Instant; -import java.time.LocalDateTime; import java.time.ZoneId; import java.time.ZoneOffset; +import java.time.ZonedDateTime; import java.util.TimeZone; import static org.junit.Assert.assertEquals; @@ -53,9 +53,13 @@ public class DateTimeUtilsTest { /** Test convertDatetimeStrToLong() method with different time precision. */ @Test public void convertDatetimeStrToLongTest1() { + zoneOffset = ZonedDateTime.now().getOffset(); zoneId = ZoneId.systemDefault(); - zoneOffset = zoneId.getRules().getOffset(LocalDateTime.of(2019, 1, 2, 15, 13, 27)); - delta = (ZoneOffset.ofHours(8).getTotalSeconds() - zoneOffset.getTotalSeconds()) * 1000L; + if (zoneOffset.toString().equals("Z")) { + delta = 8 * 3600000; + } else { + delta = (8 - Long.parseLong(zoneOffset.toString().split(":")[0])) * 3600000; + } testConvertDatetimeStrToLongWithoutMS(zoneOffset, zoneId, timestamp - 689 + delta); testConvertDatetimeStrToLongWithMS(zoneOffset, zoneId, timestamp + delta); testConvertDatetimeStrToLongWithMS2(zoneOffset, zoneId, timestamp - 9 + delta); @@ -89,7 +93,7 @@ public void convertDatetimeStrToLongTest4() { fail(); } catch (Exception e) { assertEquals( - "Text '1999-02-29T00:00:00.000' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", + "Text '1999-02-29T00:00:00.000+00:00' could not be parsed: Invalid date 'February 29' as '1999' is not a leap year", e.getMessage()); } } @@ -220,12 +224,6 @@ public void getInstantWithPrecisionTest() { Assert.assertThrows( ArithmeticException.class, () -> DateTimeUtils.getInstantWithPrecision("294247-01-10T04:00:54.775808+00:00", "us")); - assertEquals( - Long.MIN_VALUE, - DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224192Z", "ns")); - Assert.assertThrows( - ArithmeticException.class, - () -> DateTimeUtils.getInstantWithPrecision("1677-09-21T00:12:43.145224191Z", "ns")); } @Test diff --git a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java index ca273f5c8ea29..5102738df70d9 100644 --- a/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java +++ b/iotdb-core/node-commons/src/main/java/org/apache/iotdb/commons/queryengine/utils/DateTimeUtils.java @@ -539,28 +539,6 @@ public static void initTimestampPrecision() { .toFormatter() .withResolverStyle(ResolverStyle.STRICT); - private static final DateTimeFormatter DASHED_TIMESTAMP = - timestampParser(ISO_LOCAL_DATE_WIDTH_1_2); - private static final DateTimeFormatter ISO_TIMESTAMP = - timestampParser(DateTimeFormatter.ISO_LOCAL_DATE); - private static final DateTimeFormatter SLASHED_TIMESTAMP = - timestampParser(ISO_LOCAL_DATE_WITH_SLASH); - private static final DateTimeFormatter DOTTED_TIMESTAMP = - timestampParser(ISO_LOCAL_DATE_WITH_DOT); - - private static DateTimeFormatter timestampParser(DateTimeFormatter date) { - return new DateTimeFormatterBuilder() - .parseCaseInsensitive() - .append(date) - .appendLiteral('T') - .append(ISO_LOCAL_TIME_WITH_NS) - .optionalStart() - .appendOffsetId() - .optionalEnd() - .toFormatter() - .withResolverStyle(ResolverStyle.STRICT); - } - public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String timeStr) { try { return Long.parseLong(timeStr); @@ -571,58 +549,38 @@ public static long convertTimestampOrDatetimeStrToLongWithDefaultZone(String tim public static long convertDatetimeStrToLong(String str, ZoneId zoneId) { return convertDatetimeStrToLong( - str, zoneId, CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); + str, + toZoneOffset(zoneId), + 0, + CommonDescriptor.getInstance().getConfig().getTimestampPrecision()); } public static long convertDatetimeStrToLong( String str, ZoneId zoneId, String timestampPrecision) { - if (str.contains("[") || str.contains("]")) { - throw new DateTimeException( - String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); - } - if (str.length() == 10) { - str += "T00:00:00"; - } - return getInstantWithPrecision(parseDateTime(str, zoneId), timestampPrecision); + return convertDatetimeStrToLong(str, toZoneOffset(zoneId), 0, timestampPrecision); } public static long getInstantWithPrecision(String str, String timestampPrecision) { - return getInstantWithPrecision(parseDateTime(str, null), timestampPrecision); - } - - private static Instant parseDateTime(String str, ZoneId defaultZone) { - DateTimeFormatter parser; - int dot = str.indexOf('.'); - if (str.indexOf('/') >= 0) { - parser = SLASHED_TIMESTAMP; - } else if (dot >= 0 && dot < str.indexOf(':')) { - parser = DOTTED_TIMESTAMP; - } else { - // The space-separated ISO form also supports signed years. - parser = str.indexOf(' ') >= 0 ? ISO_TIMESTAMP : DASHED_TIMESTAMP; - } - return parser.withZone(defaultZone).parse(str.replace(' ', 'T'), Instant::from); - } - - private static long getInstantWithPrecision(Instant instant, String timestampPrecision) { + ZonedDateTime zonedDateTime = ZonedDateTime.parse(str, formatter); + Instant instant = zonedDateTime.toInstant(); if ("us".equals(timestampPrecision) || "microsecond".equals(timestampPrecision)) { - return scaleEpochSecond(instant, 1_000_000L, instant.getNano() / 1000); + if (instant.getEpochSecond() < 0 && instant.getNano() > 0) { + // Same as Instant#toEpochMilli: multiply (epochSecond + 1) so that the product cannot + // overflow near Long.MIN_VALUE, then subtract that extra second (1_000_000 us). + long millis = Math.multiplyExact(instant.getEpochSecond() + 1, 1000_000L); + long adjustment = instant.getNano() / 1000 - 1_000_000L; + return Math.addExact(millis, adjustment); + } else { + long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000L); + return Math.addExact(millis, instant.getNano() / 1000); + } } else if ("ns".equals(timestampPrecision) || "nanosecond".equals(timestampPrecision)) { - return scaleEpochSecond(instant, 1_000_000_000L, instant.getNano()); + long millis = Math.multiplyExact(instant.getEpochSecond(), 1000_000_000L); + return Math.addExact(millis, instant.getNano()); } return instant.toEpochMilli(); } - private static long scaleEpochSecond(Instant instant, long unitsPerSecond, long fraction) { - long seconds = instant.getEpochSecond(); - if (seconds < 0 && fraction > 0) { - // As in Instant.toEpochMilli(), avoid intermediate overflow near Long.MIN_VALUE. - seconds++; - fraction -= unitsPerSecond; - } - return Math.addExact(Math.multiplyExact(seconds, unitsPerSecond), fraction); - } - /** convert date time string to millisecond, microsecond or nanosecond. */ public static long convertDatetimeStrToLong( String str, ZoneOffset offset, int depth, String timestampPrecision) { @@ -630,7 +588,19 @@ public static long convertDatetimeStrToLong( throw new DateTimeException( String.format(QueryMessages.DATETIME_CONVERT_FAILED, str, offset)); } - return convertDatetimeStrToLong(str, offset, timestampPrecision); + if (str.contains("Z")) { + return convertDatetimeStrToLong( + str.substring(0, str.indexOf('Z')) + "+00:00", offset, depth, timestampPrecision); + } else if (str.length() == 10) { + return convertDatetimeStrToLong(str + "T00:00:00", offset, depth, timestampPrecision); + } else if (str.length() - str.lastIndexOf('+') != 6 + && str.length() - str.lastIndexOf('-') != 6) { + return convertDatetimeStrToLong(str + offset, offset, depth + 1, timestampPrecision); + } else if (str.contains("[") || str.contains("]")) { + throw new DateTimeException( + String.format(QueryMessages.DATETIME_TIME_REGION_NOT_SUPPORTED, str)); + } + return getInstantWithPrecision(str, timestampPrecision); } public static TimeUnit timestampPrecisionStringToTimeUnit(String timestampPrecision) {