Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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) {
Expand All @@ -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<String> headerNames, List<CSVRecord> records, String failedFilePath) {
Map<String, TSDataType> headerTypeMap = new HashMap<>();
Expand All @@ -338,9 +346,30 @@ protected boolean writeData(
List<ColumnCategory> 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)) {
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Call out the wider exit-status change in the PR description. This return false applies to every failed record, not only TIMESTAMP fields. A CSV with abc in an INT32 column, or a column whose type cannot be inferred, used to print Import completely! and exit 0; it now exits 1. I think the new behavior is correct and matches ImportSchemaTable, but it is a user-visible change for scripts, so please state in the description that any partially failed table CSV now produces a nonzero exit status.

}
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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P2] Reject trailing characters after the UTC designator. Importing 2026-12-04T03:33:17.083Zjunk stored 1796355197083 and exited 0 without producing a failed-row file. The shared parser truncates the string at the first Z, so the exception handler never sees the malformed suffix. Please validate the entire field and cover this case with assertions for exit code 1 and the row in .failed_0. UTC normalization

} catch (DateTimeException | ArithmeticException e) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[P3] Preserve valid nanosecond timestamps near Long.MIN_VALUE. The default CSV export of -9223372036854775807 is 1677-09-21T00:12:43.145224193Z. Importing that CSV with -tp ns left the field NULL and exited 1. The numeric export of the same value round-tripped.

The nanosecond conversion multiplies the epoch second by one billion before adding the fractional part. The intermediate product overflows even though the final value fits in a long. Please use the negative-instant adjustment already present in the microsecond branch and cover this value in a round-trip test. Precision conversion

return null;
}
}

private static void writeAndEmptyDataSet(Tablet tablet, int retryTime) {
executeWithRetry(
() -> {
Expand Down
Loading