diff --git a/integration-test/src/test/java/org/apache/iotdb/tools/it/SchemaTagsRoundTripIT.java b/integration-test/src/test/java/org/apache/iotdb/tools/it/SchemaTagsRoundTripIT.java new file mode 100644 index 0000000000000..8d9b26fb7f800 --- /dev/null +++ b/integration-test/src/test/java/org/apache/iotdb/tools/it/SchemaTagsRoundTripIT.java @@ -0,0 +1,859 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ +package org.apache.iotdb.tools.it; + +import org.apache.iotdb.cli.i18n.CliMessages; +import org.apache.iotdb.cli.it.AbstractScriptIT; +import org.apache.iotdb.isession.ISession; +import org.apache.iotdb.isession.SessionConfig; +import org.apache.iotdb.isession.SessionDataSet; +import org.apache.iotdb.it.env.EnvFactory; +import org.apache.iotdb.it.framework.IoTDBTestRunner; +import org.apache.iotdb.itbase.category.ClusterIT; +import org.apache.iotdb.itbase.category.LocalStandaloneIT; +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.tool.common.Constants; + +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVPrinter; +import org.apache.commons.csv.CSVRecord; +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.reflect.TypeToken; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.apache.tsfile.read.common.Field; +import org.awaitility.Awaitility; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.experimental.categories.Category; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; + +import java.io.BufferedReader; +import java.io.File; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.StringWriter; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.EnumSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeMap; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; +import java.util.stream.Stream; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +/** + * Proves that the tree model schema tools restore the tags and attributes of every time series: + * {@code export-schema} writes them as RFC4180 quoted JSON, {@code import-schema} reads that format + * back, and awkward characters survive the round trip unchanged. + * + *

The schema of one database and one exported file mixes everything the tools have to keep + * apart: every data type/encoding/compression combination, all four tag/attribute combinations on + * different devices, and several combinations across the measurements of one device. + */ +@RunWith(IoTDBTestRunner.class) +@Category({LocalStandaloneIT.class, ClusterIT.class}) +public class SchemaTagsRoundTripIT extends AbstractScriptIT { + + private static final String DATABASE = "root.rt"; + private static final String EXPORT_PREFIX = "schema_tags"; + private static final String HEADER = + "Timeseries,Alias,DataType,Encoding,Compression,Tags,Attributes"; + private static final String ALIAS = "aliased"; + + /** The row whose tag value carries a double quote, i.e. the row that must be RFC4180 quoted. */ + private static final String QUOTE_ROW = DATABASE + ".quote.s1"; + + /** The JSON object the export writes for the tag value {@code a"b}. */ + private static final String QUOTE_ROW_TAGS_JSON = "{\"k\":\"a\\\"b\"}"; + + private static final String NO_ATTRIBUTES_ROW = DATABASE + ".none.s1"; + + /** How long the metadata drop may take to become visible on every node. */ + private static final int SCHEMA_CLEANUP_TIMEOUT_SECONDS = 60; + + private static final Map NO_VALUES = Collections.emptyMap(); + + /** Time series path to the tags, attributes and alias the test creates for it. */ + private static final Map CREATED = new LinkedHashMap<>(); + + static { + // Awkward tag values, one device per value because tags belong to the device. + singleTag("v1", "v1", Format.BOOLEAN_PLAIN_SNAPPY); + singleTag("comma", "a,b", Format.INT32_TS_2DIFF_SNAPPY); + singleTag("quote", "a\"b", Format.DOUBLE_GORILLA_LZ4); + singleTag("backslash", "a\\b", Format.INT64_GORILLA_LZ4); + singleTag("backslashn", "a\\nb", Format.FLOAT_GORILLA_GZIP); + singleTag("tab", "a\tb", Format.DOUBLE_GORILLA_LZ4); + singleTag("newline", "a\nb", Format.TEXT_DICTIONARY_SNAPPY); + singleTag("cjk", "中文😀", Format.INT64_GORILLA_LZ4); + singleTag("nulllit", "null", Format.BOOLEAN_PLAIN_SNAPPY); + singleTag("empty", "", Format.INT32_TS_2DIFF_SNAPPY); + singleTag("backtick", "`x`", Format.FLOAT_GORILLA_GZIP); + tagged("spacedkey", "k e y", "v", Format.TEXT_DICTIONARY_SNAPPY); + + // The four tag/attribute combinations, each on a device of its own. + series( + "both", + "s1", + Format.BOOLEAN_PLAIN_SNAPPY, + mapOf("t1", "v1", "t2", "a,b"), + mapOf("a1", "one", "a2", "he said \"hi\""), + null); + series( + "multi", + "s1", + Format.TEXT_DICTIONARY_SNAPPY, + mapOf("a", "1", "b", "a,b", "c", "a\"b"), + NO_VALUES, + null); + series( + "attr", + "s1", + Format.TEXT_DICTIONARY_SNAPPY, + NO_VALUES, + mapOf("note", "he said \"hi\"", "plain", "v"), + null); + series("none", "s1", Format.TEXT_DICTIONARY_SNAPPY, NO_VALUES, NO_VALUES, null); + series("alias", "s1", Format.FLOAT_GORILLA_GZIP, mapOf("aliasTag", "v"), NO_VALUES, ALIAS); + + // One device mixing three of the combinations across its measurements. + series( + "mixed", + "tagsOnly", + Format.INT32_TS_2DIFF_SNAPPY, + mapOf("m1", "x", "m2", "y"), + NO_VALUES, + null); + series( + "mixed", + "attrsOnly", + Format.INT64_GORILLA_LZ4, + NO_VALUES, + mapOf("m1", "x", "m2", "y"), + null); + series("mixed", "neither", Format.DOUBLE_GORILLA_LZ4, NO_VALUES, NO_VALUES, null); + } + + @Rule public TemporaryFolder folder = new TemporaryFolder(); + + private static String ip; + private static String port; + private static String toolsPath; + private static String homePath; + + @BeforeClass + public static void setUp() { + EnvFactory.getEnv().initClusterEnvironment(); + ip = EnvFactory.getEnv().getIP(); + port = EnvFactory.getEnv().getPort(); + toolsPath = EnvFactory.getEnv().getToolsPath(); + final String libPath = EnvFactory.getEnv().getLibPath(); + homePath = + libPath.substring(0, libPath.lastIndexOf(File.separator + "lib" + File.separator + "*")); + } + + @AfterClass + public static void tearDown() { + EnvFactory.getEnv().cleanClusterEnvironment(); + } + + @Test + public void test() throws IOException { + String os = System.getProperty("os.name").toLowerCase(); + if (os.startsWith("windows")) { + testOnWindows(); + } else { + testOnUnix(); + } + } + + @Test + public void alignedImportThroughCliPreservesEveryRow() throws Exception { + String database = "root.aligned_schema_import"; + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.createDatabase(database); + } + Map expected = new LinkedHashMap<>(); + expected.put( + database + ".d1.s1", + new Series( + Format.INT32_TS_2DIFF_SNAPPY, mapOf("room", "a,b"), mapOf("owner", "中文😀"), "alias1")); + expected.put( + database + ".d1.s2", + new Series(Format.TEXT_DICTIONARY_SNAPPY, NO_VALUES, mapOf("note", "v2"), null)); + expected.put( + database + ".d2.`s.3`", + new Series(Format.FLOAT_GORILLA_GZIP, mapOf("room", "101"), NO_VALUES, "alias3")); + Path csv = writeSchemaFile("aligned.csv", expected, false); + // Exercise the same BOM/empty-line rules through the actual script and parser as well. + Files.writeString( + csv, "\uFEFF\n\n" + Files.readString(csv, StandardCharsets.UTF_8), StandardCharsets.UTF_8); + boolean windows = System.getProperty("os.name").toLowerCase().startsWith("windows"); + testOutput( + importProcessBuilder(windows, csv, "-aligned", "true"), + new String[] {Constants.IMPORT_COMPLETELY}, + 0); + assertSchemaEquals(expected, readSchema(database)); + + Map legacy = new LinkedHashMap<>(); + legacy.put( + database + ".legacy.s1", + new Series(Format.BOOLEAN_PLAIN_SNAPPY, NO_VALUES, NO_VALUES, null)); + legacy.put( + database + ".legacy.s2", + new Series(Format.DOUBLE_GORILLA_LZ4, NO_VALUES, NO_VALUES, "legacyAlias")); + testOutput( + importProcessBuilder( + windows, writeSchemaFile("legacy-aligned.csv", legacy, true), "-aligned", "true"), + new String[] {Constants.IMPORT_COMPLETELY}, + 0); + expected.putAll(legacy); + assertSchemaEquals(expected, readSchema(database)); + + try (ISession session = EnvFactory.getEnv().getSessionConnection(); + SessionDataSet devices = + session.executeQueryStatement("SHOW DEVICES " + database + ".**")) { + int alignedIndex = devices.getColumnNames().indexOf("IsAligned"); + assertTrue(devices.getColumnNames().toString(), alignedIndex >= 0); + int count = 0; + while (devices.hasNext()) { + assertEquals("true", cell(devices.next().getFields(), alignedIndex)); + count++; + } + assertEquals(3, count); + } + } + + @Test + public void invalidMetadataIsIsolatedFromValidRowsThroughCli() throws Exception { + String database = "root.invalid_schema_metadata"; + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.createDatabase(database); + } + Map expected = new LinkedHashMap<>(); + expected.put( + database + ".d1.s1", + new Series(Format.INT32_TS_2DIFF_SNAPPY, mapOf("room", "101"), NO_VALUES, null)); + expected.put( + database + ".d2.s2", + new Series(Format.TEXT_DICTIONARY_SNAPPY, NO_VALUES, mapOf("note", "null"), "alias2")); + Path csv = writeSchemaFile("invalid-metadata.csv", expected, false); + List> invalidRows = new ArrayList<>(); + StringWriter invalidContent = new StringWriter(); + try (CSVPrinter printer = CSVFormat.DEFAULT.print(invalidContent)) { + for (String value : Arrays.asList("null", "101", "true", "[]", "{}")) { + for (int column = 5; column <= 6; column++) { + List row = + new ArrayList<>( + Arrays.asList( + database + ".invalid.s" + invalidRows.size(), + "", + "INT32", + "TS_2DIFF", + "SNAPPY", + "", + "")); + row.set(column, "{\"room\":" + value + "}"); + invalidRows.add(row); + printer.printRecord(row); + } + } + } + Files.writeString( + csv, + "\uFEFF\n\n" + Files.readString(csv, StandardCharsets.UTF_8) + invalidContent, + StandardCharsets.UTF_8); + boolean windows = System.getProperty("os.name").toLowerCase().startsWith("windows"); + testOutput(importProcessBuilder(windows, csv), new String[] {Constants.IMPORT_COMPLETELY}, 0); + assertSchemaEquals(expected, readSchema(database)); + // The generated file ends in csv, so the CLI can import it again without renaming it first. + Path failedFile = failedFile(csv, 0); + try (CSVParser parser = + CSVParser.parse(failedFile.toFile(), StandardCharsets.UTF_8, CSVFormat.DEFAULT)) { + List> failedRows = + parser.getRecords().stream() + .map(record -> record.stream().collect(Collectors.toList())) + .collect(Collectors.toList()); + // The failed file starts with the header its rows follow. + assertEquals(Constants.HEAD_COLUMNS_V2, failedRows.get(0)); + assertEquals(invalidRows, failedRows.subList(1, failedRows.size())); + } + List retryOutput = importOutput(windows, failedFile); + assertFalse( + "the generated file must not be skipped because of its name: " + retryOutput, + retryOutput.contains( + String.format( + CliMessages + .MESSAGE_ARG_THE_FILE_NAME_MUST_END_WITH_CSV_WHEN_SQL_DIALECT_TREE_OR_SQL_WHEN_SQL_DIALECT_TABLE_7A2FD49A, + failedFile.getFileName().toString()))); + assertTrue( + "the rows of the generated file must be processed: " + retryOutput, + retryOutput.contains( + String.format( + CliMessages.MESSAGE_ARG_IMPORT_COMPLETELY_FAIL_9B6F42FD, + failedFile.getFileName().toString()))); + } + + /** + * The failed-record file the import generates for a source file: {@code .failed_.csv}. + */ + private static Path failedFile(Path csv, int index) { + String name = csv.getFileName().toString(); + String stem = name.endsWith(".csv") ? name.substring(0, name.length() - ".csv".length()) : name; + return csv.resolveSibling(stem + ".failed_" + index + ".csv"); + } + + /** + * Runs the import and returns its output, so that a test can assert on what the CLI did not + * print, which {@link #testOutput} cannot express. + */ + private List importOutput(boolean windows, Path csv) throws Exception { + ProcessBuilder builder = importProcessBuilder(windows, csv); + builder.redirectErrorStream(true); + Process process = builder.start(); + List output = new ArrayList<>(); + try (BufferedReader reader = + new BufferedReader(new InputStreamReader(process.getInputStream()))) { + String line; + while ((line = reader.readLine()) != null) { + output.add(line); + } + } + assertEquals(output.toString(), 0, process.waitFor()); + return output; + } + + private Path writeSchemaFile(String name, Map schema, boolean legacy) + throws IOException { + Path csv = folder.newFile(name).toPath(); + try (CSVPrinter printer = CSVFormat.DEFAULT.print(csv, StandardCharsets.UTF_8)) { + printer.printRecord(legacy ? Constants.HEAD_COLUMNS : Constants.HEAD_COLUMNS_V2); + for (Map.Entry entry : schema.entrySet()) { + Series series = entry.getValue(); + List row = + new ArrayList<>( + Arrays.asList( + entry.getKey(), + series.alias == null ? "" : series.alias, + series.format.dataType.name(), + series.format.encoding.name(), + series.format.compression.name())); + if (!legacy) { + row.add(toJsonObject(series.tags)); + row.add(toJsonObject(series.attributes)); + } + printer.printRecord(row); + } + } + return csv; + } + + @Override + protected void testOnWindows() throws IOException { + try { + roundTrip(true); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } + } + + @Override + protected void testOnUnix() throws IOException { + try { + roundTrip(false); + } catch (IOException e) { + throw e; + } catch (Exception e) { + throw new IOException(e); + } + } + + /** + * Exports the schema, drops it, imports the exported file again and compares the tags and + * attributes read back from the server with the ones that were created. + */ + private void roundTrip(boolean windows) throws Exception { + final Path outputDirectory = folder.newFolder("export").toPath(); + + createSchema(); + + testOutput( + exportProcessBuilder(windows, outputDirectory), + new String[] {Constants.EXPORT_COMPLETELY}, + 0); + + final Path csv = singleExportFile(outputDirectory); + assertExportFormat(csv); + + dropSchema(); + + testOutput(importProcessBuilder(windows, csv), new String[] {Constants.IMPORT_COMPLETELY}, 0); + + assertSchemaRestored(); + } + + private static void createSchema() throws IoTDBConnectionException, StatementExecutionException { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.createDatabase(DATABASE); + for (Map.Entry entry : CREATED.entrySet()) { + final Series series = entry.getValue(); + // Set the tags and attributes through the session API, so that no SQL escaping can hide a + // character that the export or the import tool mangles. + session.createTimeseries( + entry.getKey(), + series.format.dataType, + series.format.encoding, + series.format.compression, + null, + series.tags.isEmpty() ? null : series.tags, + series.attributes.isEmpty() ? null : series.attributes, + series.alias); + } + } + } + + private static void dropSchema() throws IoTDBConnectionException, StatementExecutionException { + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + session.executeNonQueryStatement("DROP DATABASE " + DATABASE); + } + // The drop reaches the DataNodes asynchronously. Waiting until it is observable keeps a + // leftover device from making the import pass without restoring anything. + Awaitility.await() + .atMost(SCHEMA_CLEANUP_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .pollInterval(500, TimeUnit.MILLISECONDS) + .until(() -> !databaseExists() && readSchema().isEmpty()); + try (ISession session = EnvFactory.getEnv().getSessionConnection()) { + // Importing a file only creates time series, so the database has to exist beforehand. + session.createDatabase(DATABASE); + } + } + + private static boolean databaseExists() + throws IoTDBConnectionException, StatementExecutionException { + try (ISession session = EnvFactory.getEnv().getSessionConnection(); + SessionDataSet dataSet = session.executeQueryStatement("SHOW DATABASES")) { + while (dataSet.hasNext()) { + if (DATABASE.equals(cell(dataSet.next().getFields(), 0))) { + return true; + } + } + } + return false; + } + + private Path singleExportFile(Path outputDirectory) throws IOException { + try (Stream files = Files.list(outputDirectory)) { + final List csvFiles = + files + .filter(file -> file.getFileName().toString().startsWith(EXPORT_PREFIX)) + .filter(file -> file.getFileName().toString().endsWith(".csv")) + .collect(Collectors.toList()); + assertEquals("expected exactly one exported CSV file, found " + csvFiles, 1, csvFiles.size()); + return csvFiles.get(0); + } + } + + private static void assertExportFormat(Path csv) throws IOException { + final List lines = Files.readAllLines(csv, StandardCharsets.UTF_8); + assertTrue("the exported schema file is empty", lines.size() > 1); + assertEquals(HEADER, lines.get(0)); + + final String content = Files.readString(csv, StandardCharsets.UTF_8); + // RFC4180 uses LF as the record separator; a CR would come from a platform dependent writer. + assertFalse("the export must use LF line endings", content.contains("\r")); + // RFC4180: the JSON object of the value containing a double quote is wrapped in a quoted cell + // and every inner quote is doubled, instead of being escaped with a backslash. + final String quotedCell = "\"" + QUOTE_ROW_TAGS_JSON.replace("\"", "\"\"") + "\""; + assertTrue( + "the Tags cell of " + + QUOTE_ROW + + " is not RFC4180 quoted: " + + quotedCell + + " in\n" + + content, + content.contains(quotedCell)); + + try (CSVParser parser = CSVParser.parse(csv, StandardCharsets.UTF_8, csvFormat())) { + final Map records = new TreeMap<>(); + for (CSVRecord record : parser) { + records.put(record.get("Timeseries"), record); + } + assertEquals( + "unexpected number of exported rows: " + records, CREATED.size(), records.size()); + + final Set formats = EnumSet.noneOf(Format.class); + for (Map.Entry entry : CREATED.entrySet()) { + final String path = entry.getKey(); + final Series series = entry.getValue(); + final CSVRecord record = records.get(path); + assertNotNull("the export is missing " + path, record); + assertEquals(path + " DataType", series.format.dataType.name(), record.get("DataType")); + assertEquals(path + " Encoding", series.format.encoding.name(), record.get("Encoding")); + assertEquals( + path + " Compression", series.format.compression.name(), record.get("Compression")); + assertEquals( + path + " Alias", series.alias == null ? "" : series.alias, record.get("Alias")); + assertEquals(path + " Tags", series.tags, parseJsonObject(record.get("Tags"))); + assertEquals( + path + " Attributes", series.attributes, parseJsonObject(record.get("Attributes"))); + // The three assertions above proved that the file carries this combination. + formats.add(series.format); + } + assertEquals( + "the file must carry every data type, encoding and compression combination", + EnumSet.allOf(Format.class), + formats); + + // Nothing to write is written as an empty cell, not as {} and not as null. + assertEquals("", records.get(NO_ATTRIBUTES_ROW).get("Tags")); + assertEquals("", records.get(NO_ATTRIBUTES_ROW).get("Attributes")); + + assertPresenceCombinations(records); + } + } + + /** + * The one exported file must carry all four tag/attribute combinations, spread over several + * devices, and at least one device must mix several of them across its measurements. + */ + private static void assertPresenceCombinations(Map records) { + final Set presences = EnumSet.noneOf(Presence.class); + final Map> presencesByDevice = new TreeMap<>(); + for (Map.Entry entry : records.entrySet()) { + final String path = entry.getKey(); + final CSVRecord record = entry.getValue(); + final Presence presence = + Presence.of( + parseJsonObject(record.get("Tags")), parseJsonObject(record.get("Attributes"))); + presences.add(presence); + presencesByDevice + .computeIfAbsent( + path.substring(0, path.lastIndexOf('.')), device -> EnumSet.noneOf(Presence.class)) + .add(presence); + } + assertEquals( + "the file must carry every tag/attribute combination", + EnumSet.allOf(Presence.class), + presences); + assertTrue( + "the combinations must be spread over at least four devices: " + presencesByDevice, + presencesByDevice.size() >= 4); + assertTrue( + "one device must mix several combinations across its measurements: " + presencesByDevice, + presencesByDevice.values().stream().mapToInt(Set::size).max().orElse(0) >= 3); + } + + private static void assertSchemaRestored() + throws IoTDBConnectionException, StatementExecutionException { + assertSchemaEquals(CREATED, readSchema()); + } + + private static void assertSchemaEquals( + Map expectedSchema, Map restored) { + assertEquals( + "the import must restore every time series", expectedSchema.keySet(), restored.keySet()); + for (Map.Entry entry : expectedSchema.entrySet()) { + final String path = entry.getKey(); + final Series expected = entry.getValue(); + final Series actual = restored.get(path); + assertEquals(path + " data type/encoding/compression", expected.format, actual.format); + assertEquals(path + " tags", expected.tags, actual.tags); + assertEquals(path + " attributes", expected.attributes, actual.attributes); + assertEquals(path + " alias", expected.alias, actual.alias); + } + } + + /** Reads the tags, attributes and alias of every time series of the test database. */ + private static Map readSchema() + throws IoTDBConnectionException, StatementExecutionException { + return readSchema(DATABASE); + } + + private static Map readSchema(String database) + throws IoTDBConnectionException, StatementExecutionException { + final Map schema = new TreeMap<>(); + try (ISession session = EnvFactory.getEnv().getSessionConnection(); + SessionDataSet dataSet = + session.executeQueryStatement("SHOW TIMESERIES " + database + ".**")) { + final List columns = dataSet.getColumnNames(); + final int timeseriesIndex = columns.indexOf("Timeseries"); + final int aliasIndex = columns.indexOf("Alias"); + final int dataTypeIndex = columns.indexOf("DataType"); + final int encodingIndex = columns.indexOf("Encoding"); + final int compressionIndex = columns.indexOf("Compression"); + final int tagsIndex = columns.indexOf("Tags"); + final int attributesIndex = columns.indexOf("Attributes"); + assertTrue( + "SHOW TIMESERIES must expose the Timeseries, Alias, DataType, Encoding, Compression, " + + "Tags and Attributes columns: " + + columns, + timeseriesIndex >= 0 + && aliasIndex >= 0 + && dataTypeIndex >= 0 + && encodingIndex >= 0 + && compressionIndex >= 0 + && tagsIndex >= 0 + && attributesIndex >= 0); + while (dataSet.hasNext()) { + final List fields = dataSet.next().getFields(); + final String path = cell(fields, timeseriesIndex); + schema.put( + path, + new Series( + Format.of( + cell(fields, dataTypeIndex), + cell(fields, encodingIndex), + cell(fields, compressionIndex)), + parseJsonObject(cell(fields, tagsIndex)), + parseJsonObject(cell(fields, attributesIndex)), + cell(fields, aliasIndex))); + } + } + return schema; + } + + /** Returns a cell of a schema row, or {@code null} when the server sent a NULL there. */ + private static String cell(List fields, int index) { + if (index < 0 || index >= fields.size()) { + return null; + } + final Field field = fields.get(index); + if (field == null) { + return null; + } + // A NULL field is rendered as the text "null" by getStringValue(), which is how the export + // tool distinguishes a missing value as well. + final String value = field.getStringValue(); + return "null".equals(value) ? null : value; + } + + /** Parses a JSON object cell into a map; an empty cell carries no tags and no attributes. */ + private static final Gson GSON = new GsonBuilder().disableHtmlEscaping().create(); + + private static final Type JSON_MAP_TYPE = new TypeToken>() {}.getType(); + + private static String toJsonObject(Map values) { + return GSON.toJson(new TreeMap<>(values)); + } + + private static Map parseJsonObject(String cell) { + if (cell == null || cell.trim().isEmpty() || "null".equals(cell.trim())) { + return new TreeMap<>(); + } + Map parsed = GSON.fromJson(cell.trim(), JSON_MAP_TYPE); + return parsed == null ? new TreeMap<>() : new TreeMap<>(parsed); + } + + private static CSVFormat csvFormat() { + return CSVFormat.Builder.create(CSVFormat.DEFAULT) + .setHeader() + .setSkipHeaderRecord(true) + .build(); + } + + private ProcessBuilder exportProcessBuilder(boolean windows, Path outputDirectory) { + final List command = new ArrayList<>(); + addScriptInvocation(command, windows, "export-schema"); + addConnectionArguments(command); + command.addAll( + Arrays.asList( + "-t", + outputDirectory.toAbsolutePath().toString(), + "-pfn", + EXPORT_PREFIX, + "-path", + DATABASE + ".**")); + return processBuilder(command, windows); + } + + private ProcessBuilder importProcessBuilder(boolean windows, Path csv, String... options) { + final List command = new ArrayList<>(); + addScriptInvocation(command, windows, "import-schema"); + addConnectionArguments(command); + command.addAll(Arrays.asList("-db", DATABASE, "-s", csv.toAbsolutePath().toString())); + command.addAll(Arrays.asList(options)); + return processBuilder(command, windows); + } + + private static void addConnectionArguments(List command) { + command.addAll( + Arrays.asList( + "-h", + ip, + "-p", + port, + "-u", + SessionConfig.DEFAULT_USER, + "-pw", + SessionConfig.DEFAULT_PASSWORD)); + } + + private static void addScriptInvocation(List command, boolean windows, String script) { + if (windows) { + command.add("cmd.exe"); + command.add("/c"); + command.add( + toolsPath + + File.separator + + "windows" + + File.separator + + "schema" + + File.separator + + script + + ".bat"); + } else { + command.add("bash"); + command.add(toolsPath + File.separator + "schema" + File.separator + script + ".sh"); + } + } + + private static ProcessBuilder processBuilder(List command, boolean windows) { + if (windows) { + // cmd.exe exits with the error level of the script it ran. + command.add("&"); + command.add("exit"); + command.add("%^errorlevel%"); + } + final ProcessBuilder builder = new ProcessBuilder(command); + builder.environment().put("IOTDB_HOME", homePath); + return builder; + } + + private static void singleTag(String device, String value, Format format) { + tagged(device, "k", value, format); + } + + private static void tagged(String device, String key, String value, Format format) { + series(device, "s1", format, mapOf(key, value), NO_VALUES, null); + } + + private static void series( + String device, + String measurement, + Format format, + Map tags, + Map attributes, + String alias) { + CREATED.put( + DATABASE + "." + device + "." + measurement, new Series(format, tags, attributes, alias)); + } + + private static Map mapOf(String... keysAndValues) { + final Map map = new LinkedHashMap<>(); + for (int i = 0; i < keysAndValues.length; i += 2) { + map.put(keysAndValues[i], keysAndValues[i + 1]); + } + return map; + } + + /** + * A data type, encoding and compression combination of the test schema. Every combination has to + * appear in the exported file, and the server renders them with these names. + */ + private enum Format { + BOOLEAN_PLAIN_SNAPPY(TSDataType.BOOLEAN, TSEncoding.PLAIN, CompressionType.SNAPPY), + INT32_TS_2DIFF_SNAPPY(TSDataType.INT32, TSEncoding.TS_2DIFF, CompressionType.SNAPPY), + INT64_GORILLA_LZ4(TSDataType.INT64, TSEncoding.GORILLA, CompressionType.LZ4), + DOUBLE_GORILLA_LZ4(TSDataType.DOUBLE, TSEncoding.GORILLA, CompressionType.LZ4), + FLOAT_GORILLA_GZIP(TSDataType.FLOAT, TSEncoding.GORILLA, CompressionType.GZIP), + TEXT_DICTIONARY_SNAPPY(TSDataType.TEXT, TSEncoding.DICTIONARY, CompressionType.SNAPPY); + + private final TSDataType dataType; + private final TSEncoding encoding; + private final CompressionType compression; + + Format(TSDataType dataType, TSEncoding encoding, CompressionType compression) { + this.dataType = dataType; + this.encoding = encoding; + this.compression = compression; + } + + /** Resolves the combination rendered by {@code SHOW TIMESERIES}, i.e. by the export. */ + private static Format of(String dataType, String encoding, String compression) { + for (Format format : values()) { + if (format.dataType.name().equals(dataType) + && format.encoding.name().equals(encoding) + && format.compression.name().equals(compression)) { + return format; + } + } + throw new AssertionError( + "unexpected data type/encoding/compression combination: " + + dataType + + "/" + + encoding + + "/" + + compression); + } + } + + /** Whether a time series carries tags and attributes; all four must coexist in one file. */ + private enum Presence { + BOTH, + TAGS_ONLY, + ATTRIBUTES_ONLY, + NEITHER; + + private static Presence of(Map tags, Map attributes) { + if (!tags.isEmpty()) { + return attributes.isEmpty() ? TAGS_ONLY : BOTH; + } + return attributes.isEmpty() ? NEITHER : ATTRIBUTES_ONLY; + } + } + + /** One time series of the test schema, i.e. one row of the exported file. */ + private static final class Series { + private final Format format; + private final Map tags; + private final Map attributes; + private final String alias; + + private Series( + Format format, Map tags, Map attributes, String alias) { + this.format = format; + this.tags = tags; + this.attributes = attributes; + this.alias = alias; + } + } +} diff --git a/iotdb-client/cli/pom.xml b/iotdb-client/cli/pom.xml index 61cd91f62fae7..8b6430c125880 100644 --- a/iotdb-client/cli/pom.xml +++ b/iotdb-client/cli/pom.xml @@ -144,6 +144,10 @@ org.apache.commons commons-csv + + org.apache.ratis + ratis-thirdparty-misc + junit junit 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..fd3d88b66e8dc 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 @@ -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() {} 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..c3b15ee2f5b15 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 @@ -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() {} diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/Constants.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/Constants.java index ec4d2c7632cbc..e2c96f4d2e744 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/Constants.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/Constants.java @@ -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 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 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; diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/OptionsUtil.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/OptionsUtil.java index cf060f66d116e..d0df306d367bc 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/OptionsUtil.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/common/OptionsUtil.java @@ -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() diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractSchemaTool.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractSchemaTool.java index b88cfda2c0a32..e7e01ca07da8b 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractSchemaTool.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractSchemaTool.java @@ -34,6 +34,11 @@ 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; @@ -41,8 +46,12 @@ 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 { @@ -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); @@ -204,8 +216,23 @@ protected static void parseBasicParams(CommandLine commandLine) * @param filePath the directory to save the file */ public static Boolean writeCsvFile(List> 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> records, String filePath, boolean legacy) { try { - final CSVPrinterWrapper csvPrinterWrapper = new CSVPrinterWrapper(filePath); + final CSVPrinterWrapper csvPrinterWrapper = + new CSVPrinterWrapper( + filePath, legacy ? createLegacyCsvFormat() : createRfc4180CsvFormat()); for (List CsvRecord : records) { csvPrinterWrapper.printRecordLn(CsvRecord); } @@ -218,32 +245,126 @@ public static Boolean writeCsvFile(List> 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 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 parseJsonCell(String cell) { + if (cell == null) { + return null; + } + String trimmed = cell.trim(); + if (trimmed.isEmpty() || "null".equals(trimmed)) { + return null; + } + Map values = parseStrictJsonObject(trimmed); + return values.isEmpty() ? null : values; + } + + private static Map 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 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(); @@ -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; diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTable.java index 9d184c089c8c2..045a232e7d941 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTable.java @@ -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; @@ -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(); @@ -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(); @@ -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(); diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTree.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTree.java index b8cd60323e22c..12e3b5066485a 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTree.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ExportSchemaTree.java @@ -32,7 +32,9 @@ import java.io.File; import java.io.IOException; +import java.util.ArrayList; import java.util.List; +import java.util.Map; import static org.apache.iotdb.commons.schema.SchemaConstant.AUDIT_DATABASE; import static org.apache.iotdb.commons.schema.SchemaConstant.SYSTEM_DATABASE; @@ -98,25 +100,19 @@ private static void writeCsvFile( while (i++ < linesPerFile) { if (sessionDataSet.hasNext()) { if (i == 1) { - csvPrinterWrapper.printRecord(Constants.HEAD_COLUMNS); + csvPrinterWrapper.printRecord(Constants.HEAD_COLUMNS_V2); } RowRecord rowRecord = sessionDataSet.next(); List fields = rowRecord.getFields(); - if (fields.get(timeseriesIndex).getStringValue().startsWith(SYSTEM_DATABASE + ".") - || fields.get(timeseriesIndex).getStringValue().startsWith(AUDIT_DATABASE + ".") - || !fields.get(viewTypeIndex).getStringValue().equals(Constants.BASE_VIEW_TYPE)) { + String timeseries = fields.get(timeseriesIndex).getStringValue(); + if (timeseries.startsWith(SYSTEM_DATABASE + ".") + || timeseries.startsWith(AUDIT_DATABASE + ".") + || !Constants.BASE_VIEW_TYPE.equals(fields.get(viewTypeIndex).getStringValue())) { + continue; + } + if (!printRecord(csvPrinterWrapper, headers, fields, timeseries)) { continue; } - Constants.HEAD_COLUMNS.forEach( - column -> { - Field field = fields.get(headers.indexOf(column)); - String fieldStringValue = field.getStringValue(); - if (!"null".equals(field.getStringValue())) { - csvPrinterWrapper.print(fieldStringValue); - } else { - csvPrinterWrapper.print(""); - } - }); csvPrinterWrapper.println(); } else { hasNext = false; @@ -128,4 +124,44 @@ private static void writeCsvFile( csvPrinterWrapper.close(); } } + + /** + * Writes the cells of one {@code SHOW TIMESERIES} record. + * + * @return {@code false} when the record must be skipped because a Tags or Attributes cell could + * not be parsed, in which case nothing has been written for it + */ + static boolean printRecord( + CSVPrinterWrapper csvPrinterWrapper, + List headers, + List fields, + String timeseries) { + List cells = new ArrayList<>(Constants.HEAD_COLUMNS_V2.size()); + for (String column : Constants.HEAD_COLUMNS_V2) { + int index = headers.indexOf(column); + Field field = index < 0 ? null : fields.get(index); + String fieldStringValue = field == null ? null : field.getStringValue(); + if (Constants.HEADER_TAGS.equals(column) || Constants.HEADER_ATTRIBUTES.equals(column)) { + Map tags; + try { + tags = parseJsonCell(fieldStringValue); + } catch (RuntimeException e) { + ioTPrinter.println( + String.format( + CliMessages + .MESSAGE_FAILED_TO_PARSE_THE_ARG_COLUMN_OF_TIMESERIES_ARG_AS_JSON_THE_RECORD_IS_SKIPPED_ARG_35D898C8, + column, + timeseries, + String.valueOf(e.getMessage()))); + return false; + } + cells.add(toJsonCell(tags)); + } else { + cells.add( + "null".equals(fieldStringValue) || fieldStringValue == null ? "" : fieldStringValue); + } + } + cells.forEach(csvPrinterWrapper::print); + return true; + } } diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchema.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchema.java index 996cfeb76fda7..d2b183bc27a0c 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchema.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchema.java @@ -160,7 +160,10 @@ private static int importFromTargetPath() { importSchema = new ImportSchemaTable(); } importSchema.init(); - return importSchema.importFiles(); + // importFiles() reports the per-file failures; connectionFailed covers a file that ran + // out of connection retries, whose failure has already been printed by that file. + int statusCode = importSchema.importFiles(); + return connectionFailed ? Constants.CODE_ERROR : statusCode; } catch (InterruptedException e) { ioTPrinter.println( String.format(CliMessages.MESSAGE_IMPORT_SCHEMA_FAIL_ARG_609A6D30, e.getMessage())); diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTable.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTable.java index 494cf083be01f..f254c06c72141 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTable.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTable.java @@ -44,6 +44,7 @@ import java.io.FileWriter; import java.io.IOException; import java.io.Reader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collections; import java.util.List; @@ -122,7 +123,8 @@ protected void importSchemaFromSqlFile(File file) { failedFilePath = failedFileDirectory + file.getName() + ".failed"; } boolean readFailed = false; - try (BufferedReader br = new BufferedReader(new FileReader(file.getAbsolutePath()))) { + try (BufferedReader br = + new BufferedReader(new FileReader(file.getAbsolutePath(), StandardCharsets.UTF_8))) { forEachSqlStatement( br, sql -> { @@ -147,7 +149,7 @@ protected void importSchemaFromSqlFile(File file) { if (!failedRecords.isEmpty()) { ioTPrinter.println( String.format(CliMessages.MESSAGE_ARG_IMPORT_COMPLETELY_FAIL_9B6F42FD, file.getPath())); - try (FileWriter writer = new FileWriter(failedFilePath)) { + try (FileWriter writer = new FileWriter(failedFilePath, StandardCharsets.UTF_8)) { for (String failedRecord : failedRecords) { writer.write(failedRecord + ";\n"); } diff --git a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTree.java b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTree.java index df627bffbb87b..ff3bfef228f66 100644 --- a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTree.java +++ b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/ImportSchemaTree.java @@ -22,6 +22,7 @@ import org.apache.iotdb.cli.i18n.CliMessages; import org.apache.iotdb.cli.utils.IoTPrinter; import org.apache.iotdb.commons.exception.IllegalPathException; +import org.apache.iotdb.commons.path.MeasurementPath; import org.apache.iotdb.rpc.IoTDBConnectionException; import org.apache.iotdb.rpc.StatementExecutionException; import org.apache.iotdb.session.pool.SessionPool; @@ -38,11 +39,14 @@ import org.apache.tsfile.file.metadata.enums.CompressionType; import org.apache.tsfile.file.metadata.enums.TSEncoding; +import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; import java.util.ArrayList; +import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; @@ -58,7 +62,7 @@ public class ImportSchemaTree extends AbstractImportSchema { private static final IoTPrinter ioTPrinter = new IoTPrinter(System.out); - private static SessionPool sessionPool; + static SessionPool sessionPool; public void init() throws InterruptedException, IoTDBConnectionException, StatementExecutionException { @@ -96,8 +100,7 @@ protected void importSchemaFromSqlFile(File file) { @Override protected void importSchemaFromCsvFile(File file) { - try { - CSVParser csvRecords = readCsvFile(file.getAbsolutePath()); + try (CSVParser csvRecords = readCsvFile(file.getAbsolutePath())) { List headerNames = csvRecords.getHeaderNames(); Stream records = csvRecords.stream(); if (headerNames.isEmpty()) { @@ -109,14 +112,21 @@ protected void importSchemaFromCsvFile(File file) { if (!checkHeader(headerNames)) { return; } - String failedFilePath = null; + String failedFileBase; if (failedFileDirectory == null) { - failedFilePath = file.getAbsolutePath() + ".failed"; + failedFileBase = failedFileBaseName(file.getAbsolutePath()); } else { - failedFilePath = failedFileDirectory + file.getName() + ".failed"; + failedFileBase = failedFileBaseName(failedFileDirectory + file.getName()); } - writeScheme(file.getName(), headerNames, records, failedFilePath); + writeScheme(file.getName(), headerNames, records, failedFileBase); processSuccessFile(); + } catch (ConnectionRetriesExhaustedException e) { + // The failed rows are already in the failed-record file; keep importing the remaining files + // and let the entry point turn the flag into a non-zero exit status. + connectionFailed = true; + ioTPrinter.println( + String.format( + CliMessages.MESSAGE_IMPORT_SCHEMA_FAIL_ARG_609A6D30, String.valueOf(e.getMessage()))); } catch (IOException | IllegalPathException e) { ioTPrinter.println( String.format( @@ -126,22 +136,93 @@ protected void importSchemaFromCsvFile(File file) { } } - private static CSVParser readCsvFile(String path) throws IOException { - return CSVFormat.Builder.create(CSVFormat.DEFAULT) - .setHeader() - .setSkipHeaderRecord(true) - .setQuote('`') - .setEscape('\\') - .setIgnoreEmptyLines(true) - .build() - .parse(new InputStreamReader(new FileInputStream(path))); + static CSVParser readCsvFile(String path) throws IOException { + CSVFormat.Builder builder = + CSVFormat.Builder.create(CSVFormat.DEFAULT) + .setHeader() + .setSkipHeaderRecord(true) + .setIgnoreEmptyLines(true); + if (isV2Format(readHeaderNames(path))) { + builder.setQuote('"'); + } else { + builder.setQuote('`').setEscape('\\'); + } + return builder.build().parse(openCsvReader(path)); } - private static boolean checkHeader(List headerNames) { - if (CollectionUtils.isNotEmpty(headerNames) - && new HashSet<>(headerNames).size() == Constants.HEAD_COLUMNS.size()) { + private static BufferedReader openCsvReader(String path) throws IOException { + BufferedReader reader = + new BufferedReader( + new InputStreamReader(new FileInputStream(path), StandardCharsets.UTF_8)); + reader.mark(1); + if (reader.read() != '\uFEFF') { + reader.reset(); + } + return reader; + } + + /** + * Reads the column names of a schema file without parsing it, so that the CSV settings of the + * file can be selected before it is read. + */ + static List readHeaderNames(String path) throws IOException { + try (BufferedReader reader = openCsvReader(path)) { + String headerLine; + do { + headerLine = reader.readLine(); + } while (headerLine != null && headerLine.isEmpty()); + if (headerLine == null) { + return Collections.emptyList(); + } + return Arrays.stream(headerLine.split(",")) + .map(ImportSchemaTree::unquoteColumnName) + .collect(Collectors.toList()); + } + } + + /** Accepts a header written by a spreadsheet tool, which quotes every column name. */ + private static String unquoteColumnName(String columnName) { + String name = columnName.trim(); + if (name.length() > 1 && name.startsWith("\"") && name.endsWith("\"")) { + return name.substring(1, name.length() - 1).trim(); + } + return name; + } + + /** + * Applies the same normalisation to a whole header that the format probe applies, so detection, + * validation and column lookup cannot disagree about a header written by a spreadsheet tool. + */ + static List normalizeHeaderNames(List headerNames) { + return headerNames.stream() + .map(ImportSchemaTree::unquoteColumnName) + .collect(Collectors.toList()); + } + + /** + * A file whose header carries a Tags or an Attributes column is a v2 file, which is RFC4180 and + * holds JSON cells. Everything else is a legacy file and keeps the settings it was written with. + */ + static boolean isV2Format(List headerNames) { + return headerNames.contains(Constants.HEADER_TAGS) + || headerNames.contains(Constants.HEADER_ATTRIBUTES); + } + + static boolean checkHeader(List headerNames) { + List columns = normalizeHeaderNames(headerNames); + if (isV2Format(columns)) { + if (columns.containsAll(Constants.HEAD_COLUMNS_V2)) { + return true; + } + ioTPrinter.println( + CliMessages + .MESSAGE_THE_HEADER_OF_THE_CSV_FILE_TO_BE_IMPORTED_IS_ILLEGAL_THE_CORRECT_FORMAT_IS_TIMESERIES_ALIAS_DATATYPE_ENCODING_COMPRESSION_TAGS_ATTRIBUTES_14EDBFB9); + return false; + } + if (CollectionUtils.isNotEmpty(columns) + && new HashSet<>(columns).size() == Constants.HEAD_COLUMNS.size()) { List strangers = - headerNames.stream() + columns.stream() .filter(t -> !Constants.HEAD_COLUMNS.contains(t)) .collect(Collectors.toList()); if (CollectionUtils.isNotEmpty(strangers)) { @@ -154,77 +235,172 @@ private static boolean checkHeader(List headerNames) { return true; } - private static void writeScheme( - String fileName, List headerNames, Stream records, String failedFilePath) + static void writeScheme( + String fileName, List headerNames, Stream records, String failedFileBase) throws IllegalPathException { + // Look the columns up in the same normalised names the format probe saw. + List columns = normalizeHeaderNames(headerNames); + boolean v2 = isV2Format(columns); + int tagsIndex = columns.indexOf(Constants.HEADER_TAGS); + int attributesIndex = columns.indexOf(Constants.HEADER_ATTRIBUTES); List paths = new ArrayList<>(); List dataTypes = new ArrayList<>(); List encodings = new ArrayList<>(); List compressors = new ArrayList<>(); + List> tags = v2 ? new ArrayList<>() : null; + List> attributes = v2 ? new ArrayList<>() : null; List pathsWithAlias = new ArrayList<>(); List dataTypesWithAlias = new ArrayList<>(); List encodingsWithAlias = new ArrayList<>(); List compressorsWithAlias = new ArrayList<>(); List measurementAlias = new ArrayList<>(); + List> tagsWithAlias = v2 ? new ArrayList<>() : null; + List> attributesWithAlias = v2 ? new ArrayList<>() : null; AtomicReference hasStarted = new AtomicReference<>(false); + AtomicReference connectionFailures = new AtomicReference<>(); AtomicInteger pointSize = new AtomicInteger(0); ArrayList> failedRecords = new ArrayList<>(); records.forEach( recordObj -> { - boolean failed = false; if (!aligned) { if (Boolean.FALSE.equals(hasStarted.get())) { hasStarted.set(true); } else if (pointSize.get() >= batchPointSize) { try { if (CollectionUtils.isNotEmpty(paths)) { - writeAndEmptyDataSet( - paths, dataTypes, encodings, compressors, null, null, null, null, 3); + String failure = + writeAndEmptyDataSet( + paths, + dataTypes, + encodings, + compressors, + null, + tags, + attributes, + null, + 3); + if (failure != null) { + connectionFailures.compareAndSet(null, failure); + recordBatchFailure( + failedRecords, + paths, + null, + dataTypes, + encodings, + compressors, + tags, + attributes); + } } } catch (Exception e) { - paths.forEach(t -> failedRecords.add(Collections.singletonList(t))); + recordBatchFailure( + failedRecords, + paths, + null, + dataTypes, + encodings, + compressors, + tags, + attributes); } try { if (CollectionUtils.isNotEmpty(pathsWithAlias)) { - writeAndEmptyDataSet( - pathsWithAlias, - dataTypesWithAlias, - encodingsWithAlias, - compressorsWithAlias, - null, - null, - null, - measurementAlias, - 3); + String failure = + writeAndEmptyDataSet( + pathsWithAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + null, + tagsWithAlias, + attributesWithAlias, + measurementAlias, + 3); + if (failure != null) { + connectionFailures.compareAndSet(null, failure); + recordBatchFailure( + failedRecords, + pathsWithAlias, + measurementAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + tagsWithAlias, + attributesWithAlias); + } } } catch (Exception e) { - paths.forEach(t -> failedRecords.add(Collections.singletonList(t))); + recordBatchFailure( + failedRecords, + pathsWithAlias, + measurementAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + tagsWithAlias, + attributesWithAlias); } paths.clear(); dataTypes.clear(); encodings.clear(); compressors.clear(); + pathsWithAlias.clear(); + dataTypesWithAlias.clear(); + encodingsWithAlias.clear(); + compressorsWithAlias.clear(); measurementAlias.clear(); + if (v2) { + tags.clear(); + attributes.clear(); + tagsWithAlias.clear(); + attributesWithAlias.clear(); + } pointSize.set(0); } } else { + hasStarted.set(true); paths.clear(); dataTypes.clear(); encodings.clear(); compressors.clear(); + pathsWithAlias.clear(); + dataTypesWithAlias.clear(); + encodingsWithAlias.clear(); + compressorsWithAlias.clear(); measurementAlias.clear(); + if (v2) { + tags.clear(); + attributes.clear(); + tagsWithAlias.clear(); + attributesWithAlias.clear(); + } } - String path = recordObj.get(headerNames.indexOf(Constants.HEAD_COLUMNS.get(0))); - String alias = recordObj.get(headerNames.indexOf(Constants.HEAD_COLUMNS.get(1))); - String dataTypeRaw = recordObj.get(headerNames.indexOf(Constants.HEAD_COLUMNS.get(2))); + String path = recordObj.get(columns.indexOf(Constants.HEAD_COLUMNS.get(0))); + String alias = recordObj.get(columns.indexOf(Constants.HEAD_COLUMNS.get(1))); + String dataTypeRaw = recordObj.get(columns.indexOf(Constants.HEAD_COLUMNS.get(2))); TSDataType dataType = typeInfer(dataTypeRaw); - String encodingTypeRaw = - recordObj.get(headerNames.indexOf(Constants.HEAD_COLUMNS.get(3))); + String encodingTypeRaw = recordObj.get(columns.indexOf(Constants.HEAD_COLUMNS.get(3))); TSEncoding encodingType = encodingInfer(encodingTypeRaw); - String compressionTypeRaw = - recordObj.get(headerNames.indexOf(Constants.HEAD_COLUMNS.get(4))); + String compressionTypeRaw = recordObj.get(columns.indexOf(Constants.HEAD_COLUMNS.get(4))); CompressionType compressionType = compressInfer(compressionTypeRaw); + Map recordTags = null; + Map recordAttributes = null; + boolean tagsParsed = true; + if (v2) { + try { + recordTags = parseJsonCell(recordObj.get(tagsIndex)); + } catch (RuntimeException e) { + ioTPrinter.println(invalidJsonMessage(Constants.HEADER_TAGS, path, e)); + tagsParsed = false; + } + try { + recordAttributes = parseJsonCell(recordObj.get(attributesIndex)); + } catch (RuntimeException e) { + ioTPrinter.println(invalidJsonMessage(Constants.HEADER_ATTRIBUTES, path, e)); + tagsParsed = false; + } + } if (StringUtils.isBlank(path) || path.trim().startsWith(SYSTEM_DATABASE) || path.trim().startsWith(AUDIT_DATABASE)) { @@ -234,8 +410,7 @@ private static void writeScheme( recordObj.getRecordNumber(), headerNames, path)); - failedRecords.add(recordObj.stream().collect(Collectors.toList())); - failed = true; + failedRecords.add(failedRow(recordObj, columns)); } else if (ObjectUtils.isEmpty(dataType)) { ioTPrinter.println( String.format( @@ -243,8 +418,7 @@ private static void writeScheme( recordObj.getRecordNumber(), path, dataTypeRaw)); - failedRecords.add(recordObj.stream().collect(Collectors.toList())); - failed = true; + failedRecords.add(failedRow(recordObj, columns)); } else if (ObjectUtils.isEmpty(encodingType)) { ioTPrinter.println( String.format( @@ -252,8 +426,7 @@ private static void writeScheme( recordObj.getRecordNumber(), path, encodingTypeRaw)); - failedRecords.add(recordObj.stream().collect(Collectors.toList())); - failed = true; + failedRecords.add(failedRow(recordObj, columns)); } else if (ObjectUtils.isEmpty(compressionType)) { ioTPrinter.println( String.format( @@ -261,56 +434,126 @@ private static void writeScheme( recordObj.getRecordNumber(), path, compressionTypeRaw)); - failedRecords.add(recordObj.stream().collect(Collectors.toList())); - failed = true; + failedRecords.add(failedRow(recordObj, columns)); + } else if (!tagsParsed) { + failedRecords.add(failedRow(recordObj, columns)); + } else if (aligned) { + MeasurementPath timeseries; + try { + timeseries = new MeasurementPath(path); + } catch (IllegalPathException | IllegalArgumentException e) { + ioTPrinter.println( + String.format( + CliMessages.MESSAGE_LINE_ARG_COLUMN_ARG_ILLEGAL_PATH_ARG_D5C1EBD6, + recordObj.getRecordNumber(), + headerNames, + path)); + failedRecords.add(failedRow(recordObj, columns)); + return; + } + paths.add(timeseries.getMeasurement()); + dataTypes.add(dataType); + encodings.add(encodingType); + compressors.add(compressionType); + measurementAlias.add(StringUtils.isBlank(alias) ? null : alias); + if (v2) { + tags.add(recordTags); + attributes.add(recordAttributes); + } + String failure = + writeAndEmptyDataSetAligned( + timeseries.getDevicePath().getFullPath(), + paths, + dataTypes, + encodings, + compressors, + measurementAlias, + tags, + attributes, + failedRecords, + 3); + if (failure != null) { + connectionFailures.compareAndSet(null, failure); + } } else { if (StringUtils.isBlank(alias)) { paths.add(path); dataTypes.add(dataType); encodings.add(encodingType); compressors.add(compressionType); + if (v2) { + tags.add(recordTags); + attributes.add(recordAttributes); + } } else { pathsWithAlias.add(path); dataTypesWithAlias.add(dataType); encodingsWithAlias.add(encodingType); compressorsWithAlias.add(compressionType); measurementAlias.add(alias); + if (v2) { + tagsWithAlias.add(recordTags); + attributesWithAlias.add(recordAttributes); + } } pointSize.getAndIncrement(); } - if (!failed && aligned) { - String deviceId = path.substring(0, path.lastIndexOf(".")); - paths.add(0, path.substring(deviceId.length() + 1)); - writeAndEmptyDataSetAligned( - deviceId, paths, dataTypes, encodings, compressors, measurementAlias, 3); - } }); try { if (CollectionUtils.isNotEmpty(paths)) { - writeAndEmptyDataSet(paths, dataTypes, encodings, compressors, null, null, null, null, 3); + String failure = + writeAndEmptyDataSet( + paths, dataTypes, encodings, compressors, null, tags, attributes, null, 3); + if (failure != null) { + connectionFailures.compareAndSet(null, failure); + recordBatchFailure( + failedRecords, paths, null, dataTypes, encodings, compressors, tags, attributes); + } } } catch (Exception e) { - paths.forEach(t -> failedRecords.add(Collections.singletonList(t))); + recordBatchFailure( + failedRecords, paths, null, dataTypes, encodings, compressors, tags, attributes); } try { if (CollectionUtils.isNotEmpty(pathsWithAlias)) { - writeAndEmptyDataSet( - pathsWithAlias, - dataTypesWithAlias, - encodingsWithAlias, - compressorsWithAlias, - null, - null, - null, - measurementAlias, - 3); + String failure = + writeAndEmptyDataSet( + pathsWithAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + null, + tagsWithAlias, + attributesWithAlias, + measurementAlias, + 3); + if (failure != null) { + connectionFailures.compareAndSet(null, failure); + recordBatchFailure( + failedRecords, + pathsWithAlias, + measurementAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + tagsWithAlias, + attributesWithAlias); + } } } catch (Exception e) { - pathsWithAlias.forEach(t -> failedRecords.add(Collections.singletonList(t))); + recordBatchFailure( + failedRecords, + pathsWithAlias, + measurementAlias, + dataTypesWithAlias, + encodingsWithAlias, + compressorsWithAlias, + tagsWithAlias, + attributesWithAlias); } pointSize.set(0); if (!failedRecords.isEmpty()) { - writeFailedLinesFile(failedFilePath, failedRecords); + writeFailedLinesFile(failedFileBase, columns, failedRecords); } if (Boolean.TRUE.equals(hasStarted.get())) { if (!failedRecords.isEmpty()) { @@ -327,9 +570,20 @@ private static void writeScheme( ioTPrinter.println( String.format(CliMessages.MESSAGE_ARG_NO_RECORDS_5672039C, String.valueOf(fileName))); } + if (connectionFailures.get() != null) { + // The failed rows are already in the failed-record file; surface the error so that the + // command exits with a non-zero status instead of reporting success. + throw new ConnectionRetriesExhaustedException(connectionFailures.get()); + } } - private static void writeAndEmptyDataSet( + /** + * Creates one batch of time series. + * + * @return {@code null} on success, otherwise the message describing why the connection retries + * were exhausted + */ + private static String writeAndEmptyDataSet( List paths, List dataTypes, List encodings, @@ -350,9 +604,10 @@ private static void writeAndEmptyDataSet( tagsList, attributesList, measurementAliasList); + return null; } catch (IoTDBConnectionException e) { if (retryTime > 0) { - writeAndEmptyDataSet( + return writeAndEmptyDataSet( paths, dataTypes, encodings, @@ -363,36 +618,197 @@ private static void writeAndEmptyDataSet( measurementAliasList, --retryTime); } + return String.format( + CliMessages + .EXCEPTION_FAILED_TO_CREATE_ARG_BECAUSE_THE_CONNECTION_COULD_NOT_BE_RE_ESTABLISHED_ARG_3956569A, + paths.isEmpty() ? "" : paths.get(0), + String.valueOf(e.getMessage())); } catch (StatementExecutionException e) { throw e; } } - private static void writeAndEmptyDataSetAligned( + /** + * Records the whole row of every measurement of a rejected aligned batch. Must run before the + * caller's finally block empties the batch lists. + */ + private static void recordAlignedBatchFailure( + List> failedRecords, + String deviceId, + List measurements, + List measurementAliasList, + List dataTypes, + List encodings, + List compressors, + List> tagsList, + List> attributesList) { + List fullPaths = new ArrayList<>(measurements.size()); + for (String measurement : measurements) { + fullPaths.add(deviceId + "." + measurement); + } + recordBatchFailure( + failedRecords, + fullPaths, + measurementAliasList, + dataTypes, + encodings, + compressors, + tagsList, + attributesList); + } + + /** Records one canonical row per rejected record so the failed file can retry them. */ + private static void recordBatchFailure( + List> failedRecords, + List failedPaths, + List aliases, + List dataTypes, + List encodings, + List compressors, + List> tagsList, + List> attributesList) { + for (int i = 0; i < failedPaths.size(); i++) { + failedRecords.add( + failedRow( + failedPaths.get(i), + item(aliases, i), + item(dataTypes, i), + item(encodings, i), + item(compressors, i), + item(tagsList, i), + item(attributesList, i))); + } + } + + /** + * Builds the canonical row of a rejected record. Every failed row is kept in the column order of + * {@link Constants#HEAD_COLUMNS_V2} and is only projected onto the columns of the imported file + * when the failed file is written, so rows rejected by different stages end up in one layout. + */ + private static List failedRow( + String path, + String alias, + TSDataType dataType, + TSEncoding encoding, + CompressionType compressionType, + Map tags, + Map attributes) { + List row = new ArrayList<>(Constants.HEAD_COLUMNS_V2.size()); + row.add(path == null ? "" : path); + row.add(alias == null ? "" : alias); + row.add(ObjectUtils.isEmpty(dataType) ? "" : dataType.name()); + row.add(ObjectUtils.isEmpty(encoding) ? "" : encoding.name()); + row.add(ObjectUtils.isEmpty(compressionType) ? "" : compressionType.name()); + row.add(toJsonCell(tags)); + row.add(toJsonCell(attributes)); + return row; + } + + /** + * Converts a record rejected by the CSV validation into the canonical failed row. Every cell is + * copied verbatim, because a rejected JSON cell has to be retried exactly as it was read. + */ + private static List failedRow(CSVRecord record, List columns) { + List row = new ArrayList<>(Constants.HEAD_COLUMNS_V2.size()); + for (String column : Constants.HEAD_COLUMNS_V2) { + int index = columns.indexOf(column); + row.add(index >= 0 && index < record.size() ? record.get(index) : ""); + } + return row; + } + + /** Reads the value a batch list holds for one position, {@code null} when it holds none. */ + private static T item(List values, int index) { + return values != null && index < values.size() ? values.get(index) : null; + } + + private static boolean allNull(List values) { + if (values == null) { + return true; + } + for (Object value : values) { + if (value != null) { + return false; + } + } + return true; + } + + private static String writeAndEmptyDataSetAligned( String deviceId, List measurements, List dataTypes, List encodings, List compressors, List measurementAliasList, + List> tagsList, + List> attributesList, + List> failedRecords, int retryTime) { try { - sessionPool.createAlignedTimeseries( - deviceId, measurements, dataTypes, encodings, compressors, measurementAliasList); + // An all-null metadata list still makes the server write a tag log record per row, so the + // metadata parameters are omitted entirely when the row carries neither tags nor attributes. + if (allNull(tagsList) && allNull(attributesList)) { + sessionPool.createAlignedTimeseries( + deviceId, measurements, dataTypes, encodings, compressors, measurementAliasList); + } else { + sessionPool.createAlignedTimeseries( + deviceId, + measurements, + dataTypes, + encodings, + compressors, + measurementAliasList, + tagsList, + attributesList); + } + return null; } catch (IoTDBConnectionException e) { if (retryTime > 0) { - writeAndEmptyDataSetAligned( + return writeAndEmptyDataSetAligned( deviceId, measurements, dataTypes, encodings, compressors, measurementAliasList, + tagsList, + attributesList, + failedRecords, --retryTime); } + // Keep the whole row of every measurement before the finally block empties the batch, so the + // failed file can retry them. + recordAlignedBatchFailure( + failedRecords, + deviceId, + measurements, + measurementAliasList, + dataTypes, + encodings, + compressors, + tagsList, + attributesList); + return String.format( + CliMessages + .EXCEPTION_FAILED_TO_CREATE_ARG_BECAUSE_THE_CONNECTION_COULD_NOT_BE_RE_ESTABLISHED_ARG_3956569A, + deviceId, + String.valueOf(e.getMessage())); } catch (StatementExecutionException e) { + // The server rejected the batch: keep the rows for a retry and let this file finish, so the + // remaining records are still imported and the entry point reports the failure at the end. ioTPrinter.println(Constants.INSERT_CSV_MEET_ERROR_MSG + e.getMessage()); - System.exit(1); + recordAlignedBatchFailure( + failedRecords, + deviceId, + measurements, + measurementAliasList, + dataTypes, + encodings, + compressors, + tagsList, + attributesList); + return Constants.INSERT_CSV_MEET_ERROR_MSG + e.getMessage(); } finally { deviceId = null; measurements.clear(); @@ -400,9 +816,24 @@ private static void writeAndEmptyDataSetAligned( encodings.clear(); compressors.clear(); measurementAliasList.clear(); + if (tagsList != null) { + tagsList.clear(); + } + if (attributesList != null) { + attributesList.clear(); + } } } + private static String invalidJsonMessage(String column, String path, Exception e) { + return String.format( + CliMessages + .MESSAGE_FAILED_TO_PARSE_THE_ARG_COLUMN_OF_TIMESERIES_ARG_AS_JSON_THE_RECORD_IS_SKIPPED_ARG_35D898C8, + column, + path, + String.valueOf(e.getMessage())); + } + private static TSDataType typeInfer(String typeStr) { try { if (StringUtils.isNotBlank(typeStr)) { @@ -436,17 +867,66 @@ private static TSEncoding encodingInfer(String encodingType) { return null; } + /** + * Raised by {@link #writeScheme} after the rows hit by exhausted connection retries are saved. + */ + static class ConnectionRetriesExhaustedException extends IllegalStateException { + ConnectionRetriesExhaustedException(String message) { + super(message); + } + } + + /** + * The path of the failed-record files of a source file without their chunk index and csv suffix: + * the source keeps its name but loses the csv suffix, so the chunks end in {@code .csv} and can + * be imported again through this tool without being renamed first. + */ + static String failedFileBaseName(String sourcePath) { + String csvSuffix = "." + Constants.CSV_SUFFIXS; + return sourcePath.endsWith(csvSuffix) + ? sourcePath.substring(0, sourcePath.length() - csvSuffix.length()) + : sourcePath; + } + + /** + * Writes the canonical failed rows into files of {@link #linesPerFailedFile} rows. Every file + * starts with the column names it is written with and the rows follow that order, so a file can + * be imported again as it is, also when the header of the imported file was not in the canonical + * order or did not carry the Tags and Attributes columns at all. The dialect follows the columns + * written: a file without Tags and Attributes columns is read back with the legacy dialect, so it + * has to be written with it, otherwise an escaped comma inside a path would shift the cells that + * follow it. + */ private static void writeFailedLinesFile( - String failedFilePath, ArrayList> failedRecords) { + String failedFileBase, List columns, List> failedRecords) { + boolean legacy = !isV2Format(columns); int fileIndex = 0; int from = 0; int failedRecordsSize = failedRecords.size(); int restFailedRecords = failedRecordsSize; while (from < failedRecordsSize) { int step = Math.min(restFailedRecords, linesPerFailedFile); - writeCsvFile(failedRecords.subList(from, from + step), failedFilePath + "_" + fileIndex++); + List> failureFileRecords = new ArrayList<>(step + 1); + failureFileRecords.add(new ArrayList<>(columns)); + for (List failedRow : failedRecords.subList(from, from + step)) { + failureFileRecords.add(projectFailedRow(failedRow, columns)); + } + writeCsvFile( + failureFileRecords, + failedFileBase + ".failed_" + fileIndex++ + "." + Constants.CSV_SUFFIXS, + legacy); from += step; restFailedRecords -= step; } } + + /** Projects a canonical failed row onto the columns the failed file is written with. */ + private static List projectFailedRow(List failedRow, List columns) { + List row = new ArrayList<>(columns.size()); + for (String column : columns) { + int index = Constants.HEAD_COLUMNS_V2.indexOf(column); + row.add(index >= 0 && index < failedRow.size() ? failedRow.get(index) : ""); + } + return row; + } } diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsFidelityTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsFidelityTest.java new file mode 100644 index 0000000000000..4aade0d00b368 --- /dev/null +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsFidelityTest.java @@ -0,0 +1,453 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.tool.schema; + +import org.apache.iotdb.tool.common.Constants; + +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVRecord; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.read.common.Field; +import org.apache.tsfile.utils.Binary; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; + +/** Guards the lossless Tags / Attributes round trip of the tree model schema tools. */ +public class SchemaTagsFidelityTest { + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @Test + public void jsonCellSortsKeysAndKeepsPrintableCharactersReadable() { + Map tags = new LinkedHashMap<>(); + tags.put("type", "sensor"); + tags.put("room", "101"); + tags.put("a-b", "it's = & w"); + + assertEquals( + "{\"a-b\":\"it's = & w\",\"room\":\"101\",\"type\":\"sensor\"}", + AbstractSchemaTool.toJsonCell(tags)); + } + + @Test + public void jsonCellEscapesOnlyWhatJsonRequires() { + Map tags = new LinkedHashMap<>(); + tags.put("quote", "a\"b"); + tags.put("backslash", "a\\b"); + tags.put("tab", "a\tb"); + tags.put("newline", "a\nb"); + tags.put("comma", "a,b"); + tags.put("cjk", "中文😀"); + tags.put("backtick", "`x`"); + tags.put("null", "null"); + tags.put("empty", ""); + + assertEquals( + "{\"backslash\":\"a\\\\b\",\"backtick\":\"`x`\",\"cjk\":\"中文😀\",\"comma\":\"a,b\"," + + "\"empty\":\"\",\"newline\":\"a\\nb\",\"null\":\"null\",\"quote\":\"a\\\"b\"," + + "\"tab\":\"a\\tb\"}", + AbstractSchemaTool.toJsonCell(tags)); + } + + @Test + public void jsonCellOfMissingValuesIsAnEmptyCell() { + assertEquals("", AbstractSchemaTool.toJsonCell(null)); + assertEquals("", AbstractSchemaTool.toJsonCell(new LinkedHashMap<>())); + } + + @Test + public void jsonCellRoundTripsEveryCharacter() { + Map tags = new LinkedHashMap<>(); + tags.put("quote", "a\"b"); + tags.put("backslash", "a\\b"); + tags.put("tab", "a\tb"); + tags.put("newline", "a\nb"); + tags.put("comma", "a,b"); + tags.put("cjk", "中文😀"); + tags.put("backtick", "`x`"); + tags.put("null", "null"); + tags.put("empty", ""); + tags.put("key with space", "[ C ]"); + + assertEquals(tags, AbstractSchemaTool.parseJsonCell(AbstractSchemaTool.toJsonCell(tags))); + } + + @Test + public void jsonCellOfNothingParsesToNoValue() { + assertNull(AbstractSchemaTool.parseJsonCell(null)); + assertNull(AbstractSchemaTool.parseJsonCell("")); + assertNull(AbstractSchemaTool.parseJsonCell(" ")); + assertNull(AbstractSchemaTool.parseJsonCell("null")); + assertNull(AbstractSchemaTool.parseJsonCell("{}")); + } + + @Test + public void invalidJsonCellIsRejected() { + for (String cell : + Arrays.asList( + "not json", + "[1,2]", + "\"abc\"", + "{\"k\":\"v\"} trailing", + "{\"room\":null}", + "{\"room\":101}", + "{\"room\":true}", + "{\"room\":[]}", + "{\"room\":{}}", + "{\"room\":\"101\",\"room\":\"102\"}")) { + try { + AbstractSchemaTool.parseJsonCell(cell); + throw new AssertionError("expected a parse failure for " + cell); + } catch (RuntimeException expected) { + // the export reports this and skips the record + } + } + } + + /** + * The metadata cells must be JSON: a raw control character or an invalid escape is outside of the + * syntax even though the bundled reader accepted both before it was switched to + * Strictness.STRICT. + */ + @Test + public void jsonSyntaxIsStrictlyEnforced() { + assertThrows( + "a raw tab inside a string is not JSON", + IllegalArgumentException.class, + () -> AbstractSchemaTool.parseJsonCell("{\"room\":\"a\tb\"}")); + assertThrows( + "the escape \\' is not JSON", + IllegalArgumentException.class, + () -> AbstractSchemaTool.parseJsonCell("{\"room\":\"it\\'s\"}")); + assertEquals( + Collections.singletonMap("room", "a\tb"), + AbstractSchemaTool.parseJsonCell("{\"room\":\"a\\tb\"}")); + assertEquals( + Collections.singletonMap("room", "it's"), + AbstractSchemaTool.parseJsonCell("{\"room\":\"it's\"}")); + } + + @Test + public void csvRoundTripKeepsEveryFieldByteIdentical() throws IOException { + Map tags = new LinkedHashMap<>(); + tags.put("quote", "a\"b"); + tags.put("backslash", "a\\b"); + tags.put("comma", "a,b"); + tags.put("tab", "a\tb"); + tags.put("newline", "a\nb"); + Map attributes = new LinkedHashMap<>(); + attributes.put("owner", "team a"); + attributes.put("note", "q\"w\\e,r\ty\nz"); + + List row = + Arrays.asList( + "root.t.d1.s1", + "aliasA", + "INT64", + "TS_2DIFF", + "SNAPPY", + AbstractSchemaTool.toJsonCell(tags), + AbstractSchemaTool.toJsonCell(attributes)); + File csv = writeV2File("roundtrip.csv", row); + + CSVParser parser = ImportSchemaTree.readCsvFile(csv.getAbsolutePath()); + List records = parser.getRecords(); + assertEquals(1, records.size()); + CSVRecord record = records.get(0); + for (int i = 0; i < row.size(); i++) { + assertEquals(row.get(i), record.get(Constants.HEAD_COLUMNS_V2.get(i))); + } + assertEquals(tags, AbstractSchemaTool.parseJsonCell(record.get(Constants.HEADER_TAGS))); + assertEquals( + attributes, AbstractSchemaTool.parseJsonCell(record.get(Constants.HEADER_ATTRIBUTES))); + } + + @Test + public void emptyTagsAndAttributesAreWrittenAsEmptyCells() throws IOException { + File csv = + writeV2File( + "empty.csv", Arrays.asList("root.t.d1.s1", "", "INT64", "TS_2DIFF", "SNAPPY", "", "")); + + assertEquals( + "Timeseries,Alias,DataType,Encoding,Compression,Tags,Attributes\n" + + "root.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,,\n", + new String(Files.readAllBytes(csv.toPath()), StandardCharsets.UTF_8)); + CSVRecord record = ImportSchemaTree.readCsvFile(csv.getAbsolutePath()).getRecords().get(0); + assertNull(AbstractSchemaTool.parseJsonCell(record.get(Constants.HEADER_TAGS))); + assertNull(AbstractSchemaTool.parseJsonCell(record.get(Constants.HEADER_ATTRIBUTES))); + } + + @Test + public void jsonCellsAreRfc4180Quoted() throws IOException { + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + tags.put("type", "sensor"); + File csv = + writeV2File( + "quoted.csv", + Arrays.asList( + "root.t.d1.s1", + "", + "INT64", + "TS_2DIFF", + "SNAPPY", + AbstractSchemaTool.toJsonCell(tags), + "")); + + assertEquals( + "Timeseries,Alias,DataType,Encoding,Compression,Tags,Attributes\n" + + "root.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,\"{\"\"room\"\":\"\"101\"\"," + + "\"\"type\"\":\"\"sensor\"\"}\",\n", + new String(Files.readAllBytes(csv.toPath()), StandardCharsets.UTF_8)); + } + + @Test + public void csvIsWrittenAsUtf8RegardlessOfThePlatformDefault() throws IOException { + Map tags = new LinkedHashMap<>(); + tags.put("cn", "中文😀"); + File csv = + writeV2File( + "utf8-written.csv", + Arrays.asList( + "root.t.d1.s1", + "", + "INT64", + "TS_2DIFF", + "SNAPPY", + AbstractSchemaTool.toJsonCell(tags), + "")); + + // RFC4180: the cell holds a JSON object, so it is quoted and its inner quotes are doubled. + String expected = + String.join(",", Constants.HEAD_COLUMNS_V2) + + "\n" + + "root.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\n"; + assertEquals( + "the schema CSV must be written as UTF-8", + expected, + new String(Files.readAllBytes(csv.toPath()), StandardCharsets.UTF_8)); + } + + @Test + public void csvIsParsedAsUtf8RegardlessOfThePlatformDefault() throws IOException { + Map tags = new LinkedHashMap<>(); + tags.put("cn", "中文😀"); + String content = + String.join(",", Constants.HEAD_COLUMNS_V2) + + "\n" + + "root.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\n"; + // Written as UTF-8 bytes directly, so only the reader's charset can change the outcome. + File csv = temporaryFolder.newFile("utf8-read.csv"); + Files.write(csv.toPath(), content.getBytes(StandardCharsets.UTF_8)); + + assertEquals( + Constants.HEAD_COLUMNS_V2, ImportSchemaTree.readHeaderNames(csv.getAbsolutePath())); + CSVRecord record = ImportSchemaTree.readCsvFile(csv.getAbsolutePath()).getRecords().get(0); + assertEquals(tags, AbstractSchemaTool.parseJsonCell(record.get(Constants.HEADER_TAGS))); + } + + @Test + public void legacyFiveColumnHeaderSelectsTheLegacyPath() { + assertFalse(ImportSchemaTree.isV2Format(Constants.HEAD_COLUMNS)); + assertTrue(ImportSchemaTree.isV2Format(Constants.HEAD_COLUMNS_V2)); + } + + @Test + public void quotedHeaderStillSelectsTheV2Path() throws IOException { + File csv = temporaryFolder.newFile("quoted_header.csv"); + Files.write( + csv.toPath(), + ("\"Timeseries\",\"Alias\",\"DataType\",\"Encoding\",\"Compression\",\"Tags\"," + + "\"Attributes\"\nroot.t.d1.s1,,INT64,TS_2DIFF,SNAPPY,,\n") + .getBytes(StandardCharsets.UTF_8)); + + assertTrue( + ImportSchemaTree.isV2Format(ImportSchemaTree.readHeaderNames(csv.getAbsolutePath()))); + } + + @Test + public void v2HeaderDetectionAndParsingSkipEmptyLinesAndBom() throws IOException { + for (String prefix : Arrays.asList("\n", "\r\n\r\n", "\uFEFF", "\uFEFF\r\n\r\n")) { + for (boolean quotedHeader : Arrays.asList(false, true)) { + File csv = temporaryFolder.newFile(); + String header = + quotedHeader + ? "\"" + String.join("\",\"", Constants.HEAD_COLUMNS_V2) + "\"" + : String.join(",", Constants.HEAD_COLUMNS_V2); + Files.write( + csv.toPath(), + (prefix + + header + + "\r\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY," + + "\"{\"\"room\"\":\"\"a,b\"\"}\",\r\n") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals( + Constants.HEAD_COLUMNS_V2, ImportSchemaTree.readHeaderNames(csv.getAbsolutePath())); + try (CSVParser parser = ImportSchemaTree.readCsvFile(csv.getAbsolutePath())) { + assertEquals(Constants.HEAD_COLUMNS_V2, parser.getHeaderNames()); + assertTrue(ImportSchemaTree.checkHeader(parser.getHeaderNames())); + List records = parser.getRecords(); + assertEquals(1, records.size()); + assertEquals(7, records.get(0).size()); + assertEquals("{\"room\":\"a,b\"}", records.get(0).get(Constants.HEADER_TAGS)); + } + } + } + } + + @Test + public void legacyHeaderHandlingPreservesBackticksAndBackslashEscapes() throws IOException { + File csv = temporaryFolder.newFile(); + Files.write( + csv.toPath(), + ("\uFEFF\n\nTimeseries,Alias,DataType,Encoding,Compression\n" + + "`root.sg.d.s1`,a\\,b,INT64,TS_2DIFF,SNAPPY\n") + .getBytes(StandardCharsets.UTF_8)); + + assertEquals(Constants.HEAD_COLUMNS, ImportSchemaTree.readHeaderNames(csv.getAbsolutePath())); + try (CSVParser parser = ImportSchemaTree.readCsvFile(csv.getAbsolutePath())) { + assertEquals(Constants.HEAD_COLUMNS, parser.getHeaderNames()); + CSVRecord record = parser.getRecords().get(0); + assertEquals(5, record.size()); + assertEquals("root.sg.d.s1", record.get(Constants.HEADER_TIMESERIES)); + assertEquals("a,b", record.get(Constants.HEADER_ALIAS)); + } + } + + @Test + public void legacyFileKeepsItsBackslashEscapes() throws IOException { + File csv = temporaryFolder.newFile("legacy.csv"); + Files.write( + csv.toPath(), + ("Timeseries,Alias,DataType,Encoding,Compression\n" + + "root.sg.d.s1,a\\,b,INT64,TS_2DIFF,SNAPPY\n") + .getBytes(StandardCharsets.UTF_8)); + + CSVRecord record = ImportSchemaTree.readCsvFile(csv.getAbsolutePath()).getRecords().get(0); + assertEquals(5, record.size()); + assertEquals("a,b", record.get(Constants.HEADER_ALIAS)); + } + + @Test + public void exportedRecordCarriesTagsAndAttributes() throws IOException { + File csv = temporaryFolder.newFile("export.csv"); + AbstractSchemaTool.CSVPrinterWrapper printer = + new AbstractSchemaTool.CSVPrinterWrapper(csv.getAbsolutePath()); + printer.printRecord(Constants.HEAD_COLUMNS_V2); + + List headers = + Arrays.asList( + Constants.HEADER_TIMESERIES, + Constants.HEADER_ALIAS, + "Database", + Constants.HEADER_DATATYPE, + Constants.HEADER_ENCODING, + Constants.HEADER_COMPRESSION, + Constants.HEADER_TAGS, + Constants.HEADER_ATTRIBUTES, + Constants.HEADER_VIEW_TYPE); + List fields = + Arrays.asList( + text("root.t.d1.s1"), + emptyField(), + text("root.t"), + text("INT64"), + text("TS_2DIFF"), + text("SNAPPY"), + text("{\"room\": \"101\", \"type\": \"sensor\"}"), + emptyField(), + text(Constants.BASE_VIEW_TYPE)); + assertTrue(ExportSchemaTree.printRecord(printer, headers, fields, "root.t.d1.s1")); + printer.println(); + printer.close(); + + CSVRecord record = ImportSchemaTree.readCsvFile(csv.getAbsolutePath()).getRecords().get(0); + assertEquals("root.t.d1.s1", record.get(Constants.HEADER_TIMESERIES)); + assertEquals("", record.get(Constants.HEADER_ALIAS)); + assertEquals("INT64", record.get(Constants.HEADER_DATATYPE)); + assertEquals("TS_2DIFF", record.get(Constants.HEADER_ENCODING)); + assertEquals("SNAPPY", record.get(Constants.HEADER_COMPRESSION)); + assertEquals("{\"room\":\"101\",\"type\":\"sensor\"}", record.get(Constants.HEADER_TAGS)); + assertEquals("", record.get(Constants.HEADER_ATTRIBUTES)); + } + + @Test + public void exportedRecordWithBrokenJsonIsSkipped() throws IOException { + File csv = temporaryFolder.newFile("broken.csv"); + AbstractSchemaTool.CSVPrinterWrapper printer = + new AbstractSchemaTool.CSVPrinterWrapper(csv.getAbsolutePath()); + List headers = + Arrays.asList( + Constants.HEADER_TIMESERIES, Constants.HEADER_TAGS, Constants.HEADER_ATTRIBUTES); + List fields = Arrays.asList(text("root.t.d1.s1"), text("not json"), emptyField()); + + assertFalse(ExportSchemaTree.printRecord(printer, headers, fields, "root.t.d1.s1")); + printer.close(); + assertEquals(0, csv.length()); + } + + /** + * Writes a v2 file with the writer of the schema tools so that the reader is exercised against + * the bytes the export really produces. + */ + private File writeV2File(String name, List row) throws IOException { + File csv = temporaryFolder.newFile(name); + AbstractSchemaTool.CSVPrinterWrapper printer = + new AbstractSchemaTool.CSVPrinterWrapper(csv.getAbsolutePath()); + printer.printRecord(Constants.HEAD_COLUMNS_V2); + row.forEach(printer::print); + printer.println(); + printer.close(); + return csv; + } + + private static Field text(String value) { + Field field = new Field(TSDataType.TEXT); + field.setBinaryV(new Binary(value, StandardCharsets.UTF_8)); + return field; + } + + /** The shape SHOW TIMESERIES uses for a cell without a value. */ + private static Field emptyField() { + return new Field(null); + } +} diff --git a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsImportTest.java b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsImportTest.java new file mode 100644 index 0000000000000..f0a88cafd90a4 --- /dev/null +++ b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/SchemaTagsImportTest.java @@ -0,0 +1,952 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.tool.schema; + +import org.apache.iotdb.rpc.IoTDBConnectionException; +import org.apache.iotdb.rpc.StatementExecutionException; +import org.apache.iotdb.session.pool.SessionPool; +import org.apache.iotdb.tool.common.Constants; +import org.apache.iotdb.tool.common.OptionsUtil; + +import org.apache.commons.cli.CommandLine; +import org.apache.commons.cli.DefaultParser; +import org.apache.commons.csv.CSVFormat; +import org.apache.commons.csv.CSVParser; +import org.apache.commons.csv.CSVPrinter; +import org.apache.tsfile.enums.TSDataType; +import org.apache.tsfile.external.commons.collections4.CollectionUtils; +import org.apache.tsfile.file.metadata.enums.CompressionType; +import org.apache.tsfile.file.metadata.enums.TSEncoding; +import org.junit.After; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import java.io.File; +import java.nio.charset.StandardCharsets; +import java.nio.file.Files; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertNull; +import static org.junit.Assert.assertThrows; +import static org.junit.Assert.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; + +/** Checks that the import passes the parsed tags and attributes on to the client API. */ +public class SchemaTagsImportTest { + + @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder(); + + @After + public void reset() { + ImportSchemaTree.sessionPool = null; + ImportSchemaTree.aligned = false; + ImportSchemaTree.batchPointSize = Constants.BATCH_POINT_SIZE; + ImportSchemaTree.failedFileDirectory = null; + AbstractSchemaTool.connectionFailed = false; + } + + @Test + public void alignedOptionIsAcceptedByTheImportSchemaCli() throws Exception { + for (String option : Arrays.asList("-aligned", "--use_aligned")) { + CommandLine commandLine = + new DefaultParser() + .parse( + OptionsUtil.createImportSchemaOptions(), + new String[] {"-s", "schema.csv", option, "true"}); + assertEquals("true", commandLine.getOptionValue(Constants.ALIGNED_ARGS)); + } + } + + @Test + public void legacyFileKeepsTheLegacyCreateCall() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + + runImport( + "Timeseries,Alias,DataType,Encoding,Compression\n" + + "root.sg.d.s1,,INT64,TS_2DIFF,SNAPPY\n" + + "root.sg.d.s2,aliasB,INT64,TS_2DIFF,SNAPPY\n"); + + verify(pool) + .createMultiTimeseries( + Arrays.asList("root.sg.d.s1"), + Arrays.asList(TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY), + null, + null, + null, + null); + verify(pool) + .createMultiTimeseries( + Arrays.asList("root.sg.d.s2"), + Arrays.asList(TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY), + null, + null, + null, + Arrays.asList("aliasB")); + } + + @Test + public void v2FilePassesTagsAndAttributesToCreateMultiTimeseries() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + tags.put("type", "sensor"); + Map attributes = new LinkedHashMap<>(); + attributes.put("owner", "team a"); + + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\"" + + AbstractSchemaTool.toJsonCell(attributes).replace("\"", "\"\"") + + "\"\n" + + "root.sg.d.s2,,INT64,TS_2DIFF,SNAPPY,,\n"); + + verify(pool) + .createMultiTimeseries( + Arrays.asList("root.sg.d.s1", "root.sg.d.s2"), + Arrays.asList(TSDataType.INT64, TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF, TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY, CompressionType.SNAPPY), + null, + Arrays.asList(new LinkedHashMap<>(tags), null), + Arrays.asList(new LinkedHashMap<>(attributes), null), + null); + } + + @Test + public void v2AlignedFilePassesTagsAndAttributesToCreateAlignedTimeseries() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + Map attributes = new LinkedHashMap<>(); + attributes.put("owner", "team a"); + // the aligned writer empties its lists in a finally block, so snapshot the arguments + List alignedCall = new ArrayList<>(); + doAnswer( + call -> { + for (Object argument : call.getArguments()) { + alignedCall.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\"" + + AbstractSchemaTool.toJsonCell(attributes).replace("\"", "\"\"") + + "\"\n"); + + assertEquals( + Arrays.asList( + "root.sg.d", + Arrays.asList("s1"), + Arrays.asList(TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY), + Arrays.asList((String) null), + Arrays.asList(new LinkedHashMap<>(tags)), + Arrays.asList(new LinkedHashMap<>(attributes))), + alignedCall); + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + public void alignedRowsKeepAliasesAndMetadataPairedAcrossDevices() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + List> calls = new ArrayList<>(); + doAnswer( + call -> { + List snapshot = new ArrayList<>(); + for (Object argument : call.getArguments()) { + snapshot.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + calls.add(snapshot); + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + // A row without metadata omits both metadata parameters, so the shorter overload is used. + doAnswer( + call -> { + List snapshot = new ArrayList<>(); + for (Object argument : call.getArguments()) { + snapshot.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + calls.add(snapshot); + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any()); + + runImport( + String.join(",", Constants.HEAD_COLUMNS_V2) + + "\nroot.sg.d.s1,alias1,INT64,TS_2DIFF,SNAPPY,\"{\"\"k\"\":\"\"v1\"\"}\",\n" + + "root.sg.d.s2,,TEXT,PLAIN,LZ4,,\"{\"\"k\"\":\"\"v2\"\"}\"\n" + + "root.sg.other.`s.3`,alias3,BOOLEAN,PLAIN,GZIP,,\n"); + + assertEquals( + Arrays.asList( + Arrays.asList( + "root.sg.d", + Collections.singletonList("s1"), + Collections.singletonList(TSDataType.INT64), + Collections.singletonList(TSEncoding.TS_2DIFF), + Collections.singletonList(CompressionType.SNAPPY), + Collections.singletonList("alias1"), + Collections.singletonList(Collections.singletonMap("k", "v1")), + Collections.singletonList(null)), + Arrays.asList( + "root.sg.d", + Collections.singletonList("s2"), + Collections.singletonList(TSDataType.TEXT), + Collections.singletonList(TSEncoding.PLAIN), + Collections.singletonList(CompressionType.LZ4), + Collections.singletonList(null), + Collections.singletonList(null), + Collections.singletonList(Collections.singletonMap("k", "v2"))), + Arrays.asList( + "root.sg.other", + Collections.singletonList("`s.3`"), + Collections.singletonList(TSDataType.BOOLEAN), + Collections.singletonList(TSEncoding.PLAIN), + Collections.singletonList(CompressionType.GZIP), + Collections.singletonList("alias3"))), + calls); + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + public void legacyAlignedImportKeepsTheLegacyApi() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + // Snapshot mutable arguments before the writer clears them. + List callArguments = new ArrayList<>(); + doAnswer( + call -> { + for (Object argument : call.getArguments()) { + callArguments.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any()); + + runImport( + "Timeseries,Alias,DataType,Encoding,Compression\n" + + "root.sg.d.s1,alias1,INT64,TS_2DIFF,SNAPPY\n"); + + assertEquals( + Arrays.asList( + "root.sg.d", + Collections.singletonList("s1"), + Collections.singletonList(TSDataType.INT64), + Collections.singletonList(TSEncoding.TS_2DIFF), + Collections.singletonList(CompressionType.SNAPPY), + Collections.singletonList("alias1")), + callArguments); + verify(pool, never()) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + public void invalidMetadataDoesNotPoisonTheBatchAndIsWrittenToFailedFile() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + File csv = temporaryFolder.newFile("invalid-metadata.csv"); + List> invalidRecords = new ArrayList<>(); + try (CSVPrinter printer = CSVFormat.DEFAULT.print(csv.toPath(), StandardCharsets.UTF_8)) { + printer.printRecord(Constants.HEAD_COLUMNS_V2); + printer.printRecord("root.sg.d.valid1", "", "INT64", "TS_2DIFF", "SNAPPY", "", ""); + for (String invalidValue : Arrays.asList("null", "101", "true", "[]", "{}")) { + for (int column = 5; column <= 6; column++) { + List row = + new ArrayList<>( + Arrays.asList( + "root.sg.d.invalid" + invalidRecords.size(), + "", + "INT64", + "TS_2DIFF", + "SNAPPY", + "", + "")); + row.set(column, "{\"room\":" + invalidValue + "}"); + invalidRecords.add(row); + printer.printRecord(row); + } + } + printer.printRecord("root.sg.d.valid2", "", "TEXT", "PLAIN", "LZ4", "", ""); + } + runImportCsv(csv); + + verify(pool, times(1)) + .createMultiTimeseries( + Arrays.asList("root.sg.d.valid1", "root.sg.d.valid2"), + Arrays.asList(TSDataType.INT64, TSDataType.TEXT), + Arrays.asList(TSEncoding.TS_2DIFF, TSEncoding.PLAIN), + Arrays.asList(CompressionType.SNAPPY, CompressionType.LZ4), + null, + Arrays.asList(null, null), + Arrays.asList(null, null), + null); + List> failedRows = readRows(singleFailedFile(temporaryFolder.getRoot())); + assertEquals(Constants.HEAD_COLUMNS_V2, failedRows.get(0)); + assertEquals(invalidRecords, failedRows.subList(1, failedRows.size())); + } + + @Test + public void v2HeaderWithoutAllColumnsCreatesNothing() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + assertFalse( + ImportSchemaTree.checkHeader( + Arrays.asList("Timeseries", "Alias", "DataType", "Encoding", "Compression", "Tags"))); + + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + public void brokenJsonCellSkipsTheRecord() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,\"{not json}\",\n"); + + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + /** + * Guards the batch-flush boundary: every aliased list must be emptied together, otherwise the + * next batch pairs the aliases still buffered with the wrong paths. + */ + @Test + public void batchedAliasedRecordsKeepAliasTagsAndPathsPaired() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.batchPointSize = 2; + List>> calls = new ArrayList<>(); + doAnswer( + call -> { + List> snapshot = new ArrayList<>(); + for (int i = 0; i < call.getArguments().length; i++) { + List argument = call.getArgument(i); + snapshot.add(argument == null ? null : new ArrayList<>(argument)); + } + calls.add(snapshot); + return null; + }) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + File csv = temporaryFolder.newFile("batch.csv"); + AbstractSchemaTool.CSVPrinterWrapper printer = + new AbstractSchemaTool.CSVPrinterWrapper(csv.getAbsolutePath()); + printer.printRecord(Constants.HEAD_COLUMNS_V2); + for (int i = 1; i <= 5; i++) { + printer.print("root.sg.d.s" + i); + printer.print("alias" + i); + printer.print("INT64"); + printer.print("TS_2DIFF"); + printer.print("SNAPPY"); + printer.print(AbstractSchemaTool.toJsonCell(Collections.singletonMap("k", "v" + i))); + printer.print(""); + printer.println(); + } + printer.close(); + runImportCsv(csv); + + // 3 flushes with batchPointSize 2: [s1,s2], [s3,s4], [s5] + assertEquals(3, calls.size()); + List sentPaths = new ArrayList<>(); + for (List> call : calls) { + List paths = call.get(0); + List dataTypes = call.get(1); + List encodings = call.get(2); + List compressors = call.get(3); + List tags = call.get(5); + List attributes = call.get(6); + List measurementAlias = call.get(7); + assertTrue(CollectionUtils.isNotEmpty(paths)); + // every list that is indexed by the path position must have the same length + for (List parallel : + Arrays.asList(dataTypes, encodings, compressors, tags, attributes, measurementAlias)) { + assertEquals("lists must stay positionally aligned", paths.size(), parallel.size()); + } + for (int i = 0; i < paths.size(); i++) { + String path = (String) paths.get(i); + String seq = path.substring(path.length() - 1); + sentPaths.add(path); + // s must travel with alias and with the tag built from the same n + assertEquals(path, "alias" + seq, measurementAlias.get(i)); + assertEquals("v" + seq, ((Map) tags.get(i)).get("k")); + } + } + assertEquals( + Arrays.asList( + "root.sg.d.s1", "root.sg.d.s2", "root.sg.d.s3", "root.sg.d.s4", "root.sg.d.s5"), + sentPaths); + } + + @Test + public void metadataCellsMustBeStrictJsonObjects() { + assertThrows( + IllegalArgumentException.class, + () -> AbstractSchemaTool.parseJsonCell("[[\"room\",\"101\"]]")); + assertThrows( + IllegalArgumentException.class, () -> AbstractSchemaTool.parseJsonCell("{\"room\":yes}")); + assertThrows( + IllegalArgumentException.class, () -> AbstractSchemaTool.parseJsonCell("{\"room\":101}")); + assertThrows( + IllegalArgumentException.class, + () -> AbstractSchemaTool.parseJsonCell("{\"room\":\"101\"} tail")); + assertEquals( + Collections.singletonMap("room", "101"), + AbstractSchemaTool.parseJsonCell("{\"room\":\"101\"}")); + assertNull(AbstractSchemaTool.parseJsonCell("")); + assertNull(AbstractSchemaTool.parseJsonCell("null")); + } + + @Test + public void duplicateKeyInMetadataCellIsRejected() { + IllegalArgumentException error = + assertThrows( + IllegalArgumentException.class, + () -> AbstractSchemaTool.parseJsonCell("{\"a\":\"1\",\"a\":\"2\"}")); + assertTrue(error.getMessage(), error.getMessage().contains("a")); + } + + @Test + public void paddedHeaderNamesAreStillImportedAsV2() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + + runImport( + " Tags , Attributes ,Timeseries,Alias,DataType,Encoding,Compression\n" + + "\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",,root.sg.d.s1,,INT64,TS_2DIFF,SNAPPY\n"); + + verify(pool) + .createMultiTimeseries( + Arrays.asList("root.sg.d.s1"), + Arrays.asList(TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY), + null, + Arrays.asList(new LinkedHashMap<>(tags)), + Arrays.asList((Map) null), + null); + } + + @Test + public void alignedRowsWithoutMetadataOmitTheMetadataParameters() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + List> calls = new ArrayList<>(); + doAnswer( + call -> { + List snapshot = new ArrayList<>(); + for (Object argument : call.getArguments()) { + snapshot.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + calls.add(snapshot); + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any()); + + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,,\n"); + + assertEquals(1, calls.size()); + assertEquals("both metadata parameters must be omitted: " + calls, 6, calls.get(0).size()); + assertEquals( + Arrays.asList( + "root.sg.d", + Collections.singletonList("s1"), + Arrays.asList(TSDataType.INT64), + Arrays.asList(TSEncoding.TS_2DIFF), + Arrays.asList(CompressionType.SNAPPY), + Arrays.asList((String) null)), + calls.get(0)); + } + + @Test + public void rejectedAliasedBatchIsRecordedWithItsAliasAndMetadata() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.batchPointSize = 2; + doThrow(new StatementExecutionException("rejected")) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,a1,INT64,TS_2DIFF,SNAPPY,,\n" + + "root.sg.d.s2,a2,INT64,TS_2DIFF,SNAPPY,,\n"); + + String failed = readFailedFile(); + assertTrue(failed, failed.contains("root.sg.d.s1")); + assertTrue(failed, failed.contains("root.sg.d.s2")); + assertTrue("the alias must be kept for a retry: " + failed, failed.contains("a1")); + assertTrue("the alias must be kept for a retry: " + failed, failed.contains("a2")); + } + + @Test + public void exhaustedConnectionRetriesFailTheImportAndKeepTheRow() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + doThrow(new IoTDBConnectionException(new IllegalStateException("down"))) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,,\n")); + + assertTrue(error.getMessage(), error.getMessage().contains("could not be re-established")); + String failed = readFailedFile(); + assertTrue(failed, failed.contains("root.sg.d.s1")); + } + + @Test + public void exhaustedAlignedConnectionRetriesFailTheImportAndKeepTheRow() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + doThrow(new IoTDBConnectionException(new IllegalStateException("down"))) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + IllegalStateException error = + assertThrows( + IllegalStateException.class, + () -> + runImport( + Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\n")); + + assertTrue(error.getMessage(), error.getMessage().contains("could not be re-established")); + String failed = readFailedFile(); + assertTrue(failed, failed.contains("root.sg.d.s1")); + } + + /** + * The exhausted retry must survive the per-file handler: {@code run()} swallows every exception, + * so the flag is the only way the entry point learns that it has to exit non-zero. + */ + @Test + public void exhaustedConnectionRetriesMarkTheImportAsFailed() throws Exception { + for (boolean useAligned : new boolean[] {false, true}) { + AbstractSchemaTool.connectionFailed = false; + ImportSchemaTree.aligned = useAligned; + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + IoTDBConnectionException down = + new IoTDBConnectionException(new IllegalStateException("down")); + doThrow(down) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + doThrow(down) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + doThrow(down).when(pool).createAlignedTimeseries(any(), any(), any(), any(), any(), any()); + + File directory = temporaryFolder.newFolder("exhausted_" + useAligned); + File csv = new File(directory, "schema.csv"); + Files.write( + csv.toPath(), + (Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,,\n") + .getBytes(StandardCharsets.UTF_8)); + ImportSchemaTree.failedFileDirectory = directory.getAbsolutePath() + File.separator; + + new ImportSchemaTree().importSchemaFromCsvFile(csv); + + assertTrue("aligned=" + useAligned, AbstractSchemaTool.connectionFailed); + File[] failedFiles = directory.listFiles((dir, name) -> name.startsWith("schema.failed_")); + assertTrue("aligned=" + useAligned, failedFiles != null && failedFiles.length == 1); + String failed = + new String(Files.readAllBytes(failedFiles[0].toPath()), StandardCharsets.UTF_8); + assertTrue(failed, failed.contains("root.sg.d.s1")); + } + } + + @Test + public void successfulImportDoesNotMarkTheImportAsFailed() throws Exception { + ImportSchemaTree.sessionPool = mock(SessionPool.class); + File directory = temporaryFolder.newFolder("ok"); + File csv = new File(directory, "schema.csv"); + Files.write( + csv.toPath(), + (Constants.HEAD_COLUMNS_V2.stream().collect(Collectors.joining(",")) + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,,\n") + .getBytes(StandardCharsets.UTF_8)); + ImportSchemaTree.failedFileDirectory = directory.getAbsolutePath() + File.separator; + + new ImportSchemaTree().importSchemaFromCsvFile(csv); + + assertFalse(AbstractSchemaTool.connectionFailed); + } + + /** + * A failed file keeps one column layout for every row: the rows rejected by the CSV validation + * used to follow the source header while the rows rejected by the RPC were written in + * Tags,Attributes order, so restoring the header of the failed file swapped the two columns. + */ + @Test + public void failedFileUsesOneColumnOrderForValidationAndRpcRejections() throws Exception { + String sourceHeader = "Timeseries,Alias,DataType,Encoding,Compression,Attributes,Tags"; + // Spacing a re-serialization would drop, so the cells prove that the rejected text is kept. + String invalidTagsCell = "{\"room\": \"101\"}"; + String invalidAttributesCell = "{\"owner\": \"team-a\"}"; + Map rejectedTags = new LinkedHashMap<>(); + rejectedTags.put("room", "102"); + Map rejectedAttributes = new LinkedHashMap<>(); + rejectedAttributes.put("owner", "team-b"); + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + doThrow(new StatementExecutionException("rejected")) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + runImport( + sourceHeader + + "\nroot.sg.d.invalid,,NOPE,TS_2DIFF,SNAPPY,\"" + + invalidAttributesCell.replace("\"", "\"\"") + + "\",\"" + + invalidTagsCell.replace("\"", "\"\"") + + "\"\nroot.sg.d.rejected,,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(rejectedAttributes).replace("\"", "\"\"") + + "\",\"" + + AbstractSchemaTool.toJsonCell(rejectedTags).replace("\"", "\"\"") + + "\"\n"); + + File failedFile = singleFailedFile(temporaryFolder.getRoot()); + List> rows = readRows(failedFile); + assertEquals( + "the first line of the failed file must be the header its rows follow", + Arrays.asList(sourceHeader.split(",")), + rows.get(0)); + assertEquals(3, rows.size()); + for (List row : rows) { + assertEquals(row.toString(), 7, row.size()); + } + assertEquals("root.sg.d.invalid", rows.get(1).get(0)); + assertEquals( + "a rejected JSON cell must be retried verbatim", invalidAttributesCell, rows.get(1).get(5)); + assertEquals(invalidTagsCell, rows.get(1).get(6)); + assertEquals("root.sg.d.rejected", rows.get(2).get(0)); + assertEquals(AbstractSchemaTool.toJsonCell(rejectedAttributes), rows.get(2).get(5)); + assertEquals(AbstractSchemaTool.toJsonCell(rejectedTags), rows.get(2).get(6)); + + // The generated file must be importable under the name the tool gave it. + File retryDirectory = temporaryFolder.newFolder("retry"); + SessionPool retryPool = mock(SessionPool.class); + List> createdCalls = new ArrayList<>(); + doAnswer( + call -> { + List snapshot = new ArrayList<>(); + for (Object argument : call.getArguments()) { + snapshot.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + createdCalls.add(snapshot); + return null; + }) + .when(retryPool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + ImportSchemaTree.sessionPool = retryPool; + ImportSchemaTree.failedFileDirectory = retryDirectory.getAbsolutePath() + File.separator; + new ImportSchemaTree().importSchemaFromCsvFile(failedFile); + + assertEquals(1, createdCalls.size()); + assertEquals( + "the owner attribute must come back as an attribute: " + createdCalls, + Arrays.asList(rejectedAttributes), + createdCalls.get(0).get(6)); + assertEquals( + "the room tag must come back as a tag: " + createdCalls, + Arrays.asList(rejectedTags), + createdCalls.get(0).get(5)); + } + + /** + * An exhausted retry must keep the whole row: the failed file used to hold the path only, so + * importing it under the seven-column header failed with an index out of bounds. + */ + @Test + public void exhaustedAlignedConnectionRetriesKeepTheWholeRow() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + Map tags = new LinkedHashMap<>(); + tags.put("room", "101"); + Map attributes = new LinkedHashMap<>(); + attributes.put("owner", "team-a"); + doThrow(new IoTDBConnectionException(new IllegalStateException("down"))) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + assertThrows( + IllegalStateException.class, + () -> + runImport( + String.join(",", Constants.HEAD_COLUMNS_V2) + + "\nroot.sg.d.s1,alias1,INT64,TS_2DIFF,SNAPPY,\"" + + AbstractSchemaTool.toJsonCell(tags).replace("\"", "\"\"") + + "\",\"" + + AbstractSchemaTool.toJsonCell(attributes).replace("\"", "\"\"") + + "\"\n")); + + List> rows = readRows(singleFailedFile(temporaryFolder.getRoot())); + assertEquals(Constants.HEAD_COLUMNS_V2, rows.get(0)); + assertEquals(2, rows.size()); + assertEquals( + Arrays.asList( + "root.sg.d.s1", + "alias1", + "INT64", + "TS_2DIFF", + "SNAPPY", + AbstractSchemaTool.toJsonCell(tags), + AbstractSchemaTool.toJsonCell(attributes)), + rows.get(1)); + } + + /** + * A create the server rejects must not terminate the JVM: the rejected row is kept for a retry, + * the remaining records are still imported, and the entry point exits non-zero. + */ + @Test + public void serverRejectedAlignedRowIsRecordedAndTheRestIsStillImported() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + ImportSchemaTree.aligned = true; + List createdPaths = new ArrayList<>(); + doAnswer( + call -> { + List aliases = call.getArgument(5); + if (aliases != null && aliases.contains("bad.alias")) { + throw new StatementExecutionException("alias bad.alias is invalid"); + } + createdPaths.add(call.getArgument(0) + "." + ((List) call.getArgument(1)).get(0)); + return null; + }) + .when(pool) + .createAlignedTimeseries(any(), any(), any(), any(), any(), any()); + File directory = temporaryFolder.newFolder("aligned-rejected"); + File csv = new File(directory, "schema.csv"); + Files.write( + csv.toPath(), + (String.join(",", Constants.HEAD_COLUMNS_V2) + + "\nroot.sg.d.badmetadata,,NOPE,TS_2DIFF,SNAPPY,," + + "\nroot.sg.d.s1,,INT64,TS_2DIFF,SNAPPY,," + + "\nroot.sg.d.s2,bad.alias,INT64,TS_2DIFF,SNAPPY,," + + "\nroot.sg.d.s3,,INT64,TS_2DIFF,SNAPPY,,\n") + .getBytes(StandardCharsets.UTF_8)); + ImportSchemaTree.failedFileDirectory = directory.getAbsolutePath() + File.separator; + + new ImportSchemaTree().importSchemaFromCsvFile(csv); + + assertTrue("the server rejection must fail the command", AbstractSchemaTool.connectionFailed); + assertEquals(Arrays.asList("root.sg.d.s1", "root.sg.d.s3"), createdPaths); + List> rows = readRows(singleFailedFile(directory)); + assertEquals(Constants.HEAD_COLUMNS_V2, rows.get(0)); + assertEquals(3, rows.size()); + assertEquals("root.sg.d.badmetadata", rows.get(1).get(0)); + assertEquals("NOPE", rows.get(1).get(2)); + assertEquals("root.sg.d.s2", rows.get(2).get(0)); + assertEquals("bad.alias", rows.get(2).get(1)); + } + + /** A legacy file keeps failing into a five-column file, only its header line is new. */ + @Test + public void legacyFileFailsIntoAFiveColumnFileWithItsOwnHeader() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + + runImport( + "Timeseries,Alias,DataType,Encoding,Compression\n" + + "root.sg.d.s1,aliasA,NOPE,TS_2DIFF,SNAPPY\n"); + + List> rows = readRows(singleFailedFile(temporaryFolder.getRoot())); + assertEquals(Constants.HEAD_COLUMNS, rows.get(0)); + assertEquals(2, rows.size()); + assertEquals( + Arrays.asList("root.sg.d.s1", "aliasA", "NOPE", "TS_2DIFF", "SNAPPY"), rows.get(1)); + verify(pool, never()) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + } + + /** + * A failed file of a five-column source is read back with the legacy dialect, so it must be + * written with it: RFC4180 quoting around a path that carries an escaped comma would shift the + * cells that follow it when the file is imported again. + */ + @Test + public void legacyFailedFileKeepsItsEscapedCommaAndCanBeImportedAgain() throws Exception { + SessionPool pool = mock(SessionPool.class); + ImportSchemaTree.sessionPool = pool; + doThrow(new IoTDBConnectionException(new IllegalStateException("down"))) + .when(pool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + + assertThrows( + IllegalStateException.class, + () -> + runImport( + "Timeseries,Alias,DataType,Encoding,Compression\n" + + "root.sg.d.sensor\\,1,aliasA,INT64,TS_2DIFF,SNAPPY\n")); + + File failedFile = singleFailedFile(temporaryFolder.getRoot()); + assertTrue( + "the failed file must be importable by name: " + failedFile, + failedFile.getName().endsWith(".csv")); + String content = new String(Files.readAllBytes(failedFile.toPath()), StandardCharsets.UTF_8); + assertFalse("the legacy dialect does not quote: " + content, content.contains("\"")); + List lines = Arrays.asList(content.split("\\n")); + assertEquals("Timeseries,Alias,DataType,Encoding,Compression", lines.get(0)); + assertEquals( + "the escaped comma of the source must survive: " + content, + "root.sg.d.sensor\\,1,aliasA,INT64,TS_2DIFF,SNAPPY", + lines.get(1)); + + SessionPool retryPool = mock(SessionPool.class); + List> createdCalls = new ArrayList<>(); + doAnswer( + call -> { + List snapshot = new ArrayList<>(); + for (Object argument : call.getArguments()) { + snapshot.add( + argument instanceof List ? new ArrayList<>((List) argument) : argument); + } + createdCalls.add(snapshot); + return null; + }) + .when(retryPool) + .createMultiTimeseries(any(), any(), any(), any(), any(), any(), any(), any()); + ImportSchemaTree.sessionPool = retryPool; + ImportSchemaTree.failedFileDirectory = + temporaryFolder.newFolder("retry").getAbsolutePath() + File.separator; + new ImportSchemaTree().importSchemaFromCsvFile(failedFile); + + assertEquals(1, createdCalls.size()); + assertEquals(Arrays.asList("root.sg.d.sensor,1"), createdCalls.get(0).get(0)); + assertEquals(Arrays.asList(TSDataType.INT64), createdCalls.get(0).get(1)); + assertEquals(Arrays.asList(TSEncoding.TS_2DIFF), createdCalls.get(0).get(2)); + assertEquals(Arrays.asList(CompressionType.SNAPPY), createdCalls.get(0).get(3)); + assertEquals(Arrays.asList("aliasA"), createdCalls.get(0).get(7)); + } + + /** The single failed-record file the tool generated in the directory. */ + private File singleFailedFile(File directory) { + File[] failedFiles = + directory.listFiles((dir, name) -> name.contains(".failed_") && name.endsWith(".csv")); + assertTrue( + "exactly one failed-record file is expected in " + directory, + failedFiles != null && failedFiles.length == 1); + return failedFiles[0]; + } + + private static List> readRows(File file) throws Exception { + try (CSVParser parser = CSVParser.parse(file, StandardCharsets.UTF_8, CSVFormat.DEFAULT)) { + return parser.getRecords().stream() + .map(record -> record.stream().collect(Collectors.toList())) + .collect(Collectors.toList()); + } + } + + private String readFailedFile() throws Exception { + return new String( + Files.readAllBytes(singleFailedFile(temporaryFolder.getRoot()).toPath()), + StandardCharsets.UTF_8); + } + + private void runImport(String csvContent) throws Exception { + File csv = temporaryFolder.newFile("schema_" + System.nanoTime() + ".csv"); + Files.write(csv.toPath(), csvContent.getBytes(StandardCharsets.UTF_8)); + runImportCsv(csv); + } + + private void runImportCsv(File csv) throws Exception { + String failedFileBase = ImportSchemaTree.failedFileBaseName(csv.getAbsolutePath()); + try (CSVParser parser = ImportSchemaTree.readCsvFile(csv.getAbsolutePath())) { + List headerNames = parser.getHeaderNames(); + assertTrue(ImportSchemaTree.checkHeader(headerNames)); + ImportSchemaTree.writeScheme(csv.getName(), headerNames, parser.stream(), failedFileBase); + } + } +} diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/LogicalViewSchemaSource.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/LogicalViewSchemaSource.java index 144ec16d4a37e..6d2a6f061b864 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/LogicalViewSchemaSource.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/LogicalViewSchemaSource.java @@ -38,8 +38,8 @@ import java.util.Collections; import java.util.List; -import java.util.Map; -import java.util.stream.Collectors; + +import static org.apache.iotdb.db.queryengine.execution.operator.schema.source.TimeSeriesSchemaSource.mapToString; public class LogicalViewSchemaSource implements ISchemaSource { @@ -118,15 +118,4 @@ public boolean hasSchemaStatistic(ISchemaRegion schemaRegion) { public long getSchemaStatistic(ISchemaRegion schemaRegion) { return 0; } - - private String mapToString(Map map) { - if (map == null || map.isEmpty()) { - return null; - } - String content = - map.entrySet().stream() - .map(e -> "\"" + e.getKey() + "\"" + ":" + "\"" + e.getValue() + "\"") - .collect(Collectors.joining(",")); - return "{" + content + "}"; - } } diff --git a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java index 0b89998052b00..832cf46100def 100644 --- a/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java +++ b/iotdb-core/datanode/src/main/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSource.java @@ -42,7 +42,6 @@ import java.util.List; import java.util.Map; -import java.util.stream.Collectors; import static org.apache.iotdb.commons.schema.SchemaConstant.ALL_MATCH_PATTERN; @@ -161,14 +160,68 @@ public boolean shouldSkipSchemaRegion(final ISchemaRegion schemaRegion) { return false; } + /** + * Renders a tag/attribute map as a JSON object (RFC 8259). Keys and values are escaped as JSON + * strings, while non-ASCII characters are kept raw for readability. + * + * @return the JSON object text, or {@code null} when the map is null or empty + */ public static String mapToString(Map map) { if (map == null || map.isEmpty()) { return null; } - String content = - map.entrySet().stream() - .map(e -> "\"" + e.getKey() + "\"" + ":" + "\"" + e.getValue() + "\"") - .collect(Collectors.joining(",")); - return "{" + content + "}"; + final StringBuilder builder = new StringBuilder("{"); + boolean first = true; + for (final Map.Entry entry : map.entrySet()) { + if (!first) { + builder.append(','); + } + first = false; + appendJsonString(builder, entry.getKey()); + builder.append(':'); + appendJsonString(builder, entry.getValue()); + } + return builder.append('}').toString(); + } + + private static final char[] HEX_DIGITS = "0123456789abcdef".toCharArray(); + + private static void appendJsonString(final StringBuilder builder, final String raw) { + // a null key or value is rendered as the literal text "null", as before + final String value = raw == null ? "null" : raw; + builder.append('"'); + for (int i = 0, length = value.length(); i < length; i++) { + final char c = value.charAt(i); + switch (c) { + case '"': + builder.append("\\\""); + break; + case '\\': + builder.append("\\\\"); + break; + case '\b': + builder.append("\\b"); + break; + case '\f': + builder.append("\\f"); + break; + case '\n': + builder.append("\\n"); + break; + case '\r': + builder.append("\\r"); + break; + case '\t': + builder.append("\\t"); + break; + default: + if (c < 0x20) { + builder.append("\\u00").append(HEX_DIGITS[(c >> 4) & 0xF]).append(HEX_DIGITS[c & 0xF]); + } else { + builder.append(c); + } + } + } + builder.append('"'); } } diff --git a/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSourceMapToStringTest.java b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSourceMapToStringTest.java new file mode 100644 index 0000000000000..b94067cca863c --- /dev/null +++ b/iotdb-core/datanode/src/test/java/org/apache/iotdb/db/queryengine/execution/operator/schema/source/TimeSeriesSchemaSourceMapToStringTest.java @@ -0,0 +1,182 @@ +/* + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, + * software distributed under the License is distributed on an + * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY + * KIND, either express or implied. See the License for the + * specific language governing permissions and limitations + * under the License. + */ + +package org.apache.iotdb.db.queryengine.execution.operator.schema.source; + +import org.junit.Test; + +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +import static org.apache.iotdb.db.queryengine.execution.operator.schema.source.TimeSeriesSchemaSource.mapToString; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +public class TimeSeriesSchemaSourceMapToStringTest { + + /** The pre-escaping implementation, kept here to prove backward compatibility. */ + private static String legacyMapToString(final Map map) { + if (map == null || map.isEmpty()) { + return null; + } + final String content = + map.entrySet().stream() + .map(e -> "\"" + e.getKey() + "\"" + ":" + "\"" + e.getValue() + "\"") + .collect(Collectors.joining(",")); + return "{" + content + "}"; + } + + private static Map mapOf(final String key, final String value) { + final Map map = new LinkedHashMap<>(); + map.put(key, value); + return map; + } + + @Test + public void testPlainValue() { + final Map map = mapOf("room", "101"); + assertEquals("{\"room\":\"101\"}", mapToString(map)); + } + + @Test + public void testCommaIsNotEscaped() { + final Map map = mapOf("k", "a,b"); + assertEquals("{\"k\":\"a,b\"}", mapToString(map)); + } + + @Test + public void testDoubleQuote() { + final Map map = mapOf("k", "a\"b"); + assertEquals("{\"k\":\"a\\\"b\"}", mapToString(map)); + // the escaped quote must not split the document into extra keys + } + + @Test + public void testBackslash() { + final Map map = mapOf("k", "a\\b"); + assertEquals("{\"k\":\"a\\\\b\"}", mapToString(map)); + } + + @Test + public void testLiteralBackslashAndN() { + final Map map = mapOf("k", "a\\nb"); + assertEquals("{\"k\":\"a\\\\nb\"}", mapToString(map)); + } + + @Test + public void testDoubleBackslash() { + final Map map = mapOf("k", "a\\\\b"); + assertEquals("{\"k\":\"a\\\\\\\\b\"}", mapToString(map)); + } + + @Test + public void testTab() { + final Map map = mapOf("k", "\t"); + assertEquals("{\"k\":\"\\t\"}", mapToString(map)); + } + + @Test + public void testLineFeed() { + final Map map = mapOf("k", "a\nb"); + assertEquals("{\"k\":\"a\\nb\"}", mapToString(map)); + } + + @Test + public void testCarriageReturnAndLineFeed() { + final Map map = mapOf("k", "a\r\nb"); + assertEquals("{\"k\":\"a\\r\\nb\"}", mapToString(map)); + } + + @Test + public void testBackspaceAndFormFeed() { + final Map map = mapOf("k", "a\bb\fc"); + assertEquals("{\"k\":\"a\\bb\\fc\"}", mapToString(map)); + } + + @Test + public void testOtherControlCharacterUsesUnicodeEscape() { + final Map map = mapOf("k", "a\u0001b"); + assertEquals("{\"k\":\"a\\u0001b\"}", mapToString(map)); + } + + @Test + public void testNonAsciiIsKeptRaw() { + final Map map = mapOf("cn", "中文\uD83D\uDE00"); + assertEquals("{\"cn\":\"中文\uD83D\uDE00\"}", mapToString(map)); + // no \\uXXXX escaping of non-ASCII characters + assertEquals(false, mapToString(map).contains("\\u")); + } + + @Test + public void testEmptyStringValue() { + final Map map = mapOf("k", ""); + assertEquals("{\"k\":\"\"}", mapToString(map)); + } + + @Test + public void testEscapingInKey() { + final Map map = mapOf("a\"b\\c\td", "v"); + assertEquals("{\"a\\\"b\\\\c\\td\":\"v\"}", mapToString(map)); + } + + @Test + public void testMultipleKeys() { + final Map map = new LinkedHashMap<>(); + map.put("root.sg", "101"); + map.put("unit", "celsius"); + map.put("note", "a\"b\\c"); + assertEquals( + "{\"root.sg\":\"101\",\"unit\":\"celsius\",\"note\":\"a\\\"b\\\\c\"}", mapToString(map)); + } + + @Test + public void testNullAndEmptyMap() { + assertNull(mapToString(null)); + assertNull(mapToString(Collections.emptyMap())); + } + + @Test + public void testIdenticalToLegacyOutputWhenNothingNeedsEscaping() { + final Map plain = new LinkedHashMap<>(); + plain.put("room", "101"); + plain.put("sensor", "temperature"); + plain.put("path", "root.sg.d1.s1"); + plain.put("empty", ""); + plain.put("punctuation", "a,b;c=d (e) [f] {g} /h@i#j$k%l^m&n*o-p+q_r"); + plain.put("cjk", "中文😀"); + plain.put("single", "x"); + + assertEquals(legacyMapToString(plain), mapToString(plain)); + + final Map single = mapOf("room", "101"); + assertEquals(legacyMapToString(single), mapToString(single)); + } + + @Test + public void testLegacyComparisonForMultiplePlainMaps() { + final Map map = new LinkedHashMap<>(); + map.put("a", "1"); + map.put("b", "2"); + map.put("c", "3"); + assertEquals(legacyMapToString(map), mapToString(map)); + assertEquals("{\"a\":\"1\",\"b\":\"2\",\"c\":\"3\"}", mapToString(map)); + } +}