mchades commented on code in PR #9207:
URL: https://github.com/apache/gravitino/pull/9207#discussion_r2564835303


##########
core/src/test/java/org/apache/gravitino/storage/TestSQLScripts.java:
##########
@@ -18,164 +18,139 @@
  */
 package org.apache.gravitino.storage;
 
-import static 
org.apache.gravitino.integration.test.util.TestDatabaseName.MYSQL_JDBC_BACKEND;
-import static 
org.apache.gravitino.integration.test.util.TestDatabaseName.PG_JDBC_BACKEND;
-
 import java.io.File;
 import java.io.IOException;
-import java.nio.file.Files;
 import java.nio.file.Path;
 import java.sql.Connection;
-import java.sql.DriverManager;
+import java.sql.ResultSet;
 import java.sql.SQLException;
 import java.sql.Statement;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Comparator;
 import java.util.HashMap;
+import java.util.List;
 import java.util.Map;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 import org.apache.commons.io.FileUtils;
-import org.apache.commons.lang3.StringUtils;
-import org.apache.gravitino.integration.test.container.MySQLContainer;
-import org.apache.gravitino.integration.test.container.PostgreSQLContainer;
-import org.apache.gravitino.integration.test.util.BaseIT;
-import org.junit.jupiter.api.AfterAll;
+import org.apache.gravitino.storage.relational.TestJDBCBackend;
+import org.apache.gravitino.storage.relational.session.SqlSessionFactoryHelper;
+import org.apache.ibatis.session.SqlSession;
 import org.junit.jupiter.api.Assertions;
-import org.junit.jupiter.api.BeforeAll;
-import org.junit.jupiter.api.Test;
-import org.junit.jupiter.api.io.TempDir;
-
-public class TestSQLScripts extends BaseIT {
-
-  private String jdbcBackend;
-  private Path scriptDir;
-  @TempDir private File tempDir;
-  private Map<String, Connection> versionConnections;
+import org.junit.jupiter.api.TestTemplate;
 
-  @BeforeAll
-  public void startIntegrationTest() {
-    jdbcBackend = System.getenv("jdbcBackend");
-    Assertions.assertNotNull(jdbcBackend, "jdbcBackend environment variable is 
not set");
+public class TestSQLScripts extends TestJDBCBackend {
 
+  @TestTemplate
+  public void testSQLScripts() throws SQLException, IOException {
     String gravitinoHome = System.getenv("GRAVITINO_HOME");
     Assertions.assertNotNull(gravitinoHome, "GRAVITINO_HOME environment 
variable is not set");
-    scriptDir = Path.of(gravitinoHome, "scripts", jdbcBackend.toLowerCase());
-    Assertions.assertTrue(Files.exists(scriptDir), "Script directory does not 
exist: " + scriptDir);
-    versionConnections = new HashMap<>();
-  }
-
-  @AfterAll
-  public void stopIntegrationTest() {
-    // Close all connections
-    for (Connection conn : versionConnections.values()) {
-      if (conn != null) {
-        try {
-          conn.close();
-        } catch (SQLException e) {
-          // Ignore
-        }
-      }
-    }
-    versionConnections.clear();
-  }
+    Path scriptDir = Path.of(gravitinoHome, "scripts", 
backendType.toLowerCase());
 
-  @Test
-  public void testSQLScripts() throws SQLException {
     File[] scriptFiles = scriptDir.toFile().listFiles();
     Assertions.assertNotNull(scriptFiles, "No script files found in " + 
scriptDir);
     // Sort files to ensure the correct execution order (schema -> upgrade)
     Arrays.sort(scriptFiles, Comparator.comparing(File::getName));
 
     // A map to store connections for different schema versions
     Pattern schemaPattern =
-        Pattern.compile("schema-([\\d.]+)-" + jdbcBackend.toLowerCase() + 
"\\.sql");
+        Pattern.compile("schema-([\\d.]+)-" + backendType.toLowerCase() + 
"\\.sql");
     Pattern upgradePattern =
-        Pattern.compile("upgrade-([\\d.]+)-to-([\\d.]+)-" + 
jdbcBackend.toLowerCase() + "\\.sql");
+        Pattern.compile("upgrade-([\\d.]+)-to-([\\d.]+)-" + 
backendType.toLowerCase() + "\\.sql");
     Pattern metricsPattern =
-        Pattern.compile("iceberg-metrics-schema-([\\d.]+)-" + 
jdbcBackend.toLowerCase() + "\\.sql");
+        Pattern.compile("iceberg-metrics-schema-([\\d.]+)-" + 
backendType.toLowerCase() + "\\.sql");
 
+    Map<String, List<File>> versionScrips = new HashMap<>();
     for (File scriptFile : scriptFiles) {
       Matcher schemaMatcher = schemaPattern.matcher(scriptFile.getName());
       Matcher upgradeMatcher = upgradePattern.matcher(scriptFile.getName());
       Matcher metricsMatcher = metricsPattern.matcher(scriptFile.getName());
 
       if (schemaMatcher.matches()) {
         String version = schemaMatcher.group(1);
-        String dbName = "schema_" + version.replace('.', '_');
-
-        Connection conn = getSQLConnection(jdbcBackend, dbName);
-        Assertions.assertDoesNotThrow(
-            () -> executeSQLScript(conn, scriptFile),
-            "Failed to execute schema script for version " + version);
-        versionConnections.put(version, conn);
+        versionScrips.computeIfAbsent(version, k -> new 
ArrayList<>()).add(scriptFile);
 
       } else if (upgradeMatcher.matches()) {
         String fromVersion = upgradeMatcher.group(1);
+        Assertions.assertTrue(
+            versionScrips.containsKey(fromVersion), "No schema script found 
for " + fromVersion);
 
-        Connection conn = versionConnections.get(fromVersion);
-        Assertions.assertNotNull(
-            conn, "No existing database connection found for version " + 
fromVersion);
-        Assertions.assertDoesNotThrow(
-            () -> executeSQLScript(conn, scriptFile),
-            "Failed to execute upgrade script" + " in file " + 
scriptFile.getName());
       } else if (metricsMatcher.matches()) {
-        // ignore iceberg metrics scripts for now
+        String version = metricsMatcher.group(1);
+        versionScrips.computeIfAbsent(version, k -> new 
ArrayList<>()).add(scriptFile);
+
       } else {
         Assertions.fail("Unrecognized script file name: " + 
scriptFile.getName());
       }
     }
+
+    for (List<File> scripts : versionScrips.values()) {
+      dropAllTables();
+      for (File scriptFile : scripts) {
+        String sqlContent = FileUtils.readFileToString(scriptFile, "UTF-8");
+        List<String> ddls =
+            Arrays.stream(sqlContent.split(";"))
+                .map(String::trim)
+                .filter(s -> !s.isEmpty())
+                .toList();
+
+        try (SqlSession sqlSession =
+            
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) 
{
+          try (Connection connection = sqlSession.getConnection()) {
+            try (Statement statement = connection.createStatement()) {
+              for (String ddl : ddls) {
+                Assertions.assertDoesNotThrow(
+                    () -> statement.execute(ddl),
+                    "Failed to execute DDL in file " + scriptFile.getName() + 
"ddl: " + ddl);
+              }
+            }
+          }
+        }
+      }
+    }
   }
 
-  private void executeSQLScript(Connection connection, File scriptFile) throws 
IOException {
-    String sqlContent = FileUtils.readFileToString(scriptFile, "UTF-8");
-    Arrays.stream(sqlContent.split(";"))
-        .map(String::trim)
-        .filter(s -> !s.isEmpty())
-        .forEach(
-            sql -> {
-              try (Statement stmt = connection.createStatement()) {
-                stmt.execute(sql);
-              } catch (SQLException e) {
-                throw new RuntimeException("Failed to execute SQL: " + sql, e);
+  private void dropAllTables() throws SQLException {
+    try (SqlSession sqlSession =
+        
SqlSessionFactoryHelper.getInstance().getSqlSessionFactory().openSession(true)) 
{
+      try (Connection connection = sqlSession.getConnection()) {
+        try (Statement statement = connection.createStatement()) {
+          if ("postgresql".equals(backendType)) {
+            dropAllTablesForPostgreSQL(connection);
+          } else {
+            String query = "SHOW TABLES";

Review Comment:
   fixed



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to