You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by ch...@apache.org on 2023/06/28 03:18:15 UTC
[shardingsphere] branch master updated: Move openGauss system function query logic to sql federation (#26581)
This is an automated email from the ASF dual-hosted git repository.
chengzhang 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 367ce3d7ced Move openGauss system function query logic to sql federation (#26581)
367ce3d7ced is described below
commit 367ce3d7ced673a5eec76b04bb18d4338b7e8553
Author: Zhengqiang Duan <du...@apache.org>
AuthorDate: Wed Jun 28 11:18:07 2023 +0800
Move openGauss system function query logic to sql federation (#26581)
* Move openGauss system function query logic to sql federation
* fix unit test and e2e
* extract magic number to constant
* replace treeset with hashset
* put constant to left condition
* revert unit test
* replace treeset with hashset in SystemSchemaUtils
* fix hep planner exception when execute same sql with different database
* fix hep planner optimize exception
* test e2e
* test e2e
* test e2e
* correct ShardingSQLFederationDecider judge logic when contains only one sharding table
* Remove metadata in ThreadLocal
* Remove wrong scenario
* Remove wrong scenario
* Revert e2e test
* Refactor SQLFederationCompiler logic
* revise logic
* test e2e
* Revert e2e test case
* close useCache temporarily
* Revert e2e config
---
.../decider/ShardingSQLFederationDecider.java | 2 +-
.../decider/ShardingSQLFederationDeciderTest.java | 13 ++
.../database/schema/util/SystemSchemaUtils.java | 27 ++++
.../compiler/SQLFederationCompilerEngine.java | 7 +-
.../dialect/impl/OpenGaussOptimizerBuilder.java | 2 +-
.../dialect/impl/PostgreSQLOptimizerBuilder.java | 2 +-
.../metadata/schema/SQLFederationTable.java | 4 +-
.../planner/cache/ExecutionPlanCacheBuilder.java | 7 +-
.../planner/cache/ExecutionPlanCacheKey.java | 3 +
.../planner/cache/ExecutionPlanCacheLoader.java | 9 +-
.../planner/util/SQLFederationFunctionUtils.java | 116 +++++++++++++++
.../planner/util/SQLFederationPlannerUtils.java | 34 +----
.../compiler/statement/SQLStatementCompiler.java | 1 +
.../statement/SQLStatementCompilerEngine.java | 9 +-
.../SQLStatementCompilerEngineFactory.java | 9 +-
.../sqlfederation/engine/SQLFederationEngine.java | 17 ++-
.../EnumerablePushDownTableScanExecutor.java | 105 ++++++++++++--
.../resultset/SQLFederationResultSetMetaData.java | 13 +-
.../compiler/it/SQLFederationCompilerEngineIT.java | 13 +-
.../admin/OpenGaussAdminExecutorCreator.java | 2 +-
.../OpenGaussSystemCatalogAdminQueryExecutor.java | 156 ++++++++-------------
.../handler/admin/schema/OpenGaussDatabase.java | 33 -----
.../handler/admin/schema/OpenGaussRoles.java | 33 -----
.../admin/schema/OpenGaussSystemCatalog.java | 36 -----
.../handler/admin/schema/OpenGaussTables.java | 33 -----
.../admin/OpenGaussAdminExecutorCreatorTest.java | 2 +-
.../admin/OpenGaussAdminExecutorFactoryTest.java | 2 +-
...enGaussSystemCatalogAdminQueryExecutorTest.java | 145 ++++++++++++++++---
.../test/e2e/engine/type/dql/GeneralDQLE2EIT.java | 1 -
.../cases/dql/dql-integration-select-sub-query.xml | 3 +-
30 files changed, 498 insertions(+), 341 deletions(-)
diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDecider.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDecider.java
index 0c13840cc1a..b3db13e145b 100644
--- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDecider.java
+++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDecider.java
@@ -57,7 +57,7 @@ public final class ShardingSQLFederationDecider implements SQLFederationDecider<
if (!selectStatementContext.isContainsJoinQuery() || rule.isAllTablesInSameDataSource(tableNames)) {
return false;
}
- return tableNames.size() <= 1 || !rule.isAllBindingTables(database, selectStatementContext, tableNames);
+ return tableNames.size() > 1 && !rule.isAllBindingTables(database, selectStatementContext, tableNames);
}
private Collection<DataNode> getTableDataNodes(final ShardingRule rule, final Collection<String> tableNames) {
diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDeciderTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDeciderTest.java
index 6466af9bd83..579d8e08747 100644
--- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDeciderTest.java
+++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/decider/ShardingSQLFederationDeciderTest.java
@@ -134,6 +134,19 @@ class ShardingSQLFederationDeciderTest {
assertThat(includedDataNodes.size(), is(4));
}
+ @Test
+ void assertDecideWhenContainsOnlyOneTable() {
+ SelectStatementContext select = createStatementContext();
+ when(select.getTablesContext().getTableNames()).thenReturn(Collections.singletonList("t_order"));
+ when(select.isContainsJoinQuery()).thenReturn(true);
+ ShardingRule shardingRule = createShardingRule();
+ when(shardingRule.getShardingLogicTableNames(Collections.singletonList("t_order"))).thenReturn(Collections.singletonList("t_order"));
+ ShardingSphereDatabase database = createDatabase();
+ when(shardingRule.isAllBindingTables(database, select, Collections.singletonList("t_order"))).thenReturn(false);
+ Collection<DataNode> includedDataNodes = new HashSet<>();
+ assertFalse(new ShardingSQLFederationDecider().decide(select, Collections.emptyList(), mock(ShardingSphereRuleMetaData.class), database, shardingRule, includedDataNodes));
+ }
+
@Test
void assertDecideWhenAllTablesIsNotBindingTablesAndContainsPagination() {
SelectStatementContext select = createStatementContext();
diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/util/SystemSchemaUtils.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/util/SystemSchemaUtils.java
index 13099561142..2ff3f23ba23 100644
--- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/util/SystemSchemaUtils.java
+++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/util/SystemSchemaUtils.java
@@ -21,9 +21,13 @@ import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.database.type.SchemaSupportedDatabaseType;
+import org.apache.shardingsphere.infra.database.type.dialect.OpenGaussDatabaseType;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ExpressionProjectionSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ProjectionSegment;
import java.util.Collection;
+import java.util.HashSet;
/**
* System schema utility.
@@ -31,6 +35,14 @@ import java.util.Collection;
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class SystemSchemaUtils {
+ private static final Collection<String> SYSTEM_CATALOG_QUERY_EXPRESSIONS = new HashSet<>(3, 1F);
+
+ static {
+ SYSTEM_CATALOG_QUERY_EXPRESSIONS.add("version()");
+ SYSTEM_CATALOG_QUERY_EXPRESSIONS.add("intervaltonum(gs_password_deadline())");
+ SYSTEM_CATALOG_QUERY_EXPRESSIONS.add("gs_password_notifytime()");
+ }
+
/**
* Judge whether SQL statement contains system schema or not.
*
@@ -50,4 +62,19 @@ public final class SystemSchemaUtils {
}
return !(databaseType instanceof SchemaSupportedDatabaseType) && databaseType.getSystemSchemas().contains(database.getName());
}
+
+ /**
+ * Judge whether query is openGauss system catalog query or not.
+ *
+ * @param databaseType database type
+ * @param projections projections
+ * @return whether query is openGauss system catalog query or not
+ */
+ public static boolean isOpenGaussSystemCatalogQuery(final DatabaseType databaseType, final Collection<ProjectionSegment> projections) {
+ if (!(databaseType instanceof OpenGaussDatabaseType)) {
+ return false;
+ }
+ return 1 == projections.size() && projections.iterator().next() instanceof ExpressionProjectionSegment
+ && SYSTEM_CATALOG_QUERY_EXPRESSIONS.contains(((ExpressionProjectionSegment) projections.iterator().next()).getText().toLowerCase());
+ }
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/SQLFederationCompilerEngine.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/SQLFederationCompilerEngine.java
index 5156c0a5213..33fdbe240da 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/SQLFederationCompilerEngine.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/SQLFederationCompilerEngine.java
@@ -18,10 +18,9 @@
package org.apache.shardingsphere.sqlfederation.compiler;
import org.apache.shardingsphere.sql.parser.api.CacheOption;
-import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
+import org.apache.shardingsphere.sqlfederation.compiler.planner.cache.ExecutionPlanCacheKey;
import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompilerEngine;
import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompilerEngineFactory;
-import org.apache.shardingsphere.sqlfederation.compiler.planner.cache.ExecutionPlanCacheKey;
/**
* SQL federation compiler engine.
@@ -30,8 +29,8 @@ public final class SQLFederationCompilerEngine {
private final SQLStatementCompilerEngine sqlStatementCompilerEngine;
- public SQLFederationCompilerEngine(final String schemaName, final SQLStatementCompiler sqlStatementCompiler, final CacheOption cacheOption) {
- sqlStatementCompilerEngine = SQLStatementCompilerEngineFactory.getSQLStatementCompilerEngine(schemaName, sqlStatementCompiler, cacheOption);
+ public SQLFederationCompilerEngine(final String databaseName, final String schemaName, final CacheOption cacheOption) {
+ sqlStatementCompilerEngine = SQLStatementCompilerEngineFactory.getSQLStatementCompilerEngine(databaseName, schemaName, cacheOption);
}
/**
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/OpenGaussOptimizerBuilder.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/OpenGaussOptimizerBuilder.java
index 00a6b021357..cb7bc9903c5 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/OpenGaussOptimizerBuilder.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/OpenGaussOptimizerBuilder.java
@@ -36,7 +36,7 @@ public final class OpenGaussOptimizerBuilder implements OptimizerSQLDialectBuild
result.setProperty(CalciteConnectionProperty.LEX.camelName(), Lex.JAVA.name());
result.setProperty(CalciteConnectionProperty.CONFORMANCE.camelName(), SqlConformanceEnum.BABEL.name());
result.setProperty(CalciteConnectionProperty.FUN.camelName(), SqlLibrary.POSTGRESQL.fun);
- result.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), String.valueOf(Lex.JAVA.caseSensitive));
+ result.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), String.valueOf(false));
return result;
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/PostgreSQLOptimizerBuilder.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/PostgreSQLOptimizerBuilder.java
index 09e69781171..95f63b635f4 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/PostgreSQLOptimizerBuilder.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/context/parser/dialect/impl/PostgreSQLOptimizerBuilder.java
@@ -36,7 +36,7 @@ public final class PostgreSQLOptimizerBuilder implements OptimizerSQLDialectBuil
result.setProperty(CalciteConnectionProperty.LEX.camelName(), Lex.JAVA.name());
result.setProperty(CalciteConnectionProperty.CONFORMANCE.camelName(), SqlConformanceEnum.BABEL.name());
result.setProperty(CalciteConnectionProperty.FUN.camelName(), SqlLibrary.POSTGRESQL.fun);
- result.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), String.valueOf(Lex.JAVA.caseSensitive));
+ result.setProperty(CalciteConnectionProperty.CASE_SENSITIVE.camelName(), String.valueOf(false));
return result;
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/metadata/schema/SQLFederationTable.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/metadata/schema/SQLFederationTable.java
index 84c718f0dde..5cce718f439 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/metadata/schema/SQLFederationTable.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/metadata/schema/SQLFederationTable.java
@@ -38,11 +38,11 @@ import org.apache.calcite.schema.impl.AbstractTable;
import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.infra.util.exception.external.sql.type.generic.UnsupportedSQLOperationException;
-import org.apache.shardingsphere.sqlfederation.executor.enumerable.EnumerablePushDownTableScanExecutorContext;
-import org.apache.shardingsphere.sqlfederation.executor.enumerable.EnumerablePushDownTableScanExecutor;
import org.apache.shardingsphere.sqlfederation.compiler.metadata.util.SQLFederationDataTypeUtils;
import org.apache.shardingsphere.sqlfederation.compiler.operator.physical.enumerable.EnumerablePushDownTableScan;
import org.apache.shardingsphere.sqlfederation.compiler.statistic.SQLFederationStatistic;
+import org.apache.shardingsphere.sqlfederation.executor.enumerable.EnumerablePushDownTableScanExecutor;
+import org.apache.shardingsphere.sqlfederation.executor.enumerable.EnumerablePushDownTableScanExecutorContext;
import java.lang.reflect.Type;
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheBuilder.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheBuilder.java
index 6dd2878a619..8ebe8e5a9df 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheBuilder.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheBuilder.java
@@ -22,7 +22,6 @@ import com.github.benmanes.caffeine.cache.LoadingCache;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.sql.parser.api.CacheOption;
-import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
import org.apache.shardingsphere.sqlfederation.compiler.SQLFederationExecutionPlan;
/**
@@ -35,11 +34,9 @@ public final class ExecutionPlanCacheBuilder {
* Build execution plan cache.
*
* @param executionPlanCache execution plan cache option
- * @param sqlFederationCompiler sql federation compiler
* @return built execution plan cache
*/
- public static LoadingCache<ExecutionPlanCacheKey, SQLFederationExecutionPlan> build(final CacheOption executionPlanCache, final SQLStatementCompiler sqlFederationCompiler) {
- return Caffeine.newBuilder().softValues().initialCapacity(executionPlanCache.getInitialCapacity()).maximumSize(executionPlanCache.getMaximumSize())
- .build(new ExecutionPlanCacheLoader(sqlFederationCompiler));
+ public static LoadingCache<ExecutionPlanCacheKey, SQLFederationExecutionPlan> build(final CacheOption executionPlanCache) {
+ return Caffeine.newBuilder().softValues().initialCapacity(executionPlanCache.getInitialCapacity()).maximumSize(executionPlanCache.getMaximumSize()).build(new ExecutionPlanCacheLoader());
}
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheKey.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheKey.java
index 9d2107240ee..7b8417be5ff 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheKey.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheKey.java
@@ -21,6 +21,7 @@ import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
+import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
import java.util.LinkedHashMap;
import java.util.Map;
@@ -38,5 +39,7 @@ public final class ExecutionPlanCacheKey {
private final SQLStatement sqlStatement;
+ private final SQLStatementCompiler sqlStatementCompiler;
+
private final Map<String, Integer> tableMetaDataVersions = new LinkedHashMap<>();
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheLoader.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheLoader.java
index f891b69e2dd..8e0fcfd81d1 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheLoader.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/cache/ExecutionPlanCacheLoader.java
@@ -19,7 +19,6 @@ package org.apache.shardingsphere.sqlfederation.compiler.planner.cache;
import com.github.benmanes.caffeine.cache.CacheLoader;
import org.apache.shardingsphere.sqlfederation.compiler.SQLFederationExecutionPlan;
-import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
import javax.annotation.ParametersAreNonnullByDefault;
@@ -28,15 +27,9 @@ import javax.annotation.ParametersAreNonnullByDefault;
*/
public final class ExecutionPlanCacheLoader implements CacheLoader<ExecutionPlanCacheKey, SQLFederationExecutionPlan> {
- private final SQLStatementCompiler sqlStatementCompiler;
-
- public ExecutionPlanCacheLoader(final SQLStatementCompiler sqlStatementCompiler) {
- this.sqlStatementCompiler = sqlStatementCompiler;
- }
-
@ParametersAreNonnullByDefault
@Override
public SQLFederationExecutionPlan load(final ExecutionPlanCacheKey cacheKey) {
- return sqlStatementCompiler.compile(cacheKey.getSqlStatement());
+ return cacheKey.getSqlStatementCompiler().compile(cacheKey.getSqlStatement());
}
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationFunctionUtils.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationFunctionUtils.java
new file mode 100644
index 00000000000..62214255474
--- /dev/null
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationFunctionUtils.java
@@ -0,0 +1,116 @@
+/*
+ * 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.sqlfederation.compiler.planner.util;
+
+import lombok.AccessLevel;
+import lombok.NoArgsConstructor;
+import org.apache.calcite.schema.SchemaPlus;
+import org.apache.calcite.schema.impl.ScalarFunctionImpl;
+import org.apache.shardingsphere.infra.autogen.version.ShardingSphereVersion;
+
+/**
+ * SQL federation function utility class.
+ */
+@NoArgsConstructor(access = AccessLevel.PRIVATE)
+public final class SQLFederationFunctionUtils {
+
+ private static final int DEFAULT_PASSWORD_DEADLINE = 90;
+
+ private static final int DEFAULT_PASSWORD_NOTIFY_TIME = 7;
+
+ /**
+ * Registry user defined function.
+ *
+ * @param schemaName schema name
+ * @param schemaPlus schema plus
+ */
+ public static void registryUserDefinedFunction(final String schemaName, final SchemaPlus schemaPlus) {
+ schemaPlus.add("version", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "version"));
+ schemaPlus.add("gs_password_deadline", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "gsPasswordDeadline"));
+ schemaPlus.add("intervaltonum", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "intervalToNum"));
+ schemaPlus.add("gs_password_notifyTime", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "gsPasswordNotifyTime"));
+ if ("pg_catalog".equalsIgnoreCase(schemaName)) {
+ schemaPlus.add("pg_catalog.pg_table_is_visible", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "pgTableIsVisible"));
+ schemaPlus.add("pg_catalog.pg_get_userbyid", ScalarFunctionImpl.create(SQLFederationFunctionUtils.class, "pgGetUserById"));
+ }
+ }
+
+ /**
+ * Mock pg_table_is_visible function.
+ *
+ * @param oid oid
+ * @return true
+ */
+ @SuppressWarnings("unused")
+ public static boolean pgTableIsVisible(final Long oid) {
+ return true;
+ }
+
+ /**
+ * Mock pg_get_userbyid function.
+ *
+ * @param oid oid
+ * @return user name
+ */
+ @SuppressWarnings("unused")
+ public static String pgGetUserById(final Long oid) {
+ return "mock user";
+ }
+
+ /**
+ * Get version of ShardingSphere-Proxy.
+ *
+ * @return version message
+ */
+ public static String version() {
+ return "ShardingSphere-Proxy " + ShardingSphereVersion.VERSION + ("-" + ShardingSphereVersion.BUILD_GIT_COMMIT_ID_ABBREV) + (ShardingSphereVersion.BUILD_GIT_DIRTY ? "-dirty" : "");
+ }
+
+ /**
+ * The type interval is not supported in standard JDBC.
+ * Indicates the number of remaining days before the password of the current user expires.
+ *
+ * @return 90 days
+ */
+ @SuppressWarnings("unused")
+ public static int gsPasswordDeadline() {
+ return DEFAULT_PASSWORD_DEADLINE;
+ }
+
+ /**
+ * The type interval is not supported in standard JDBC.
+ * Convert interval to num.
+ *
+ * @param result result
+ * @return result
+ */
+ @SuppressWarnings("unused")
+ public static int intervalToNum(final int result) {
+ return result;
+ }
+
+ /**
+ * Specifies the number of days prior to password expiration that a user will receive a reminder.
+ *
+ * @return 7 days
+ */
+ @SuppressWarnings("unused")
+ public static int gsPasswordNotifyTime() {
+ return DEFAULT_PASSWORD_NOTIFY_TIME;
+ }
+}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationPlannerUtils.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationPlannerUtils.java
index e5851e60e0a..8ae33aa54f6 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationPlannerUtils.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/planner/util/SQLFederationPlannerUtils.java
@@ -39,8 +39,6 @@ import org.apache.calcite.rel.rules.ProjectRemoveRule;
import org.apache.calcite.rel.type.RelDataTypeFactory;
import org.apache.calcite.rex.RexBuilder;
import org.apache.calcite.schema.Schema;
-import org.apache.calcite.schema.SchemaPlus;
-import org.apache.calcite.schema.impl.ScalarFunctionImpl;
import org.apache.calcite.sql.SqlOperatorTable;
import org.apache.calcite.sql.fun.SqlLibrary;
import org.apache.calcite.sql.fun.SqlLibraryOperatorTableFactory;
@@ -181,40 +179,10 @@ public final class SQLFederationPlannerUtils {
public static CalciteCatalogReader createCatalogReader(final String schemaName, final Schema schema, final RelDataTypeFactory relDataTypeFactory, final CalciteConnectionConfig connectionConfig) {
CalciteSchema rootSchema = CalciteSchema.createRootSchema(true);
rootSchema.add(schemaName, schema);
- registryUserDefinedFunction(schemaName, rootSchema.plus());
+ SQLFederationFunctionUtils.registryUserDefinedFunction(schemaName, rootSchema.plus());
return new CalciteCatalogReader(rootSchema, Collections.singletonList(schemaName), relDataTypeFactory, connectionConfig);
}
- private static void registryUserDefinedFunction(final String schemaName, final SchemaPlus schemaPlus) {
- if (!"pg_catalog".equalsIgnoreCase(schemaName)) {
- return;
- }
- schemaPlus.add("pg_catalog.pg_table_is_visible", ScalarFunctionImpl.create(SQLFederationPlannerUtils.class, "pgTableIsVisible"));
- schemaPlus.add("pg_catalog.pg_get_userbyid", ScalarFunctionImpl.create(SQLFederationPlannerUtils.class, "pgGetUserById"));
- }
-
- /**
- * Mock pg_table_is_visible function.
- *
- * @param oid oid
- * @return true
- */
- @SuppressWarnings("unused")
- public static boolean pgTableIsVisible(final Long oid) {
- return true;
- }
-
- /**
- * Mock pg_get_userbyid function.
- *
- * @param oid oid
- * @return user name
- */
- @SuppressWarnings("unused")
- public static String pgGetUserById(final Long oid) {
- return "mock user";
- }
-
/**
* Create sql validator.
*
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompiler.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompiler.java
index 04b8cdd3c0c..9f98b508966 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompiler.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompiler.java
@@ -55,6 +55,7 @@ public final class SQLStatementCompiler {
RelDataType resultColumnType = Objects.requireNonNull(converter.validator).getValidatedNodeType(sqlNode);
RelNode rewritePlan = rewrite(logicPlan, hepPlanner);
RelNode physicalPlan = optimize(rewritePlan, converter);
+ RelMetadataQueryBase.THREAD_PROVIDERS.remove();
return new SQLFederationExecutionPlan(physicalPlan, resultColumnType);
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngine.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngine.java
index 8603d395d2c..c008edebc56 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngine.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngine.java
@@ -28,13 +28,10 @@ import org.apache.shardingsphere.sqlfederation.compiler.planner.cache.ExecutionP
*/
public final class SQLStatementCompilerEngine {
- private final SQLStatementCompiler sqlFederationCompiler;
-
private final LoadingCache<ExecutionPlanCacheKey, SQLFederationExecutionPlan> executionPlanCache;
- public SQLStatementCompilerEngine(final SQLStatementCompiler sqlFederationCompiler, final CacheOption cacheOption) {
- this.sqlFederationCompiler = sqlFederationCompiler;
- executionPlanCache = ExecutionPlanCacheBuilder.build(cacheOption, sqlFederationCompiler);
+ public SQLStatementCompilerEngine(final CacheOption cacheOption) {
+ executionPlanCache = ExecutionPlanCacheBuilder.build(cacheOption);
}
/**
@@ -45,6 +42,6 @@ public final class SQLStatementCompilerEngine {
* @return SQL federation execution plan
*/
public SQLFederationExecutionPlan compile(final ExecutionPlanCacheKey cacheKey, final boolean useCache) {
- return useCache ? executionPlanCache.get(cacheKey) : sqlFederationCompiler.compile(cacheKey.getSqlStatement());
+ return useCache ? executionPlanCache.get(cacheKey) : cacheKey.getSqlStatementCompiler().compile(cacheKey.getSqlStatement());
}
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngineFactory.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngineFactory.java
index 1392603a987..61e329018d0 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngineFactory.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/compiler/statement/SQLStatementCompilerEngineFactory.java
@@ -35,15 +35,16 @@ public final class SQLStatementCompilerEngineFactory {
/**
* Get SQL statement compiler engine.
*
+ * @param databaseName database name
* @param schemaName schema name
- * @param sqlStatementCompiler sql statement compiler
* @param cacheOption execution plan cache option
* @return SQL statement compiler engine
*/
- public static SQLStatementCompilerEngine getSQLStatementCompilerEngine(final String schemaName, final SQLStatementCompiler sqlStatementCompiler, final CacheOption cacheOption) {
- SQLStatementCompilerEngine result = COMPILER_ENGINES.get(schemaName);
+ public static SQLStatementCompilerEngine getSQLStatementCompilerEngine(final String databaseName, final String schemaName, final CacheOption cacheOption) {
+ String cacheKey = databaseName + "." + schemaName;
+ SQLStatementCompilerEngine result = COMPILER_ENGINES.get(cacheKey);
if (null == result) {
- result = COMPILER_ENGINES.computeIfAbsent(schemaName, unused -> new SQLStatementCompilerEngine(sqlStatementCompiler, cacheOption));
+ result = COMPILER_ENGINES.computeIfAbsent(cacheKey, unused -> new SQLStatementCompilerEngine(cacheOption));
}
return result;
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/engine/SQLFederationEngine.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/engine/SQLFederationEngine.java
index dc567efeacb..757cd973fdf 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/engine/SQLFederationEngine.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/engine/SQLFederationEngine.java
@@ -34,12 +34,12 @@ import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.J
import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;
import org.apache.shardingsphere.infra.executor.sql.prepare.driver.DriverExecutionPrepareEngine;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
-import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereStatistics;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.infra.metadata.database.schema.util.SystemSchemaUtils;
+import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereStatistics;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.infra.util.exception.ShardingSpherePreconditions;
import org.apache.shardingsphere.infra.util.spi.type.ordered.OrderedSPILoader;
@@ -137,7 +137,9 @@ public final class SQLFederationEngine implements AutoCloseable {
private boolean isQuerySystemSchema(final SQLStatementContext sqlStatementContext, final ShardingSphereDatabase database) {
return sqlStatementContext instanceof SelectStatementContext
- && SystemSchemaUtils.containsSystemSchema(sqlStatementContext.getDatabaseType(), sqlStatementContext.getTablesContext().getSchemaNames(), database);
+ && (SystemSchemaUtils.containsSystemSchema(sqlStatementContext.getDatabaseType(), sqlStatementContext.getTablesContext().getSchemaNames(), database)
+ || SystemSchemaUtils.isOpenGaussSystemCatalogQuery(sqlStatementContext.getDatabaseType(),
+ ((SelectStatementContext) sqlStatementContext).getSqlStatement().getProjections().getProjections()));
}
/**
@@ -171,14 +173,15 @@ public final class SQLFederationEngine implements AutoCloseable {
OptimizerPlannerContext plannerContext = sqlFederationRule.getOptimizerContext().getPlannerContext(databaseName);
Schema sqlFederationSchema = plannerContext.getValidator(schemaName).getCatalogReader().getRootSchema().plus().getSubSchema(schemaName);
registerTableScanExecutor(sqlFederationSchema, prepareEngine, callback, federationContext, sqlFederationRule.getOptimizerContext());
- SQLFederationCompilerEngine compilerEngine = new SQLFederationCompilerEngine(schemaName, new SQLStatementCompiler(plannerContext.getConverter(schemaName), plannerContext.getHepPlanner()),
- sqlFederationRule.getConfiguration().getExecutionPlanCache());
- return compilerEngine.compile(buildCacheKey(federationContext, selectStatementContext), federationContext.getQueryContext().isUseCache());
+ SQLStatementCompiler sqlStatementCompiler = new SQLStatementCompiler(plannerContext.getConverter(schemaName), plannerContext.getHepPlanner());
+ SQLFederationCompilerEngine compilerEngine = new SQLFederationCompilerEngine(databaseName, schemaName, sqlFederationRule.getConfiguration().getExecutionPlanCache());
+ return compilerEngine.compile(buildCacheKey(federationContext, selectStatementContext, sqlStatementCompiler), federationContext.getQueryContext().isUseCache());
}
- private ExecutionPlanCacheKey buildCacheKey(final SQLFederationExecutorContext federationContext, final SelectStatementContext selectStatementContext) {
+ private ExecutionPlanCacheKey buildCacheKey(final SQLFederationExecutorContext federationContext, final SelectStatementContext selectStatementContext,
+ final SQLStatementCompiler sqlStatementCompiler) {
ShardingSphereSchema schema = federationContext.getMetaData().getDatabase(databaseName).getSchema(schemaName);
- ExecutionPlanCacheKey result = new ExecutionPlanCacheKey(federationContext.getQueryContext().getSql(), selectStatementContext.getSqlStatement());
+ ExecutionPlanCacheKey result = new ExecutionPlanCacheKey(federationContext.getQueryContext().getSql(), selectStatementContext.getSqlStatement(), sqlStatementCompiler);
for (String each : selectStatementContext.getTablesContext().getTableNames()) {
ShardingSphereTable table = schema.getTable(each);
ShardingSpherePreconditions.checkState(null != table, () -> new NoSuchTableException(each));
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/executor/enumerable/EnumerablePushDownTableScanExecutor.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/executor/enumerable/EnumerablePushDownTableScanExecutor.java
index 3d3fd0ecbef..5573393ecad 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/executor/enumerable/EnumerablePushDownTableScanExecutor.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/executor/enumerable/EnumerablePushDownTableScanExecutor.java
@@ -40,11 +40,13 @@ import org.apache.calcite.rex.RexNode;
import org.apache.calcite.sql.SqlDialect;
import org.apache.calcite.sql.util.SqlString;
import org.apache.calcite.tools.RelBuilder;
+import org.apache.shardingsphere.authority.rule.AuthorityRule;
import org.apache.shardingsphere.infra.binder.SQLStatementContextFactory;
import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;
import org.apache.shardingsphere.infra.connection.kernel.KernelProcessor;
import org.apache.shardingsphere.infra.database.type.DatabaseType;
import org.apache.shardingsphere.infra.database.type.DatabaseTypeEngine;
+import org.apache.shardingsphere.infra.database.type.dialect.OpenGaussDatabaseType;
import org.apache.shardingsphere.infra.executor.kernel.model.ExecutionGroup;
import org.apache.shardingsphere.infra.executor.kernel.model.ExecutionGroupContext;
import org.apache.shardingsphere.infra.executor.kernel.model.ExecutionGroupReportContext;
@@ -62,12 +64,15 @@ import org.apache.shardingsphere.infra.hint.HintValueContext;
import org.apache.shardingsphere.infra.merge.MergeEngine;
import org.apache.shardingsphere.infra.merge.result.MergedResult;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
-import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereStatistics;
-import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereSchemaData;
-import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereTableData;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
+import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
+import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereRowData;
+import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereSchemaData;
+import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereStatistics;
+import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereTableData;
+import org.apache.shardingsphere.infra.metadata.user.ShardingSphereUser;
import org.apache.shardingsphere.infra.parser.sql.SQLStatementParserEngine;
import org.apache.shardingsphere.infra.session.connection.ConnectionContext;
import org.apache.shardingsphere.infra.session.query.QueryContext;
@@ -90,11 +95,14 @@ import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
+import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
+import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
+import java.util.Map.Entry;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -110,6 +118,16 @@ public final class EnumerablePushDownTableScanExecutor {
private static final Pattern COLUMN_INFORMATION_PATTERN = Pattern.compile("\\{.*}");
+ private static final Collection<String> SYSTEM_CATALOG_TABLES = new HashSet<>(3, 1F);
+
+ private static final String DAT_COMPATIBILITY = "PG";
+
+ private static final String PG_DATABASE = "pg_database";
+
+ private static final String PG_TABLES = "pg_tables";
+
+ private static final String PG_ROLES = "pg_roles";
+
private final DriverExecutionPrepareEngine<JDBCExecutionUnit, Connection> prepareEngine;
private final JDBCExecutor jdbcExecutor;
@@ -122,10 +140,16 @@ public final class EnumerablePushDownTableScanExecutor {
private final TableScanExecutorContext executorContext;
- private final ShardingSphereStatistics data;
+ private final ShardingSphereStatistics statistics;
private final ProcessEngine processEngine = new ProcessEngine();
+ static {
+ SYSTEM_CATALOG_TABLES.add(PG_DATABASE);
+ SYSTEM_CATALOG_TABLES.add(PG_TABLES);
+ SYSTEM_CATALOG_TABLES.add(PG_ROLES);
+ }
+
/**
* Execute.
*
@@ -138,7 +162,7 @@ public final class EnumerablePushDownTableScanExecutor {
String schemaName = executorContext.getSchemaName().toLowerCase();
DatabaseType databaseType = DatabaseTypeEngine.getTrunkDatabaseType(optimizerContext.getParserContext(databaseName).getDatabaseType().getType());
if (databaseType.getSystemSchemas().contains(schemaName)) {
- return executeByScalarShardingSphereData(databaseName, schemaName, table);
+ return executeByScalarShardingSphereData(databaseName, schemaName, table, databaseType, scanContext.getProjects());
}
SqlString sqlString = createSQLString(table, scanContext, SQLDialectFactory.getSQLDialect(databaseType.getType()));
SQLFederationExecutorContext federationContext = executorContext.getFederationContext();
@@ -162,12 +186,68 @@ public final class EnumerablePushDownTableScanExecutor {
};
}
- private Enumerable<Object> executeByScalarShardingSphereData(final String databaseName, final String schemaName, final ShardingSphereTable table) {
- Optional<ShardingSphereTableData> tableData = Optional.ofNullable(data.getDatabaseData().get(databaseName)).map(optional -> optional.getSchemaData().get(schemaName))
+ private Enumerable<Object> executeByScalarShardingSphereData(final String databaseName, final String schemaName, final ShardingSphereTable table, final DatabaseType databaseType,
+ final int[] projects) {
+ // TODO move this logic to ShardingSphere statistics
+ if (databaseType instanceof OpenGaussDatabaseType && SYSTEM_CATALOG_TABLES.contains(table.getName().toLowerCase())) {
+ return createMemoryScalarEnumerator(createSystemCatalogTableData(table, projects));
+ }
+ Optional<ShardingSphereTableData> tableData = Optional.ofNullable(statistics.getDatabaseData().get(databaseName)).map(optional -> optional.getSchemaData().get(schemaName))
.map(ShardingSphereSchemaData::getTableData).map(shardingSphereData -> shardingSphereData.get(table.getName()));
return tableData.map(this::createMemoryScalarEnumerator).orElseGet(this::createEmptyScalarEnumerable);
}
+ private ShardingSphereTableData createSystemCatalogTableData(final ShardingSphereTable table, final int[] projects) {
+ ShardingSphereTableData result = new ShardingSphereTableData(table.getName());
+ ShardingSphereMetaData metaData = executorContext.getFederationContext().getMetaData();
+ if (PG_DATABASE.equalsIgnoreCase(table.getName())) {
+ appendOpenGaussDatabaseData(result, metaData.getDatabases().values(), projects);
+ } else if (PG_TABLES.equalsIgnoreCase(table.getName())) {
+ for (ShardingSphereDatabase each : metaData.getDatabases().values()) {
+ appendOpenGaussTableData(result, each.getSchemas(), projects);
+ }
+ } else if (PG_ROLES.equalsIgnoreCase(table.getName())) {
+ appendOpenGaussRoleData(result, metaData, projects);
+ }
+ return result;
+ }
+
+ private void appendOpenGaussDatabaseData(final ShardingSphereTableData tableData, final Collection<ShardingSphereDatabase> databases, final int[] projects) {
+ for (ShardingSphereDatabase each : databases) {
+ Object[] rows = new Object[15];
+ rows[0] = each.getName();
+ rows[11] = DAT_COMPATIBILITY;
+ tableData.getRows().add(new ShardingSphereRowData(Arrays.asList(filterRows(rows, projects))));
+ }
+ }
+
+ private Object[] filterRows(final Object[] rows, final int[] projects) {
+ Object[] result = new Object[projects.length];
+ for (int index = 0; index < projects.length; index++) {
+ result[index] = rows[projects[index]];
+ }
+ return result;
+ }
+
+ private void appendOpenGaussTableData(final ShardingSphereTableData tableData, final Map<String, ShardingSphereSchema> schemas, final int[] projects) {
+ for (Entry<String, ShardingSphereSchema> entry : schemas.entrySet()) {
+ for (String each : entry.getValue().getAllTableNames()) {
+ Object[] rows = new Object[10];
+ rows[0] = entry.getKey();
+ rows[1] = each;
+ tableData.getRows().add(new ShardingSphereRowData(Arrays.asList(filterRows(rows, projects))));
+ }
+ }
+ }
+
+ private void appendOpenGaussRoleData(final ShardingSphereTableData tableData, final ShardingSphereMetaData metaData, final int[] projects) {
+ for (ShardingSphereUser each : metaData.getGlobalRuleMetaData().getSingleRule(AuthorityRule.class).getConfiguration().getUsers()) {
+ Object[] rows = new Object[27];
+ rows[0] = each.getGrantee().getUsername();
+ tableData.getRows().add(new ShardingSphereRowData(Arrays.asList(filterRows(rows, projects))));
+ }
+ }
+
private Enumerable<Object> createMemoryScalarEnumerator(final ShardingSphereTableData tableData) {
return new AbstractEnumerable<Object>() {
@@ -230,7 +310,7 @@ public final class EnumerablePushDownTableScanExecutor {
String schemaName = executorContext.getSchemaName().toLowerCase();
DatabaseType databaseType = DatabaseTypeEngine.getTrunkDatabaseType(optimizerContext.getParserContext(databaseName).getDatabaseType().getType());
if (databaseType.getSystemSchemas().contains(schemaName)) {
- return executeByShardingSphereData(databaseName, schemaName, table);
+ return executeByShardingSphereData(databaseName, schemaName, table, databaseType, scanContext.getProjects());
}
SqlString sqlString = createSQLString(table, scanContext, SQLDialectFactory.getSQLDialect(databaseType.getType()));
SQLFederationExecutorContext federationContext = executorContext.getFederationContext();
@@ -263,8 +343,13 @@ public final class EnumerablePushDownTableScanExecutor {
}
}
- private Enumerable<Object[]> executeByShardingSphereData(final String databaseName, final String schemaName, final ShardingSphereTable table) {
- Optional<ShardingSphereTableData> tableData = Optional.ofNullable(data.getDatabaseData().get(databaseName)).map(optional -> optional.getSchemaData().get(schemaName))
+ private Enumerable<Object[]> executeByShardingSphereData(final String databaseName, final String schemaName, final ShardingSphereTable table, final DatabaseType databaseType,
+ final int[] projects) {
+ // TODO move this logic to ShardingSphere statistics
+ if (databaseType instanceof OpenGaussDatabaseType && SYSTEM_CATALOG_TABLES.contains(table.getName().toLowerCase())) {
+ return createMemoryEnumerator(createSystemCatalogTableData(table, projects));
+ }
+ Optional<ShardingSphereTableData> tableData = Optional.ofNullable(statistics.getDatabaseData().get(databaseName)).map(optional -> optional.getSchemaData().get(schemaName))
.map(ShardingSphereSchemaData::getTableData).map(shardingSphereData -> shardingSphereData.get(table.getName()));
return tableData.map(this::createMemoryEnumerator).orElseGet(this::createEmptyEnumerable);
}
diff --git a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/resultset/SQLFederationResultSetMetaData.java b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/resultset/SQLFederationResultSetMetaData.java
index b52d391009a..8e8269f6492 100644
--- a/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/resultset/SQLFederationResultSetMetaData.java
+++ b/kernel/sql-federation/core/src/main/java/org/apache/shardingsphere/sqlfederation/resultset/SQLFederationResultSetMetaData.java
@@ -30,6 +30,7 @@ import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSp
import java.sql.ResultSetMetaData;
import java.util.Collections;
+import java.util.List;
import java.util.Map;
import java.util.Optional;
@@ -103,12 +104,19 @@ public final class SQLFederationResultSetMetaData extends WrapperAdapter impleme
@Override
public String getColumnLabel(final int column) {
+ if (indexAndColumnLabels.size() < column) {
+ return resultColumnType.getFieldList().get(column - 1).getName();
+ }
return indexAndColumnLabels.get(column);
}
@Override
public String getColumnName(final int column) {
- Projection projection = selectStatementContext.getProjectionsContext().getExpandProjections().get(column - 1);
+ List<Projection> expandProjections = selectStatementContext.getProjectionsContext().getExpandProjections();
+ if (expandProjections.size() < column) {
+ return resultColumnType.getFieldList().get(column - 1).getName();
+ }
+ Projection projection = expandProjections.get(column - 1);
if (projection instanceof ColumnProjection) {
return ((ColumnProjection) projection).getName();
}
@@ -173,7 +181,8 @@ public final class SQLFederationResultSetMetaData extends WrapperAdapter impleme
}
private Optional<String> findTableName(final int column) {
- Projection projection = selectStatementContext.getProjectionsContext().getExpandProjections().get(column - 1);
+ List<Projection> expandProjections = selectStatementContext.getProjectionsContext().getExpandProjections();
+ Projection projection = expandProjections.size() < column ? new ColumnProjection(null, resultColumnType.getFieldList().get(column - 1).getName(), null) : expandProjections.get(column - 1);
if (projection instanceof ColumnProjection) {
Map<String, String> tableNamesByColumnProjection =
selectStatementContext.getTablesContext().findTableNamesByColumnProjection(Collections.singletonList((ColumnProjection) projection), schema);
diff --git a/kernel/sql-federation/core/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/it/SQLFederationCompilerEngineIT.java b/kernel/sql-federation/core/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/it/SQLFederationCompilerEngineIT.java
index 60fc5e3b3d4..b0dbdf07197 100644
--- a/kernel/sql-federation/core/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/it/SQLFederationCompilerEngineIT.java
+++ b/kernel/sql-federation/core/src/test/java/org/apache/shardingsphere/sqlfederation/compiler/it/SQLFederationCompilerEngineIT.java
@@ -38,10 +38,10 @@ import org.apache.shardingsphere.parser.rule.SQLParserRule;
import org.apache.shardingsphere.parser.rule.builder.DefaultSQLParserRuleConfigurationBuilder;
import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
import org.apache.shardingsphere.sqlfederation.compiler.SQLFederationCompilerEngine;
-import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
import org.apache.shardingsphere.sqlfederation.compiler.metadata.schema.SQLFederationSchema;
import org.apache.shardingsphere.sqlfederation.compiler.planner.cache.ExecutionPlanCacheKey;
import org.apache.shardingsphere.sqlfederation.compiler.planner.util.SQLFederationPlannerUtils;
+import org.apache.shardingsphere.sqlfederation.compiler.statement.SQLStatementCompiler;
import org.apache.shardingsphere.sqlfederation.rule.builder.DefaultSQLFederationRuleConfigurationBuilder;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.extension.ExtensionContext;
@@ -72,6 +72,8 @@ class SQLFederationCompilerEngineIT {
private SQLFederationCompilerEngine sqlFederationCompilerEngine;
+ private SQLStatementCompiler sqlStatementCompiler;
+
@BeforeEach
void init() {
Map<String, ShardingSphereTable> tables = new HashMap<>();
@@ -87,9 +89,9 @@ class SQLFederationCompilerEngineIT {
tables.put("t_product_detail", createTProductDetailMetaData());
tables.put("multi_types_first", createMultiTypesFirstTableMetaData());
tables.put("multi_types_second", createMultiTypesSecondTableMetaData());
- sqlFederationCompilerEngine = new SQLFederationCompilerEngine(DefaultDatabase.LOGIC_NAME,
- new SQLStatementCompiler(createSqlToRelConverter(new ShardingSphereSchema(tables, Collections.emptyMap())), SQLFederationPlannerUtils.createHepPlanner()),
- DefaultSQLFederationRuleConfigurationBuilder.DEFAULT_EXECUTION_PLAN_CACHE_OPTION);
+ sqlStatementCompiler = new SQLStatementCompiler(createSqlToRelConverter(new ShardingSphereSchema(tables, Collections.emptyMap())), SQLFederationPlannerUtils.createHepPlanner());
+ sqlFederationCompilerEngine =
+ new SQLFederationCompilerEngine(DefaultDatabase.LOGIC_NAME, DefaultDatabase.LOGIC_NAME, DefaultSQLFederationRuleConfigurationBuilder.DEFAULT_EXECUTION_PLAN_CACHE_OPTION);
}
private ShardingSphereTable createOrderFederationTableMetaData() {
@@ -253,7 +255,8 @@ class SQLFederationCompilerEngineIT {
@ArgumentsSource(TestCaseArgumentsProvider.class)
void assertCompile(final TestCase testcase) {
SQLStatement sqlStatement = sqlParserRule.getSQLParserEngine(DatabaseTypeEngine.getTrunkDatabaseTypeName(new H2DatabaseType())).parse(testcase.getSql(), false);
- String actual = sqlFederationCompilerEngine.compile(new ExecutionPlanCacheKey(testcase.getSql(), sqlStatement), false).getPhysicalPlan().explain().replaceAll("[\r\n]", "");
+ String actual = sqlFederationCompilerEngine.compile(new ExecutionPlanCacheKey(testcase.getSql(), sqlStatement, sqlStatementCompiler), false).getPhysicalPlan()
+ .explain().replaceAll("[\r\n]", "");
assertThat(actual, is(testcase.getAssertion().getExpectedResult()));
}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreator.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreator.java
index 9cd59d4e757..82c75dc6e3f 100644
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreator.java
+++ b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreator.java
@@ -59,7 +59,7 @@ public final class OpenGaussAdminExecutorCreator implements DatabaseAdminExecuto
@Override
public Optional<DatabaseAdminExecutor> create(final SQLStatementContext sqlStatementContext, final String sql, final String databaseName, final List<Object> parameters) {
if (isSystemCatalogQuery(sqlStatementContext)) {
- return Optional.of(new OpenGaussSystemCatalogAdminQueryExecutor(sql));
+ return Optional.of(new OpenGaussSystemCatalogAdminQueryExecutor(sqlStatementContext, sql, databaseName, parameters));
}
return delegated.create(sqlStatementContext, sql, databaseName, parameters);
}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutor.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutor.java
index 94eecefd513..2125aa36d3f 100644
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutor.java
+++ b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutor.java
@@ -18,140 +18,104 @@
package org.apache.shardingsphere.proxy.backend.opengauss.handler.admin;
import lombok.Getter;
-import org.apache.calcite.adapter.java.ReflectiveSchema;
-import org.apache.calcite.jdbc.CalciteConnection;
-import org.apache.calcite.schema.impl.ScalarFunctionImpl;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
-import org.apache.shardingsphere.infra.autogen.version.ShardingSphereVersion;
+import lombok.RequiredArgsConstructor;
+import org.apache.shardingsphere.infra.binder.statement.SQLStatementContext;
+import org.apache.shardingsphere.infra.config.props.ConfigurationPropertyKey;
+import org.apache.shardingsphere.infra.database.type.DatabaseType;
+import org.apache.shardingsphere.infra.executor.sql.execute.engine.ConnectionMode;
+import org.apache.shardingsphere.infra.executor.sql.execute.engine.SQLExecutorExceptionHandler;
+import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutionUnit;
+import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutor;
+import org.apache.shardingsphere.infra.executor.sql.execute.engine.driver.jdbc.JDBCExecutorCallback;
+import org.apache.shardingsphere.infra.executor.sql.execute.result.ExecuteResult;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.driver.jdbc.metadata.JDBCQueryResultMetaData;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.driver.jdbc.type.memory.JDBCMemoryQueryResult;
+import org.apache.shardingsphere.infra.executor.sql.execute.result.query.impl.driver.jdbc.type.stream.JDBCStreamQueryResult;
+import org.apache.shardingsphere.infra.executor.sql.prepare.driver.DriverExecutionPrepareEngine;
+import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.JDBCDriverType;
+import org.apache.shardingsphere.infra.executor.sql.prepare.driver.jdbc.StatementOption;
import org.apache.shardingsphere.infra.merge.result.MergedResult;
-import org.apache.shardingsphere.infra.metadata.database.schema.builder.SystemSchemaBuilderRule;
-import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
+import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import org.apache.shardingsphere.infra.session.query.QueryContext;
+import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
+import org.apache.shardingsphere.proxy.backend.context.BackendExecutorContext;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.handler.admin.executor.DatabaseAdminQueryExecutor;
-import org.apache.shardingsphere.proxy.backend.opengauss.handler.admin.schema.OpenGaussDatabase;
-import org.apache.shardingsphere.proxy.backend.opengauss.handler.admin.schema.OpenGaussRoles;
-import org.apache.shardingsphere.proxy.backend.opengauss.handler.admin.schema.OpenGaussSystemCatalog;
-import org.apache.shardingsphere.proxy.backend.opengauss.handler.admin.schema.OpenGaussTables;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
import org.apache.shardingsphere.sharding.merge.common.IteratorStreamMergedResult;
-import org.apache.shardingsphere.sql.parser.sql.common.util.SQLUtils;
+import org.apache.shardingsphere.sql.parser.sql.common.statement.SQLStatement;
+import org.apache.shardingsphere.sqlfederation.engine.SQLFederationEngine;
+import org.apache.shardingsphere.sqlfederation.executor.SQLFederationExecutorContext;
import java.sql.Connection;
-import java.sql.DriverManager;
-import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
-import java.util.Collection;
+import java.sql.Statement;
import java.util.Collections;
-import java.util.LinkedList;
import java.util.List;
-import java.util.Map.Entry;
-import java.util.stream.Collectors;
+import java.util.Map;
+import java.util.Optional;
/**
* Select database executor for openGauss.
*/
-@SuppressWarnings("unused")
+@RequiredArgsConstructor
public final class OpenGaussSystemCatalogAdminQueryExecutor implements DatabaseAdminQueryExecutor {
private static final String PG_CATALOG = "pg_catalog";
- private static final String DAT_COMPATIBILITY = "PG";
+ private final SQLStatementContext sqlStatementContext;
private final String sql;
+ private final String databaseName;
+
+ private final List<Object> parameters;
+
@Getter
private QueryResultMetaData queryResultMetaData;
@Getter
private MergedResult mergedResult;
- public OpenGaussSystemCatalogAdminQueryExecutor(final String sql) {
- this.sql = SQLUtils.trimSemicolon(sql);
- }
-
@Override
public void execute(final ConnectionSession connectionSession) throws SQLException {
- try (Connection connection = DriverManager.getConnection("jdbc:calcite:caseSensitive=false")) {
- prepareCalciteConnection(connection);
- connection.setSchema(PG_CATALOG);
- try (PreparedStatement statement = connection.prepareStatement(sql); ResultSet resultSet = statement.executeQuery()) {
- queryResultMetaData = new JDBCQueryResultMetaData(resultSet.getMetaData());
- mergedResult = new IteratorStreamMergedResult(Collections.singletonList(new JDBCMemoryQueryResult(resultSet, connectionSession.getProtocolType())));
- }
+ MetaDataContexts metaDataContexts = ProxyContext.getInstance().getContextManager().getMetaDataContexts();
+ JDBCExecutor jdbcExecutor = new JDBCExecutor(BackendExecutorContext.getInstance().getExecutorEngine(), connectionSession.getConnectionContext());
+ try (SQLFederationEngine sqlFederationEngine = new SQLFederationEngine(databaseName, PG_CATALOG, metaDataContexts.getMetaData(), metaDataContexts.getShardingSphereData(), jdbcExecutor)) {
+ DriverExecutionPrepareEngine<JDBCExecutionUnit, Connection> prepareEngine = createDriverExecutionPrepareEngine(metaDataContexts, connectionSession);
+ SQLFederationExecutorContext context = new SQLFederationExecutorContext(false, new QueryContext(sqlStatementContext, sql, parameters), metaDataContexts.getMetaData());
+ ShardingSphereDatabase database = metaDataContexts.getMetaData().getDatabase(databaseName);
+ ResultSet resultSet = sqlFederationEngine.executeQuery(prepareEngine,
+ createOpenGaussSystemCatalogAdminQueryCallback(database.getProtocolType(), database.getResourceMetaData().getStorageTypes(), sqlStatementContext.getSqlStatement()), context);
+ queryResultMetaData = new JDBCQueryResultMetaData(resultSet.getMetaData());
+ mergedResult = new IteratorStreamMergedResult(Collections.singletonList(new JDBCMemoryQueryResult(resultSet, connectionSession.getProtocolType())));
}
}
- private void prepareCalciteConnection(final Connection connection) throws SQLException {
- CalciteConnection calciteConnection = connection.unwrap(CalciteConnection.class);
- calciteConnection.getRootSchema().add(PG_CATALOG, new ReflectiveSchema(constructOgCatalog()));
- calciteConnection.getRootSchema().add("version", ScalarFunctionImpl.create(getClass(), "version"));
- calciteConnection.getRootSchema().add("gs_password_deadline", ScalarFunctionImpl.create(getClass(), "gsPasswordDeadline"));
- calciteConnection.getRootSchema().add("intervaltonum", ScalarFunctionImpl.create(getClass(), "intervalToNum"));
- calciteConnection.getRootSchema().add("gs_password_notifyTime", ScalarFunctionImpl.create(getClass(), "gsPasswordNotifyTime"));
+ @SuppressWarnings({"rawtypes", "unchecked"})
+ private DriverExecutionPrepareEngine<JDBCExecutionUnit, Connection> createDriverExecutionPrepareEngine(final MetaDataContexts metaDataContexts, final ConnectionSession connectionSession) {
+ int maxConnectionsSizePerQuery = metaDataContexts.getMetaData().getProps().<Integer>getValue(ConfigurationPropertyKey.MAX_CONNECTIONS_SIZE_PER_QUERY);
+ return new DriverExecutionPrepareEngine<>(JDBCDriverType.STATEMENT, maxConnectionsSizePerQuery, connectionSession.getDatabaseConnectionManager(),
+ connectionSession.getStatementManager(), new StatementOption(false),
+ metaDataContexts.getMetaData().getDatabase(databaseName).getRuleMetaData().getRules(),
+ metaDataContexts.getMetaData().getDatabase(databaseName).getResourceMetaData().getStorageTypes());
}
- private OpenGaussSystemCatalog constructOgCatalog() {
- Collection<String> allDatabaseNames = ProxyContext.getInstance().getAllDatabaseNames();
- OpenGaussDatabase[] openGaussDatabases = new OpenGaussDatabase[allDatabaseNames.size()];
- List<OpenGaussTables> openGaussTables = new LinkedList<>();
- List<OpenGaussRoles> openGaussRoles = new LinkedList<>();
- ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData().getSingleRule(AuthorityRule.class)
- .getConfiguration().getUsers().stream().map(user -> user.getGrantee().getUsername())
- .forEach(userName -> openGaussRoles.add(new OpenGaussRoles(userName)));
- int index = 0;
- for (String each : allDatabaseNames) {
- for (Entry<String, ShardingSphereSchema> entry : ProxyContext.getInstance().getDatabase(each).getSchemas().entrySet()) {
- for (String tableName : entry.getValue().getAllTableNames()) {
- openGaussTables.add(new OpenGaussTables(entry.getKey(), tableName));
- }
+ private JDBCExecutorCallback<ExecuteResult> createOpenGaussSystemCatalogAdminQueryCallback(final DatabaseType protocolType, final Map<String, DatabaseType> storageTypes,
+ final SQLStatement sqlStatement) {
+ return new JDBCExecutorCallback<ExecuteResult>(protocolType, storageTypes, sqlStatement, SQLExecutorExceptionHandler.isExceptionThrown()) {
+
+ @Override
+ protected ExecuteResult executeSQL(final String sql, final Statement statement, final ConnectionMode connectionMode, final DatabaseType storageType) throws SQLException {
+ return new JDBCStreamQueryResult(statement.executeQuery(sql));
}
- openGaussDatabases[index++] = new OpenGaussDatabase(each, DAT_COMPATIBILITY);
- }
- openGaussTables.addAll(SystemSchemaBuilderRule.OPEN_GAUSS_PG_CATALOG.getTables().stream().map(tableName -> new OpenGaussTables(PG_CATALOG, tableName)).collect(Collectors.toSet()));
- openGaussTables.addAll(SystemSchemaBuilderRule.POSTGRESQL_PG_CATALOG.getTables().stream().map(tableName -> new OpenGaussTables(PG_CATALOG, tableName)).collect(Collectors.toSet()));
- return new OpenGaussSystemCatalog(openGaussDatabases, openGaussTables.toArray(new OpenGaussTables[0]), openGaussRoles.toArray(new OpenGaussRoles[0]));
- }
-
- /**
- * Get version of ShardingSphere-Proxy.
- *
- * @return version message
- */
- public static String version() {
- return "ShardingSphere-Proxy " + ShardingSphereVersion.VERSION + ("-" + ShardingSphereVersion.BUILD_GIT_COMMIT_ID_ABBREV) + (ShardingSphereVersion.BUILD_GIT_DIRTY ? "-dirty" : "");
- }
-
- /**
- * The type interval is not supported in standard JDBC.
- * Indicates the number of remaining days before the password of the current user expires.
- *
- * @return 90 days
- */
- public static int gsPasswordDeadline() {
- return 90;
- }
-
- /**
- * The type interval is not supported in standard JDBC.
- * Convert interval to num.
- *
- * @param result result
- * @return result
- */
- public static int intervalToNum(final int result) {
- return result;
- }
-
- /**
- * Specifies the number of days prior to password expiration that a user will receive a reminder.
- *
- * @return 7 days
- */
- public static int gsPasswordNotifyTime() {
- return 7;
+
+ @Override
+ protected Optional<ExecuteResult> getSaneResult(final SQLStatement sqlStatement, final SQLException ex) {
+ return Optional.empty();
+ }
+ };
}
}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussDatabase.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussDatabase.java
deleted file mode 100644
index 1a5654c4c12..00000000000
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussDatabase.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.proxy.backend.opengauss.handler.admin.schema;
-
-import lombok.RequiredArgsConstructor;
-
-/**
- * System table which maintains databases in openGauss system catalog schema.
- */
-@RequiredArgsConstructor
-public final class OpenGaussDatabase {
-
- // CHECKSTYLE:OFF
- public final String datname;
-
- public final String datcompatibility;
- // CHECKSTYLE:ON
-}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussRoles.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussRoles.java
deleted file mode 100644
index e8bdd04d34a..00000000000
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussRoles.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.proxy.backend.opengauss.handler.admin.schema;
-
-import lombok.EqualsAndHashCode;
-import lombok.RequiredArgsConstructor;
-
-/**
- * System table which maintains tables in openGauss system catalog schema.
- */
-@EqualsAndHashCode
-@RequiredArgsConstructor
-public final class OpenGaussRoles {
-
- // CHECKSTYLE:OFF
- public final String rolname;
- // CHECKSTYLE:ON
-}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussSystemCatalog.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussSystemCatalog.java
deleted file mode 100644
index 5912bd4c247..00000000000
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussSystemCatalog.java
+++ /dev/null
@@ -1,36 +0,0 @@
-/*
- * 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.proxy.backend.opengauss.handler.admin.schema;
-
-import lombok.RequiredArgsConstructor;
-
-/**
- * TODO we should refactor this with our federation modules.
- * System catalog schema of openGauss.
- */
-@RequiredArgsConstructor
-public final class OpenGaussSystemCatalog {
-
- // CHECKSTYLE:OFF
- public final OpenGaussDatabase[] pg_database;
-
- public final OpenGaussTables[] pg_tables;
-
- public final OpenGaussRoles[] pg_roles;
- // CHECKSTYLE:ON
-}
diff --git a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussTables.java b/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussTables.java
deleted file mode 100644
index fb853ff2579..00000000000
--- a/proxy/backend/type/opengauss/src/main/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/schema/OpenGaussTables.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * 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.proxy.backend.opengauss.handler.admin.schema;
-
-import lombok.RequiredArgsConstructor;
-
-/**
- * System table which maintains tables in openGauss system catalog schema.
- */
-@RequiredArgsConstructor
-public final class OpenGaussTables {
-
- // CHECKSTYLE:OFF
- public final String schemaname;
-
- public final String tablename;
- // CHECKSTYLE:ON
-}
diff --git a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreatorTest.java b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreatorTest.java
index d3dda3fd624..d17123b9e4f 100644
--- a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreatorTest.java
+++ b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorCreatorTest.java
@@ -26,9 +26,9 @@ import org.junit.jupiter.api.Test;
import java.util.Collections;
import java.util.Optional;
-import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
diff --git a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorFactoryTest.java b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorFactoryTest.java
index 67946db94ce..2072c883e0c 100644
--- a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorFactoryTest.java
+++ b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussAdminExecutorFactoryTest.java
@@ -30,9 +30,9 @@ import org.mockito.junit.jupiter.MockitoExtension;
import java.util.Collections;
import java.util.Optional;
-import static org.hamcrest.CoreMatchers.instanceOf;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.instanceOf;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
import static org.mockito.Mockito.mock;
diff --git a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutorTest.java b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutorTest.java
index 7959b39c333..896349d8370 100644
--- a/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutorTest.java
+++ b/proxy/backend/type/opengauss/src/test/java/org/apache/shardingsphere/proxy/backend/opengauss/handler/admin/OpenGaussSystemCatalogAdminQueryExecutorTest.java
@@ -17,14 +17,35 @@
package org.apache.shardingsphere.proxy.backend.opengauss.handler.admin;
-import org.apache.shardingsphere.authority.config.AuthorityRuleConfiguration;
-import org.apache.shardingsphere.authority.rule.AuthorityRule;
+import org.apache.shardingsphere.infra.binder.statement.dml.SelectStatementContext;
+import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.infra.database.type.dialect.OpenGaussDatabaseType;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResultMetaData;
import org.apache.shardingsphere.infra.merge.result.MergedResult;
+import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
+import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import org.apache.shardingsphere.infra.metadata.database.resource.ShardingSphereResourceMetaData;
import org.apache.shardingsphere.infra.metadata.database.rule.ShardingSphereRuleMetaData;
+import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereColumn;
+import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
+import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
+import org.apache.shardingsphere.sql.parser.api.CacheOption;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.column.ColumnSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.BinaryOperationExpression;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.FunctionSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.expr.simple.LiteralExpressionSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ColumnProjectionSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ExpressionProjectionSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.item.ProjectionsSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.dml.predicate.WhereSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.table.SimpleTableSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.segment.generic.table.TableNameSegment;
+import org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue;
+import org.apache.shardingsphere.sql.parser.sql.dialect.statement.opengauss.dml.OpenGaussSelectStatement;
+import org.apache.shardingsphere.sqlfederation.api.config.SQLFederationRuleConfiguration;
+import org.apache.shardingsphere.sqlfederation.rule.SQLFederationRule;
import org.apache.shardingsphere.test.mock.AutoMockExtension;
import org.apache.shardingsphere.test.mock.StaticMockSettings;
import org.junit.jupiter.api.Test;
@@ -33,6 +54,11 @@ import org.junit.jupiter.api.extension.ExtendWith;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Arrays;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Properties;
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
@@ -50,13 +76,19 @@ class OpenGaussSystemCatalogAdminQueryExecutorTest {
void assertExecuteSelectFromPgDatabase() throws SQLException {
when(ProxyContext.getInstance()).thenReturn(mock(ProxyContext.class, RETURNS_DEEP_STUBS));
when(ProxyContext.getInstance().getAllDatabaseNames()).thenReturn(Arrays.asList("foo", "bar", "sharding_db", "other_db"));
+ ConfigurationProperties properties = new ConfigurationProperties(new Properties());
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps()).thenReturn(properties);
ConnectionSession connectionSession = mock(ConnectionSession.class);
when(connectionSession.getProtocolType()).thenReturn(new OpenGaussDatabaseType());
- ShardingSphereRuleMetaData shardingSphereRuleMetaData = mock(ShardingSphereRuleMetaData.class);
- when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(shardingSphereRuleMetaData);
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class)).thenReturn(mock(AuthorityRule.class));
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class).getConfiguration()).thenReturn(mock(AuthorityRuleConfiguration.class));
- OpenGaussSystemCatalogAdminQueryExecutor executor = new OpenGaussSystemCatalogAdminQueryExecutor("select datname, datcompatibility from pg_database where datname = 'sharding_db'");
+ Map<String, ShardingSphereDatabase> databases = createShardingSphereDatabaseMap();
+ SQLFederationRule sqlFederationRule = new SQLFederationRule(new SQLFederationRuleConfiguration(false, new CacheOption(1, 1)), databases, properties);
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(mock(ShardingSphereRuleMetaData.class));
+ OpenGaussSelectStatement sqlStatement = createSelectStatementForPgDatabase();
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(databases, new ShardingSphereRuleMetaData(Collections.singletonList(sqlFederationRule)), properties);
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData()).thenReturn(metaData);
+ SelectStatementContext sqlStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), sqlStatement, "sharding_db");
+ OpenGaussSystemCatalogAdminQueryExecutor executor = new OpenGaussSystemCatalogAdminQueryExecutor(sqlStatementContext,
+ "select datname, datcompatibility from pg_database where datname = 'sharding_db'", "sharding_db", Collections.emptyList());
executor.execute(connectionSession);
QueryResultMetaData actualMetaData = executor.getQueryResultMetaData();
assertThat(actualMetaData.getColumnCount(), is(2));
@@ -68,14 +100,57 @@ class OpenGaussSystemCatalogAdminQueryExecutorTest {
assertThat(actualResult.getValue(2, String.class), is("PG"));
}
+ private OpenGaussSelectStatement createSelectStatementForPgDatabase() {
+ OpenGaussSelectStatement result = new OpenGaussSelectStatement();
+ result.setProjections(new ProjectionsSegment(0, 0));
+ result.getProjections().getProjections().add(new ColumnProjectionSegment(new ColumnSegment(0, 0, new IdentifierValue("datname"))));
+ result.getProjections().getProjections().add(new ColumnProjectionSegment(new ColumnSegment(0, 0, new IdentifierValue("datcompatibility"))));
+ result.setFrom(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("pg_database"))));
+ result.setWhere(new WhereSegment(0, 0,
+ new BinaryOperationExpression(0, 0, new ColumnSegment(0, 0, new IdentifierValue("datname")), new LiteralExpressionSegment(0, 0, "sharding_db"), "=", "datname = 'sharding_db'")));
+ return result;
+ }
+
+ private Map<String, ShardingSphereDatabase> createShardingSphereDatabaseMap() {
+ Map<String, ShardingSphereDatabase> result = new LinkedHashMap<>(1, 1F);
+ Collection<ShardingSphereColumn> columns = Arrays.asList(
+ new ShardingSphereColumn("datname", 12, false, false, false, true, false),
+ new ShardingSphereColumn("datdba", -5, false, false, false, true, false),
+ new ShardingSphereColumn("encoding", 4, false, false, false, true, false),
+ new ShardingSphereColumn("datcollate", 12, false, false, false, true, false),
+ new ShardingSphereColumn("datctype", 12, false, false, false, true, false),
+ new ShardingSphereColumn("datistemplate", -7, false, false, false, true, false),
+ new ShardingSphereColumn("datallowconn", -7, false, false, false, true, false),
+ new ShardingSphereColumn("datconnlimit", 4, false, false, false, true, false),
+ new ShardingSphereColumn("datlastsysoid", -5, false, false, false, true, false),
+ new ShardingSphereColumn("datfrozenxid", 1111, false, false, false, true, false),
+ new ShardingSphereColumn("dattablespace", -5, false, false, false, true, false),
+ new ShardingSphereColumn("datcompatibility", 12, false, false, false, true, false),
+ new ShardingSphereColumn("datacl", 2003, false, false, false, true, false),
+ new ShardingSphereColumn("datfrozenxid64", 1111, false, false, false, true, false),
+ new ShardingSphereColumn("datminmxid", 1111, false, false, false, true, false));
+ ShardingSphereSchema schema = new ShardingSphereSchema(
+ Collections.singletonMap("pg_database", new ShardingSphereTable("pg_database", columns, Collections.emptyList(), Collections.emptyList())), Collections.emptyMap());
+ result.put("sharding_db", new ShardingSphereDatabase("sharding_db", new OpenGaussDatabaseType(), mock(ShardingSphereResourceMetaData.class), mock(ShardingSphereRuleMetaData.class),
+ Collections.singletonMap("pg_catalog", schema)));
+ return result;
+ }
+
@Test
void assertExecuteSelectVersion() throws SQLException {
when(ProxyContext.getInstance()).thenReturn(mock(ProxyContext.class, RETURNS_DEEP_STUBS));
ShardingSphereRuleMetaData shardingSphereRuleMetaData = mock(ShardingSphereRuleMetaData.class);
when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(shardingSphereRuleMetaData);
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class)).thenReturn(mock(AuthorityRule.class));
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class).getConfiguration()).thenReturn(mock(AuthorityRuleConfiguration.class));
- OpenGaussSystemCatalogAdminQueryExecutor executor = new OpenGaussSystemCatalogAdminQueryExecutor("select VERSION()");
+ ConfigurationProperties properties = new ConfigurationProperties(new Properties());
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps()).thenReturn(properties);
+ Map<String, ShardingSphereDatabase> databases = createShardingSphereDatabaseMap();
+ SQLFederationRule sqlFederationRule = new SQLFederationRule(new SQLFederationRuleConfiguration(false, new CacheOption(1, 1)), databases, properties);
+ OpenGaussSelectStatement sqlStatement = createSelectStatementForVersion();
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(databases, new ShardingSphereRuleMetaData(Collections.singletonList(sqlFederationRule)), properties);
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData()).thenReturn(metaData);
+ SelectStatementContext sqlStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), sqlStatement, "sharding_db");
+ OpenGaussSystemCatalogAdminQueryExecutor executor =
+ new OpenGaussSystemCatalogAdminQueryExecutor(sqlStatementContext, "select VERSION()", "sharding_db", Collections.emptyList());
ConnectionSession connectionSession = mock(ConnectionSession.class);
when(connectionSession.getProtocolType()).thenReturn(new OpenGaussDatabaseType());
executor.execute(connectionSession);
@@ -87,14 +162,28 @@ class OpenGaussSystemCatalogAdminQueryExecutorTest {
assertThat((String) actualResult.getValue(1, String.class), containsString("ShardingSphere-Proxy"));
}
+ private OpenGaussSelectStatement createSelectStatementForVersion() {
+ OpenGaussSelectStatement result = new OpenGaussSelectStatement();
+ result.setProjections(new ProjectionsSegment(0, 0));
+ result.getProjections().getProjections().add(new ExpressionProjectionSegment(0, 0, "VERSION()", new FunctionSegment(0, 0, "VERSION", "VERSION()")));
+ return result;
+ }
+
@Test
void assertExecuteSelectGsPasswordDeadlineAndIntervalToNum() throws SQLException {
when(ProxyContext.getInstance()).thenReturn(mock(ProxyContext.class, RETURNS_DEEP_STUBS));
ShardingSphereRuleMetaData shardingSphereRuleMetaData = mock(ShardingSphereRuleMetaData.class);
when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(shardingSphereRuleMetaData);
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class)).thenReturn(mock(AuthorityRule.class));
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class).getConfiguration()).thenReturn(mock(AuthorityRuleConfiguration.class));
- OpenGaussSystemCatalogAdminQueryExecutor executor = new OpenGaussSystemCatalogAdminQueryExecutor("select intervaltonum(gs_password_deadline())");
+ ConfigurationProperties properties = new ConfigurationProperties(new Properties());
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps()).thenReturn(properties);
+ Map<String, ShardingSphereDatabase> databases = createShardingSphereDatabaseMap();
+ SQLFederationRule sqlFederationRule = new SQLFederationRule(new SQLFederationRuleConfiguration(false, new CacheOption(1, 1)), databases, properties);
+ OpenGaussSelectStatement sqlStatement = createSelectStatementForGsPasswordDeadlineAndIntervalToNum();
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(databases, new ShardingSphereRuleMetaData(Collections.singletonList(sqlFederationRule)), properties);
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData()).thenReturn(metaData);
+ SelectStatementContext sqlStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), sqlStatement, "sharding_db");
+ OpenGaussSystemCatalogAdminQueryExecutor executor =
+ new OpenGaussSystemCatalogAdminQueryExecutor(sqlStatementContext, "select intervaltonum(gs_password_deadline())", "sharding_db", Collections.emptyList());
ConnectionSession connectionSession = mock(ConnectionSession.class);
when(connectionSession.getProtocolType()).thenReturn(new OpenGaussDatabaseType());
executor.execute(connectionSession);
@@ -106,14 +195,30 @@ class OpenGaussSystemCatalogAdminQueryExecutorTest {
assertThat(actualResult.getValue(1, Integer.class), is(90));
}
+ private OpenGaussSelectStatement createSelectStatementForGsPasswordDeadlineAndIntervalToNum() {
+ OpenGaussSelectStatement result = new OpenGaussSelectStatement();
+ result.setProjections(new ProjectionsSegment(0, 0));
+ FunctionSegment intervalToNumFunction = new FunctionSegment(0, 0, "intervaltonum", "intervaltonum(gs_password_deadline())");
+ intervalToNumFunction.getParameters().add(new FunctionSegment(0, 0, "gs_password_deadline", "gs_password_deadline()"));
+ result.getProjections().getProjections().add(new ExpressionProjectionSegment(0, 0, "intervaltonum(gs_password_deadline())", intervalToNumFunction));
+ return result;
+ }
+
@Test
void assertExecuteSelectGsPasswordNotifyTime() throws SQLException {
when(ProxyContext.getInstance()).thenReturn(mock(ProxyContext.class, RETURNS_DEEP_STUBS));
ShardingSphereRuleMetaData shardingSphereRuleMetaData = mock(ShardingSphereRuleMetaData.class);
when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getGlobalRuleMetaData()).thenReturn(shardingSphereRuleMetaData);
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class)).thenReturn(mock(AuthorityRule.class));
- when(shardingSphereRuleMetaData.getSingleRule(AuthorityRule.class).getConfiguration()).thenReturn(mock(AuthorityRuleConfiguration.class));
- OpenGaussSystemCatalogAdminQueryExecutor executor = new OpenGaussSystemCatalogAdminQueryExecutor("select gs_password_notifytime()");
+ ConfigurationProperties properties = new ConfigurationProperties(new Properties());
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData().getProps()).thenReturn(properties);
+ Map<String, ShardingSphereDatabase> databases = createShardingSphereDatabaseMap();
+ SQLFederationRule sqlFederationRule = new SQLFederationRule(new SQLFederationRuleConfiguration(false, new CacheOption(1, 1)), databases, properties);
+ OpenGaussSelectStatement sqlStatement = createSelectStatementForGsPasswordNotifyTime();
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(databases, new ShardingSphereRuleMetaData(Collections.singletonList(sqlFederationRule)), properties);
+ when(ProxyContext.getInstance().getContextManager().getMetaDataContexts().getMetaData()).thenReturn(metaData);
+ SelectStatementContext sqlStatementContext = new SelectStatementContext(metaData, Collections.emptyList(), sqlStatement, "sharding_db");
+ OpenGaussSystemCatalogAdminQueryExecutor executor =
+ new OpenGaussSystemCatalogAdminQueryExecutor(sqlStatementContext, "select gs_password_notifytime()", "sharding_db", Collections.emptyList());
ConnectionSession connectionSession = mock(ConnectionSession.class);
when(connectionSession.getProtocolType()).thenReturn(new OpenGaussDatabaseType());
executor.execute(connectionSession);
@@ -124,4 +229,12 @@ class OpenGaussSystemCatalogAdminQueryExecutorTest {
assertTrue(actualResult.next());
assertThat(actualResult.getValue(1, Integer.class), is(7));
}
+
+ private OpenGaussSelectStatement createSelectStatementForGsPasswordNotifyTime() {
+ OpenGaussSelectStatement result = new OpenGaussSelectStatement();
+ result.setProjections(new ProjectionsSegment(0, 0));
+ result.getProjections().getProjections()
+ .add(new ExpressionProjectionSegment(0, 0, "gs_password_notifytime()", new FunctionSegment(0, 0, "gs_password_notifytime", "gs_password_notifytime()")));
+ return result;
+ }
}
diff --git a/test/e2e/sql/src/test/java/org/apache/shardingsphere/test/e2e/engine/type/dql/GeneralDQLE2EIT.java b/test/e2e/sql/src/test/java/org/apache/shardingsphere/test/e2e/engine/type/dql/GeneralDQLE2EIT.java
index 73568800aae..c032d2c2dc5 100644
--- a/test/e2e/sql/src/test/java/org/apache/shardingsphere/test/e2e/engine/type/dql/GeneralDQLE2EIT.java
+++ b/test/e2e/sql/src/test/java/org/apache/shardingsphere/test/e2e/engine/type/dql/GeneralDQLE2EIT.java
@@ -58,7 +58,6 @@ class GeneralDQLE2EIT extends BaseDQLE2EIT {
assertExecuteQueryWithExpectedDataSource(containerComposer);
}
}
-
}
private void assertExecuteQueryWithXmlExpected(final AssertionTestParameter testParam, final SingleE2EContainerComposer containerComposer) throws SQLException {
diff --git a/test/e2e/sql/src/test/resources/cases/dql/dql-integration-select-sub-query.xml b/test/e2e/sql/src/test/resources/cases/dql/dql-integration-select-sub-query.xml
index 928c0eabcfd..4d2f1061d34 100644
--- a/test/e2e/sql/src/test/resources/cases/dql/dql-integration-select-sub-query.xml
+++ b/test/e2e/sql/src/test/resources/cases/dql/dql-integration-select-sub-query.xml
@@ -66,7 +66,8 @@
<assertion expected-data-source-name="expected_dataset" />
</test-case>
- <test-case sql="SELECT * FROM (SELECT u1.* FROM t_user u1 INNER JOIN t_user u2 ON u1.user_id = u2.user_id) temp ORDER BY user_id" db-types="MySQL,PostgreSQL,openGauss" scenario-types="mask,mask_encrypt,mask_sharding,mask_encrypt_sharding">
+ <!-- TODO support sql federation with mask_sharding,mask_encrypt_sharding -->
+ <test-case sql="SELECT * FROM (SELECT u1.* FROM t_user u1 INNER JOIN t_user u2 ON u1.user_id = u2.user_id) temp ORDER BY user_id" db-types="MySQL,PostgreSQL,openGauss" scenario-types="mask,mask_encrypt">
<assertion expected-data-source-name="expected_dataset" />
</test-case>