This is an automated email from the ASF dual-hosted git repository.

JackieTien97 pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/iotdb.git


The following commit(s) were added to refs/heads/master by this push:
     new c272a5c1c79 Preserve quoted semicolons when importing table schemas
c272a5c1c79 is described below

commit c272a5c1c797d530315b9dcb0a01f78fa9b4acae
Author: DaZuiZui <[email protected]>
AuthorDate: Tue Dec 1 19:35:42 2026 +0800

    Preserve quoted semicolons when importing table schemas
---
 .../en/org/apache/iotdb/cli/i18n/CliMessages.java  |   4 +
 .../zh/org/apache/iotdb/cli/i18n/CliMessages.java  |   4 +
 .../iotdb/tool/schema/AbstractImportSchema.java    |  69 +++++----
 .../org/apache/iotdb/tool/schema/ImportSchema.java |   3 +-
 .../iotdb/tool/schema/ImportSchemaTable.java       | 157 ++++++++++++---------
 .../apache/iotdb/tool/schema/ImportSchemaTree.java |   5 -
 .../tool/schema/ImportSchemaTableStatusTest.java   | 105 ++++++++++++++
 .../iotdb/tool/schema/ImportSchemaTableTest.java   | 143 +++++++++++++++++++
 8 files changed, 388 insertions(+), 102 deletions(-)

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 2db32c12487..25ceeee707a 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
@@ -112,6 +112,10 @@ public final class CliMessages {
       "SQL file read exception because: %s";
   public static final String EXCEPTION_UNEXPECTED_ERROR_OCCURRED_ARG_402FA331 =
       "Unexpected error occurred: %s";
+  public static final String 
EXCEPTION_UNTERMINATED_BLOCK_COMMENT_STARTING_AT_LINE_ARG_E08CEA95 =
+      "Unterminated block comment starting at line %d";
+  public static final String 
EXCEPTION_UNTERMINATED_QUOTE_ARG_AT_LINE_ARG_D26DE017 =
+      "Unterminated quote %s at line %d";
   public static final String MESSAGE_ARG_EMPTY_FILE_4366EB0C = "%s : Empty 
file!";
   public static final String MESSAGE_ARG_IMPORT_COMPLETELY_FAIL_9B6F42FD =
       "%s : Import completely fail!";
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 c7b1ec739dc..aba90733ec1 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
@@ -108,6 +108,10 @@ public final class CliMessages {
   public static final String 
EXCEPTION_SQL_FILE_READ_EXCEPTION_BECAUSE_ARG_1626B867 =
       "读取 SQL 文件异常,原因是:%s";
   public static final String EXCEPTION_UNEXPECTED_ERROR_OCCURRED_ARG_402FA331 
= "发生意外错误:%s";
+  public static final String 
EXCEPTION_UNTERMINATED_BLOCK_COMMENT_STARTING_AT_LINE_ARG_E08CEA95 =
+      "从第 %d 行开始的块注释未闭合";
+  public static final String 
EXCEPTION_UNTERMINATED_QUOTE_ARG_AT_LINE_ARG_D26DE017 =
+      "引号 %s 在第 %d 行未闭合";
   public static final String MESSAGE_ARG_EMPTY_FILE_4366EB0C = "%s : 空文件!";
   public static final String MESSAGE_ARG_IMPORT_COMPLETELY_FAIL_9B6F42FD = "%s 
: 导入全部失败!";
   public static final String MESSAGE_ARG_IMPORT_COMPLETELY_SUCCESSFUL_BB17250E 
= "%s : 导入全部成功!";
diff --git 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractImportSchema.java
 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractImportSchema.java
index 14be504494b..b693cec7d57 100644
--- 
a/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractImportSchema.java
+++ 
b/iotdb-client/cli/src/main/java/org/apache/iotdb/tool/schema/AbstractImportSchema.java
@@ -33,6 +33,7 @@ import java.util.List;
 public abstract class AbstractImportSchema extends AbstractSchemaTool 
implements Runnable {
 
   private static final IoTPrinter ioTPrinter = new IoTPrinter(System.out);
+  protected volatile boolean importFailed;
 
   public abstract void init()
       throws InterruptedException, IoTDBConnectionException, 
StatementExecutionException;
@@ -40,8 +41,8 @@ public abstract class AbstractImportSchema extends 
AbstractSchemaTool implements
   @Override
   public void run() {
     String filePath;
-    try {
-      while ((filePath = ImportDataScanTool.pollFromQueue()) != null) {
+    while ((filePath = ImportDataScanTool.pollFromQueue()) != null) {
+      try {
         File file = new File(filePath);
         if (!sqlDialectTree && file.getName().endsWith(Constants.SQL_SUFFIXS)) 
{
           importSchemaFromSqlFile(file);
@@ -54,43 +55,51 @@ public abstract class AbstractImportSchema extends 
AbstractSchemaTool implements
                       
.MESSAGE_ARG_THE_FILE_NAME_MUST_END_WITH_CSV_WHEN_SQL_DIALECT_TREE_OR_SQL_WHEN_SQL_DIALECT_TABLE_7A2FD49A,
                   String.valueOf(file.getName())));
         }
+      } catch (Exception e) {
+        importFailed = true;
+        ioTPrinter.println(
+            String.format(
+                CliMessages.EXCEPTION_UNEXPECTED_ERROR_OCCURRED_ARG_402FA331,
+                String.valueOf(e.getMessage())));
       }
-    } catch (Exception e) {
-      ioTPrinter.println(
-          String.format(
-              CliMessages.EXCEPTION_UNEXPECTED_ERROR_OCCURRED_ARG_402FA331,
-              String.valueOf(e.getMessage())));
     }
   }
 
-  protected abstract Runnable getAsyncImportRunnable();
-
-  protected class ThreadManager {
-    public void asyncImportSchemaFiles() {
-      List<Thread> list = new ArrayList<>(threadNum);
-      for (int i = 0; i < threadNum; i++) {
-        Thread thread = new Thread(getAsyncImportRunnable());
-        thread.start();
-        list.add(thread);
+  int importFiles() {
+    importFailed = false;
+    List<Thread> workers = new ArrayList<>(threadNum);
+    for (int i = 0; i < threadNum; i++) {
+      Thread worker = new Thread(this);
+      worker.start();
+      workers.add(worker);
+    }
+    boolean interrupted = false;
+    for (Thread worker : workers) {
+      while (worker.isAlive()) {
+        try {
+          worker.join();
+        } catch (InterruptedException e) {
+          interrupted = true;
+          ioTPrinter.println(
+              String.format(
+                  
CliMessages.EXCEPTION_IMPORTDATA_THREAD_JOIN_INTERRUPTED_ARG_B94FC04B,
+                  String.valueOf(e.getMessage())));
+        }
       }
-      list.forEach(
-          thread -> {
-            try {
-              thread.join();
-            } catch (InterruptedException e) {
-              Thread.currentThread().interrupt();
-              ioTPrinter.println(
-                  String.format(
-                      
CliMessages.EXCEPTION_IMPORTDATA_THREAD_JOIN_INTERRUPTED_ARG_B94FC04B,
-                      String.valueOf(e.getMessage())));
-            }
-          });
-      ioTPrinter.println(Constants.IMPORT_COMPLETELY);
     }
+    if (interrupted) {
+      Thread.currentThread().interrupt();
+      return Constants.CODE_ERROR;
+    }
+    if (importFailed) {
+      return Constants.CODE_ERROR;
+    }
+    ioTPrinter.println(Constants.IMPORT_COMPLETELY);
+    return Constants.CODE_OK;
   }
 
   public static void init(AbstractImportSchema instance) {
-    instance.new ThreadManager().asyncImportSchemaFiles();
+    instance.importFiles();
   }
 
   protected abstract void importSchemaFromSqlFile(File file);
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 eb446a9f705..996cfeb76fd 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,8 +160,7 @@ public class ImportSchema extends AbstractSchemaTool {
         importSchema = new ImportSchemaTable();
       }
       importSchema.init();
-      AbstractImportSchema.init(importSchema);
-      return Constants.CODE_OK;
+      return importSchema.importFiles();
     } 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 8c5902fc284..494cf083be0 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
@@ -21,6 +21,7 @@ package org.apache.iotdb.tool.schema;
 
 import org.apache.iotdb.cli.i18n.CliMessages;
 import org.apache.iotdb.cli.utils.IoTPrinter;
+import org.apache.iotdb.db.relational.grammar.sql.RelationalSqlLexer;
 import org.apache.iotdb.isession.ITableSession;
 import org.apache.iotdb.isession.SessionDataSet;
 import org.apache.iotdb.isession.pool.ITableSessionPool;
@@ -31,8 +32,10 @@ import org.apache.iotdb.session.pool.TableSessionPoolBuilder;
 import org.apache.iotdb.tool.common.Constants;
 import org.apache.iotdb.tool.data.ImportDataScanTool;
 
+import org.antlr.v4.runtime.CommonTokenFactory;
+import org.antlr.v4.runtime.Token;
+import org.antlr.v4.runtime.UnbufferedCharStream;
 import org.apache.tsfile.external.commons.lang3.ObjectUtils;
-import org.apache.tsfile.external.commons.lang3.StringUtils;
 import org.apache.tsfile.read.common.RowRecord;
 
 import java.io.BufferedReader;
@@ -40,14 +43,22 @@ import java.io.File;
 import java.io.FileReader;
 import java.io.FileWriter;
 import java.io.IOException;
+import java.io.Reader;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.List;
+import java.util.function.Consumer;
 
 public class ImportSchemaTable extends AbstractImportSchema {
 
   private static final IoTPrinter ioTPrinter = new IoTPrinter(System.out);
-  private static ITableSessionPool sessionPool;
+  private ITableSessionPool sessionPool;
+
+  public ImportSchemaTable() {}
+
+  ImportSchemaTable(ITableSessionPool sessionPool) {
+    this.sessionPool = sessionPool;
+  }
 
   public void init() throws InterruptedException {
     TableSessionPoolBuilder tableSessionPoolBuilder =
@@ -101,95 +112,111 @@ public class ImportSchemaTable extends 
AbstractImportSchema {
     ImportDataScanTool.traverseAndCollectFiles();
   }
 
-  @Override
-  protected Runnable getAsyncImportRunnable() {
-    return new ImportSchemaTable();
-  }
-
   @Override
   protected void importSchemaFromSqlFile(File file) {
-    ArrayList<List<Object>> failedRecords = new ArrayList<>();
+    List<String> failedRecords = new ArrayList<>();
     String failedFilePath;
     if (failedFileDirectory == null) {
       failedFilePath = file.getAbsolutePath() + ".failed";
     } else {
       failedFilePath = failedFileDirectory + file.getName() + ".failed";
     }
+    boolean readFailed = false;
     try (BufferedReader br = new BufferedReader(new 
FileReader(file.getAbsolutePath()))) {
-      StringBuilder sqlBuilder = new StringBuilder();
-      String sql;
-      while ((sql = br.readLine()) != null) {
-        if (!sql.contains(";")) {
-          sqlBuilder.append(sql);
-        } else {
-          String[] sqls = sql.split(";");
-          boolean addBuilder = false;
-          if (sqls.length > 0) {
-            if (!sql.endsWith(";")) {
-              addBuilder = true;
-            }
-            for (int i = 0; i < sqls.length; i++) {
-              sqlBuilder.append(sqls[i]);
-              if (i == sqls.length - 1 && addBuilder) {
-                break;
-              }
-              String builderString = sqlBuilder.toString();
-              try (ITableSession session = sessionPool.getSession()) {
-                session.executeNonQueryStatement(builderString);
-                sqlBuilder = new StringBuilder();
-              } catch (IoTDBConnectionException | StatementExecutionException 
e) {
-                failedRecords.add(Collections.singletonList(builderString));
-                sqlBuilder = new StringBuilder();
-              }
-            }
-          } else {
-            String builderString = sqlBuilder.toString();
+      forEachSqlStatement(
+          br,
+          sql -> {
             try (ITableSession session = sessionPool.getSession()) {
-              session.executeNonQueryStatement(builderString);
-              sqlBuilder = new StringBuilder();
+              session.executeNonQueryStatement(sql);
             } catch (IoTDBConnectionException | StatementExecutionException e) 
{
-              failedRecords.add(Collections.singletonList(builderString));
-              sqlBuilder = new StringBuilder();
+              failedRecords.add(sql);
             }
-          }
-        }
-      }
-      String builderString = sqlBuilder.toString();
-      if (StringUtils.isNotBlank(builderString)) {
-        try (ITableSession session = sessionPool.getSession()) {
-          session.executeNonQueryStatement(sqlBuilder.toString());
-        } catch (IoTDBConnectionException | StatementExecutionException e) {
-          failedRecords.add(Collections.singletonList(builderString));
-          sqlBuilder = new StringBuilder();
-        }
-      }
-      processSuccessFile();
+          });
     } catch (IOException e) {
+      readFailed = true;
       ioTPrinter.println(
           String.format(
               
CliMessages.EXCEPTION_SQL_FILE_READ_EXCEPTION_BECAUSE_ARG_1626B867,
               String.valueOf(e.getMessage())));
     }
+    if (!readFailed && failedRecords.isEmpty()) {
+      processSuccessFile();
+      return;
+    }
+    importFailed = true;
     if (!failedRecords.isEmpty()) {
-      FileWriter writer = null;
-      try {
-        writer = new FileWriter(failedFilePath);
-        for (List<Object> failedRecord : failedRecords) {
-          writer.write(failedRecord.get(0).toString() + ";\n");
+      ioTPrinter.println(
+          
String.format(CliMessages.MESSAGE_ARG_IMPORT_COMPLETELY_FAIL_9B6F42FD, 
file.getPath()));
+      try (FileWriter writer = new FileWriter(failedFilePath)) {
+        for (String failedRecord : failedRecords) {
+          writer.write(failedRecord + ";\n");
         }
       } catch (IOException e) {
         ioTPrinter.println(
             String.format(
                 
CliMessages.EXCEPTION_CANNOT_DUMP_FAIL_RESULT_BECAUSE_ARG_5C6E82E0,
                 String.valueOf(e.getMessage())));
-      } finally {
-        if (ObjectUtils.isNotEmpty(writer)) {
-          try {
-            writer.flush();
-            writer.close();
-          } catch (IOException e) {
-            ;
+      }
+    }
+  }
+
+  static void forEachSqlStatement(Reader reader, Consumer<String> consumer) 
throws IOException {
+    try {
+      new SqlStatementStream(reader).forEachStatement(consumer);
+    } catch (RuntimeException e) {
+      // UnbufferedCharStream wraps IOExceptions from the reader.
+      if (e.getCause() instanceof IOException) {
+        throw (IOException) e.getCause();
+      }
+      throw e;
+    }
+  }
+
+  static class SqlStatementStream extends UnbufferedCharStream {
+    SqlStatementStream(Reader reader) {
+      super(reader);
+    }
+
+    void forEachStatement(Consumer<String> consumer) throws IOException {
+      RelationalSqlLexer lexer = new RelationalSqlLexer(this);
+      // Copy token text before the streaming lexer releases its input buffer.
+      lexer.setTokenFactory(new CommonTokenFactory(true));
+      StringBuilder sql = new StringBuilder();
+      boolean hasStatement = false;
+      while (true) {
+        Token token = lexer.nextToken();
+        // A closed block comment is a single token. A slash followed by '*' 
means EOF
+        // was reached without finding its closing delimiter.
+        if (token.getType() == RelationalSqlLexer.SLASH && LA(1) == '*') {
+          throw new IOException(
+              String.format(
+                  
CliMessages.EXCEPTION_UNTERMINATED_BLOCK_COMMENT_STARTING_AT_LINE_ARG_E08CEA95,
+                  token.getLine()));
+        }
+        if (token.getType() == RelationalSqlLexer.SEMICOLON || token.getType() 
== Token.EOF) {
+          if (hasStatement) {
+            consumer.accept(sql.toString());
+          }
+          if (token.getType() == Token.EOF) {
+            return;
+          }
+          // nextToken() released its marks. Rebase ANTLR's int index but keep 
buffered lookahead.
+          currentCharIndex = 0;
+          sql.setLength(0);
+          hasStatement = false;
+        } else {
+          String text = token.getText();
+          // A matched string or identifier includes both quotes in a single 
token.
+          if (token.getType() == RelationalSqlLexer.UNRECOGNIZED
+              && ("'".equals(text) || "\"".equals(text) || "`".equals(text))) {
+            throw new IOException(
+                String.format(
+                    
CliMessages.EXCEPTION_UNTERMINATED_QUOTE_ARG_AT_LINE_ARG_D26DE017,
+                    text,
+                    token.getLine()));
           }
+          sql.append(text);
+          hasStatement |= token.getChannel() == Token.DEFAULT_CHANNEL;
         }
       }
     }
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 f8db79c884e..df627bffbb8 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
@@ -89,11 +89,6 @@ public class ImportSchemaTree extends AbstractImportSchema {
     ImportDataScanTool.traverseAndCollectFiles();
   }
 
-  @Override
-  protected Runnable getAsyncImportRunnable() {
-    return new ImportSchemaTree();
-  }
-
   @Override
   protected void importSchemaFromSqlFile(File file) {
     throw new UnsupportedOperationException(CliMessages.NOT_SUPPORTED_YET);
diff --git 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableStatusTest.java
 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableStatusTest.java
new file mode 100644
index 00000000000..00a9b5dc007
--- /dev/null
+++ 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableStatusTest.java
@@ -0,0 +1,105 @@
+/*
+ * 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.isession.ITableSession;
+import org.apache.iotdb.isession.pool.ITableSessionPool;
+import org.apache.iotdb.rpc.StatementExecutionException;
+import org.apache.iotdb.tool.common.Constants;
+import org.apache.iotdb.tool.data.ImportDataScanTool;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TemporaryFolder;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+public class ImportSchemaTableStatusTest {
+
+  @Rule public TemporaryFolder temporaryFolder = new TemporaryFolder();
+
+  private final Boolean previousDialect = AbstractSchemaTool.sqlDialectTree;
+  private final int previousThreadCount = AbstractSchemaTool.threadNum;
+  private final String previousFailedDirectory = 
AbstractSchemaTool.failedFileDirectory;
+  private final long previousSuccessCount = 
AbstractSchemaTool.loadFileSuccessfulNum.sum();
+
+  private final ITableSessionPool sessionPool = mock(ITableSessionPool.class);
+  private final ITableSession session = mock(ITableSession.class);
+
+  @Before
+  public void setUp() throws Exception {
+    AbstractSchemaTool.sqlDialectTree = false;
+    AbstractSchemaTool.threadNum = 2;
+    AbstractSchemaTool.failedFileDirectory = null;
+    when(sessionPool.getSession()).thenReturn(session);
+  }
+
+  @After
+  public void tearDown() {
+    AbstractSchemaTool.sqlDialectTree = previousDialect;
+    AbstractSchemaTool.threadNum = previousThreadCount;
+    AbstractSchemaTool.failedFileDirectory = previousFailedDirectory;
+    AbstractSchemaTool.loadFileSuccessfulNum.reset();
+    AbstractSchemaTool.loadFileSuccessfulNum.add(previousSuccessCount);
+  }
+
+  @Test
+  public void testMixedFilesReturnErrorAndNextImportSucceeds() throws 
Exception {
+    queueFile("unfinished.sql", "/* unfinished");
+    Path valid = queueFile("valid.sql", "SELECT 1;");
+    assertEquals(Constants.CODE_ERROR, new 
ImportSchemaTable(sessionPool).importFiles());
+    assertEquals(previousSuccessCount + 1, 
AbstractSchemaTool.loadFileSuccessfulNum.sum());
+
+    ImportDataScanTool.putToQueue(valid.toString());
+    assertEquals(Constants.CODE_OK, new 
ImportSchemaTable(sessionPool).importFiles());
+    assertEquals(previousSuccessCount + 2, 
AbstractSchemaTool.loadFileSuccessfulNum.sum());
+    verify(session, times(2)).executeNonQueryStatement("SELECT 1");
+  }
+
+  @Test
+  public void testExecutionFailureWritesFailedStatementAndReturnsError() 
throws Exception {
+    doThrow(new StatementExecutionException("rejected"))
+        .when(session)
+        .executeNonQueryStatement("SELECT 1");
+    Path input = queueFile("statements.sql", "SELECT 1;SELECT 2;");
+    assertEquals(Constants.CODE_ERROR, new 
ImportSchemaTable(sessionPool).importFiles());
+    assertEquals(previousSuccessCount, 
AbstractSchemaTool.loadFileSuccessfulNum.sum());
+    assertEquals("SELECT 1;\n", 
Files.readString(input.resolveSibling("statements.sql.failed")));
+    verify(session).executeNonQueryStatement("SELECT 2");
+  }
+
+  private Path queueFile(String name, String content) throws IOException, 
InterruptedException {
+    Path path = temporaryFolder.newFile(name).toPath();
+    Files.writeString(path, content);
+    ImportDataScanTool.putToQueue(path.toString());
+    return path;
+  }
+}
diff --git 
a/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableTest.java
 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableTest.java
new file mode 100644
index 00000000000..bb31bc615be
--- /dev/null
+++ 
b/iotdb-client/cli/src/test/java/org/apache/iotdb/tool/schema/ImportSchemaTableTest.java
@@ -0,0 +1,143 @@
+/*
+ * 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.cli.i18n.CliMessages;
+
+import org.junit.Test;
+
+import java.io.IOException;
+import java.io.StringReader;
+import java.util.ArrayList;
+import java.util.List;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThrows;
+
+public class ImportSchemaTableTest {
+
+  @Test
+  public void testAdjacentStatementsAndFinalStatementWithoutDelimiter() throws 
IOException {
+    String drop = "DROP TABLE IF EXISTS measurements";
+    String create = "CREATE TABLE measurements (v INT64 FIELD COMMENT 'intake; 
exhaust')";
+    assertEquals(List.of(drop, create), splitStatements(drop + ";" + create));
+  }
+
+  @Test
+  public void testQuotedIdentifiersAndMultilineCommentsKeepSemicolons() throws 
IOException {
+    String drop = "DROP TABLE IF EXISTS \"room\"\";one\"";
+    String create =
+        "\nCREATE TABLE \"room\"\";one\" (v INT64 FIELD COMMENT 
'operator''s;\ncalibration')";
+    assertEquals(List.of(drop, create), splitStatements(drop + ";" + create + 
";\n"));
+  }
+
+  @Test
+  public void testPrefixedLiteralsAndBackquotedIdentifiersStayIntact() throws 
IOException {
+    String sql = "SELECT U&'a'';b', X'AB', `a``;b`";
+    assertEquals(List.of(sql), splitStatements(sql + ";"));
+  }
+
+  @Test
+  public void testUnterminatedQuotesEmitNoStatements() {
+    for (String opener : List.of("'", "U&'", "X'", "\"", "`")) {
+      StringReader input = new StringReader("\n" + opener + "one; two");
+      List<String> statements = new ArrayList<>();
+      IOException error =
+          assertThrows(
+              IOException.class,
+              () -> ImportSchemaTable.forEachSqlStatement(input, 
statements::add));
+      assertEquals(
+          String.format(
+              
CliMessages.EXCEPTION_UNTERMINATED_QUOTE_ARG_AT_LINE_ARG_D26DE017,
+              opener.charAt(opener.length() - 1),
+              2),
+          error.getMessage());
+      assertEquals(List.of(), statements);
+    }
+  }
+
+  @Test
+  public void testUnterminatedQuoteDiscardsOnlyIncompleteStatement() {
+    String complete = "SELECT 'one; two'";
+    StringReader input = new StringReader(complete + "; SELECT 'three''; 
four");
+    List<String> statements = new ArrayList<>();
+    assertThrows(
+        IOException.class, () -> ImportSchemaTable.forEachSqlStatement(input, 
statements::add));
+    assertEquals(List.of(complete), statements);
+  }
+
+  @Test
+  public void testLineAndBlockCommentsKeepSemicolons() throws IOException {
+    String create = "-- input; units\nCREATE TABLE t (v /* unit; scale */ 
INT64 FIELD)";
+    assertEquals(List.of(create), splitStatements(create + ";"));
+  }
+
+  @Test
+  public void testCommentOnlyInput() throws IOException {
+    assertEquals(List.of(), splitStatements("-- first; comment\n; /* second; 
comment */"));
+  }
+
+  @Test
+  public void testUnterminatedBlockCommentEmitsNoStatements() {
+    StringReader input = new StringReader("/* paused;\nSELECT 1;");
+    List<String> statements = new ArrayList<>();
+    assertThrows(
+        IOException.class, () -> ImportSchemaTable.forEachSqlStatement(input, 
statements::add));
+    assertEquals(List.of(), statements);
+  }
+
+  @Test
+  public void testUnterminatedBlockCommentDiscardsIncompleteStatement() {
+    String complete = "SELECT 6 / 2, '/*'";
+    StringReader input = new StringReader(complete + ";\nSELECT 3 /* 
unfinished");
+    List<String> statements = new ArrayList<>();
+    IOException error =
+        assertThrows(
+            IOException.class, () -> 
ImportSchemaTable.forEachSqlStatement(input, statements::add));
+    assertEquals(
+        String.format(
+            
CliMessages.EXCEPTION_UNTERMINATED_BLOCK_COMMENT_STARTING_AT_LINE_ARG_E08CEA95, 
2),
+        error.getMessage());
+    assertEquals(List.of(complete), statements);
+  }
+
+  @Test
+  public void testStatementsAcrossIntegerIndexLimit() throws IOException {
+    String drop = "DROP TABLE t";
+    String create = "CREATE TABLE t (v INT64 FIELD COMMENT 'intake; exhaust')";
+    class NearLimitStream extends ImportSchemaTable.SqlStatementStream {
+      NearLimitStream() {
+        super(new StringReader(drop + ";" + create));
+        // Leave room for the first delimiter and lookahead, but not the 
second statement.
+        currentCharIndex = Integer.MAX_VALUE - drop.length() - 8;
+      }
+    }
+
+    List<String> statements = new ArrayList<>();
+    new NearLimitStream().forEachStatement(statements::add);
+    assertEquals(List.of(drop, create), statements);
+  }
+
+  private List<String> splitStatements(String sql) throws IOException {
+    List<String> statements = new ArrayList<>();
+    ImportSchemaTable.forEachSqlStatement(new StringReader(sql), 
statements::add);
+    return statements;
+  }
+}

Reply via email to