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/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/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..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,6 +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; @@ -292,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) { @@ -314,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<>(); @@ -338,9 +346,30 @@ 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) { + 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)) { @@ -376,7 +405,7 @@ protected boolean writeData( } type = headerTypeMap.get(headerName); if (type != null) { - Object valueTrans = typeTrans(value, type); + Object valueTrans = parseField(value, type); if (valueTrans == null) { isFail = true; ioTPrinter.printf( @@ -404,11 +433,47 @@ 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); + } 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..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 @@ -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; @@ -46,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; @@ -59,6 +63,9 @@ import java.nio.file.FileAlreadyExistsException; 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; import java.util.Arrays; @@ -66,6 +73,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; @@ -87,6 +95,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; @@ -104,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()) { @@ -756,6 +766,328 @@ 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; + 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 testTableCsvMicrosecondTimestampFieldRoundTrip() throws Exception { + assertTimestampRoundTrip( + 1796355197083123L, ZoneOffset.UTC, "us", "2026-12-04T03:33:17.083123Z"); + } + + @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[] {rowTime, 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 = offset; + exporter.timestampPrecision = precision; + exporter.export(new ExportTask(sql, directory.resolve("dump"), null, "t")); + } + return directory.resolve("dump_0.csv"); + } + + private Map captureTimestampField(ITableSession session) throws Exception { + 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)); + return imported; + } + + @Test + public void testTableCsvInvalidTimestampFieldFailsFile() throws Exception { + 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 { + 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( + List.of("time,event_ts", "2," + value), + 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()); + } + + @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"))); + } + + @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"; + 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 { + 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<>(); 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..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 @@ -344,6 +344,17 @@ public static String formatDatetimeStr(String datetime, StringBuilder digits) { } } + 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 public static String parseLongToDateWithPrecision( DateTimeFormatter formatter, long timestamp, ZoneId zoneid, String timestampPrecision) { @@ -359,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; @@ -377,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; @@ -395,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 4702dd6082789..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 @@ -78,6 +78,29 @@ 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")); + 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