Skip to content
Open

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions iotdb-client/cli/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,10 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-csv</artifactId>
</dependency>
<dependency>
<groupId>org.apache.ratis</groupId>
<artifactId>ratis-thirdparty-misc</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -161,6 +161,22 @@ public final class CliMessages {
MESSAGE_THE_HEADER_OF_THE_CSV_FILE_TO_BE_IMPORTED_IS_ILLEGAL_THE_CORRECT_FORMAT_IS_TIMESERIES_ALIAS_DATATYPE_ENCODING_COMPRESSION_FB573E37 =
"The header of the CSV file to be imported is illegal. The correct format is"
+ " \"Timeseries, Alias, DataType, Encoding, Compression\"!";
public static final String
MESSAGE_THE_HEADER_OF_THE_CSV_FILE_TO_BE_IMPORTED_IS_ILLEGAL_THE_CORRECT_FORMAT_IS_TIMESERIES_ALIAS_DATATYPE_ENCODING_COMPRESSION_TAGS_ATTRIBUTES_14EDBFB9 =
"The header of the CSV file to be imported is illegal. The correct format is"
+ " \"Timeseries, Alias, DataType, Encoding, Compression, Tags, Attributes\"!";
public static final String
MESSAGE_FAILED_TO_PARSE_THE_ARG_COLUMN_OF_TIMESERIES_ARG_AS_JSON_THE_RECORD_IS_SKIPPED_ARG_35D898C8 =
"Failed to parse the %s column of timeseries %s as JSON, the record is skipped: %s";
public static final String EXCEPTION_TAGS_AND_ATTRIBUTES_VALUES_MUST_BE_JSON_STRINGS_C0A5BF8E =
"Tags and Attributes values must be JSON strings";
public static final String EXCEPTION_TAGS_AND_ATTRIBUTES_CELLS_MUST_BE_A_JSON_OBJECT_567BB6E5 =
"Tags and Attributes cells must be a JSON object";
public static final String EXCEPTION_DUPLICATE_KEY_ARG_IN_A_JSON_OBJECT_F12787DC =
"Duplicate key %s in a JSON object";
public static final String
EXCEPTION_FAILED_TO_CREATE_ARG_BECAUSE_THE_CONNECTION_COULD_NOT_BE_RE_ESTABLISHED_ARG_3956569A =
"Failed to create %s because the connection could not be re-established: %s";

private CliMessages() {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,22 @@ public final class CliMessages {
public static final String
MESSAGE_THE_HEADER_OF_THE_CSV_FILE_TO_BE_IMPORTED_IS_ILLEGAL_THE_CORRECT_FORMAT_IS_TIMESERIES_ALIAS_DATATYPE_ENCODING_COMPRESSION_FB573E37 =
"待导入的 CSV 文件表头不合法,正确格式为 \"Timeseries, Alias, DataType, Encoding, Compression\"!";
public static final String
MESSAGE_THE_HEADER_OF_THE_CSV_FILE_TO_BE_IMPORTED_IS_ILLEGAL_THE_CORRECT_FORMAT_IS_TIMESERIES_ALIAS_DATATYPE_ENCODING_COMPRESSION_TAGS_ATTRIBUTES_14EDBFB9 =
"待导入的 CSV 文件表头不合法,正确格式为"
+ " \"Timeseries, Alias, DataType, Encoding, Compression, Tags, Attributes\"!";
public static final String
MESSAGE_FAILED_TO_PARSE_THE_ARG_COLUMN_OF_TIMESERIES_ARG_AS_JSON_THE_RECORD_IS_SKIPPED_ARG_35D898C8 =
"时序 JSON 解析失败,列:%s,时序:%s,已跳过该记录,原因:%s";
public static final String EXCEPTION_TAGS_AND_ATTRIBUTES_VALUES_MUST_BE_JSON_STRINGS_C0A5BF8E =
"Tags 和 Attributes 的值必须是 JSON 字符串";
public static final String EXCEPTION_TAGS_AND_ATTRIBUTES_CELLS_MUST_BE_A_JSON_OBJECT_567BB6E5 =
"Tags 和 Attributes 列必须是 JSON 对象";
public static final String EXCEPTION_DUPLICATE_KEY_ARG_IN_A_JSON_OBJECT_F12787DC =
"JSON 对象中存在重复的键:%s";
public static final String
EXCEPTION_FAILED_TO_CREATE_ARG_BECAUSE_THE_CONNECTION_COULD_NOT_BE_RE_ESTABLISHED_ARG_3956569A =
"创建 %s 失败,连接无法重新建立:%s";

private CliMessages() {}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,8 +204,31 @@ public class Constants {
public static final String COLON = ": ";
public static final String MINUS = "-";

public static final String HEADER_TAGS = "Tags";
public static final String HEADER_ATTRIBUTES = "Attributes";
public static final String HEADER_ALIAS = "Alias";
public static final String HEADER_DATATYPE = "DataType";
public static final String HEADER_ENCODING = "Encoding";
public static final String HEADER_COMPRESSION = "Compression";

public static final List<String> HEAD_COLUMNS =
Arrays.asList("Timeseries", "Alias", "DataType", "Encoding", "Compression");
Arrays.asList(
"Timeseries", HEADER_ALIAS, HEADER_DATATYPE, HEADER_ENCODING, HEADER_COMPRESSION);

/**
* Column layout written by the tree model schema export. The Tags and Attributes cells hold a
* JSON object, so files carrying them are parsed with the RFC4180 settings instead of the legacy
* ones.
*/
public static final List<String> HEAD_COLUMNS_V2 =
Arrays.asList(
"Timeseries",
HEADER_ALIAS,
HEADER_DATATYPE,
HEADER_ENCODING,
HEADER_COMPRESSION,
HEADER_TAGS,
HEADER_ATTRIBUTES);

// export constants
public static final String EXPORT_CLI_PREFIX = CliMessages.EXCEPTION_EXPORT_DATA_2F1FB3D9;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1210,6 +1210,15 @@ public static Options createExportSchemaOptions() {
public static Options createImportSchemaOptions() {
Options options = createCommonOptions(new Options());

Option opAligned =
Option.builder(ALIGNED_ARGS)
.longOpt(ALIGNED_NAME)
.argName(ALIGNED_ARGS_NAME_IMPORT)
.hasArg()
.desc(ALIGNED_IMPORT_DESC)
.build();
options.addOption(opAligned);

Option opFile =
Option.builder(FILE_ARGS)
.required()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,24 @@
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.QuoteMode;
import org.apache.ratis.thirdparty.com.google.gson.Gson;
import org.apache.ratis.thirdparty.com.google.gson.GsonBuilder;
import org.apache.ratis.thirdparty.com.google.gson.Strictness;
import org.apache.ratis.thirdparty.com.google.gson.stream.JsonReader;
import org.apache.ratis.thirdparty.com.google.gson.stream.JsonToken;
import org.apache.tsfile.external.commons.lang3.StringUtils;
import org.jline.reader.LineReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.concurrent.atomic.LongAdder;

public abstract class AbstractSchemaTool {
Expand Down Expand Up @@ -74,6 +83,9 @@ public abstract class AbstractSchemaTool {
protected static String targetFile = Constants.DUMP_FILE_NAME_DEFAULT;
protected static final LongAdder loadFileSuccessfulNum = new LongAdder();

/** Set when an imported file ran out of connection retries, so the import exits non-zero. */
protected static volatile boolean connectionFailed = false;

private static final IoTPrinter ioTPrinter = new IoTPrinter(System.out);
private static final Logger LOGGER = LoggerFactory.getLogger(AbstractSchemaTool.class);

Expand Down Expand Up @@ -204,8 +216,23 @@ protected static void parseBasicParams(CommandLine commandLine)
* @param filePath the directory to save the file
*/
public static Boolean writeCsvFile(List<List<Object>> records, String filePath) {
return writeCsvFile(records, filePath, false);
}

/**
* write data to CSV file.
*
* @param records the records of CSV file
* @param filePath the directory to save the file
* @param legacy write with the escaped delimiter of the legacy schema files instead of RFC4180
* quoting, i.e. the layout {@link ImportSchemaTree#readCsvFile(String)} selects for a file
* whose header has no Tags or Attributes column
*/
public static Boolean writeCsvFile(List<List<Object>> records, String filePath, boolean legacy) {
try {
final CSVPrinterWrapper csvPrinterWrapper = new CSVPrinterWrapper(filePath);
final CSVPrinterWrapper csvPrinterWrapper =
new CSVPrinterWrapper(
filePath, legacy ? createLegacyCsvFormat() : createRfc4180CsvFormat());
for (List<Object> CsvRecord : records) {
csvPrinterWrapper.printRecordLn(CsvRecord);
}
Expand All @@ -218,32 +245,126 @@ public static Boolean writeCsvFile(List<List<Object>> records, String filePath)
}
}

/**
* The RFC4180 CSV layout of the schema files, i.e. the delimiter is {@code ','}, the quote char
* is {@code '"'} and no escape char is configured. A JSON object cell is therefore always quoted
* and its inner quotes are doubled, which is exactly what RFC4180 asks for.
*/
static CSVFormat.Builder createRfc4180CsvFormat() {
return CSVFormat.Builder.create(CSVFormat.DEFAULT)
.setQuote('"')
.setQuoteMode(QuoteMode.MINIMAL)
.setRecordSeparator('\n');
}

/**
* The CSV layout the legacy schema files were read and written with: a backslash escapes the
* delimiter and no quote char is used, so a comma inside a cell is written as {@code \,}. {@link
* ImportSchemaTree#readCsvFile(String)} selects it for a file whose header has no Tags or
* Attributes column, so a failed file written for such a file has to use it as well.
*/
static CSVFormat.Builder createLegacyCsvFormat() {
return CSVFormat.Builder.create(CSVFormat.DEFAULT)
.setEscape('\\')
.setQuoteMode(QuoteMode.NONE)
.setRecordSeparator('\n');
}

private static final Gson JSON_GSON = new GsonBuilder().disableHtmlEscaping().create();

/**
* Serializes tags or attributes into the compact JSON object cell of the schema file. Keys are
* sorted so that repeated exports of the same schema are identical.
*
* @return an empty string when there is nothing to write, never {@code {}} or {@code null}
*/
static String toJsonCell(Map<String, String> values) {
if (values == null || values.isEmpty()) {
return "";
}
return JSON_GSON.toJson(new TreeMap<>(values));
}

/**
* Parses a Tags / Attributes cell written by {@link #toJsonCell(Map)}. The reader enforces the
* JSON syntax, so a raw control character such as a literal tab inside a string, an invalid
* escape such as {@code \'}, a trailing token and an unquoted token such as {@code {"room":yes}}
* are all rejected; the document must be a JSON object whose values are strings.
*
* @return {@code null} when the cell carries no value, never an empty map
* @throws IllegalArgumentException when the cell is not such an object
*/
static Map<String, String> parseJsonCell(String cell) {
if (cell == null) {
return null;
}
String trimmed = cell.trim();
if (trimmed.isEmpty() || "null".equals(trimmed)) {
return null;
}
Map<String, String> values = parseStrictJsonObject(trimmed);
return values.isEmpty() ? null : values;
}

private static Map<String, String> parseStrictJsonObject(String text) {
JsonReader reader = new JsonReader(new StringReader(text));
// setLenient(false) only selects LEGACY_STRICT, which still accepts a raw control character
// inside a string and the escape \'.
reader.setStrictness(Strictness.STRICT);
Map<String, String> values = new TreeMap<>();
try {
reader.beginObject();
while (reader.hasNext()) {
String name = reader.nextName();
if (reader.peek() != JsonToken.STRING) {
throw new IllegalArgumentException(
CliMessages.EXCEPTION_TAGS_AND_ATTRIBUTES_VALUES_MUST_BE_JSON_STRINGS_C0A5BF8E);
}
if (values.put(name, reader.nextString()) != null) {
throw new IllegalArgumentException(
String.format(
CliMessages.EXCEPTION_DUPLICATE_KEY_ARG_IN_A_JSON_OBJECT_F12787DC, name));
}
}
reader.endObject();
if (reader.peek() != JsonToken.END_DOCUMENT) {
throw new IllegalArgumentException(
CliMessages.EXCEPTION_TAGS_AND_ATTRIBUTES_CELLS_MUST_BE_A_JSON_OBJECT_567BB6E5);
}
return values;
} catch (IOException e) {
throw new IllegalArgumentException(
CliMessages.EXCEPTION_TAGS_AND_ATTRIBUTES_CELLS_MUST_BE_A_JSON_OBJECT_567BB6E5, e);
} catch (IllegalStateException e) {
throw new IllegalArgumentException(
CliMessages.EXCEPTION_TAGS_AND_ATTRIBUTES_CELLS_MUST_BE_A_JSON_OBJECT_567BB6E5, e);
}
}

static class CSVPrinterWrapper {
private final String filePath;
private final CSVFormat csvFormat;
private CSVPrinter csvPrinter;

public CSVPrinterWrapper(String filePath) {
this(filePath, createRfc4180CsvFormat());
}

CSVPrinterWrapper(String filePath, CSVFormat.Builder csvFormat) {
this.filePath = filePath;
this.csvFormat =
CSVFormat.Builder.create(CSVFormat.DEFAULT)
.setHeader()
.setSkipHeaderRecord(true)
.setEscape('\\')
.setQuoteMode(QuoteMode.NONE)
.build();
this.csvFormat = csvFormat.setHeader().setSkipHeaderRecord(true).build();
}

public void printRecord(final Iterable<?> values) throws IOException {
if (csvPrinter == null) {
csvPrinter = csvFormat.print(new PrintWriter(filePath));
csvPrinter = csvFormat.print(new PrintWriter(filePath, StandardCharsets.UTF_8));
}
csvPrinter.printRecord(values);
}

public void printRecordLn(final Iterable<?> values) throws IOException {
if (csvPrinter == null) {
csvPrinter = csvFormat.print(new PrintWriter(filePath));
csvPrinter = csvFormat.print(new PrintWriter(filePath, StandardCharsets.UTF_8));
}
Iterator var2 = values.iterator();

Expand All @@ -257,7 +378,7 @@ public void printRecordLn(final Iterable<?> values) throws IOException {
public void print(Object value) {
if (csvPrinter == null) {
try {
csvPrinter = csvFormat.print(new PrintWriter(filePath));
csvPrinter = csvFormat.print(new PrintWriter(filePath, StandardCharsets.UTF_8));
} catch (IOException e) {
ioTPrinter.printException(e);
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@

import java.io.FileWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Collections;
Expand Down Expand Up @@ -233,7 +234,7 @@ private void exportSchemaByShowCreate(
String dropSql =
String.format(Constants.DROP_TABLE_IF_EXIST, escapeSqlIdentifer(tableName)) + ";\n";
StringBuilder sb = new StringBuilder(dropSql);
try (FileWriter writer = new FileWriter(fileName, true)) {
try (FileWriter writer = new FileWriter(fileName, StandardCharsets.UTF_8, true)) {
while (sessionDataSet.hasNext()) {
RowRecord rowRecord = sessionDataSet.next();
String res = rowRecord.getField(1).getStringValue();
Expand All @@ -251,7 +252,7 @@ private void exportSchemaByDesc(
String dropSql = "DROP TABLE IF EXISTS " + tableName + ";\n";
StringBuilder sb = new StringBuilder(dropSql);
sb.append("CREATE TABLE " + tableName + "(\n");
try (FileWriter writer = new FileWriter(fileName, true)) {
try (FileWriter writer = new FileWriter(fileName, StandardCharsets.UTF_8, true)) {
boolean hasNext = sessionDataSet.hasNext();
while (hasNext) {
RowRecord rowRecord = sessionDataSet.next();
Expand Down Expand Up @@ -287,7 +288,7 @@ private void exportSchemaBySelect(
String dropSql = "DROP TABLE IF EXISTS " + tableName + ";\n";
StringBuilder sb = new StringBuilder(dropSql);
sb.append("CREATE TABLE " + tableName + "(\n");
try (FileWriter writer = new FileWriter(fileName, true)) {
try (FileWriter writer = new FileWriter(fileName, StandardCharsets.UTF_8, true)) {
boolean hasNext = sessionDataSet.hasNext();
while (hasNext) {
RowRecord rowRecord = sessionDataSet.next();
Expand Down
Loading
Loading