org.testcontainers
junit-jupiter
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 762ab420aa3ff4..395515a37272a1 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
@@ -119,6 +119,28 @@ public void processSuccessInClickHouse() throws SQLException {
assertThat(addressRepository.selectAll(), equalTo(Collections.emptyList()));
}
+ /**
+ * Process success in Hive.
+ * Hive has not fully supported BEGIN, COMMIT, and ROLLBACK. Refer to Hive Transactions.
+ * So ShardingSphere should not use {@link OrderItemRepository#assertRollbackWithTransactions()}
+ * TODO It seems that there is no way to force all HiveServer2 insert statements to complete.
+ * This results in the following assertion always failing, which needs to be investigated on the apache/hive side.
+ *
+ * insertDataInHive();
+ * assertThat(addressRepository.selectAll(),
+ * equalTo(LongStream.range(1L, 11L).mapToObj(each -> new Address(each, "address_test_" + each)).collect(Collectors.toList())));
+ *
+ * TODO It is currently not convenient to operate on the `t_order` and `t_order_item` tables because
+ * {@link org.apache.hive.jdbc.HiveStatement} does not implement {@link Statement#getGeneratedKeys()}
+ *
+ * @throws SQLException An exception that provides information on a database access error or other errors.
+ */
+ public void processSuccessInHive() throws SQLException {
+ insertDataInHive();
+ deleteDataInHive();
+ assertThat(addressRepository.selectAll(), equalTo(Collections.emptyList()));
+ }
+
/**
* Insert data.
*
@@ -151,6 +173,20 @@ public Collection insertData(final int autoGeneratedKeys) throws SQLExcept
return result;
}
+ /**
+ * Insert data in Hive.
+ */
+ public void insertDataInHive() {
+ LongStream.range(1L, 11L).forEach(action -> {
+ Address address = new Address(action, "address_test_" + action);
+ try {
+ addressRepository.insert(address);
+ } catch (final SQLException ex) {
+ throw new RuntimeException(ex);
+ }
+ });
+ }
+
/**
* Delete data.
*
@@ -181,6 +217,18 @@ public void deleteDataInClickHouse(final Collection orderIds) throws SQLEx
}
}
+ /**
+ * Delete data in Hive.
+ *
+ * @throws SQLException An exception that provides information on a database access error or other errors.
+ */
+ public void deleteDataInHive() throws SQLException {
+ long count = 1L;
+ for (int i = 1; i <= 10; i++) {
+ addressRepository.deleteInHive(count++);
+ }
+ }
+
/**
* Clean environment.
*
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 182913898cd479..ce0712efed868b 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
@@ -70,6 +70,25 @@ public void createTableInSQLServer() throws SQLException {
}
}
+ /**
+ * create table t_address if not exists in Hive.
+ *
+ * @throws SQLException SQL exception
+ */
+ public void createTableIfNotExistsInHive() throws SQLException {
+ String sql = "CREATE TABLE IF NOT EXISTS t_address\n"
+ + "(\n"
+ + " address_id BIGINT NOT NULL,\n"
+ + " address_name VARCHAR(100) NOT NULL,\n"
+ + " PRIMARY KEY (address_id) disable novalidate\n"
+ + ") CLUSTERED BY (address_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional'='true')";
+ try (
+ Connection connection = dataSource.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.executeUpdate(sql);
+ }
+ }
+
/**
* drop table t_address.
*
@@ -133,6 +152,22 @@ public void delete(final Long id) throws SQLException {
}
}
+ /**
+ * delete by id.
+ *
+ * @param id id
+ * @throws SQLException SQL exception
+ */
+ public void deleteInHive(final Long id) throws SQLException {
+ String sql = "DELETE FROM t_address WHERE address_id=?";
+ try (
+ Connection connection = dataSource.getConnection();
+ PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
+ preparedStatement.setLong(1, id);
+ preparedStatement.executeUpdate();
+ }
+ }
+
/**
* delete by id in ClickHouse.
*
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 b53071fb09087f..d9b32cbc462284 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
@@ -125,6 +125,28 @@ public void createTableIfNotExistsInClickHouse() throws SQLException {
}
}
+ /**
+ * create table if not exists in Hive.
+ * Hive does not support `AUTO_INCREMENT`, refer to HIVE-6905 .
+ *
+ * @throws SQLException SQL exception
+ */
+ public void createTableIfNotExistsInHive() throws SQLException {
+ String sql = "CREATE TABLE IF NOT EXISTS t_order_item\n"
+ + "(order_item_id BIGINT,\n"
+ + " order_id BIGINT NOT NULL,\n"
+ + " user_id INT NOT NULL,\n"
+ + " phone VARCHAR(50),\n"
+ + " status VARCHAR(50),\n"
+ + " PRIMARY KEY (order_item_id) disable novalidate\n"
+ + ") CLUSTERED BY (order_item_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional'='true')";
+ try (
+ Connection connection = dataSource.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.executeUpdate(sql);
+ }
+ }
+
/**
* drop table.
*
diff --git a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderRepository.java b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderRepository.java
index 7cded2baf10f56..b595b672190ba4 100644
--- a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderRepository.java
+++ b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/commons/repository/OrderRepository.java
@@ -122,6 +122,29 @@ public void createTableIfNotExistsInClickHouse() throws SQLException {
}
}
+ /**
+ * create table in Hive.
+ * Hive does not support `AUTO_INCREMENT`, refer to HIVE-6905 .
+ *
+ * @throws SQLException SQL exception
+ */
+ public void createTableIfNotExistsInHive() throws SQLException {
+ String sql = "CREATE TABLE IF NOT EXISTS t_order\n"
+ + "(\n"
+ + " order_id BIGINT,\n"
+ + " order_type INT,\n"
+ + " user_id INT NOT NULL,\n"
+ + " address_id BIGINT NOT NULL,\n"
+ + " status VARCHAR(50),\n"
+ + " PRIMARY KEY (order_id) disable novalidate\n"
+ + ") CLUSTERED BY (order_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional'='true')";
+ try (
+ Connection connection = dataSource.getConnection();
+ Statement statement = connection.createStatement()) {
+ statement.executeUpdate(sql);
+ }
+ }
+
/**
* drop table.
* TODO There is a bug in this function in shadow's unit test and requires additional fixes.
diff --git a/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/databases/HiveTest.java b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/databases/HiveTest.java
new file mode 100644
index 00000000000000..0c21ab91fcfe0c
--- /dev/null
+++ b/test/native/src/test/java/org/apache/shardingsphere/test/natived/jdbc/databases/HiveTest.java
@@ -0,0 +1,137 @@
+/*
+ * 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.shardingsphere.test.natived.jdbc.databases;
+
+import com.zaxxer.hikari.HikariConfig;
+import com.zaxxer.hikari.HikariDataSource;
+import org.apache.shardingsphere.test.natived.jdbc.commons.TestShardingService;
+import org.awaitility.Awaitility;
+import org.junit.jupiter.api.AfterAll;
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.condition.EnabledInNativeImage;
+import org.testcontainers.containers.GenericContainer;
+import org.testcontainers.junit.jupiter.Container;
+import org.testcontainers.junit.jupiter.Testcontainers;
+import org.testcontainers.utility.DockerImageName;
+
+import javax.sql.DataSource;
+import java.nio.file.Paths;
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.SQLException;
+import java.sql.Statement;
+import java.time.Duration;
+import java.util.Properties;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.nullValue;
+
+@SuppressWarnings({"SqlDialectInspection", "SqlNoDataSourceInspection"})
+@EnabledInNativeImage
+@Testcontainers
+class HiveTest {
+
+ @SuppressWarnings("resource")
+ @Container
+ public static final GenericContainer> CONTAINER = new GenericContainer<>(DockerImageName.parse("apache/hive:4.0.0"))
+ .withEnv("SERVICE_NAME", "hiveserver2")
+ .withExposedPorts(10000, 10002);
+
+ private static final String SYSTEM_PROP_KEY_PREFIX = "fixture.test-native.yaml.database.hive.";
+
+ // Due to https://issues.apache.org/jira/browse/HIVE-28317 , the `initFile` parameter of HiveServer2 JDBC Driver must be an absolute path.
+ private static final String ABSOLUTE_PATH = Paths.get("src/test/resources/test-native/sql/test-native-databases-hive.sql").toAbsolutePath().normalize().toString();
+
+ private String jdbcUrlPrefix;
+
+ private TestShardingService testShardingService;
+
+ @BeforeAll
+ static void beforeAll() {
+ assertThat(System.getProperty(SYSTEM_PROP_KEY_PREFIX + "ds0.jdbc-url"), is(nullValue()));
+ assertThat(System.getProperty(SYSTEM_PROP_KEY_PREFIX + "ds1.jdbc-url"), is(nullValue()));
+ assertThat(System.getProperty(SYSTEM_PROP_KEY_PREFIX + "ds2.jdbc-url"), is(nullValue()));
+ }
+
+ @AfterAll
+ static void afterAll() {
+ System.clearProperty(SYSTEM_PROP_KEY_PREFIX + "ds0.jdbc-url");
+ System.clearProperty(SYSTEM_PROP_KEY_PREFIX + "ds1.jdbc-url");
+ System.clearProperty(SYSTEM_PROP_KEY_PREFIX + "ds2.jdbc-url");
+ }
+
+ /**
+ * TODO Need to fix `shardingsphere-parser-sql-hive` module to use {@link TestShardingService#cleanEnvironment()}
+ * after {@link TestShardingService#processSuccessInHive()}.
+ *
+ * @throws SQLException An exception that provides information on a database access error or other errors.
+ */
+ @Test
+ void assertShardingInLocalTransactions() throws SQLException {
+ jdbcUrlPrefix = "jdbc:hive2://localhost:" + CONTAINER.getMappedPort(10000) + "/";
+ DataSource dataSource = createDataSource();
+ testShardingService = new TestShardingService(dataSource);
+ testShardingService.processSuccessInHive();
+ }
+
+ /**
+ * TODO Need to fix `shardingsphere-parser-sql-hive` module to use `initEnvironment()` before {@link TestShardingService#processSuccessInHive()}.
+ *
+ * @throws SQLException An exception that provides information on a database access error or other errors.
+ */
+ @SuppressWarnings("unused")
+ private void initEnvironment() throws SQLException {
+ testShardingService.getOrderRepository().createTableIfNotExistsInHive();
+ testShardingService.getOrderItemRepository().createTableIfNotExistsInHive();
+ testShardingService.getAddressRepository().createTableIfNotExistsInHive();
+ testShardingService.getOrderRepository().truncateTable();
+ testShardingService.getOrderItemRepository().truncateTable();
+ testShardingService.getAddressRepository().truncateTable();
+ }
+
+ private Connection openConnection() throws SQLException {
+ Properties props = new Properties();
+ return DriverManager.getConnection(jdbcUrlPrefix, props);
+ }
+
+ private DataSource createDataSource() throws SQLException {
+ Awaitility.await().atMost(Duration.ofMinutes(1L)).ignoreExceptions().until(() -> {
+ openConnection().close();
+ return true;
+ });
+ try (
+ Connection connection = openConnection();
+ Statement statement = connection.createStatement()) {
+ statement.execute("set metastore.compactor.initiator.on=true");
+ statement.execute("set metastore.compactor.cleaner.on=true");
+ statement.execute("set metastore.compactor.worker.threads=5");
+ statement.executeUpdate("CREATE DATABASE demo_ds_0");
+ statement.executeUpdate("CREATE DATABASE demo_ds_1");
+ statement.executeUpdate("CREATE DATABASE demo_ds_2");
+ }
+ HikariConfig config = new HikariConfig();
+ config.setDriverClassName("org.apache.shardingsphere.driver.ShardingSphereDriver");
+ config.setJdbcUrl("jdbc:shardingsphere:classpath:test-native/yaml/databases/hive.yaml?placeholder-type=system_props");
+ System.setProperty(SYSTEM_PROP_KEY_PREFIX + "ds0.jdbc-url", jdbcUrlPrefix + "demo_ds_0" + ";initFile=" + ABSOLUTE_PATH);
+ System.setProperty(SYSTEM_PROP_KEY_PREFIX + "ds1.jdbc-url", jdbcUrlPrefix + "demo_ds_1" + ";initFile=" + ABSOLUTE_PATH);
+ System.setProperty(SYSTEM_PROP_KEY_PREFIX + "ds2.jdbc-url", jdbcUrlPrefix + "demo_ds_2" + ";initFile=" + ABSOLUTE_PATH);
+ return new HikariDataSource(config);
+ }
+}
diff --git a/infra/database/type/hive/src/main/resources/META-INF/services/org.apache.shardingsphere.infra.database.core.metadata.data.loader.DialectMetaDataLoader b/test/native/src/test/resources/META-INF/native-image/io.grpc/grpc-netty-shaded/native-image.properties
similarity index 57%
rename from infra/database/type/hive/src/main/resources/META-INF/services/org.apache.shardingsphere.infra.database.core.metadata.data.loader.DialectMetaDataLoader
rename to test/native/src/test/resources/META-INF/native-image/io.grpc/grpc-netty-shaded/native-image.properties
index 6522f228700754..9178449a17048a 100644
--- a/infra/database/type/hive/src/main/resources/META-INF/services/org.apache.shardingsphere.infra.database.core.metadata.data.loader.DialectMetaDataLoader
+++ b/test/native/src/test/resources/META-INF/native-image/io.grpc/grpc-netty-shaded/native-image.properties
@@ -14,5 +14,12 @@
# See the License for the specific language governing permissions and
# limitations under the License.
#
-
-org.apache.shardingsphere.infra.database.hive.metadata.data.loader.HiveMetaDataLoader
+# TODO This file exists to address https://github.com/grpc/grpc-java/issues/10601 .
+Args=--initialize-at-run-time=\
+ io.grpc.netty.shaded.io.netty.channel.ChannelHandlerMask,\
+ io.grpc.netty.shaded.io.netty.channel.nio.AbstractNioChannel,\
+ io.grpc.netty.shaded.io.netty.channel.socket.nio.SelectorProviderUtil,\
+ io.grpc.netty.shaded.io.netty.util.concurrent.DefaultPromise,\
+ io.grpc.netty.shaded.io.netty.util.internal.MacAddressUtil,\
+ io.grpc.netty.shaded.io.netty.util.internal.SystemPropertyUtil,\
+ io.grpc.netty.shaded.io.netty.util.NetUtilInitializations
diff --git a/test/native/src/test/resources/test-native/sql/test-native-databases-hive.sql b/test/native/src/test/resources/test-native/sql/test-native-databases-hive.sql
new file mode 100644
index 00000000000000..d23900f7d799c0
--- /dev/null
+++ b/test/native/src/test/resources/test-native/sql/test-native-databases-hive.sql
@@ -0,0 +1,54 @@
+--
+-- 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.
+--
+
+
+-- TODO To execute SQL like `DELETE FROM t_address WHERE address_id=?`, we always need to execute the following Hive Session-level SQL in the current `javax.sql.DataSource`.
+-- `shardingsphere-parser-sql-hive` module does not support `CREATE`, `SET`, `TRUNCATE` statements yet.
+set hive.support.concurrency=true;
+set hive.exec.dynamic.partition.mode=nonstrict;
+set hive.txn.manager=org.apache.hadoop.hive.ql.lockmgr.DbTxnManager;
+
+CREATE TABLE IF NOT EXISTS t_order
+(
+ order_id BIGINT,
+ order_type INT,
+ user_id INT NOT NULL,
+ address_id BIGINT NOT NULL,
+ status VARCHAR(50),
+ PRIMARY KEY (order_id) disable novalidate
+) CLUSTERED BY (order_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional' = 'true');
+
+CREATE TABLE IF NOT EXISTS t_order_item
+(
+ order_item_id BIGINT,
+ order_id BIGINT NOT NULL,
+ user_id INT NOT NULL,
+ phone VARCHAR(50),
+ status VARCHAR(50),
+ PRIMARY KEY (order_item_id) disable novalidate
+) CLUSTERED BY (order_item_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional' = 'true');
+
+CREATE TABLE IF NOT EXISTS t_address
+(
+ address_id BIGINT NOT NULL,
+ address_name VARCHAR(100) NOT NULL,
+ PRIMARY KEY (address_id) disable novalidate
+) CLUSTERED BY (address_id) INTO 2 BUCKETS STORED AS ORC TBLPROPERTIES ('transactional' = 'true');
+
+TRUNCATE TABLE t_order;
+TRUNCATE TABLE t_order_item;
+TRUNCATE TABLE t_address;
diff --git a/test/native/src/test/resources/test-native/yaml/databases/hive.yaml b/test/native/src/test/resources/test-native/yaml/databases/hive.yaml
new file mode 100644
index 00000000000000..c44cd303bb3bc5
--- /dev/null
+++ b/test/native/src/test/resources/test-native/yaml/databases/hive.yaml
@@ -0,0 +1,72 @@
+#
+# 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.
+#
+
+mode:
+ type: Standalone
+ repository:
+ type: JDBC
+
+dataSources:
+ ds_0:
+ dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+ driverClassName: org.apache.hive.jdbc.HiveDriver
+ jdbcUrl: $${fixture.test-native.yaml.database.hive.ds0.jdbc-url::}
+ ds_1:
+ dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+ driverClassName: org.apache.hive.jdbc.HiveDriver
+ jdbcUrl: $${fixture.test-native.yaml.database.hive.ds1.jdbc-url::}
+ ds_2:
+ dataSourceClassName: com.zaxxer.hikari.HikariDataSource
+ driverClassName: org.apache.hive.jdbc.HiveDriver
+ jdbcUrl: $${fixture.test-native.yaml.database.hive.ds2.jdbc-url::}
+
+rules:
+- !SHARDING
+ tables:
+ t_order:
+ actualDataNodes:
+ keyGenerateStrategy:
+ column: order_id
+ keyGeneratorName: snowflake
+ t_order_item:
+ actualDataNodes:
+ keyGenerateStrategy:
+ column: order_item_id
+ keyGeneratorName: snowflake
+ defaultDatabaseStrategy:
+ standard:
+ shardingColumn: user_id
+ shardingAlgorithmName: inline
+ shardingAlgorithms:
+ inline:
+ type: CLASS_BASED
+ props:
+ strategy: STANDARD
+ algorithmClassName: org.apache.shardingsphere.test.natived.jdbc.commons.algorithm.ClassBasedInlineShardingAlgorithmFixture
+ keyGenerators:
+ snowflake:
+ type: SNOWFLAKE
+ auditors:
+ sharding_key_required_auditor:
+ type: DML_SHARDING_CONDITIONS
+
+- !BROADCAST
+ tables:
+ - t_address
+
+props:
+ sql-show: false