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

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


The following commit(s) were added to refs/heads/master by this push:
     new ff8363027df Refactor Seata's nativeTest integrated under GraalVM 
Native Image (#30655)
ff8363027df is described below

commit ff8363027df30a72c60ad92424d8ce3f29c807d3
Author: Ling Hengqian <[email protected]>
AuthorDate: Tue Mar 26 17:23:55 2024 +0800

    Refactor Seata's nativeTest integrated under GraalVM Native Image (#30655)
---
 .../natived/jdbc/commons/TestShardingService.java  |  2 +-
 .../jdbc/commons/repository/AddressRepository.java | 29 -------
 .../commons/repository/OrderItemRepository.java    | 29 +++++++
 .../natived/jdbc/transactions/base/SeataTest.java  | 90 +++-------------------
 .../resource-config.json                           |  5 +-
 .../sql/seata-script-client-at-postgresql.sql      | 42 ++++++++++
 .../test-native/yaml/transactions/base/seata.yaml  |  6 +-
 7 files changed, 88 insertions(+), 115 deletions(-)

diff --git 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/TestShardingService.java
 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/TestShardingService.java
index 8e734f8d956..420d449a5b4 100644
--- 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/TestShardingService.java
+++ 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/TestShardingService.java
@@ -81,7 +81,7 @@ public final class TestShardingService {
         assertThat(orderRepository.selectAll(), equalTo(new ArrayList<>()));
         assertThat(orderItemRepository.selectAll(), equalTo(new 
ArrayList<>()));
         assertThat(addressRepository.selectAll(), equalTo(new ArrayList<>()));
-        addressRepository.assertRollbackWithTransactions();
+        orderItemRepository.assertRollbackWithTransactions();
     }
     
     /**
diff --git 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/AddressRepository.java
 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/AddressRepository.java
index 20dae557980..4c6f5f2c124 100644
--- 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/AddressRepository.java
+++ 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/AddressRepository.java
@@ -28,9 +28,6 @@ import java.sql.Statement;
 import java.util.LinkedList;
 import java.util.List;
 
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-
 @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"})
 public final class AddressRepository {
     
@@ -158,30 +155,4 @@ public final class AddressRepository {
         }
         return result;
     }
-    
-    /**
-     * Assert rollback with transactions.
-     * This is currently just a simple test against a non-existent table and 
does not involve the competition scenario of distributed transactions.
-     *
-     * @throws SQLException An exception that provides information on a 
database access error or other errors.
-     */
-    public void assertRollbackWithTransactions() throws SQLException {
-        Connection connection = dataSource.getConnection();
-        try {
-            connection.setAutoCommit(false);
-            connection.createStatement().executeUpdate("INSERT INTO t_address 
(address_id, address_name) VALUES (2024, 'address_test_2024')");
-            connection.createStatement().executeUpdate("INSERT INTO 
t_table_does_not_exist (test_id_does_not_exist) VALUES (2024)");
-            connection.commit();
-        } catch (SQLException e) {
-            connection.rollback();
-        } finally {
-            connection.setAutoCommit(true);
-            connection.close();
-        }
-        try (
-                Connection conn = dataSource.getConnection();
-                ResultSet resultSet = 
conn.createStatement().executeQuery("SELECT * FROM t_address WHERE address_id = 
2024")) {
-            assertThat(resultSet.next(), is(false));
-        }
-    }
 }
diff --git 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderItemRepository.java
 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderItemRepository.java
index 28933d400dc..c76158b5a73 100644
--- 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderItemRepository.java
+++ 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderItemRepository.java
@@ -28,6 +28,9 @@ import java.sql.Statement;
 import java.util.LinkedList;
 import java.util.List;
 
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+
 @SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"})
 public final class OrderItemRepository {
     
@@ -222,4 +225,30 @@ public final class OrderItemRepository {
         }
         return result;
     }
+    
+    /**
+     * Assert rollback with transactions.
+     * This is currently just a simple test against a non-existent table and 
does not involve the competition scenario of distributed transactions.
+     *
+     * @throws SQLException An exception that provides information on a 
database access error or other errors.
+     */
+    public void assertRollbackWithTransactions() throws SQLException {
+        Connection connection = dataSource.getConnection();
+        try {
+            connection.setAutoCommit(false);
+            connection.createStatement().executeUpdate("INSERT INTO 
t_order_item (order_id, user_id, phone, status) VALUES (2024, 2024, 
'13800000001', 'INSERT_TEST')");
+            connection.createStatement().executeUpdate("INSERT INTO 
t_order_item_does_not_exist (test_id_does_not_exist) VALUES (2024)");
+            connection.commit();
+        } catch (SQLException e) {
+            connection.rollback();
+        } finally {
+            connection.setAutoCommit(true);
+            connection.close();
+        }
+        try (
+                Connection conn = dataSource.getConnection();
+                ResultSet resultSet = 
conn.createStatement().executeQuery("SELECT * FROM t_order_item WHERE user_id = 
2024")) {
+            assertThat(resultSet.next(), is(false));
+        }
+    }
 }
diff --git 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/transactions/base/SeataTest.java
 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/transactions/base/SeataTest.java
index 24c845fd382..51d87aefda0 100644
--- 
a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/transactions/base/SeataTest.java
+++ 
b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/transactions/base/SeataTest.java
@@ -19,32 +19,25 @@ package 
org.apache.shardingsphere.test.natived.jdbc.transactions.base;
 
 import com.zaxxer.hikari.HikariConfig;
 import com.zaxxer.hikari.HikariDataSource;
-import org.apache.hc.client5.http.classic.methods.HttpGet;
-import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
-import org.apache.hc.client5.http.impl.classic.CloseableHttpResponse;
-import org.apache.hc.client5.http.impl.classic.HttpClients;
 import org.apache.hc.core5.http.HttpStatus;
-import org.apache.hc.core5.http.io.entity.EntityUtils;
 import org.apache.shardingsphere.test.natived.jdbc.commons.TestShardingService;
-import org.awaitility.Awaitility;
 import org.junit.jupiter.api.Test;
 import org.junit.jupiter.api.condition.EnabledInNativeImage;
 import org.testcontainers.containers.FixedHostPortGenericContainer;
 import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.containers.wait.strategy.Wait;
 
 import javax.sql.DataSource;
-import java.io.IOException;
-import java.sql.Connection;
-import java.sql.DriverManager;
 import java.sql.SQLException;
-import java.time.Duration;
-import java.util.Properties;
-import java.util.stream.Stream;
 
 class SeataTest {
     
     private TestShardingService testShardingService;
     
+    /**
+     * Further processing of `/health` awaits <a 
href="https://github.com/apache/incubator-seata/pull/6356";>apache/incubator-seata#6356</a>.
+     * @throws SQLException An exception that provides information on a 
database access error or other errors.
+     */
     @SuppressWarnings({"resource", "deprecation"})
     @Test
     @EnabledInNativeImage
@@ -52,9 +45,10 @@ class SeataTest {
         try (
                 GenericContainer<?> container = new 
FixedHostPortGenericContainer<>("seataio/seata-server:1.8.0")
                         .withFixedExposedPort(39567, 8091)
-                        .withExposedPorts(7091)) {
+                        .withExposedPorts(7091)
+                        
.waitingFor(Wait.forHttp("/health").forPort(7091).forStatusCode(HttpStatus.SC_UNAUTHORIZED)))
 {
             container.start();
-            DataSource dataSource = 
createDataSource(container.getMappedPort(7091));
+            DataSource dataSource = createDataSource();
             testShardingService = new TestShardingService(dataSource);
             this.initEnvironment();
             testShardingService.processSuccess();
@@ -71,76 +65,10 @@ class SeataTest {
         testShardingService.getAddressRepository().truncateTable();
     }
     
-    private Connection openConnection(final String databaseName) throws 
SQLException {
-        final String jdbcUrlPrefix = 
"jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/";
-        return DriverManager.getConnection(jdbcUrlPrefix + databaseName + 
"?TC_DAEMON=true", new Properties());
-    }
-    
-    private DataSource createDataSource(final Integer 
seataServerHealthCheckPort) {
-        Awaitility.await().atMost(Duration.ofMinutes(1)).ignoreExceptions()
-                .until(() -> 
verifySeataServerRunning(seataServerHealthCheckPort));
-        final String firstSql = "CREATE TABLE IF NOT EXISTS public.undo_log\n"
-                + "(\n"
-                + "    id            SERIAL       NOT NULL,\n"
-                + "    branch_id     BIGINT       NOT NULL,\n"
-                + "    xid           VARCHAR(128) NOT NULL,\n"
-                + "    context       VARCHAR(128) NOT NULL,\n"
-                + "    rollback_info BYTEA        NOT NULL,\n"
-                + "    log_status    INT          NOT NULL,\n"
-                + "    log_created   TIMESTAMP(0) NOT NULL,\n"
-                + "    log_modified  TIMESTAMP(0) NOT NULL,\n"
-                + "    CONSTRAINT pk_undo_log PRIMARY KEY (id),\n"
-                + "    CONSTRAINT ux_undo_log UNIQUE (xid, branch_id)\n"
-                + ");";
-        final String secondSql = "CREATE INDEX ix_log_created ON 
undo_log(log_created);";
-        final String thirdSql = "COMMENT ON TABLE public.undo_log IS 'AT 
transaction mode undo table';";
-        final String fourthSql = "COMMENT ON COLUMN public.undo_log.branch_id 
IS 'branch transaction id';";
-        final String fifthSql = "COMMENT ON COLUMN public.undo_log.xid IS 
'global transaction id';";
-        final String sixthSql = "COMMENT ON COLUMN public.undo_log.context IS 
'undo_log context,such as serialization';";
-        final String seventhSql = "COMMENT ON COLUMN 
public.undo_log.rollback_info IS 'rollback info';";
-        final String eighthSql = "COMMENT ON COLUMN public.undo_log.log_status 
IS '0:normal status,1:defense status';";
-        final String ninthSql = "COMMENT ON COLUMN public.undo_log.log_created 
IS 'create datetime';";
-        final String tenthSql = "COMMENT ON COLUMN 
public.undo_log.log_modified IS 'modify datetime';";
-        final String eleventhSql = "CREATE SEQUENCE IF NOT EXISTS 
undo_log_id_seq INCREMENT BY 1 MINVALUE 1 ;";
-        Stream.of(firstSql, secondSql, thirdSql, fourthSql, fifthSql, 
sixthSql, seventhSql, eighthSql, ninthSql, tenthSql, eleventhSql)
-                .forEachOrdered(this::executeSqlToShardingDB);
+    private DataSource createDataSource() {
         HikariConfig config = new HikariConfig();
         
config.setDriverClassName("org.apache.shardingsphere.driver.ShardingSphereDriver");
         
config.setJdbcUrl("jdbc:shardingsphere:classpath:test-native/yaml/transactions/base/seata.yaml");
         return new HikariDataSource(config);
     }
-    
-    /**
-     * Further processing of this class awaits <a 
href="https://github.com/apache/incubator-seata/pull/6356";>apache/incubator-seata#6356</a>.
-     *
-     * @param seataServerHealthCheckPort The port of the host corresponding to 
port `7091` inside the container
-     * @return Returns true if Seata Server is running normally.
-     * @throws IOException Signals that an I/O exception to some sort has 
occurred.
-     */
-    private static boolean verifySeataServerRunning(final Integer 
seataServerHealthCheckPort) throws IOException {
-        boolean flag = false;
-        HttpGet httpGet = new HttpGet("http://localhost:"; + 
seataServerHealthCheckPort + "/health");
-        try (
-                CloseableHttpClient httpclient = HttpClients.createDefault();
-                CloseableHttpResponse response = httpclient.execute(httpGet)) {
-            if (HttpStatus.SC_UNAUTHORIZED == response.getCode()) {
-                flag = true;
-            }
-            EntityUtils.consume(response.getEntity());
-        }
-        return flag;
-    }
-    
-    private void executeSqlToShardingDB(final String sqlString) {
-        try (
-                Connection ds0Connection = openConnection("demo_ds_0");
-                Connection ds1Connection = openConnection("demo_ds_1");
-                Connection ds2Connection = openConnection("demo_ds_2")) {
-            ds0Connection.createStatement().executeUpdate(sqlString);
-            ds1Connection.createStatement().executeUpdate(sqlString);
-            ds2Connection.createStatement().executeUpdate(sqlString);
-        } catch (SQLException e) {
-            throw new RuntimeException(e);
-        }
-    }
 }
diff --git 
a/test/native/src/test/resources/META-INF/native-image/shardingsphere-test-native-test-metadata/resource-config.json
 
b/test/native/src/test/resources/META-INF/native-image/shardingsphere-test-native-test-metadata/resource-config.json
index 7930e72de98..6cc480e7418 100644
--- 
a/test/native/src/test/resources/META-INF/native-image/shardingsphere-test-native-test-metadata/resource-config.json
+++ 
b/test/native/src/test/resources/META-INF/native-image/shardingsphere-test-native-test-metadata/resource-config.json
@@ -54,9 +54,12 @@
   }, {
     
"condition":{"typeReachable":"org.apache.shardingsphere.test.natived.jdbc.transactions.base.SeataTest"},
     "pattern":"\\Qregistry.conf\\E"
-  },{
+  }, {
     
"condition":{"typeReachable":"org.apache.shardingsphere.test.natived.jdbc.transactions.base.SeataTest"},
     "pattern":"\\Qseata.conf\\E"
+  }, {
+    
"condition":{"typeReachable":"org.apache.shardingsphere.test.natived.jdbc.transactions.base.SeataTest"},
+    "pattern":"\\Qtest-native/sql/seata-script-client-at-postgresql.sql\\E"
   }]},
   "bundles":[]
 }
diff --git 
a/test/native/src/test/resources/test-native/sql/seata-script-client-at-postgresql.sql
 
b/test/native/src/test/resources/test-native/sql/seata-script-client-at-postgresql.sql
new file mode 100644
index 00000000000..f0eabd93a51
--- /dev/null
+++ 
b/test/native/src/test/resources/test-native/sql/seata-script-client-at-postgresql.sql
@@ -0,0 +1,42 @@
+--
+-- 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.
+--
+
+CREATE TABLE IF NOT EXISTS public.undo_log
+(
+    id            SERIAL       NOT NULL,
+    branch_id     BIGINT       NOT NULL,
+    xid           VARCHAR(128) NOT NULL,
+    context       VARCHAR(128) NOT NULL,
+    rollback_info BYTEA        NOT NULL,
+    log_status    INT          NOT NULL,
+    log_created   TIMESTAMP(0) NOT NULL,
+    log_modified  TIMESTAMP(0) NOT NULL,
+    CONSTRAINT pk_undo_log PRIMARY KEY (id),
+    CONSTRAINT ux_undo_log UNIQUE (xid, branch_id)
+    );
+CREATE INDEX ix_log_created ON undo_log(log_created);
+
+COMMENT ON TABLE public.undo_log IS 'AT transaction mode undo table';
+COMMENT ON COLUMN public.undo_log.branch_id IS 'branch transaction id';
+COMMENT ON COLUMN public.undo_log.xid IS 'global transaction id';
+COMMENT ON COLUMN public.undo_log.context IS 'undo_log context,such as 
serialization';
+COMMENT ON COLUMN public.undo_log.rollback_info IS 'rollback info';
+COMMENT ON COLUMN public.undo_log.log_status IS '0:normal status,1:defense 
status';
+COMMENT ON COLUMN public.undo_log.log_created IS 'create datetime';
+COMMENT ON COLUMN public.undo_log.log_modified IS 'modify datetime';
+
+CREATE SEQUENCE IF NOT EXISTS undo_log_id_seq INCREMENT BY 1 MINVALUE 1 ;
diff --git 
a/test/native/src/test/resources/test-native/yaml/transactions/base/seata.yaml 
b/test/native/src/test/resources/test-native/yaml/transactions/base/seata.yaml
index 7dab3be115b..eefd8ce8ff3 100644
--- 
a/test/native/src/test/resources/test-native/yaml/transactions/base/seata.yaml
+++ 
b/test/native/src/test/resources/test-native/yaml/transactions/base/seata.yaml
@@ -24,15 +24,15 @@ dataSources:
   ds_0:
     dataSourceClassName: com.zaxxer.hikari.HikariDataSource
     driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
-    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_0?TC_DAEMON=true
+    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_0?TC_DAEMON=true?TC_INITSCRIPT=test-native/sql/seata-script-client-at-postgresql.sql
   ds_1:
     dataSourceClassName: com.zaxxer.hikari.HikariDataSource
     driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
-    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_1?TC_DAEMON=true
+    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_1?TC_DAEMON=true?TC_INITSCRIPT=test-native/sql/seata-script-client-at-postgresql.sql
   ds_2:
     dataSourceClassName: com.zaxxer.hikari.HikariDataSource
     driverClassName: org.testcontainers.jdbc.ContainerDatabaseDriver
-    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_2?TC_DAEMON=true
+    jdbcUrl: 
jdbc:tc:postgresql:16.2-bookworm://test-native-transactions-base/demo_ds_2?TC_DAEMON=true?TC_INITSCRIPT=test-native/sql/seata-script-client-at-postgresql.sql
 
 rules:
 - !SHARDING

Reply via email to