diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/constant/BroadcastOrder.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/constant/BroadcastOrder.java index 4745ee15c623aa..d2b240abd45d8e 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/constant/BroadcastOrder.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/constant/BroadcastOrder.java @@ -29,5 +29,5 @@ public final class BroadcastOrder { /** * Broadcast order. */ - public static final int ORDER = 5; + public static final int ORDER = 15; } diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouter.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouter.java index 7b44e74d57de66..e9926f0b89bf59 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouter.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouter.java @@ -19,148 +19,32 @@ import org.apache.shardingsphere.broadcast.constant.BroadcastOrder; import org.apache.shardingsphere.broadcast.route.engine.BroadcastRouteEngineFactory; -import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastDatabaseBroadcastRouteEngine; -import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastInstanceBroadcastRouteEngine; import org.apache.shardingsphere.broadcast.rule.BroadcastRule; import org.apache.shardingsphere.infra.annotation.HighFrequencyInvocation; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; -import org.apache.shardingsphere.infra.binder.context.statement.ddl.CloseStatementContext; -import org.apache.shardingsphere.infra.binder.context.type.CursorAvailable; -import org.apache.shardingsphere.infra.binder.context.type.IndexAvailable; -import org.apache.shardingsphere.infra.binder.context.type.TableAvailable; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.apache.shardingsphere.infra.route.context.RouteMapper; -import org.apache.shardingsphere.infra.route.context.RouteUnit; -import org.apache.shardingsphere.infra.route.type.DecorateSQLRouter; import org.apache.shardingsphere.infra.route.type.EntranceSQLRouter; import org.apache.shardingsphere.infra.route.type.TableSQLRouter; import org.apache.shardingsphere.infra.session.query.QueryContext; -import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.dal.DALStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.dcl.DCLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.AlterFunctionStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.AlterProcedureStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.AlterTablespaceStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateFunctionStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateProcedureStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTablespaceStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DDLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DropFunctionStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DropProcedureStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DropTablespaceStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.tcl.TCLStatement; -import org.apache.shardingsphere.sql.parser.statement.mysql.dal.MySQLCreateResourceGroupStatement; -import org.apache.shardingsphere.sql.parser.statement.mysql.dal.MySQLSetResourceGroupStatement; import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashSet; /** * Broadcast SQL router. */ @HighFrequencyInvocation -public final class BroadcastSQLRouter implements EntranceSQLRouter, DecorateSQLRouter, TableSQLRouter { +public final class BroadcastSQLRouter implements EntranceSQLRouter, TableSQLRouter { @Override - public RouteContext createRouteContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, - final ShardingSphereDatabase database, final BroadcastRule rule, final Collection tableNames, final ConfigurationProperties props) { - return BroadcastRouteEngineFactory.newInstance(rule, database, queryContext).route(new RouteContext(), rule); - } - - @Override - public void decorateRouteContext(final RouteContext routeContext, final QueryContext queryContext, - final ShardingSphereDatabase database, final BroadcastRule rule, final Collection tableNames, final ConfigurationProperties props) { - SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); - SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); - if (sqlStatement instanceof TCLStatement) { - decorateRouteContextWhenTCLStatement(routeContext, rule); - } else if (sqlStatement instanceof DDLStatement) { - decorateRouteContextWhenDDLStatement(routeContext, queryContext, database, rule); - } else if (sqlStatement instanceof DALStatement && isResourceGroupStatement(sqlStatement)) { - doInstanceBroadcastRoute(routeContext, database, rule); - } else if (sqlStatement instanceof DCLStatement && !isDCLForSingleTable(queryContext.getSqlStatementContext())) { - doInstanceBroadcastRoute(routeContext, database, rule); - } - } - - private void decorateRouteContextWhenTCLStatement(final RouteContext routeContext, final BroadcastRule rule) { - doDatabaseBroadcastRoute(routeContext, rule); - } - - private void decorateRouteContextWhenDDLStatement(final RouteContext routeContext, final QueryContext queryContext, final ShardingSphereDatabase database, final BroadcastRule rule) { - SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); - if (sqlStatementContext instanceof CursorAvailable) { - if (sqlStatementContext instanceof CloseStatementContext && ((CloseStatementContext) sqlStatementContext).getSqlStatement().isCloseAll()) { - doDatabaseBroadcastRoute(routeContext, rule); - } - return; - } - if (sqlStatementContext instanceof IndexAvailable && !routeContext.getRouteUnits().isEmpty()) { - putAllBroadcastTables(routeContext, rule, sqlStatementContext); - } - SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); - boolean functionStatement = sqlStatement instanceof CreateFunctionStatement || sqlStatement instanceof AlterFunctionStatement || sqlStatement instanceof DropFunctionStatement; - boolean procedureStatement = sqlStatement instanceof CreateProcedureStatement || sqlStatement instanceof AlterProcedureStatement || sqlStatement instanceof DropProcedureStatement; - if (functionStatement || procedureStatement) { - doDatabaseBroadcastRoute(routeContext, rule); - return; - } - // TODO BEGIN extract db route logic to common database router, eg: DCL in instance route @duanzhengqiang - if (sqlStatement instanceof CreateTablespaceStatement || sqlStatement instanceof AlterTablespaceStatement || sqlStatement instanceof DropTablespaceStatement) { - doInstanceBroadcastRoute(routeContext, database, rule); + public RouteContext createRouteContext(final QueryContext queryContext, final RuleMetaData globalRuleMetaData, final ShardingSphereDatabase database, + final BroadcastRule rule, final Collection tableNames, final ConfigurationProperties props) { + Collection broadcastTableNames = rule.getBroadcastTableNames(tableNames); + if (broadcastTableNames.isEmpty()) { + return new RouteContext(); } - // TODO END extract db route logic to common database router, eg: DCL in instance route - Collection tableNames = sqlStatementContext instanceof TableAvailable ? getTableNames((TableAvailable) sqlStatementContext) : Collections.emptyList(); - if (rule.isAllBroadcastTables(tableNames)) { - doInstanceBroadcastRoute(routeContext, database, rule); - } - } - - private Collection getTableNames(final TableAvailable sqlStatementContext) { - Collection tableSegments = sqlStatementContext.getTablesContext().getSimpleTables(); - Collection result = new LinkedHashSet<>(tableSegments.size()); - for (SimpleTableSegment each : tableSegments) { - result.add(each.getTableName().getIdentifier().getValue()); - } - return result; - } - - private void putAllBroadcastTables(final RouteContext routeContext, final BroadcastRule rule, final SQLStatementContext sqlStatementContext) { - Collection tableNames = sqlStatementContext instanceof TableAvailable ? ((TableAvailable) sqlStatementContext).getTablesContext().getTableNames() : Collections.emptyList(); - for (String each : rule.filterBroadcastTableNames(tableNames)) { - for (RouteUnit routeUnit : routeContext.getRouteUnits()) { - routeUnit.getTableMappers().add(new RouteMapper(each, each)); - } - } - } - - private boolean isResourceGroupStatement(final SQLStatement sqlStatement) { - // TODO add dropResourceGroupStatement, alterResourceGroupStatement - return sqlStatement instanceof MySQLCreateResourceGroupStatement || sqlStatement instanceof MySQLSetResourceGroupStatement; - } - - private boolean isDCLForSingleTable(final SQLStatementContext sqlStatementContext) { - if (sqlStatementContext instanceof TableAvailable) { - TableAvailable tableSegmentsAvailable = (TableAvailable) sqlStatementContext; - return 1 == tableSegmentsAvailable.getTablesContext().getSimpleTables().size() - && !"*".equals(tableSegmentsAvailable.getTablesContext().getSimpleTables().iterator().next().getTableName().getIdentifier().getValue()); - } - return false; - } - - private void doDatabaseBroadcastRoute(final RouteContext routeContext, final BroadcastRule rule) { - routeContext.getRouteUnits().clear(); - routeContext.getRouteUnits().addAll(new BroadcastDatabaseBroadcastRouteEngine().route(new RouteContext(), rule).getRouteUnits()); - } - - private void doInstanceBroadcastRoute(final RouteContext routeContext, final ShardingSphereDatabase database, final BroadcastRule rule) { - routeContext.getRouteUnits().clear(); - routeContext.getRouteUnits().addAll(new BroadcastInstanceBroadcastRouteEngine(database.getResourceMetaData()).route(new RouteContext(), rule).getRouteUnits()); + return BroadcastRouteEngineFactory.newInstance(queryContext, broadcastTableNames).route(rule); } @Override diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactory.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactory.java index 6237e1e0b4cd9d..887f45e5ee62e2 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactory.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactory.java @@ -22,16 +22,10 @@ import org.apache.shardingsphere.broadcast.route.engine.type.BroadcastRouteEngine; import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastDatabaseBroadcastRouteEngine; import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastTableBroadcastRouteEngine; -import org.apache.shardingsphere.broadcast.route.engine.type.ignore.BroadcastIgnoreRouteEngine; import org.apache.shardingsphere.broadcast.route.engine.type.unicast.BroadcastUnicastRouteEngine; -import org.apache.shardingsphere.broadcast.rule.BroadcastRule; import org.apache.shardingsphere.infra.annotation.HighFrequencyInvocation; -import org.apache.shardingsphere.infra.binder.context.extractor.SQLStatementContextExtractor; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; -import org.apache.shardingsphere.infra.binder.context.statement.ddl.CloseStatementContext; import org.apache.shardingsphere.infra.binder.context.type.CursorAvailable; -import org.apache.shardingsphere.infra.binder.context.type.TableAvailable; -import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.session.connection.ConnectionContext; import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; @@ -39,7 +33,6 @@ import org.apache.shardingsphere.sql.parser.statement.core.statement.dcl.DCLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DDLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.tcl.TCLStatement; import java.util.Collection; @@ -53,70 +46,42 @@ public final class BroadcastRouteEngineFactory { /** * Create new instance of broadcast routing engine. * - * @param rule broadcast rule - * @param database database * @param queryContext query context + * @param broadcastTableNames broadcast table names * @return broadcast route engine */ - public static BroadcastRouteEngine newInstance(final BroadcastRule rule, final ShardingSphereDatabase database, final QueryContext queryContext) { + public static BroadcastRouteEngine newInstance(final QueryContext queryContext, final Collection broadcastTableNames) { SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); SQLStatement sqlStatement = sqlStatementContext.getSqlStatement(); - if (sqlStatement instanceof TCLStatement) { - return new BroadcastDatabaseBroadcastRouteEngine(); - } if (sqlStatement instanceof DDLStatement) { - return sqlStatementContext instanceof CursorAvailable - ? getCursorRouteEngine(rule, sqlStatementContext, queryContext.getConnectionContext()) - : getDDLRouteEngine(rule, database, sqlStatementContext); - } - if (!(sqlStatementContext instanceof TableAvailable)) { - return new BroadcastIgnoreRouteEngine(); - } - Collection tableNames = ((TableAvailable) sqlStatementContext).getTablesContext().getTableNames(); - if (tableNames.isEmpty()) { - return new BroadcastIgnoreRouteEngine(); + return getDDLRouteEngine(queryContext, broadcastTableNames, sqlStatementContext); } if (sqlStatement instanceof DALStatement) { - return getDALRouteEngine(rule, tableNames); + return getDALRouteEngine(broadcastTableNames); } if (sqlStatement instanceof DCLStatement) { - return getDCLRouteEngine(rule, tableNames); - } - return getDMLRouteEngine(rule, sqlStatementContext, queryContext.getConnectionContext(), tableNames); - } - - private static BroadcastRouteEngine getCursorRouteEngine(final BroadcastRule rule, final SQLStatementContext sqlStatementContext, final ConnectionContext connectionContext) { - if (sqlStatementContext instanceof CloseStatementContext && ((CloseStatementContext) sqlStatementContext).getSqlStatement().isCloseAll()) { - return new BroadcastDatabaseBroadcastRouteEngine(); + return getDCLRouteEngine(broadcastTableNames); } - if (sqlStatementContext instanceof TableAvailable) { - Collection tableNames = ((TableAvailable) sqlStatementContext).getTablesContext().getTableNames(); - return rule.isAllBroadcastTables(tableNames) ? new BroadcastUnicastRouteEngine(sqlStatementContext, tableNames, connectionContext) : new BroadcastIgnoreRouteEngine(); - } - return new BroadcastIgnoreRouteEngine(); + return getDMLRouteEngine(sqlStatementContext, queryContext.getConnectionContext(), broadcastTableNames); } - private static BroadcastRouteEngine getDDLRouteEngine(final BroadcastRule rule, final ShardingSphereDatabase database, final SQLStatementContext sqlStatementContext) { - Collection tableNames = SQLStatementContextExtractor.getTableNames(database, sqlStatementContext); - return rule.isAllBroadcastTables(tableNames) ? new BroadcastTableBroadcastRouteEngine(tableNames) : new BroadcastIgnoreRouteEngine(); + private static BroadcastRouteEngine getDDLRouteEngine(final QueryContext queryContext, final Collection broadcastTableNames, final SQLStatementContext sqlStatementContext) { + return sqlStatementContext instanceof CursorAvailable + ? new BroadcastUnicastRouteEngine(sqlStatementContext, broadcastTableNames, queryContext.getConnectionContext()) + : new BroadcastTableBroadcastRouteEngine(broadcastTableNames); } - private static BroadcastRouteEngine getDALRouteEngine(final BroadcastRule rule, final Collection tableNames) { - return new BroadcastTableBroadcastRouteEngine(rule.filterBroadcastTableNames(tableNames)); + private static BroadcastRouteEngine getDALRouteEngine(final Collection broadcastTableNames) { + return new BroadcastTableBroadcastRouteEngine(broadcastTableNames); } - private static BroadcastRouteEngine getDCLRouteEngine(final BroadcastRule rule, final Collection tableNames) { - Collection broadcastTableNames = rule.filterBroadcastTableNames(tableNames); - return broadcastTableNames.isEmpty() ? new BroadcastIgnoreRouteEngine() : new BroadcastTableBroadcastRouteEngine(broadcastTableNames); + private static BroadcastRouteEngine getDCLRouteEngine(final Collection broadcastTableNames) { + return new BroadcastTableBroadcastRouteEngine(broadcastTableNames); } - private static BroadcastRouteEngine getDMLRouteEngine(final BroadcastRule rule, final SQLStatementContext sqlStatementContext, - final ConnectionContext connectionContext, final Collection tableNames) { - if (rule.isAllBroadcastTables(tableNames)) { - return sqlStatementContext.getSqlStatement() instanceof SelectStatement - ? new BroadcastUnicastRouteEngine(sqlStatementContext, tableNames, connectionContext) - : new BroadcastDatabaseBroadcastRouteEngine(); - } - return new BroadcastIgnoreRouteEngine(); + private static BroadcastRouteEngine getDMLRouteEngine(final SQLStatementContext sqlStatementContext, final ConnectionContext connectionContext, final Collection broadcastTableNames) { + return sqlStatementContext.getSqlStatement() instanceof SelectStatement + ? new BroadcastUnicastRouteEngine(sqlStatementContext, broadcastTableNames, connectionContext) + : new BroadcastDatabaseBroadcastRouteEngine(); } } diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/BroadcastRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/BroadcastRouteEngine.java index 76e493fbb64a7a..0825f9ffceb148 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/BroadcastRouteEngine.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/BroadcastRouteEngine.java @@ -28,9 +28,8 @@ public interface BroadcastRouteEngine { /** * Route. * - * @param routeContext route context * @param broadcastRule broadcast rule * @return route context */ - RouteContext route(RouteContext routeContext, BroadcastRule broadcastRule); + RouteContext route(BroadcastRule broadcastRule); } diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngine.java index 9269f64e419254..03a49f52475c11 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngine.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngine.java @@ -33,10 +33,11 @@ public final class BroadcastDatabaseBroadcastRouteEngine implements BroadcastRouteEngine { @Override - public RouteContext route(final RouteContext routeContext, final BroadcastRule rule) { + public RouteContext route(final BroadcastRule rule) { + RouteContext result = new RouteContext(); for (String each : rule.getDataSourceNames()) { - routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper(each, each), Collections.emptyList())); + result.getRouteUnits().add(new RouteUnit(new RouteMapper(each, each), Collections.emptyList())); } - return routeContext; + return result; } } diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngine.java deleted file mode 100644 index 3cb9ae7af77517..00000000000000 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngine.java +++ /dev/null @@ -1,50 +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.broadcast.route.engine.type.broadcast; - -import lombok.RequiredArgsConstructor; -import org.apache.shardingsphere.broadcast.route.engine.type.BroadcastRouteEngine; -import org.apache.shardingsphere.broadcast.rule.BroadcastRule; -import org.apache.shardingsphere.infra.annotation.HighFrequencyInvocation; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.apache.shardingsphere.infra.route.context.RouteMapper; -import org.apache.shardingsphere.infra.route.context.RouteUnit; - -import java.util.Collections; - -/** - * Broadcast route engine for database instance. - */ -@HighFrequencyInvocation -@RequiredArgsConstructor -public final class BroadcastInstanceBroadcastRouteEngine implements BroadcastRouteEngine { - - private final ResourceMetaData resourceMetaData; - - @Override - public RouteContext route(final RouteContext routeContext, final BroadcastRule rule) { - RouteContext result = new RouteContext(); - for (String each : rule.getDataSourceNames()) { - if (resourceMetaData.getAllInstanceDataSourceNames().contains(each)) { - result.getRouteUnits().add(new RouteUnit(new RouteMapper(each, each), Collections.emptyList())); - } - } - return result; - } -} diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngine.java index 98d59ee20682e3..a24b7169d1a9c0 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngine.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngine.java @@ -39,11 +39,12 @@ public final class BroadcastTableBroadcastRouteEngine implements BroadcastRouteE private final Collection broadcastTableNames; @Override - public RouteContext route(final RouteContext routeContext, final BroadcastRule rule) { - Collection logicTableNames = rule.filterBroadcastTableNames(broadcastTableNames); + public RouteContext route(final BroadcastRule rule) { + RouteContext result = new RouteContext(); + Collection logicTableNames = rule.getBroadcastTableNames(broadcastTableNames); RouteContext toBeAddedRouteContext = logicTableNames.isEmpty() ? getRouteContext(rule) : getRouteContext(rule, logicTableNames); - routeContext.getRouteUnits().addAll(toBeAddedRouteContext.getRouteUnits()); - return routeContext; + result.getRouteUnits().addAll(toBeAddedRouteContext.getRouteUnits()); + return result; } private RouteContext getRouteContext(final BroadcastRule rule) { diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngine.java deleted file mode 100644 index 4dc1a749507d08..00000000000000 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngine.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.broadcast.route.engine.type.ignore; - -import org.apache.shardingsphere.broadcast.route.engine.type.BroadcastRouteEngine; -import org.apache.shardingsphere.broadcast.rule.BroadcastRule; -import org.apache.shardingsphere.infra.route.context.RouteContext; - -/** - * Broadcast ignore route engine. - */ -public final class BroadcastIgnoreRouteEngine implements BroadcastRouteEngine { - - @Override - public RouteContext route(final RouteContext routeContext, final BroadcastRule rule) { - return routeContext; - } -} diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngine.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngine.java index 444116de5a0799..aa4472cc34f411 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngine.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngine.java @@ -49,10 +49,11 @@ public final class BroadcastUnicastRouteEngine implements BroadcastRouteEngine { private final ConnectionContext connectionContext; @Override - public RouteContext route(final RouteContext routeContext, final BroadcastRule rule) { + public RouteContext route(final BroadcastRule rule) { + RouteContext result = new RouteContext(); RouteMapper dataSourceMapper = getDataSourceRouteMapper(rule.getDataSourceNames()); - routeContext.getRouteUnits().add(new RouteUnit(dataSourceMapper, createTableRouteMappers())); - return routeContext; + result.getRouteUnits().add(new RouteUnit(dataSourceMapper, createTableRouteMappers())); + return result; } private RouteMapper getDataSourceRouteMapper(final Collection dataSourceNames) { diff --git a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/rule/BroadcastRule.java b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/rule/BroadcastRule.java index d40ab1e88febe0..64431426ac0e49 100644 --- a/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/rule/BroadcastRule.java +++ b/features/broadcast/core/src/main/java/org/apache/shardingsphere/broadcast/rule/BroadcastRule.java @@ -34,7 +34,6 @@ import java.util.Map; import java.util.Map.Entry; import java.util.Optional; -import java.util.stream.Collectors; /** * Broadcast rule. @@ -85,13 +84,19 @@ private Collection getAggregatedDataSourceNames(final Collection } /** - * Filter broadcast table names. + * Get broadcast table names. * - * @param logicTableNames to be filtered logic table names - * @return filtered broadcast table names + * @param logicTableNames all logic table names + * @return broadcast table names */ - public Collection filterBroadcastTableNames(final Collection logicTableNames) { - return logicTableNames.stream().filter(tables::contains).collect(Collectors.toSet()); + public Collection getBroadcastTableNames(final Collection logicTableNames) { + Collection result = new CaseInsensitiveSet<>(); + for (String each : logicTableNames) { + if (tables.contains(each)) { + result.add(each); + } + } + return result; } /** diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouterTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouterTest.java index 26ce3cc15a2541..27407ce41150a4 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouterTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/BroadcastSQLRouterTest.java @@ -17,48 +17,24 @@ package org.apache.shardingsphere.broadcast.route; -import com.google.common.collect.Lists; -import org.apache.shardingsphere.broadcast.config.BroadcastRuleConfiguration; import org.apache.shardingsphere.broadcast.route.engine.BroadcastRouteEngineFactory; import org.apache.shardingsphere.broadcast.route.engine.type.BroadcastRouteEngine; import org.apache.shardingsphere.broadcast.rule.BroadcastRule; -import org.apache.shardingsphere.infra.binder.context.statement.ddl.CreateTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; -import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; -import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; import org.apache.shardingsphere.infra.route.SQLRouter; -import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.apache.shardingsphere.infra.route.context.RouteMapper; -import org.apache.shardingsphere.infra.route.context.RouteUnit; -import org.apache.shardingsphere.infra.session.connection.ConnectionContext; import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.infra.spi.type.ordered.OrderedSPILoader; -import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment; -import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.TableNameSegment; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTableStatement; -import org.apache.shardingsphere.sql.parser.statement.core.value.identifier.IdentifierValue; -import org.apache.shardingsphere.sql.parser.statement.mysql.ddl.MySQLCreateTableStatement; -import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource; import org.apache.shardingsphere.test.mock.AutoMockExtension; import org.apache.shardingsphere.test.mock.StaticMockSettings; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import java.util.Collections; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.Optional; import java.util.Properties; -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -71,47 +47,15 @@ class BroadcastSQLRouterTest { void assertCreateRouteContext() { QueryContext queryContext = mock(QueryContext.class); BroadcastRule rule = mock(BroadcastRule.class); + when(rule.getBroadcastTableNames(Collections.singleton("t_config"))).thenReturn(Collections.singleton("t_config")); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); BroadcastRouteEngine routeEngine = mock(BroadcastRouteEngine.class); - when(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext)).thenReturn(routeEngine); - getSQLRouter(rule).createRouteContext(queryContext, mock(RuleMetaData.class), database, rule, Collections.emptyList(), new ConfigurationProperties(new Properties())); - verify(routeEngine).route(any(), eq(rule)); - } - - @Test - void assertDecorateBroadcastRouteContextWithSingleDataSource() { - BroadcastRuleConfiguration currentConfig = mock(BroadcastRuleConfiguration.class); - when(currentConfig.getTables()).thenReturn(Collections.singleton("t_order")); - BroadcastRule rule = new BroadcastRule(currentConfig, Collections.singletonMap("foo_ds", new MockedDataSource()), Collections.emptyList()); - RouteContext routeContext = new RouteContext(); - routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper("foo_ds", "foo_ds"), Lists.newArrayList())); - BroadcastSQLRouter sqlRouter = getSQLRouter(rule); - sqlRouter.decorateRouteContext(routeContext, createQueryContext(), mockSingleDatabase(), rule, Collections.emptyList(), new ConfigurationProperties(new Properties())); - Iterator routedDataSourceNames = routeContext.getActualDataSourceNames().iterator(); - assertThat(routedDataSourceNames.next(), is("foo_ds")); + when(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.singleton("t_config"))).thenReturn(routeEngine); + getSQLRouter(rule).createRouteContext(queryContext, mock(RuleMetaData.class), database, rule, Collections.singleton("t_config"), new ConfigurationProperties(new Properties())); + verify(routeEngine).route(eq(rule)); } private BroadcastSQLRouter getSQLRouter(final BroadcastRule rule) { return (BroadcastSQLRouter) OrderedSPILoader.getServices(SQLRouter.class, Collections.singleton(rule)).get(rule); } - - private ShardingSphereDatabase mockSingleDatabase() { - ShardingSphereDatabase result = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(result.getResourceMetaData().getStorageUnits()).thenReturn(Collections.singletonMap("foo_ds", mock(StorageUnit.class))); - when(result.getResourceMetaData().getAllInstanceDataSourceNames()).thenReturn(Collections.singletonList("foo_ds")); - return result; - } - - private QueryContext createQueryContext() { - CreateTableStatement createTableStatement = new MySQLCreateTableStatement(false); - createTableStatement.setTable(new SimpleTableSegment(new TableNameSegment(1, 2, new IdentifierValue("t_order")))); - return new QueryContext(new CreateTableStatementContext(createTableStatement, DefaultDatabase.LOGIC_NAME), "CREATE TABLE", new LinkedList<>(), new HintValueContext(), - mockConnectionContext(), mock(ShardingSphereMetaData.class)); - } - - private ConnectionContext mockConnectionContext() { - ConnectionContext result = mock(ConnectionContext.class); - when(result.getCurrentDatabaseName()).thenReturn(Optional.of(DefaultDatabase.LOGIC_NAME)); - return result; - } } diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactoryTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactoryTest.java index f88f78184dcbb9..ca641d5dc2b6b5 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactoryTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/BroadcastRouteEngineFactoryTest.java @@ -19,14 +19,12 @@ import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastDatabaseBroadcastRouteEngine; import org.apache.shardingsphere.broadcast.route.engine.type.broadcast.BroadcastTableBroadcastRouteEngine; -import org.apache.shardingsphere.broadcast.route.engine.type.ignore.BroadcastIgnoreRouteEngine; import org.apache.shardingsphere.broadcast.route.engine.type.unicast.BroadcastUnicastRouteEngine; import org.apache.shardingsphere.broadcast.rule.BroadcastRule; import org.apache.shardingsphere.infra.binder.context.extractor.SQLStatementContextExtractor; import org.apache.shardingsphere.infra.binder.context.segment.table.TablesContext; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.CloseStatementContext; -import org.apache.shardingsphere.infra.binder.context.type.CursorAvailable; import org.apache.shardingsphere.infra.binder.context.type.TableAvailable; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; @@ -34,11 +32,9 @@ import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.TableNameSegment; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dal.DALStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dcl.DCLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DDLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.DMLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.UpdateStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.tcl.TCLStatement; @@ -78,45 +74,22 @@ class BroadcastRouteEngineFactoryTest { @BeforeEach void setUp() { - when(rule.filterBroadcastTableNames(Collections.singleton("foo_tbl"))).thenReturn(Collections.singleton("foo_tbl")); + when(rule.getBroadcastTableNames(Collections.singleton("foo_tbl"))).thenReturn(Collections.singleton("foo_tbl")); when(rule.isAllBroadcastTables(Collections.singleton("foo_tbl"))).thenReturn(true); } @Test void assertNewInstanceWithTCLStatement() { when(queryContext.getSqlStatementContext().getSqlStatement()).thenReturn(mock(TCLStatement.class)); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastDatabaseBroadcastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithCloseStatementContextAndCloseAll() { - CloseStatementContext sqlStatementContext = mock(CloseStatementContext.class, RETURNS_DEEP_STUBS); - when(sqlStatementContext.getSqlStatement().isCloseAll()).thenReturn(true); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastDatabaseBroadcastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithCursorAvailableAndIsNotAllBroadcastTables() { - CloseStatementContext sqlStatementContext = mock(CloseStatementContext.class, RETURNS_DEEP_STUBS); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastDatabaseBroadcastRouteEngine.class)); } @Test void assertNewInstanceWithCursorAvailableAndIsAllBroadcastTables() { CloseStatementContext sqlStatementContext = mock(CloseStatementContext.class, RETURNS_DEEP_STUBS); - when(sqlStatementContext.getTablesContext()).thenReturn(createTablesContext("foo_tbl")); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastUnicastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithCursorAvailableAndNotTableAvailable() { - SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(CursorAvailable.class)); - when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DDLStatement.class)); + when(sqlStatementContext.getTablesContext()).thenReturn(createTablesContext()); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastUnicastRouteEngine.class)); } @Test @@ -125,92 +98,47 @@ void assertNewInstanceWithDDLStatementAndIsAllBroadcastTables() { when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DDLStatement.class)); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); when(SQLStatementContextExtractor.getTableNames(database, sqlStatementContext)).thenReturn(Collections.singleton("foo_tbl")); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastTableBroadcastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithDDLStatementAndIsNotAllBroadcastTables() { - SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class); - when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DDLStatement.class)); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); - } - - @Test - void assertNewInstanceWithoutTableAvailableStatement() { - when(queryContext.getSqlStatementContext().getSqlStatement()).thenReturn(mock(SQLStatement.class)); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); - } - - @Test - void assertNewInstanceWithEmptyTables() { - SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext()); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastTableBroadcastRouteEngine.class)); } @Test void assertNewInstanceWithDALStatement() { SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("foo_tbl")); + when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext()); when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DALStatement.class)); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastTableBroadcastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithDCLStatementWithoutBroadcastTables() { - SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("bar_tbl")); - when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DCLStatement.class)); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastTableBroadcastRouteEngine.class)); } @Test void assertNewInstanceWithDCLStatementWithBroadcastTables() { SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("foo_tbl")); + when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext()); when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DCLStatement.class)); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastTableBroadcastRouteEngine.class)); - } - - @Test - void assertNewInstanceWithDMLStatementAndIsNotAllBroadcastTables() { - SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("bar_tbl")); - when(sqlStatementContext.getSqlStatement()).thenReturn(mock(DMLStatement.class)); - when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastIgnoreRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastTableBroadcastRouteEngine.class)); } @Test void assertNewInstanceWithSelectStatementAndIsAllBroadcastTables() { SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("foo_tbl")); + when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext()); when(sqlStatementContext.getSqlStatement()).thenReturn(mock(SelectStatement.class)); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastUnicastRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastUnicastRouteEngine.class)); } @Test void assertNewInstanceWithUpdateStatementAndIsAllBroadcastTables() { SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, withSettings().extraInterfaces(TableAvailable.class)); - when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext("foo_tbl")); + when(((TableAvailable) sqlStatementContext).getTablesContext()).thenReturn(createTablesContext()); when(sqlStatementContext.getSqlStatement()).thenReturn(mock(UpdateStatement.class)); when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); - assertThat(BroadcastRouteEngineFactory.newInstance(rule, database, queryContext), instanceOf(BroadcastDatabaseBroadcastRouteEngine.class)); + assertThat(BroadcastRouteEngineFactory.newInstance(queryContext, Collections.emptyList()), instanceOf(BroadcastDatabaseBroadcastRouteEngine.class)); } private TablesContext createTablesContext() { DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); - return new TablesContext(Collections.emptyList(), databaseType, null); - } - - private TablesContext createTablesContext(final String tableName) { - DatabaseType databaseType = TypedSPILoader.getService(DatabaseType.class, "FIXTURE"); - return new TablesContext(Collections.singleton(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue(tableName)))), databaseType, null); + return new TablesContext(Collections.singleton(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("foo_tbl")))), databaseType, null); } } diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngineTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngineTest.java index 235728253347ec..66c7c488495676 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngineTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastDatabaseBroadcastRouteEngineTest.java @@ -37,7 +37,7 @@ void assertRoute() { BroadcastRule rule = mock(BroadcastRule.class); when(rule.getDataSourceNames()).thenReturn(Arrays.asList("ds_0", "ds_1")); BroadcastDatabaseBroadcastRouteEngine engine = new BroadcastDatabaseBroadcastRouteEngine(); - RouteContext routeContext = engine.route(new RouteContext(), rule); + RouteContext routeContext = engine.route(rule); assertThat(routeContext.getRouteUnits().size(), is(2)); Iterator iterator = routeContext.getRouteUnits().iterator(); assertDataSourceRouteMapper(iterator.next(), "ds_0"); diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngineTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngineTest.java deleted file mode 100644 index 1b6e5ca87d4d25..00000000000000 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastInstanceBroadcastRouteEngineTest.java +++ /dev/null @@ -1,52 +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.broadcast.route.engine.type.broadcast; - -import org.apache.shardingsphere.broadcast.rule.BroadcastRule; -import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; -import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.apache.shardingsphere.infra.route.context.RouteUnit; -import org.junit.jupiter.api.Test; - -import java.util.Arrays; -import java.util.Collections; - -import static org.hamcrest.CoreMatchers.is; -import static org.hamcrest.MatcherAssert.assertThat; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.when; - -class BroadcastInstanceBroadcastRouteEngineTest { - - @Test - void assertRoute() { - ResourceMetaData resourceMetaData = mock(ResourceMetaData.class); - when(resourceMetaData.getAllInstanceDataSourceNames()).thenReturn(Collections.singleton("ds_0")); - BroadcastInstanceBroadcastRouteEngine engine = new BroadcastInstanceBroadcastRouteEngine(resourceMetaData); - BroadcastRule rule = mock(BroadcastRule.class); - when(rule.getDataSourceNames()).thenReturn(Arrays.asList("ds_0", "ds_1")); - RouteContext routeContext = engine.route(new RouteContext(), rule); - assertThat(routeContext.getRouteUnits().size(), is(1)); - assertDataSourceRouteMapper(routeContext.getRouteUnits().iterator().next(), "ds_0"); - } - - private void assertDataSourceRouteMapper(final RouteUnit routeUnit, final String expected) { - assertThat(routeUnit.getDataSourceMapper().getLogicName(), is(expected)); - assertThat(routeUnit.getDataSourceMapper().getActualName(), is(expected)); - } -} diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngineTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngineTest.java index f3a11136f1f408..b2095f60debf8b 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngineTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/broadcast/BroadcastTableBroadcastRouteEngineTest.java @@ -42,8 +42,8 @@ void assertRouteWithBroadcastRuleTable() { BroadcastTableBroadcastRouteEngine engine = new BroadcastTableBroadcastRouteEngine(broadcastRuleTableNames); BroadcastRule rule = mock(BroadcastRule.class); when(rule.getDataSourceNames()).thenReturn(Arrays.asList("ds_0", "ds_1")); - when(rule.filterBroadcastTableNames(any())).thenReturn(Collections.singleton("t_address")); - RouteContext routeContext = engine.route(new RouteContext(), rule); + when(rule.getBroadcastTableNames(any())).thenReturn(Collections.singleton("t_address")); + RouteContext routeContext = engine.route(rule); assertThat(routeContext.getRouteUnits().size(), is(2)); Iterator iterator = routeContext.getRouteUnits().iterator(); assertRouteMapper(iterator.next(), "ds_0", "t_address"); @@ -56,8 +56,8 @@ void assertRouteWithoutBroadcastRuleTable() { BroadcastTableBroadcastRouteEngine engine = new BroadcastTableBroadcastRouteEngine(broadcastRuleTableNames); BroadcastRule rule = mock(BroadcastRule.class); when(rule.getDataSourceNames()).thenReturn(Arrays.asList("ds_0", "ds_1")); - when(rule.filterBroadcastTableNames(any())).thenReturn(Collections.emptyList()); - RouteContext routeContext = engine.route(new RouteContext(), rule); + when(rule.getBroadcastTableNames(any())).thenReturn(Collections.emptyList()); + RouteContext routeContext = engine.route(rule); assertThat(routeContext.getRouteUnits().size(), is(2)); Iterator iterator = routeContext.getRouteUnits().iterator(); assertRouteMapper(iterator.next(), "ds_0", ""); diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngineTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngineTest.java deleted file mode 100644 index 6bb667aa832ed3..00000000000000 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/ignore/BroadcastIgnoreRouteEngineTest.java +++ /dev/null @@ -1,35 +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.broadcast.route.engine.type.ignore; - -import org.apache.shardingsphere.broadcast.rule.BroadcastRule; -import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.junit.jupiter.api.Test; - -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -class BroadcastIgnoreRouteEngineTest { - - @Test - void assertRoute() { - BroadcastIgnoreRouteEngine engine = new BroadcastIgnoreRouteEngine(); - RouteContext routeContext = engine.route(new RouteContext(), mock(BroadcastRule.class)); - assertTrue(routeContext.getRouteUnits().isEmpty()); - } -} diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngineTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngineTest.java index 18a815a0c1ec6e..f35175c1a60913 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngineTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/route/engine/type/unicast/BroadcastUnicastRouteEngineTest.java @@ -93,7 +93,7 @@ void assertRouteToRandomDataSourceWithUsedDataSources() { @SafeVarargs private final void assertRoute(final SQLStatementContext sqlStatementContext, final Matcher... matchers) { BroadcastUnicastRouteEngine engine = new BroadcastUnicastRouteEngine(sqlStatementContext, Collections.singleton("foo_tbl"), connectionContext); - RouteContext actual = engine.route(new RouteContext(), rule); + RouteContext actual = engine.route(rule); assertThat(actual.getRouteUnits().size(), is(1)); RouteMapper actualDataSourceRouteMapper = actual.getRouteUnits().iterator().next().getDataSourceMapper(); assertThat(actualDataSourceRouteMapper.getLogicName(), anyOf(matchers)); @@ -111,7 +111,7 @@ private void assertTableRouteMapper(final Collection actual) { @Test void assertRouteWithEmptyTables() { BroadcastUnicastRouteEngine engine = new BroadcastUnicastRouteEngine(mock(SQLStatementContext.class), Collections.emptyList(), connectionContext); - RouteContext actual = engine.route(new RouteContext(), rule); + RouteContext actual = engine.route(rule); assertThat(actual.getRouteUnits().size(), is(1)); Collection actualTableRouteMappers = actual.getRouteUnits().iterator().next().getTableMappers(); assertTrue(actualTableRouteMappers.isEmpty()); diff --git a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/rule/BroadcastRuleTest.java b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/rule/BroadcastRuleTest.java index 19a604ef2c4bdb..95a1383b95bd34 100644 --- a/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/rule/BroadcastRuleTest.java +++ b/features/broadcast/core/src/test/java/org/apache/shardingsphere/broadcast/rule/BroadcastRuleTest.java @@ -67,9 +67,9 @@ private ShardingSphereRule mockBuiltRule() { } @Test - void assertFilterBroadcastTableNames() { + void assertGetBroadcastTableNames() { BroadcastRule rule = new BroadcastRule(new BroadcastRuleConfiguration(Collections.singleton("foo_tbl")), Collections.emptyMap(), Collections.emptyList()); - assertThat(rule.filterBroadcastTableNames(Arrays.asList("foo_tbl", "bar_tbl")), is(Collections.singleton("foo_tbl"))); + assertThat(rule.getBroadcastTableNames(Arrays.asList("foo_tbl", "bar_tbl")), is(Collections.singleton("foo_tbl"))); } @Test diff --git a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/constant/EncryptOrder.java b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/constant/EncryptOrder.java index dbbf4f28117f7d..649d5d672d4c09 100644 --- a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/constant/EncryptOrder.java +++ b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/constant/EncryptOrder.java @@ -29,5 +29,5 @@ public final class EncryptOrder { /** * Encrypt order. */ - public static final int ORDER = 15; + public static final int ORDER = 10; } diff --git a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/EncryptorComparator.java b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/EncryptorComparator.java index db393aec8efb03..5095ccc17e5388 100644 --- a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/EncryptorComparator.java +++ b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/EncryptorComparator.java @@ -19,7 +19,9 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; +import org.apache.shardingsphere.encrypt.rule.EncryptRule; import org.apache.shardingsphere.encrypt.spi.EncryptAlgorithm; +import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.bound.ColumnSegmentBoundInfo; /** * Encryptor comparator. @@ -27,6 +29,20 @@ @NoArgsConstructor(access = AccessLevel.PRIVATE) public final class EncryptorComparator { + /** + * Compare whether same encryptor. + * + * @param encryptRule encrypt rule + * @param leftColumnInfo left column info + * @param rightColumnInfo right column info + * @return whether is same encryptors or not + */ + public static boolean isSame(final EncryptRule encryptRule, final ColumnSegmentBoundInfo leftColumnInfo, final ColumnSegmentBoundInfo rightColumnInfo) { + EncryptAlgorithm leftColumnEncryptor = encryptRule.findQueryEncryptor(leftColumnInfo.getOriginalTable().getValue(), leftColumnInfo.getOriginalColumn().getValue()).orElse(null); + EncryptAlgorithm rightColumnEncryptor = encryptRule.findQueryEncryptor(rightColumnInfo.getOriginalTable().getValue(), rightColumnInfo.getOriginalColumn().getValue()).orElse(null); + return EncryptorComparator.isSame(leftColumnEncryptor, rightColumnEncryptor); + } + /** * Compare whether same encryptor. * diff --git a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/JoinConditionsEncryptorComparator.java b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/JoinConditionsEncryptorComparator.java index 58dec2588d65d4..35abfc56cbf66c 100644 --- a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/JoinConditionsEncryptorComparator.java +++ b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/JoinConditionsEncryptorComparator.java @@ -20,7 +20,6 @@ import lombok.AccessLevel; import lombok.NoArgsConstructor; import org.apache.shardingsphere.encrypt.rule.EncryptRule; -import org.apache.shardingsphere.encrypt.spi.EncryptAlgorithm; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.column.ColumnSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.expr.BinaryOperationExpression; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.bound.ColumnSegmentBoundInfo; @@ -46,10 +45,8 @@ public static boolean isSame(final Collection joinCon continue; } ColumnSegmentBoundInfo leftColumnInfo = ((ColumnSegment) each.getLeft()).getColumnBoundInfo(); - EncryptAlgorithm leftColumnEncryptor = encryptRule.findQueryEncryptor(leftColumnInfo.getOriginalTable().getValue(), leftColumnInfo.getOriginalColumn().getValue()).orElse(null); ColumnSegmentBoundInfo rightColumnInfo = ((ColumnSegment) each.getRight()).getColumnBoundInfo(); - EncryptAlgorithm rightColumnEncryptor = encryptRule.findQueryEncryptor(rightColumnInfo.getOriginalTable().getValue(), rightColumnInfo.getOriginalColumn().getValue()).orElse(null); - if (!EncryptorComparator.isSame(leftColumnEncryptor, rightColumnEncryptor)) { + if (!EncryptorComparator.isSame(encryptRule, leftColumnInfo, rightColumnInfo)) { return false; } } diff --git a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rule/table/EncryptTable.java b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rule/table/EncryptTable.java index 629649cde021c5..646e4b02efd43e 100644 --- a/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rule/table/EncryptTable.java +++ b/features/encrypt/core/src/main/java/org/apache/shardingsphere/encrypt/rule/table/EncryptTable.java @@ -176,9 +176,6 @@ public boolean isLikeQueryColumn(final String columnName) { */ @HighFrequencyInvocation public Optional findQueryEncryptor(final String columnName) { - if (!isEncryptColumn(columnName)) { - return Optional.empty(); - } - return Optional.of(getEncryptColumn(columnName).getQueryEncryptor()); + return isEncryptColumn(columnName) ? Optional.of(getEncryptColumn(columnName).getQueryEncryptor()) : Optional.empty(); } } diff --git a/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/InsertSelectColumnsEncryptorComparatorTest.java b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/InsertSelectColumnsEncryptorComparatorTest.java new file mode 100644 index 00000000000000..76be5b0c8dcb3b --- /dev/null +++ b/features/encrypt/core/src/test/java/org/apache/shardingsphere/encrypt/rewrite/token/comparator/InsertSelectColumnsEncryptorComparatorTest.java @@ -0,0 +1,96 @@ +/* + * 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.encrypt.rewrite.token.comparator; + +import org.apache.shardingsphere.encrypt.config.EncryptRuleConfiguration; +import org.apache.shardingsphere.encrypt.config.rule.EncryptColumnItemRuleConfiguration; +import org.apache.shardingsphere.encrypt.config.rule.EncryptColumnRuleConfiguration; +import org.apache.shardingsphere.encrypt.config.rule.EncryptTableRuleConfiguration; +import org.apache.shardingsphere.encrypt.rule.EncryptRule; +import org.apache.shardingsphere.infra.algorithm.core.config.AlgorithmConfiguration; +import org.apache.shardingsphere.infra.binder.context.segment.select.projection.impl.ColumnProjection; +import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.column.ColumnSegment; +import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.bound.ColumnSegmentBoundInfo; +import org.apache.shardingsphere.sql.parser.statement.core.value.identifier.IdentifierValue; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.util.Properties; + +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class InsertSelectColumnsEncryptorComparatorTest { + + @Test + void assertInsertSelectIsSame() { + String databaseName = "foo_db"; + IdentifierValue databaseValue = new IdentifierValue(databaseName); + IdentifierValue schemaValue = new IdentifierValue("schema"); + ColumnSegment insertColumn1 = getInsertColumnSegment(databaseValue, schemaValue, "table1", "pwd"); + ColumnSegment insertColumn2 = getInsertColumnSegment(databaseValue, schemaValue, "table1", "card"); + ColumnProjection projection1 = getSelectProjection("pwd", databaseValue, schemaValue); + ColumnProjection projection2 = getSelectProjection("card", databaseValue, schemaValue); + EncryptRule encryptRule = new EncryptRule(databaseName, createEncryptRuleConfiguration()); + boolean result = InsertSelectColumnsEncryptorComparator.isSame(Arrays.asList(insertColumn1, insertColumn2), Arrays.asList(projection1, projection2), encryptRule); + assertTrue(result); + } + + private ColumnProjection getSelectProjection(final String pwd, final IdentifierValue databaseValue, final IdentifierValue schemaValue) { + return new ColumnProjection(new IdentifierValue("table2"), new IdentifierValue(pwd), null, null, null, null, + new ColumnSegmentBoundInfo(databaseValue, schemaValue, new IdentifierValue("table2"), new IdentifierValue(pwd))); + } + + private ColumnSegment getInsertColumnSegment(final IdentifierValue databaseValue, final IdentifierValue schemaValue, final String tableName, final String columnName) { + ColumnSegment result = mock(ColumnSegment.class); + when(result.getColumnBoundInfo()) + .thenReturn(new ColumnSegmentBoundInfo(databaseValue, schemaValue, new IdentifierValue(tableName), new IdentifierValue(columnName))); + return result; + } + + private EncryptRuleConfiguration createEncryptRuleConfiguration() { + return new EncryptRuleConfiguration(Arrays.asList(getEncryptTableRuleConfiguration("table1"), getEncryptTableRuleConfiguration("table2")), + getEncryptors(new AlgorithmConfiguration("CORE.FIXTURE", new Properties()), + new AlgorithmConfiguration("CORE.QUERY_ASSISTED.FIXTURE", new Properties()), new AlgorithmConfiguration("CORE.QUERY_LIKE.FIXTURE", new Properties()))); + } + + private EncryptTableRuleConfiguration getEncryptTableRuleConfiguration(final String tableName) { + EncryptColumnRuleConfiguration pwdColumnConfig = createEncryptColumnRuleConfiguration("pwd", "standard_encryptor"); + EncryptColumnRuleConfiguration cardColumnConfig = new EncryptColumnRuleConfiguration("card", new EncryptColumnItemRuleConfiguration("card_cipher", "standard_encryptor")); + return new EncryptTableRuleConfiguration(tableName, Arrays.asList(pwdColumnConfig, cardColumnConfig)); + } + + private EncryptColumnRuleConfiguration createEncryptColumnRuleConfiguration(final String logicalName, final String encryptorName) { + return new EncryptColumnRuleConfiguration(logicalName, new EncryptColumnItemRuleConfiguration(logicalName, encryptorName)); + } + + private Map getEncryptors(final AlgorithmConfiguration standardEncryptConfig, final AlgorithmConfiguration queryAssistedEncryptConfig, + final AlgorithmConfiguration queryLikeEncryptConfig) { + Map result = new HashMap<>(3, 1F); + result.put("standard_encryptor", standardEncryptConfig); + result.put("assisted_encryptor", queryAssistedEncryptConfig); + result.put("like_encryptor", queryLikeEncryptConfig); + return result; + } +} diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/ShardingSQLRouter.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/ShardingSQLRouter.java index 0fd20f7c09a07e..1d62baef30a2c1 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/ShardingSQLRouter.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/ShardingSQLRouter.java @@ -28,12 +28,11 @@ import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.cache.route.CachedShardingSQLRouter; import org.apache.shardingsphere.sharding.constant.ShardingOrder; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextCheckerFactory; import org.apache.shardingsphere.sharding.route.engine.condition.ShardingCondition; import org.apache.shardingsphere.sharding.route.engine.condition.ShardingConditions; import org.apache.shardingsphere.sharding.route.engine.condition.engine.ShardingConditionEngine; import org.apache.shardingsphere.sharding.route.engine.type.ShardingRouteEngineFactory; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidatorFactory; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.DMLStatement; @@ -70,12 +69,11 @@ private RouteContext createRouteContext0(final QueryContext queryContext, final } SQLStatement sqlStatement = queryContext.getSqlStatementContext().getSqlStatement(); ShardingConditions shardingConditions = createShardingConditions(queryContext, globalRuleMetaData, database, rule); - Optional validator = ShardingStatementValidatorFactory.newInstance(sqlStatement, shardingConditions); if (sqlStatement instanceof DMLStatement && shardingConditions.isNeedMerge()) { shardingConditions.merge(); } RouteContext result = ShardingRouteEngineFactory.newInstance(rule, database, queryContext, shardingConditions, logicTableNames, props).route(rule); - validator.ifPresent(optional -> optional.postValidate(rule, queryContext.getSqlStatementContext(), queryContext.getHintValueContext(), queryContext.getParameters(), database, props, result)); + checkRouteContext(queryContext, database, rule, props, sqlStatement, shardingConditions, result); return result; } @@ -90,6 +88,11 @@ private ShardingConditions createShardingConditions(final QueryContext queryCont return new ShardingConditions(shardingConditions, queryContext.getSqlStatementContext(), rule); } + private void checkRouteContext(final QueryContext queryContext, final ShardingSphereDatabase database, final ShardingRule rule, final ConfigurationProperties props, + final SQLStatement sqlStatement, final ShardingConditions shardingConditions, final RouteContext routeContext) { + ShardingRouteContextCheckerFactory.newInstance(sqlStatement, shardingConditions).ifPresent(optional -> optional.check(rule, queryContext, database, props, routeContext)); + } + @Override public int getOrder() { return ShardingOrder.ORDER; diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextChecker.java similarity index 61% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextChecker.java index eadc83b753b43f..68935ed94b42db 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextChecker.java @@ -15,33 +15,27 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator; +package org.apache.shardingsphere.sharding.route.engine.checker; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.rule.ShardingRule; -import java.util.List; - /** - * Sharding statement validator. + * Sharding route context checker. */ -public interface ShardingStatementValidator { +public interface ShardingRouteContextChecker { /** - * Validate whether sharding operation is supported after route. + * Check whether sharding operation is supported after route. * * @param shardingRule sharding rule - * @param sqlStatementContext SQL statement context - * @param hintValueContext hint value context - * @param params SQL parameters + * @param queryContext query context * @param database database * @param props props * @param routeContext route context */ - void postValidate(ShardingRule shardingRule, SQLStatementContext sqlStatementContext, HintValueContext hintValueContext, List params, - ShardingSphereDatabase database, ConfigurationProperties props, RouteContext routeContext); + void check(ShardingRule shardingRule, QueryContext queryContext, ShardingSphereDatabase database, ConfigurationProperties props, RouteContext routeContext); } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidatorFactory.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextCheckerFactory.java similarity index 55% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidatorFactory.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextCheckerFactory.java index 327b861369d786..8b0aa3ff1da225 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ShardingStatementValidatorFactory.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ShardingRouteContextCheckerFactory.java @@ -15,21 +15,21 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator; +package org.apache.shardingsphere.sharding.route.engine.checker; import lombok.AccessLevel; import lombok.NoArgsConstructor; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingAlterTableRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingCreateTableRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingCreateViewRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingDropIndexRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingDropTableRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingPrepareRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.ddl.ShardingRenameTableRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.dml.ShardingDeleteRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.dml.ShardingInsertRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.dml.ShardingUpdateRouteContextChecker; import org.apache.shardingsphere.sharding.route.engine.condition.ShardingConditions; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingAlterTableStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingCreateTableStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingCreateViewStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingDropIndexStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingDropTableStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingPrepareStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingRenameTableStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.impl.ShardingDeleteStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.impl.ShardingInsertStatementValidator; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.impl.ShardingUpdateStatementValidator; import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.AlterTableStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTableStatement; @@ -47,62 +47,62 @@ import java.util.Optional; /** - * Sharding statement validator factory. + * Sharding route context checker factory. */ @NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class ShardingStatementValidatorFactory { +public final class ShardingRouteContextCheckerFactory { /** - * New instance of sharding statement validator. + * New instance of sharding route context checker. * * @param sqlStatement SQL statement * @param shardingConditions sharding conditions * @return created instance */ - public static Optional newInstance(final SQLStatement sqlStatement, final ShardingConditions shardingConditions) { + public static Optional newInstance(final SQLStatement sqlStatement, final ShardingConditions shardingConditions) { if (sqlStatement instanceof DDLStatement) { - return getDDLStatementValidator(sqlStatement); + return getDDLRouteContextChecker(sqlStatement); } if (sqlStatement instanceof DMLStatement) { - return getDMLStatementValidator(sqlStatement, shardingConditions); + return getDMLRouteContextChecker(sqlStatement, shardingConditions); } return Optional.empty(); } - private static Optional getDDLStatementValidator(final SQLStatement sqlStatement) { + private static Optional getDDLRouteContextChecker(final SQLStatement sqlStatement) { if (sqlStatement instanceof CreateTableStatement) { - return Optional.of(new ShardingCreateTableStatementValidator()); + return Optional.of(new ShardingCreateTableRouteContextChecker()); } if (sqlStatement instanceof CreateViewStatement) { - return Optional.of(new ShardingCreateViewStatementValidator()); + return Optional.of(new ShardingCreateViewRouteContextChecker()); } if (sqlStatement instanceof AlterTableStatement) { - return Optional.of(new ShardingAlterTableStatementValidator()); + return Optional.of(new ShardingAlterTableRouteContextChecker()); } if (sqlStatement instanceof RenameTableStatement) { - return Optional.of(new ShardingRenameTableStatementValidator()); + return Optional.of(new ShardingRenameTableRouteContextChecker()); } if (sqlStatement instanceof DropTableStatement) { - return Optional.of(new ShardingDropTableStatementValidator()); + return Optional.of(new ShardingDropTableRouteContextChecker()); } if (sqlStatement instanceof DropIndexStatement) { - return Optional.of(new ShardingDropIndexStatementValidator()); + return Optional.of(new ShardingDropIndexRouteContextChecker()); } if (sqlStatement instanceof PrepareStatement) { - return Optional.of(new ShardingPrepareStatementValidator()); + return Optional.of(new ShardingPrepareRouteContextChecker()); } return Optional.empty(); } - private static Optional getDMLStatementValidator(final SQLStatement sqlStatement, final ShardingConditions shardingConditions) { + private static Optional getDMLRouteContextChecker(final SQLStatement sqlStatement, final ShardingConditions shardingConditions) { if (sqlStatement instanceof InsertStatement) { - return Optional.of(new ShardingInsertStatementValidator(shardingConditions)); + return Optional.of(new ShardingInsertRouteContextChecker(shardingConditions)); } if (sqlStatement instanceof UpdateStatement) { - return Optional.of(new ShardingUpdateStatementValidator()); + return Optional.of(new ShardingUpdateRouteContextChecker()); } if (sqlStatement instanceof DeleteStatement) { - return Optional.of(new ShardingDeleteStatementValidator()); + return Optional.of(new ShardingDeleteRouteContextChecker()); } return Optional.empty(); } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextChecker.java similarity index 69% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextChecker.java index 212a4c9cae0eaa..d352e1b95c8789 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextChecker.java @@ -15,31 +15,27 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.AlterTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.checker.sql.util.ShardingSupportedCheckUtils; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; -import java.util.List; - /** - * Sharding alter table statement validator. + * Sharding alter table route context checker. */ -public final class ShardingAlterTableStatementValidator implements ShardingStatementValidator { +public final class ShardingAlterTableRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - AlterTableStatementContext alterTableStatementContext = (AlterTableStatementContext) sqlStatementContext; + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + AlterTableStatementContext alterTableStatementContext = (AlterTableStatementContext) queryContext.getSqlStatementContext(); String primaryTable = alterTableStatementContext.getSqlStatement().getTable().getTableName().getIdentifier().getValue(); ShardingSpherePreconditions.checkState(!ShardingSupportedCheckUtils.isRouteUnitDataNodeDifferentSize(shardingRule, routeContext, primaryTable), () -> new ShardingDDLRouteException("ALTER", "TABLE", alterTableStatementContext.getTablesContext().getTableNames())); diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextChecker.java similarity index 68% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextChecker.java index 8c8b8bdb83e549..13f9f9f149d432 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextChecker.java @@ -15,30 +15,26 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.CreateTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.checker.sql.util.ShardingSupportedCheckUtils; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; -import java.util.List; - /** - * Sharding create table statement validator. + * Sharding create table route context checker. */ -public final class ShardingCreateTableStatementValidator implements ShardingStatementValidator { +public final class ShardingCreateTableRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - CreateTableStatementContext createTableStatementContext = (CreateTableStatementContext) sqlStatementContext; + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + CreateTableStatementContext createTableStatementContext = (CreateTableStatementContext) queryContext.getSqlStatementContext(); String primaryTable = (createTableStatementContext.getSqlStatement()).getTable().getTableName().getIdentifier().getValue(); if (ShardingSupportedCheckUtils.isRouteUnitDataNodeDifferentSize(shardingRule, routeContext, primaryTable)) { throw new ShardingDDLRouteException("CREATE", "TABLE", createTableStatementContext.getTablesContext().getTableNames()); diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextChecker.java similarity index 78% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextChecker.java index de0071c79f0589..e7a60e78686c32 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextChecker.java @@ -15,34 +15,30 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import lombok.RequiredArgsConstructor; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedCreateViewException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.item.AggregationProjectionSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.item.ProjectionSegment; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateViewStatement; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement; -import java.util.List; - /** - * Sharding create view statement validator. + * Sharding create view route context checker. */ @RequiredArgsConstructor -public final class ShardingCreateViewStatementValidator implements ShardingStatementValidator { +public final class ShardingCreateViewRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - SelectStatement selectStatement = ((CreateViewStatement) sqlStatementContext.getSqlStatement()).getSelect(); + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + SelectStatement selectStatement = ((CreateViewStatement) queryContext.getSqlStatementContext().getSqlStatement()).getSelect(); if (isContainsNotSupportedViewStatement(selectStatement, routeContext)) { throw new UnsupportedCreateViewException(); } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextChecker.java similarity index 79% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextChecker.java index 445653b89e3038..cadc11463fa8b3 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextChecker.java @@ -15,42 +15,39 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.type.DatabaseTypeRegistry; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.checker.sql.util.ShardingSupportedCheckUtils; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.ddl.index.IndexSegment; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DropIndexStatement; import java.util.Collection; -import java.util.List; import java.util.Optional; import java.util.stream.Collectors; /** - * Sharding drop index statement validator. + * Sharding drop index route context checker. */ -public final class ShardingDropIndexStatementValidator implements ShardingStatementValidator { +public final class ShardingDropIndexRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - DropIndexStatement dropIndexStatement = (DropIndexStatement) sqlStatementContext.getSqlStatement(); + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + DropIndexStatement dropIndexStatement = (DropIndexStatement) queryContext.getSqlStatementContext().getSqlStatement(); Collection indexSegments = dropIndexStatement.getIndexes(); Optional logicTableName = dropIndexStatement.getSimpleTable().map(optional -> optional.getTableName().getIdentifier().getValue()); if (logicTableName.isPresent()) { validateDropIndexRouteUnit(shardingRule, routeContext, indexSegments, logicTableName.get()); } else { - String defaultSchemaName = new DatabaseTypeRegistry(sqlStatementContext.getDatabaseType()).getDefaultSchemaName(database.getName()); + String defaultSchemaName = new DatabaseTypeRegistry(queryContext.getSqlStatementContext().getDatabaseType()).getDefaultSchemaName(database.getName()); for (IndexSegment each : indexSegments) { ShardingSphereSchema schema = each.getOwner().map(optional -> optional.getIdentifier().getValue()) .map(database::getSchema).orElseGet(() -> database.getSchema(defaultSchemaName)); diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextChecker.java similarity index 81% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextChecker.java index 4466101c033704..e6b311e7427b7f 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextChecker.java @@ -15,40 +15,37 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import com.cedarsoftware.util.CaseInsensitiveSet; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.DropTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.datanode.DataNode; import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.checker.sql.util.ShardingSupportedCheckUtils; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.exception.metadata.InUsedTablesException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DropTableStatement; import java.util.Collection; -import java.util.List; import java.util.Set; import java.util.stream.Collectors; /** - * Sharding drop table statement validator. + * Sharding drop table route context checker. */ -public final class ShardingDropTableStatementValidator implements ShardingStatementValidator { +public final class ShardingDropTableRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - DropTableStatementContext dropTableStatementContext = (DropTableStatementContext) sqlStatementContext; + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + DropTableStatementContext dropTableStatementContext = (DropTableStatementContext) queryContext.getSqlStatementContext(); DropTableStatement dropTableStatement = dropTableStatementContext.getSqlStatement(); checkTableInUsed(shardingRule, dropTableStatementContext, routeContext); for (SimpleTableSegment each : dropTableStatement.getTables()) { diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextChecker.java similarity index 69% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextChecker.java index 118e5fb2a1904e..ff152b0a8bb266 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextChecker.java @@ -15,30 +15,27 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.EmptyShardingRouteResultException; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedPrepareRouteToSameDataSourceException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; -import java.util.List; import java.util.stream.Collectors; /** - * Sharding prepare statement validator. + * Sharding prepare route context checker. */ -public final class ShardingPrepareStatementValidator implements ShardingStatementValidator { +public final class ShardingPrepareRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { if (routeContext.getRouteUnits().isEmpty()) { throw new EmptyShardingRouteResultException(); } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextChecker.java similarity index 69% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextChecker.java index c9082db3592ea5..f947034b851c2c 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextChecker.java @@ -15,37 +15,33 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.RenameTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.checker.sql.util.ShardingSupportedCheckUtils; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.ddl.table.RenameTableDefinitionSegment; import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.RenameTableStatement; -import java.util.List; - /** - * Sharding rename table statement validator. + * Sharding rename table route context checker. */ -public final class ShardingRenameTableStatementValidator implements ShardingStatementValidator { +public final class ShardingRenameTableRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - RenameTableStatement renameTableStatement = (RenameTableStatement) sqlStatementContext.getSqlStatement(); + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + RenameTableStatement renameTableStatement = (RenameTableStatement) queryContext.getSqlStatementContext().getSqlStatement(); for (RenameTableDefinitionSegment each : renameTableStatement.getRenameTables()) { String primaryTable = each.getTable().getTableName().getIdentifier().getValue(); ShardingSpherePreconditions.checkState(!ShardingSupportedCheckUtils.isRouteUnitDataNodeDifferentSize(shardingRule, routeContext, primaryTable), - () -> new ShardingDDLRouteException("RENAME", "TABLE", ((RenameTableStatementContext) sqlStatementContext).getTablesContext().getTableNames())); + () -> new ShardingDDLRouteException("RENAME", "TABLE", ((RenameTableStatementContext) queryContext.getSqlStatementContext()).getTablesContext().getTableNames())); } } } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingDeleteStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingDeleteRouteContextChecker.java similarity index 59% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingDeleteStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingDeleteRouteContextChecker.java index f49fe92daf039e..82f20e650b0ca4 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingDeleteStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingDeleteRouteContextChecker.java @@ -15,29 +15,25 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.dml; -import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.syntax.DMLMultipleDataNodesWithLimitException; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.ShardingDMLStatementValidator; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.DeleteStatement; -import java.util.List; - /** - * Sharding delete statement validator. + * Sharding delete route context checker. */ -public final class ShardingDeleteStatementValidator extends ShardingDMLStatementValidator { +public final class ShardingDeleteRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { - if (((DeleteStatement) sqlStatementContext.getSqlStatement()).getLimit().isPresent() && routeContext.getRouteUnits().size() > 1) { + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + if (((DeleteStatement) queryContext.getSqlStatementContext().getSqlStatement()).getLimit().isPresent() && routeContext.getRouteUnits().size() > 1) { throw new DMLMultipleDataNodesWithLimitException("DELETE"); } } diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextChecker.java similarity index 72% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextChecker.java index 81e7282e3a4a13..f2b34390d237dd 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextChecker.java @@ -15,21 +15,22 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.dml; import lombok.RequiredArgsConstructor; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.algorithm.DuplicateInsertDataRecordException; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedUpdatingShardingValueException; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.util.ShardingRouteContextCheckUtils; import org.apache.shardingsphere.sharding.route.engine.condition.ShardingConditions; import org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRouteEngine; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.ShardingDMLStatementValidator; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.assignment.ColumnAssignmentSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.column.OnDuplicateKeyColumnsSegment; @@ -38,20 +39,20 @@ import java.util.Collection; import java.util.Collections; -import java.util.List; import java.util.Optional; /** - * Sharding insert statement validator. + * Sharding insert route context checker. */ @RequiredArgsConstructor -public final class ShardingInsertStatementValidator extends ShardingDMLStatementValidator { +public final class ShardingInsertRouteContextChecker implements ShardingRouteContextChecker { private final ShardingConditions shardingConditions; @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + public void check(final ShardingRule shardingRule, final QueryContext queryContext, + final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); InsertStatement insertStatement = (InsertStatement) sqlStatementContext.getSqlStatement(); Optional insertSelect = insertStatement.getInsertSelect(); String tableName = insertStatement.getTable().map(optional -> optional.getTableName().getIdentifier().getValue()).orElse(""); @@ -59,12 +60,12 @@ public void postValidate(final ShardingRule shardingRule, final SQLStatementCont boolean singleRoutingOrSameShardingCondition = routeContext.isSingleRouting() || shardingConditions.isSameShardingCondition(); ShardingSpherePreconditions.checkState(singleRoutingOrSameShardingCondition, () -> new UnsupportedShardingOperationException("INSERT ... SELECT ...", tableName)); } - Collection assignments = insertStatement.getOnDuplicateKeyColumns() - .map(OnDuplicateKeyColumnsSegment::getColumns).orElse(Collections.emptyList()); - Optional onDuplicateKeyShardingConditions = createShardingConditions(sqlStatementContext, shardingRule, assignments, params); - Optional onDuplicateKeyRouteContext = onDuplicateKeyShardingConditions.map(optional -> new ShardingStandardRouteEngine(tableName, optional, - sqlStatementContext, hintValueContext, props).route(shardingRule)); - if (onDuplicateKeyRouteContext.isPresent() && !isSameRouteContext(routeContext, onDuplicateKeyRouteContext.get())) { + Collection assignments = insertStatement.getOnDuplicateKeyColumns().map(OnDuplicateKeyColumnsSegment::getColumns).orElse(Collections.emptyList()); + Optional onDuplicateKeyShardingConditions = + ShardingRouteContextCheckUtils.createShardingConditions(sqlStatementContext, shardingRule, assignments, queryContext.getParameters()); + Optional onDuplicateKeyRouteContext = onDuplicateKeyShardingConditions + .map(optional -> new ShardingStandardRouteEngine(tableName, optional, sqlStatementContext, queryContext.getHintValueContext(), props).route(shardingRule)); + if (onDuplicateKeyRouteContext.isPresent() && !ShardingRouteContextCheckUtils.isSameRouteContext(routeContext, onDuplicateKeyRouteContext.get())) { throw new UnsupportedUpdatingShardingValueException(tableName); } if (!routeContext.isSingleRouting()) { diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextChecker.java similarity index 63% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextChecker.java index 8f898831575d81..a0b5b4dae60d10 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextChecker.java @@ -15,41 +15,42 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.dml; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.dml.UpdateStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.syntax.DMLMultipleDataNodesWithLimitException; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedUpdatingShardingValueException; +import org.apache.shardingsphere.sharding.route.engine.checker.ShardingRouteContextChecker; +import org.apache.shardingsphere.sharding.route.engine.checker.util.ShardingRouteContextCheckUtils; import org.apache.shardingsphere.sharding.route.engine.condition.ShardingConditions; import org.apache.shardingsphere.sharding.route.engine.type.standard.ShardingStandardRouteEngine; -import org.apache.shardingsphere.sharding.route.engine.validator.dml.ShardingDMLStatementValidator; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.UpdateStatement; -import java.util.List; import java.util.Optional; /** - * Sharding update statement validator. + * Sharding update route context checker. */ -public final class ShardingUpdateStatementValidator extends ShardingDMLStatementValidator { +public final class ShardingUpdateRouteContextChecker implements ShardingRouteContextChecker { @Override - public void postValidate(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext, final HintValueContext hintValueContext, final List params, - final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + public void check(final ShardingRule shardingRule, final QueryContext queryContext, final ShardingSphereDatabase database, final ConfigurationProperties props, final RouteContext routeContext) { + SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); UpdateStatementContext updateStatementContext = (UpdateStatementContext) sqlStatementContext; String tableName = updateStatementContext.getTablesContext().getTableNames().iterator().next(); UpdateStatement updateStatement = updateStatementContext.getSqlStatement(); - Optional shardingConditions = createShardingConditions(sqlStatementContext, shardingRule, updateStatement.getSetAssignment().getAssignments(), params); - Optional setAssignmentRouteContext = shardingConditions.map(optional -> new ShardingStandardRouteEngine(tableName, optional, sqlStatementContext, - hintValueContext, props).route(shardingRule)); - if (setAssignmentRouteContext.isPresent() && !isSameRouteContext(routeContext, setAssignmentRouteContext.get())) { + Optional shardingConditions = + ShardingRouteContextCheckUtils.createShardingConditions(sqlStatementContext, shardingRule, updateStatement.getSetAssignment().getAssignments(), queryContext.getParameters()); + Optional setAssignmentRouteContext = + shardingConditions.map(optional -> new ShardingStandardRouteEngine(tableName, optional, sqlStatementContext, queryContext.getHintValueContext(), props).route(shardingRule)); + if (setAssignmentRouteContext.isPresent() && !ShardingRouteContextCheckUtils.isSameRouteContext(routeContext, setAssignmentRouteContext.get())) { throw new UnsupportedUpdatingShardingValueException(tableName); } ShardingSpherePreconditions.checkState(!updateStatement.getLimit().isPresent() diff --git a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/ShardingDMLStatementValidator.java b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/util/ShardingRouteContextCheckUtils.java similarity index 86% rename from features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/ShardingDMLStatementValidator.java rename to features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/util/ShardingRouteContextCheckUtils.java index 0a8a69c5712724..d0342fecc16526 100644 --- a/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/ShardingDMLStatementValidator.java +++ b/features/sharding/core/src/main/java/org/apache/shardingsphere/sharding/route/engine/checker/util/ShardingRouteContextCheckUtils.java @@ -15,8 +15,10 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml; +package org.apache.shardingsphere.sharding.route.engine.checker.util; +import lombok.AccessLevel; +import lombok.NoArgsConstructor; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.type.TableAvailable; import org.apache.shardingsphere.infra.route.context.RouteContext; @@ -26,7 +28,6 @@ import org.apache.shardingsphere.sharding.route.engine.condition.ShardingConditions; import org.apache.shardingsphere.sharding.route.engine.condition.value.ListShardingConditionValue; import org.apache.shardingsphere.sharding.route.engine.condition.value.ShardingConditionValue; -import org.apache.shardingsphere.sharding.route.engine.validator.ShardingStatementValidator; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.assignment.ColumnAssignmentSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.expr.ExpressionSegment; @@ -41,9 +42,10 @@ import java.util.Optional; /** - * Sharding DML statement validator. + * Sharding route context check utility class. */ -public abstract class ShardingDMLStatementValidator implements ShardingStatementValidator { +@NoArgsConstructor(access = AccessLevel.PRIVATE) +public final class ShardingRouteContextCheckUtils { /** * Judge whether is same route context or not. @@ -52,7 +54,7 @@ public abstract class ShardingDMLStatementValidator implements ShardingStatement * @param subRouteContext sub route context * @return whether is same route context or not */ - protected boolean isSameRouteContext(final RouteContext routeContext, final RouteContext subRouteContext) { + public static boolean isSameRouteContext(final RouteContext routeContext, final RouteContext subRouteContext) { if (routeContext.getRouteUnits().size() != subRouteContext.getRouteUnits().size()) { return false; } @@ -72,7 +74,7 @@ protected boolean isSameRouteContext(final RouteContext routeContext, final Rout return true; } - private boolean isSameTableMapper(final Collection tableMappers, final Collection setAssignmentTableMappers) { + private static boolean isSameTableMapper(final Collection tableMappers, final Collection setAssignmentTableMappers) { if (tableMappers.size() != setAssignmentTableMappers.size()) { return false; } @@ -90,7 +92,7 @@ private boolean isSameTableMapper(final Collection tableMappers, fi } /** - * Create shardingConditions. + * Create sharding conditions. * * @param sqlStatementContext SQL statement context * @param shardingRule shardingRule @@ -99,8 +101,8 @@ private boolean isSameTableMapper(final Collection tableMappers, fi * @return sharding conditions */ @SuppressWarnings({"rawtypes", "unchecked"}) - protected Optional createShardingConditions(final SQLStatementContext sqlStatementContext, final ShardingRule shardingRule, - final Collection assignments, final List params) { + public static Optional createShardingConditions(final SQLStatementContext sqlStatementContext, final ShardingRule shardingRule, + final Collection assignments, final List params) { Collection values = new LinkedList<>(); String tableName = ((TableAvailable) sqlStatementContext).getTablesContext().getTableNames().iterator().next(); for (ColumnAssignmentSegment each : assignments) { @@ -118,7 +120,7 @@ protected Optional createShardingConditions(final SQLStateme return Optional.of(new ShardingConditions(Collections.singletonList(shardingCondition), sqlStatementContext, shardingRule)); } - private Optional getShardingColumnAssignmentValue(final ColumnAssignmentSegment assignmentSegment, final List params) { + private static Optional getShardingColumnAssignmentValue(final ColumnAssignmentSegment assignmentSegment, final List params) { ExpressionSegment segment = assignmentSegment.getValue(); int shardingSetAssignIndex = -1; if (segment instanceof ParameterMarkerExpressionSegment) { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/cache/checker/ShardingRouteCacheableCheckerTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/cache/checker/ShardingRouteCacheableCheckerTest.java index 3904d1c4620c10..b55f9355d2a932 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/cache/checker/ShardingRouteCacheableCheckerTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/cache/checker/ShardingRouteCacheableCheckerTest.java @@ -121,25 +121,25 @@ private TimestampServiceRule createTimeServiceRule() { private ShardingSphereDatabase createDatabase(final ShardingRule shardingRule, final TimestampServiceRule timestampServiceRule) { ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME); - schema.getTables().put("t_warehouse", new ShardingSphereTable("t_warehouse", Arrays.asList( + schema.putTable(new ShardingSphereTable("t_warehouse", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("warehouse_name", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - schema.getTables().put("t_order", new ShardingSphereTable("t_order", Arrays.asList( + schema.putTable(new ShardingSphereTable("t_order", Arrays.asList( new ShardingSphereColumn("warehouse_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - schema.getTables().put("t_order_item", new ShardingSphereTable("t_order_item", Arrays.asList( + schema.putTable(new ShardingSphereTable("t_order_item", Arrays.asList( new ShardingSphereColumn("warehouse_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("order_broadcast_table_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - schema.getTables().put("t_non_sharding_table", new ShardingSphereTable("t_non_sharding_table", Collections.singleton( + schema.putTable(new ShardingSphereTable("t_non_sharding_table", Collections.singleton( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - schema.getTables().put("t_non_cacheable_database_sharding", new ShardingSphereTable("t_non_cacheable_database_sharding", Collections.singleton( + schema.putTable(new ShardingSphereTable("t_non_cacheable_database_sharding", Collections.singleton( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - schema.getTables().put("t_non_cacheable_table_sharding", new ShardingSphereTable("t_non_cacheable_table_sharding", Collections.singleton( + schema.putTable(new ShardingSphereTable("t_non_cacheable_table_sharding", Collections.singleton( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); return new ShardingSphereDatabase(DATABASE_NAME, TypedSPILoader.getService(DatabaseType.class, "PostgreSQL"), diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/LogicTablesMergedResultTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/LogicTablesMergedResultTest.java index cc62ededa2a835..45d5419459c5af 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/LogicTablesMergedResultTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/LogicTablesMergedResultTest.java @@ -49,8 +49,8 @@ class LogicTablesMergedResultTest { @BeforeEach void setUp() { rule = createShardingRule(); - schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("table", - new ShardingSphereTable("table", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyMap()); + schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, + Collections.singleton(new ShardingSphereTable("table", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyList()); } private ShardingRule createShardingRule() { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowCreateTableMergedResultTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowCreateTableMergedResultTest.java index adb24b5230a189..8ca0eeff75452f 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowCreateTableMergedResultTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowCreateTableMergedResultTest.java @@ -32,9 +32,9 @@ import org.junit.jupiter.api.Test; import java.sql.SQLException; +import java.util.Collection; import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.LinkedList; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -64,11 +64,10 @@ private ShardingRule buildShardingRule() { } private ShardingSphereSchema createSchema() { - Map tables = new HashMap<>(2, 1F); - tables.put("foo_tbl", - new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.singleton(new ShardingSphereConstraint("foo_tbl_foreign_key", "bar_tbl")))); - tables.put("bar_tbl", new ShardingSphereTable("bar_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - return new ShardingSphereSchema("foo_db", tables, Collections.emptyMap()); + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.singleton(new ShardingSphereConstraint("foo_tbl_foreign_key", "bar_tbl")))); + tables.add(new ShardingSphereTable("bar_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); + return new ShardingSphereSchema("foo_db", tables, Collections.emptyList()); } @Test diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowTableStatusMergedResultTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowTableStatusMergedResultTest.java index db870b2adfc7e9..30077c7ba615ff 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowTableStatusMergedResultTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dal/show/ShowTableStatusMergedResultTest.java @@ -58,8 +58,8 @@ class ShowTableStatusMergedResultTest { @BeforeEach void setUp() { rule = buildShardingRule(); - schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("table", - new ShardingSphereTable("table", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyMap()); + schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, + Collections.singleton(new ShardingSphereTable("table", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyList()); } private ShardingRule buildShardingRule() { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/ShardingDQLResultMergerTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/ShardingDQLResultMergerTest.java index 05e69694440c25..8e41af1c91cdf8 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/ShardingDQLResultMergerTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/ShardingDQLResultMergerTest.java @@ -513,7 +513,7 @@ private ShardingSphereDatabase createDatabase() { ShardingSphereColumn column2 = new ShardingSphereColumn("col2", 0, false, false, false, true, false, false); ShardingSphereColumn column3 = new ShardingSphereColumn("col3", 0, false, false, false, true, false, false); ShardingSphereTable table = new ShardingSphereTable("tbl", Arrays.asList(column1, column2, column3), Collections.emptyList(), Collections.emptyList()); - ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); return new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "MySQL"), mock(ResourceMetaData.class), mock(RuleMetaData.class), Collections.singletonMap(DefaultDatabase.LOGIC_NAME, schema)); } @@ -523,7 +523,7 @@ private ShardingSphereDatabase createSQLServerDatabase() { ShardingSphereColumn column2 = new ShardingSphereColumn("col2", 0, false, false, false, true, false, false); ShardingSphereColumn column3 = new ShardingSphereColumn("col3", 0, false, false, false, true, false, false); ShardingSphereTable table = new ShardingSphereTable("tbl", Arrays.asList(column1, column2, column3), Collections.emptyList(), Collections.emptyList()); - ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); return new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "SQLServer"), mock(ResourceMetaData.class), mock(RuleMetaData.class), Collections.singletonMap("dbo", schema)); } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/groupby/GroupByStreamMergedResultTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/groupby/GroupByStreamMergedResultTest.java index f9ed7a3a2c5c32..b596bde1628c39 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/groupby/GroupByStreamMergedResultTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/groupby/GroupByStreamMergedResultTest.java @@ -187,7 +187,7 @@ private ShardingSphereDatabase createDatabase() { ShardingSphereColumn column2 = new ShardingSphereColumn("col2", 0, false, false, false, true, false, false); ShardingSphereColumn column3 = new ShardingSphereColumn("col3", 0, false, false, false, true, false, false); ShardingSphereTable table = new ShardingSphereTable("tbl", Arrays.asList(column1, column2, column3), Collections.emptyList(), Collections.emptyList()); - ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); return new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "MySQL"), mock(ResourceMetaData.class), mock(RuleMetaData.class), Collections.singletonMap(DefaultDatabase.LOGIC_NAME, schema)); } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/orderby/OrderByStreamMergedResultTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/orderby/OrderByStreamMergedResultTest.java index cd3e5add266b78..15cd2e9ec334bc 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/orderby/OrderByStreamMergedResultTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/merge/dql/orderby/OrderByStreamMergedResultTest.java @@ -206,7 +206,7 @@ private ShardingSphereDatabase createDatabase() { ShardingSphereColumn column1 = new ShardingSphereColumn("col1", 0, false, false, true, true, false, false); ShardingSphereColumn column2 = new ShardingSphereColumn("col2", 0, false, false, false, true, false, false); ShardingSphereTable table = new ShardingSphereTable("tbl", Arrays.asList(column1, column2), Collections.emptyList(), Collections.emptyList()); - ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); return new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, TypedSPILoader.getService(DatabaseType.class, "MySQL"), mock(ResourceMetaData.class), mock(RuleMetaData.class), Collections.singletonMap(DefaultDatabase.LOGIC_NAME, schema)); diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextCheckerTest.java similarity index 80% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextCheckerTest.java index 6200434eb41195..f36674eea958bf 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingAlterTableStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingAlterTableRouteContextCheckerTest.java @@ -15,16 +15,16 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.ddl.AlterTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sharding.rule.ShardingTable; @@ -49,7 +49,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingAlterTableStatementValidatorTest { +class ShardingAlterTableRouteContextCheckerTest { @Mock private ShardingRule shardingRule; @@ -60,8 +60,11 @@ class ShardingAlterTableStatementValidatorTest { @Mock private RouteContext routeContext; + @Mock + private QueryContext queryContext; + @Test - void assertPostValidateAlterTableWithSameRouteResultShardingTableForPostgreSQL() { + void assertCheckWithSameRouteResultShardingTableForPostgreSQL() { PostgreSQLAlterTableStatement sqlStatement = new PostgreSQLAlterTableStatement(); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -70,13 +73,12 @@ void assertPostValidateAlterTableWithSameRouteResultShardingTableForPostgreSQL() routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingAlterTableStatementValidator().postValidate( - shardingRule, new AlterTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new AlterTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingAlterTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateAlterTableWithDifferentRouteResultShardingTableForPostgreSQL() { + void assertCheckWithDifferentRouteResultShardingTableForPostgreSQL() { PostgreSQLAlterTableStatement sqlStatement = new PostgreSQLAlterTableStatement(); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -84,8 +86,7 @@ void assertPostValidateAlterTableWithDifferentRouteResultShardingTableForPostgre Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertThrows(ShardingDDLRouteException.class, - () -> new ShardingAlterTableStatementValidator().postValidate(shardingRule, new AlterTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), - new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new AlterTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertThrows(ShardingDDLRouteException.class, () -> new ShardingAlterTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextCheckerTest.java similarity index 75% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextCheckerTest.java index 7db429ca14eb10..4e6c0ec408fae7 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateTableStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateTableRouteContextCheckerTest.java @@ -15,16 +15,16 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.ddl.CreateTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sharding.rule.ShardingTable; @@ -49,7 +49,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingCreateTableStatementValidatorTest { +class ShardingCreateTableRouteContextCheckerTest { @Mock private ShardingRule shardingRule; @@ -60,8 +60,11 @@ class ShardingCreateTableStatementValidatorTest { @Mock private RouteContext routeContext; + @Mock + private QueryContext queryContext; + @Test - void assertPostValidateCreateTableWithSameRouteResultShardingTableForPostgreSQL() { + void assertCheckWithSameRouteResultShardingTableForPostgreSQL() { PostgreSQLCreateTableStatement sqlStatement = new PostgreSQLCreateTableStatement(false); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -70,13 +73,12 @@ void assertPostValidateCreateTableWithSameRouteResultShardingTableForPostgreSQL( routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingCreateTableStatementValidator().postValidate( - shardingRule, new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingCreateTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateCreateTableWithDifferentRouteResultShardingTableForPostgreSQL() { + void assertCheckWithDifferentRouteResultShardingTableForPostgreSQL() { PostgreSQLCreateTableStatement sqlStatement = new PostgreSQLCreateTableStatement(false); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -84,17 +86,16 @@ void assertPostValidateCreateTableWithDifferentRouteResultShardingTableForPostgr Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertThrows(ShardingDDLRouteException.class, () -> new ShardingCreateTableStatementValidator().postValidate(shardingRule, - new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertThrows(ShardingDDLRouteException.class, + () -> new ShardingCreateTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateCreateTableWithSameRouteResultBroadcastTableForPostgreSQL() { + void assertCheckWithSameRouteResultBroadcastTableForPostgreSQL() { PostgreSQLCreateTableStatement sqlStatement = new PostgreSQLCreateTableStatement(false); sqlStatement.setTable(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_config")))); - assertDoesNotThrow(() -> new ShardingCreateTableStatementValidator().postValidate( - shardingRule, new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new CreateTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingCreateTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextCheckerTest.java similarity index 81% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextCheckerTest.java index 145bf13fd8b847..36969868e6b23a 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingCreateViewStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingCreateViewRouteContextCheckerTest.java @@ -15,13 +15,13 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.ddl.CreateViewStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedCreateViewException; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.dml.item.ProjectionsSegment; @@ -39,7 +39,6 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; -import java.util.Collections; import java.util.Optional; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; @@ -49,7 +48,7 @@ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class ShardingCreateViewStatementValidatorTest { +class ShardingCreateViewRouteContextCheckerTest { @Mock(answer = Answers.RETURNS_DEEP_STUBS) private RouteContext routeContext; @@ -66,6 +65,9 @@ class ShardingCreateViewStatementValidatorTest { @Mock private SelectStatement selectStatement; + @Mock + private QueryContext queryContext; + @BeforeEach void setUp() { when(createViewStatementContext.getSqlStatement()).thenReturn(createViewStatement); @@ -76,20 +78,20 @@ void setUp() { } @Test - void assertPostValidateCreateView() { + void assertCheck() { ProjectionsSegment projectionsSegment = mock(ProjectionsSegment.class); when(selectStatement.getProjections()).thenReturn(projectionsSegment); - assertDoesNotThrow(() -> new ShardingCreateViewStatementValidator().postValidate( - shardingRule, createViewStatementContext, new HintValueContext(), Collections.emptyList(), mock(ShardingSphereDatabase.class), mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(createViewStatementContext); + assertDoesNotThrow(() -> new ShardingCreateViewRouteContextChecker().check(shardingRule, queryContext, mock(ShardingSphereDatabase.class), mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateCreateViewWithException() { + void assertCheckWithException() { ProjectionsSegment projectionsSegment = mock(ProjectionsSegment.class); when(projectionsSegment.isDistinctRow()).thenReturn(true); when(selectStatement.getProjections()).thenReturn(projectionsSegment); + when(queryContext.getSqlStatementContext()).thenReturn(createViewStatementContext); assertThrows(UnsupportedCreateViewException.class, - () -> new ShardingCreateViewStatementValidator().postValidate(shardingRule, - createViewStatementContext, new HintValueContext(), Collections.emptyList(), mock(ShardingSphereDatabase.class), mock(ConfigurationProperties.class), routeContext)); + () -> new ShardingCreateViewRouteContextChecker().check(shardingRule, queryContext, mock(ShardingSphereDatabase.class), mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextCheckerTest.java similarity index 83% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextCheckerTest.java index 17b1bc35f3082c..21fa1aaa3d531c 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropIndexStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropIndexRouteContextCheckerTest.java @@ -15,17 +15,17 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.ddl.DropIndexStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sharding.rule.ShardingTable; @@ -50,7 +50,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingDropIndexStatementValidatorTest { +class ShardingDropIndexRouteContextCheckerTest { @Mock private ShardingRule shardingRule; @@ -61,8 +61,11 @@ class ShardingDropIndexStatementValidatorTest { @Mock private RouteContext routeContext; + @Mock + private QueryContext queryContext; + @Test - void assertPostValidateDropIndexWithSameRouteResultShardingTableIndexForPostgreSQL() { + void assertCheckWithSameRouteResultShardingTableIndexForPostgreSQL() { PostgreSQLDropIndexStatement sqlStatement = new PostgreSQLDropIndexStatement(false); sqlStatement.getIndexes().add(new IndexSegment(0, 0, new IndexNameSegment(0, 0, new IdentifierValue("t_order_index")))); sqlStatement.getIndexes().add(new IndexSegment(0, 0, new IndexNameSegment(0, 0, new IdentifierValue("t_order_index_new")))); @@ -76,13 +79,12 @@ void assertPostValidateDropIndexWithSameRouteResultShardingTableIndexForPostgreS routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingDropIndexStatementValidator().postValidate( - shardingRule, new DropIndexStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropIndexStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingDropIndexRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateDropIndexWithDifferentRouteResultShardingTableIndexForPostgreSQL() { + void assertCheckWithDifferentRouteResultShardingTableIndexForPostgreSQL() { PostgreSQLDropIndexStatement sqlStatement = new PostgreSQLDropIndexStatement(false); sqlStatement.getIndexes().add(new IndexSegment(0, 0, new IndexNameSegment(0, 0, new IdentifierValue("t_order_index")))); sqlStatement.getIndexes().add(new IndexSegment(0, 0, new IndexNameSegment(0, 0, new IdentifierValue("t_order_index_new")))); @@ -95,8 +97,7 @@ void assertPostValidateDropIndexWithDifferentRouteResultShardingTableIndexForPos Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singletonList(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertThrows(ShardingDDLRouteException.class, - () -> new ShardingDropIndexStatementValidator().postValidate(shardingRule, new DropIndexStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropIndexStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertThrows(ShardingDDLRouteException.class, () -> new ShardingDropIndexRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextCheckerTest.java similarity index 79% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextCheckerTest.java index cc249fc8a4ada3..37b8b9b24de660 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingDropTableStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingDropTableRouteContextCheckerTest.java @@ -15,17 +15,17 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.ddl.DropTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; import org.apache.shardingsphere.infra.datanode.DataNode; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.exception.metadata.InUsedTablesException; import org.apache.shardingsphere.sharding.rule.ShardingRule; @@ -60,7 +60,7 @@ @ExtendWith(MockitoExtension.class) @MockitoSettings(strictness = Strictness.LENIENT) -class ShardingDropTableStatementValidatorTest { +class ShardingDropTableRouteContextCheckerTest { @Mock private ShardingRule shardingRule; @@ -68,6 +68,9 @@ class ShardingDropTableStatementValidatorTest { @Mock private RouteContext routeContext; + @Mock + private QueryContext queryContext; + @BeforeEach void init() { Map shardingTables = new LinkedHashMap<>(2, 1F); @@ -77,7 +80,7 @@ void init() { } @Test - void assertPostValidateWhenDropTableInUsedForMySQL() { + void assertCheckWhenDropTableInUsedForMySQL() { MySQLDropTableStatement sqlStatement = new MySQLDropTableStatement(false); sqlStatement.getTables().add(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_item")))); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); @@ -92,10 +95,8 @@ void assertPostValidateWhenDropTableInUsedForMySQL() { routeUnits.add(routeUnit); RouteContext routeContext = mock(RouteContext.class); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertThrows(InUsedTablesException.class, - () -> new ShardingDropTableStatementValidator().postValidate(shardingRule, new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), database, - mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertThrows(InUsedTablesException.class, () -> new ShardingDropTableRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } private ShardingTable createShardingTable(final String tableName) { @@ -118,7 +119,7 @@ void clean() { } @Test - void assertPostValidateDropTableWithSameRouteResultShardingTableForPostgreSQL() { + void assertCheckWithSameRouteResultShardingTableForPostgreSQL() { PostgreSQLDropTableStatement sqlStatement = new PostgreSQLDropTableStatement(false, false); sqlStatement.getTables().add(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -127,13 +128,13 @@ void assertPostValidateDropTableWithSameRouteResultShardingTableForPostgreSQL() routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singleton(new RouteMapper("t_order", "t_order_0")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.singleton(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingDropTableStatementValidator().postValidate( - shardingRule, new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), - mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingDropTableRouteContextChecker().check(shardingRule, queryContext, mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), + mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateDropTableWithDifferentRouteResultShardingTableForPostgreSQL() { + void assertCheckWithDifferentRouteResultShardingTableForPostgreSQL() { PostgreSQLDropTableStatement sqlStatement = new PostgreSQLDropTableStatement(false, false); sqlStatement.getTables().add(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order")))); when(shardingRule.isShardingTable("t_order")).thenReturn(true); @@ -141,13 +142,13 @@ void assertPostValidateDropTableWithDifferentRouteResultShardingTableForPostgreS Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singleton(new RouteMapper("t_order", "t_order_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertThrows(ShardingDDLRouteException.class, - () -> new ShardingDropTableStatementValidator().postValidate(shardingRule, new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertThrows(ShardingDDLRouteException.class, () -> new ShardingDropTableRouteContextChecker().check(shardingRule, queryContext, mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), + mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateDropTableWithSameRouteResultBroadcastTableForPostgreSQL() { + void assertCheckWithSameRouteResultBroadcastTableForPostgreSQL() { PostgreSQLDropTableStatement sqlStatement = new PostgreSQLDropTableStatement(false, false); sqlStatement.getTables().add(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_config")))); when(shardingRule.getShardingTable("t_config")).thenReturn(new ShardingTable(Arrays.asList("ds_0", "ds_1"), "t_config")); @@ -155,8 +156,8 @@ void assertPostValidateDropTableWithSameRouteResultBroadcastTableForPostgreSQL() routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.singleton(new RouteMapper("t_config", "t_config")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.singleton(new RouteMapper("t_config", "t_config")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingDropTableStatementValidator().postValidate( - shardingRule, new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(new DropTableStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingDropTableRouteContextChecker().check(shardingRule, queryContext, mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS), + mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextCheckerTest.java similarity index 63% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextCheckerTest.java index 75436fec744e98..3a9542be30071d 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingPrepareStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingPrepareRouteContextCheckerTest.java @@ -15,21 +15,17 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; -import org.apache.shardingsphere.infra.binder.context.statement.ddl.PrepareStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; -import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.EmptyShardingRouteResultException; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedPrepareRouteToSameDataSourceException; import org.apache.shardingsphere.sharding.rule.ShardingRule; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.PrepareStatement; -import org.apache.shardingsphere.sql.parser.statement.postgresql.ddl.PostgreSQLPrepareStatement; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; @@ -46,7 +42,7 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingPrepareStatementValidatorTest { +class ShardingPrepareRouteContextCheckerTest { @Mock private ShardingRule shardingRule; @@ -57,38 +53,34 @@ class ShardingPrepareStatementValidatorTest { @Mock private RouteContext routeContext; + @Mock + private QueryContext queryContext; + @Test - void assertPostValidatePrepareWithEmptyRouteResultForPostgreSQL() { - PrepareStatement sqlStatement = new PostgreSQLPrepareStatement(); + void assertCheckWithEmptyRouteResultForPostgreSQL() { when(routeContext.getRouteUnits()).thenReturn(Collections.emptyList()); assertThrows(EmptyShardingRouteResultException.class, - () -> new ShardingPrepareStatementValidator().postValidate(shardingRule, new PrepareStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + () -> new ShardingPrepareRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidatePrepareWithDifferentDataSourceForPostgreSQL() { - PrepareStatement sqlStatement = new PostgreSQLPrepareStatement(); + void assertCheckWithDifferentDataSourceForPostgreSQL() { Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Arrays.asList(new RouteMapper("t_order", "t_order_0"), new RouteMapper("t_order_item", "t_order_item_0")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - assertDoesNotThrow(() -> new ShardingPrepareStatementValidator().postValidate( - shardingRule, new PrepareStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + assertDoesNotThrow(() -> new ShardingPrepareRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidatePrepareWithSameDataSourceForPostgreSQL() { + void assertCheckWithSameDataSourceForPostgreSQL() { Collection routeUnits = new LinkedList<>(); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Arrays.asList(new RouteMapper("t_order", "t_order_0"), new RouteMapper("t_order_item", "t_order_item_0")))); routeUnits.add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Arrays.asList(new RouteMapper("t_order", "t_order_0"), new RouteMapper("t_order_item", "t_order_item_1")))); when(routeContext.getRouteUnits()).thenReturn(routeUnits); - PrepareStatement sqlStatement = new PostgreSQLPrepareStatement(); - assertThrows(UnsupportedPrepareRouteToSameDataSourceException.class, () -> new ShardingPrepareStatementValidator().postValidate( - shardingRule, new PrepareStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME), new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), - routeContext)); + assertThrows(UnsupportedPrepareRouteToSameDataSourceException.class, + () -> new ShardingPrepareRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } } diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextCheckerTest.java similarity index 85% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextCheckerTest.java index 4224543e7f1dde..4c99f5ccf23319 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/ddl/impl/ShardingRenameTableStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/ddl/ShardingRenameTableRouteContextCheckerTest.java @@ -15,17 +15,17 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.ddl; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.statement.ddl.RenameTableStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; import org.apache.shardingsphere.infra.datanode.DataNode; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.sharding.exception.connection.ShardingDDLRouteException; import org.apache.shardingsphere.sharding.rule.ShardingRule; import org.apache.shardingsphere.sharding.rule.ShardingTable; @@ -48,13 +48,16 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingRenameTableStatementValidatorTest { +class ShardingRenameTableRouteContextCheckerTest { @Mock private ShardingRule shardingRule; + @Mock + private QueryContext queryContext; + @Test - void assertPostValidateDifferentRouteUnitsAndDataNodesSize() { + void assertCheckDifferentRouteUnitsAndDataNodesSize() { RouteContext routeContext = new RouteContext(); routeContext.getRouteUnits().add(mock(RouteUnit.class)); ShardingTable shardingTable = mock(ShardingTable.class); @@ -64,12 +67,12 @@ void assertPostValidateDifferentRouteUnitsAndDataNodesSize() { SQLStatementContext sqlStatementContext = createRenameTableStatementContext(); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); ConfigurationProperties props = mock(ConfigurationProperties.class); - assertThrows(ShardingDDLRouteException.class, - () -> new ShardingRenameTableStatementValidator().postValidate(shardingRule, sqlStatementContext, new HintValueContext(), Collections.emptyList(), database, props, routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertThrows(ShardingDDLRouteException.class, () -> new ShardingRenameTableRouteContextChecker().check(shardingRule, queryContext, database, props, routeContext)); } @Test - void assertPostValidateNormalCase() { + void assertCheckNormalCase() { RouteContext routeContext = new RouteContext(); routeContext.getRouteUnits().add(mock(RouteUnit.class)); ShardingTable shardingTable = mock(ShardingTable.class); @@ -79,8 +82,8 @@ void assertPostValidateNormalCase() { SQLStatementContext sqlStatementContext = createRenameTableStatementContext(); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class); ConfigurationProperties props = mock(ConfigurationProperties.class); - assertDoesNotThrow(() -> new ShardingRenameTableStatementValidator().postValidate( - shardingRule, sqlStatementContext, new HintValueContext(), Collections.emptyList(), database, props, routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertDoesNotThrow(() -> new ShardingRenameTableRouteContextChecker().check(shardingRule, queryContext, database, props, routeContext)); } private SQLStatementContext createRenameTableStatementContext() { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextCheckerTest.java similarity index 81% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextCheckerTest.java index 36d2d13447f6d1..219c3b40ee5776 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingInsertStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingInsertRouteContextCheckerTest.java @@ -15,7 +15,7 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.dml; import org.apache.shardingsphere.infra.binder.context.segment.table.TablesContext; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; @@ -24,7 +24,6 @@ import org.apache.shardingsphere.infra.database.core.DefaultDatabase; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; import org.apache.shardingsphere.infra.datanode.DataNode; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaData; @@ -33,6 +32,7 @@ import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; import org.apache.shardingsphere.sharding.exception.algorithm.DuplicateInsertDataRecordException; @@ -76,11 +76,14 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingInsertStatementValidatorTest { +class ShardingInsertRouteContextCheckerTest { @Mock private ShardingRule shardingRule; + @Mock + private QueryContext queryContext; + @Mock private RouteContext routeContext; @@ -91,11 +94,11 @@ class ShardingInsertStatementValidatorTest { private ShardingSphereDatabase database; @Test - void assertPostValidateWhenInsertWithSingleRouting() { + void assertCheckWhenInsertWithSingleRouting() { SQLStatementContext sqlStatementContext = createInsertStatementContext(Collections.singletonList(1), createInsertStatement()); when(routeContext.isSingleRouting()).thenReturn(true); - assertDoesNotThrow(() -> new ShardingInsertStatementValidator(shardingConditions).postValidate(shardingRule, sqlStatementContext, new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertDoesNotThrow(() -> new ShardingInsertRouteContextChecker(shardingConditions).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } private InsertStatementContext createInsertStatementContext(final List params, final InsertStatement insertStatement) { @@ -106,57 +109,63 @@ private InsertStatementContext createInsertStatementContext(final List p } @Test - void assertPostValidateWhenInsertWithBroadcastTable() { + void assertCheckWhenInsertWithBroadcastTable() { SQLStatementContext sqlStatementContext = createInsertStatementContext(Collections.singletonList(1), createInsertStatement()); when(routeContext.isSingleRouting()).thenReturn(false); - assertDoesNotThrow(() -> new ShardingInsertStatementValidator(shardingConditions).postValidate(shardingRule, sqlStatementContext, new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertDoesNotThrow(() -> new ShardingInsertRouteContextChecker(shardingConditions).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateWhenInsertWithRoutingToSingleDataNode() { + void assertCheckWhenInsertWithRoutingToSingleDataNode() { SQLStatementContext sqlStatementContext = createInsertStatementContext(Collections.singletonList(1), createInsertStatement()); when(routeContext.isSingleRouting()).thenReturn(false); when(routeContext.getOriginalDataNodes()).thenReturn(getSingleRouteDataNodes()); - assertDoesNotThrow(() -> new ShardingInsertStatementValidator(shardingConditions).postValidate(shardingRule, sqlStatementContext, new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertDoesNotThrow(() -> new ShardingInsertRouteContextChecker(shardingConditions).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateWhenInsertWithRoutingToMultipleDataNodes() { + void assertCheckWhenInsertWithRoutingToMultipleDataNodes() { SQLStatementContext sqlStatementContext = createInsertStatementContext(Collections.singletonList(1), createInsertStatement()); when(routeContext.isSingleRouting()).thenReturn(false); when(routeContext.getOriginalDataNodes()).thenReturn(getMultipleRouteDataNodes()); - assertThrows(DuplicateInsertDataRecordException.class, () -> new ShardingInsertStatementValidator(shardingConditions).postValidate(shardingRule, sqlStatementContext, new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertThrows(DuplicateInsertDataRecordException.class, + () -> new ShardingInsertRouteContextChecker(shardingConditions).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateWhenNotOnDuplicateKeyUpdateShardingColumn() { + void assertCheckWhenNotOnDuplicateKeyUpdateShardingColumn() { List params = Collections.singletonList(1); RouteContext routeContext = mock(RouteContext.class); when(routeContext.isSingleRouting()).thenReturn(true); InsertStatementContext insertStatementContext = createInsertStatementContext(params, createInsertStatement()); - assertDoesNotThrow(() -> new ShardingInsertStatementValidator(mock(ShardingConditions.class)).postValidate( - shardingRule, insertStatementContext, new HintValueContext(), params, database, mock(ConfigurationProperties.class), routeContext)); + when(queryContext.getSqlStatementContext()).thenReturn(insertStatementContext); + when(queryContext.getParameters()).thenReturn(params); + assertDoesNotThrow(() -> new ShardingInsertRouteContextChecker(mock(ShardingConditions.class)).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), routeContext)); } @Test - void assertPostValidateWhenOnDuplicateKeyUpdateShardingColumnWithSameRouteContext() { + void assertCheckWhenOnDuplicateKeyUpdateShardingColumnWithSameRouteContext() { mockShardingRuleForUpdateShardingColumn(); List params = Collections.singletonList(1); InsertStatementContext insertStatementContext = createInsertStatementContext(params, createInsertStatement()); - assertDoesNotThrow(() -> new ShardingInsertStatementValidator(mock(ShardingConditions.class)).postValidate(shardingRule, - insertStatementContext, new HintValueContext(), params, database, mock(ConfigurationProperties.class), createSingleRouteContext())); + when(queryContext.getSqlStatementContext()).thenReturn(insertStatementContext); + when(queryContext.getParameters()).thenReturn(params); + assertDoesNotThrow(() -> new ShardingInsertRouteContextChecker(mock(ShardingConditions.class)).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), + createSingleRouteContext())); } @Test - void assertPostValidateWhenOnDuplicateKeyUpdateShardingColumnWithDifferentRouteContext() { + void assertCheckWhenOnDuplicateKeyUpdateShardingColumnWithDifferentRouteContext() { mockShardingRuleForUpdateShardingColumn(); List params = Collections.singletonList(1); InsertStatementContext insertStatementContext = createInsertStatementContext(params, createInsertStatement()); - assertThrows(UnsupportedUpdatingShardingValueException.class, () -> new ShardingInsertStatementValidator(mock(ShardingConditions.class)).postValidate(shardingRule, - insertStatementContext, new HintValueContext(), params, database, mock(ConfigurationProperties.class), createFullRouteContext())); + when(queryContext.getSqlStatementContext()).thenReturn(insertStatementContext); + when(queryContext.getParameters()).thenReturn(params); + assertThrows(UnsupportedUpdatingShardingValueException.class, + () -> new ShardingInsertRouteContextChecker(mock(ShardingConditions.class)).check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), createFullRouteContext())); } private void mockShardingRuleForUpdateShardingColumn() { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidatorTest.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextCheckerTest.java similarity index 79% rename from features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidatorTest.java rename to features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextCheckerTest.java index c2856b2b1df1b8..4503322886cf76 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/validator/dml/impl/ShardingUpdateStatementValidatorTest.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/checker/dml/ShardingUpdateRouteContextCheckerTest.java @@ -15,16 +15,16 @@ * limitations under the License. */ -package org.apache.shardingsphere.sharding.route.engine.validator.dml.impl; +package org.apache.shardingsphere.sharding.route.engine.checker.dml; import org.apache.shardingsphere.infra.binder.context.statement.dml.UpdateStatementContext; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; -import org.apache.shardingsphere.infra.hint.HintValueContext; import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.context.RouteMapper; import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; import org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration; import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedUpdatingShardingValueException; @@ -60,41 +60,44 @@ import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) -class ShardingUpdateStatementValidatorTest { +class ShardingUpdateRouteContextCheckerTest { @Mock private ShardingRule shardingRule; + @Mock + private QueryContext queryContext; + @Mock private ShardingSphereDatabase database; @Test - void assertPostValidateWhenNotUpdateShardingColumn() { + void assertCheckWhenNotUpdateShardingColumn() { UpdateStatementContext sqlStatementContext = new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME); - assertDoesNotThrow(() -> new ShardingUpdateStatementValidator().postValidate(shardingRule, - sqlStatementContext, new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), mock(RouteContext.class))); + when(queryContext.getSqlStatementContext()).thenReturn(sqlStatementContext); + assertDoesNotThrow(() -> new ShardingUpdateRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), mock(RouteContext.class))); } @Test - void assertPostValidateWhenUpdateShardingColumnWithSameRouteContext() { + void assertCheckWhenUpdateShardingColumnWithSameRouteContext() { mockShardingRuleForUpdateShardingColumn(); - assertDoesNotThrow(() -> new ShardingUpdateStatementValidator().postValidate(shardingRule, new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME), - new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), createSingleRouteContext())); + when(queryContext.getSqlStatementContext()).thenReturn(new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingUpdateRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), createSingleRouteContext())); } @Test - void assertPostValidateWhenTableNameIsBroadcastTable() { + void assertCheckWhenTableNameIsBroadcastTable() { mockShardingRuleForUpdateShardingColumn(); - assertDoesNotThrow(() -> new ShardingUpdateStatementValidator().postValidate(shardingRule, new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME), - new HintValueContext(), Collections.emptyList(), database, mock(ConfigurationProperties.class), createSingleRouteContext())); + when(queryContext.getSqlStatementContext()).thenReturn(new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME)); + assertDoesNotThrow(() -> new ShardingUpdateRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), createSingleRouteContext())); } @Test - void assertPostValidateWhenUpdateShardingColumnWithDifferentRouteContext() { + void assertCheckWhenUpdateShardingColumnWithDifferentRouteContext() { mockShardingRuleForUpdateShardingColumn(); + when(queryContext.getSqlStatementContext()).thenReturn(new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME)); assertThrows(UnsupportedUpdatingShardingValueException.class, - () -> new ShardingUpdateStatementValidator().postValidate(shardingRule, new UpdateStatementContext(createUpdateStatement(), DefaultDatabase.LOGIC_NAME), new HintValueContext(), - Collections.emptyList(), database, mock(ConfigurationProperties.class), createFullRouteContext())); + () -> new ShardingUpdateRouteContextChecker().check(shardingRule, queryContext, database, mock(ConfigurationProperties.class), createFullRouteContext())); } private void mockShardingRuleForUpdateShardingColumn() { diff --git a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/standard/assertion/ShardingRouteAssert.java b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/standard/assertion/ShardingRouteAssert.java index 4d6e8a3774a7b6..9b760c3a7b6b7d 100644 --- a/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/standard/assertion/ShardingRouteAssert.java +++ b/features/sharding/core/src/test/java/org/apache/shardingsphere/sharding/route/engine/type/standard/assertion/ShardingRouteAssert.java @@ -35,6 +35,8 @@ import org.apache.shardingsphere.infra.parser.sql.SQLStatementParserEngine; import org.apache.shardingsphere.infra.route.context.RouteContext; import org.apache.shardingsphere.infra.route.engine.SQLRouteEngine; +import org.apache.shardingsphere.infra.rule.ShardingSphereRule; +import org.apache.shardingsphere.infra.rule.attribute.table.TableMapperRuleAttribute; import org.apache.shardingsphere.infra.session.connection.ConnectionContext; import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader; @@ -46,14 +48,17 @@ import java.sql.Types; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; -import java.util.HashMap; +import java.util.LinkedList; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Properties; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; /** * Sharding route assert. @@ -74,16 +79,20 @@ public static RouteContext assertRoute(final String sql, final List para SingleRule singleRule = ShardingRouteEngineFixtureBuilder.createSingleRule(Collections.singleton(shardingRule)); TimestampServiceRule timestampServiceRule = ShardingRouteEngineFixtureBuilder.createTimeServiceRule(); Map schemas = buildSchemas(); - ConfigurationProperties props = new ConfigurationProperties(new Properties()); SQLStatementParserEngine sqlStatementParserEngine = new SQLStatementParserEngine(databaseType, new CacheOption(2000, 65535L), new CacheOption(128, 1024L)); - RuleMetaData ruleMetaData = new RuleMetaData(Arrays.asList(shardingRule, singleRule, timestampServiceRule)); + ShardingSphereRule broadcastRule = mock(ShardingSphereRule.class, RETURNS_DEEP_STUBS); + TableMapperRuleAttribute ruleAttribute = mock(TableMapperRuleAttribute.class); + when(ruleAttribute.getDistributedTableNames()).thenReturn(Collections.singleton("t_product")); + when(broadcastRule.getAttributes().findAttribute(TableMapperRuleAttribute.class)).thenReturn(Optional.of(ruleAttribute)); + RuleMetaData ruleMetaData = new RuleMetaData(Arrays.asList(shardingRule, broadcastRule, singleRule, timestampServiceRule)); ShardingSphereDatabase database = new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, databaseType, mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), ruleMetaData, schemas); ShardingSphereMetaData metaData = createShardingSphereMetaData(database); SQLStatementContext sqlStatementContext = new SQLBindEngine(metaData, DefaultDatabase.LOGIC_NAME, new HintValueContext()).bind(sqlStatementParserEngine.parse(sql, false), params); ConnectionContext connectionContext = new ConnectionContext(Collections::emptySet); connectionContext.setCurrentDatabaseName(DefaultDatabase.LOGIC_NAME); QueryContext queryContext = new QueryContext(sqlStatementContext, sql, params, new HintValueContext(), connectionContext, metaData); + ConfigurationProperties props = new ConfigurationProperties(new Properties()); return new SQLRouteEngine(Arrays.asList(shardingRule, singleRule), props).route(queryContext, mock(RuleMetaData.class), database); } @@ -93,27 +102,27 @@ private static ShardingSphereMetaData createShardingSphereMetaData(final Shardin } private static Map buildSchemas() { - Map tables = new HashMap<>(3, 1F); - tables.put("t_order", new ShardingSphereTable("t_order", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_order", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("product_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_order_item", new ShardingSphereTable("t_order_item", Arrays.asList(new ShardingSphereColumn("item_id", Types.INTEGER, true, false, false, true, false, false), + tables.add(new ShardingSphereTable("t_order_item", Arrays.asList(new ShardingSphereColumn("item_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("order_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("product_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("c_date", Types.TIMESTAMP, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_other", new ShardingSphereTable("t_other", Collections.singletonList( + tables.add(new ShardingSphereTable("t_other", Collections.singletonList( new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_category", new ShardingSphereTable("t_category", Collections.singleton(new ShardingSphereColumn("id", Types.INTEGER, true, false, false, true, false, false)), + tables.add(new ShardingSphereTable("t_category", Collections.singleton(new ShardingSphereColumn("id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_product", new ShardingSphereTable("t_product", Collections.singleton(new ShardingSphereColumn("product_id", Types.INTEGER, true, false, false, true, false, false)), + tables.add(new ShardingSphereTable("t_product", Collections.singleton(new ShardingSphereColumn("product_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_user", new ShardingSphereTable("t_user", Collections.singleton(new ShardingSphereColumn("user_id", Types.INTEGER, true, false, false, true, false, false)), + tables.add(new ShardingSphereTable("t_user", Collections.singleton(new ShardingSphereColumn("user_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_hint_test", new ShardingSphereTable("t_hint_test", Collections.singleton(new ShardingSphereColumn("user_id", Types.INTEGER, true, false, false, true, false, false)), + tables.add(new ShardingSphereTable("t_hint_test", Collections.singleton(new ShardingSphereColumn("user_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - return Collections.singletonMap(DefaultDatabase.LOGIC_NAME, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap())); + return Collections.singletonMap(DefaultDatabase.LOGIC_NAME, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } } diff --git a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/insert/keygen/engine/GeneratedKeyContextEngineTest.java b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/insert/keygen/engine/GeneratedKeyContextEngineTest.java index ede9e8f3e9d214..4ecee6d7705bc0 100644 --- a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/insert/keygen/engine/GeneratedKeyContextEngineTest.java +++ b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/insert/keygen/engine/GeneratedKeyContextEngineTest.java @@ -18,7 +18,6 @@ package org.apache.shardingsphere.infra.binder.context.segment.insert.keygen.engine; import com.cedarsoftware.util.CaseInsensitiveMap; -import com.google.common.collect.ImmutableMap; import org.apache.shardingsphere.infra.binder.context.segment.insert.keygen.GeneratedKeyContext; import org.apache.shardingsphere.infra.binder.context.segment.insert.values.InsertValueContext; import org.apache.shardingsphere.infra.database.core.DefaultDatabase; @@ -45,6 +44,7 @@ import org.junit.jupiter.api.Test; import java.sql.Types; +import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.List; @@ -66,7 +66,7 @@ void setUp() { "tbl", Collections.singletonList(new ShardingSphereColumn("id", Types.INTEGER, true, true, false, true, false, false)), Collections.emptyList(), Collections.emptyList()); ShardingSphereTable table2 = new ShardingSphereTable( "tbl2", Collections.singletonList(new ShardingSphereColumn("ID", Types.INTEGER, true, true, false, true, false, false)), Collections.emptyList(), Collections.emptyList()); - schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, ImmutableMap.of(table.getName(), table, table2.getName(), table2), Collections.emptyMap()); + schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Arrays.asList(table, table2), Collections.emptyList()); } @Test diff --git a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/table/TablesContextTest.java b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/table/TablesContextTest.java index 4ab7dabc18de50..d9106ed54d24a9 100644 --- a/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/table/TablesContextTest.java +++ b/infra/binder/src/test/java/org/apache/shardingsphere/infra/binder/context/segment/table/TablesContextTest.java @@ -37,8 +37,6 @@ import java.util.HashSet; import java.util.Map; import java.util.Optional; -import java.util.stream.Collectors; -import java.util.stream.Stream; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -129,8 +127,7 @@ void assertFindTableNameWhenColumnSegmentOwnerAbsentAndSchemaMetaDataContainsCol SimpleTableSegment tableSegment2 = createTableSegment("TABLE_2", "TBL_2"); ShardingSphereTable table = new ShardingSphereTable("TABLE_1", Collections.singletonList(new ShardingSphereColumn("COL", 0, false, false, true, true, false, false)), Collections.emptyList(), Collections.emptyList()); - ShardingSphereSchema schema = - new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Stream.of(table).collect(Collectors.toMap(ShardingSphereTable::getName, value -> value)), Collections.emptyMap()); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); ColumnSegment columnSegment = createColumnSegment(null, "COL"); Map actual = new TablesContext(Arrays.asList(tableSegment1, tableSegment2), databaseType, DefaultDatabase.LOGIC_NAME).findTableNames(Collections.singletonList(columnSegment), schema); diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilder.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilder.java index f0e93e12550b9b..c030d214bd6e25 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilder.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilder.java @@ -123,21 +123,14 @@ private static Map convertToSchemaMap(final Map result = new ConcurrentHashMap<>(schemaMetaDataMap.size(), 1F); for (Entry entry : schemaMetaDataMap.entrySet()) { - Map tables = convertToTableMap(entry.getValue().getTables()); - result.put(entry.getKey().toLowerCase(), new ShardingSphereSchema(entry.getKey(), tables, new LinkedHashMap<>())); + result.put(entry.getKey().toLowerCase(), new ShardingSphereSchema(entry.getKey(), convertToTables(entry.getValue().getTables()), new LinkedList<>())); } return result; } - private static Map convertToTableMap(final Collection tableMetaDataList) { - Map result = new LinkedHashMap<>(tableMetaDataList.size(), 1F); - for (TableMetaData each : tableMetaDataList) { - Collection columns = convertToColumns(each.getColumns()); - Collection indexes = convertToIndexes(each.getIndexes()); - Collection constraints = convertToConstraints(each.getConstraints()); - result.put(each.getName(), new ShardingSphereTable(each.getName(), columns, indexes, constraints, each.getType())); - } - return result; + private static Collection convertToTables(final Collection tableMetaDataList) { + return tableMetaDataList.stream().map(each -> new ShardingSphereTable( + each.getName(), convertToColumns(each.getColumns()), convertToIndexes(each.getIndexes()), convertToConstraints(each.getConstraints()), each.getType())).collect(Collectors.toList()); } private static Collection convertToColumns(final Collection columnMetaDataList) { diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilder.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilder.java index e779cefdce9b2a..9d0972466c2e8e 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilder.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilder.java @@ -36,6 +36,7 @@ import java.util.Collection; import java.util.Collections; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Properties; @@ -77,13 +78,13 @@ private static Collection getSystemSchemas(final String originalDatabase private static ShardingSphereSchema createSchema(final String schemaName, final Collection schemaStreams, final YamlTableSwapper swapper, final boolean isSystemSchemaMetadataEnabled) { - Map tables = new LinkedHashMap<>(schemaStreams.size(), 1F); + Collection tables = new LinkedList<>(); for (InputStream each : schemaStreams) { YamlShardingSphereTable metaData = new Yaml().loadAs(each, YamlShardingSphereTable.class); if (isSystemSchemaMetadataEnabled || KernelSupportedSystemTables.isSupportedSystemTable(schemaName, metaData.getName())) { - tables.put(metaData.getName(), swapper.swapToObject(metaData)); + tables.add(swapper.swapToObject(metaData)); } } - return new ShardingSphereSchema(schemaName, tables, Collections.emptyMap()); + return new ShardingSphereSchema(schemaName, tables, Collections.emptyList()); } } diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManager.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManager.java index a5be33de72f76d..f15e0e6e7b000e 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManager.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManager.java @@ -22,7 +22,9 @@ import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable; +import java.util.Collection; import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.stream.Collectors; @@ -49,18 +51,18 @@ public static Map getToBeAddedTablesBySchemas(fina } private static ShardingSphereSchema getToBeAddedTablesBySchema(final ShardingSphereSchema reloadSchema, final ShardingSphereSchema currentSchema) { - return new ShardingSphereSchema(currentSchema.getName(), getToBeAddedTables(reloadSchema.getTables(), currentSchema.getTables()), new LinkedHashMap<>()); + return new ShardingSphereSchema(currentSchema.getName(), getToBeAddedTables(reloadSchema, currentSchema), new LinkedList<>()); } /** * Get to be added tables. * - * @param reloadTables reload tables - * @param currentTables current tables + * @param reloadSchema reload schema + * @param currentSchema current schema * @return to be added tables */ - public static Map getToBeAddedTables(final Map reloadTables, final Map currentTables) { - return reloadTables.entrySet().stream().filter(entry -> !entry.getValue().equals(currentTables.get(entry.getKey()))).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + public static Collection getToBeAddedTables(final ShardingSphereSchema reloadSchema, final ShardingSphereSchema currentSchema) { + return reloadSchema.getAllTables().stream().filter(each -> !each.equals(currentSchema.getTable(each.getName().toLowerCase()))).collect(Collectors.toList()); } /** @@ -78,18 +80,18 @@ public static Map getToBeDroppedTablesBySchemas(fi } private static ShardingSphereSchema getToBeDroppedTablesBySchema(final ShardingSphereSchema reloadSchema, final ShardingSphereSchema currentSchema) { - return new ShardingSphereSchema(currentSchema.getName(), getToBeDroppedTables(reloadSchema.getTables(), currentSchema.getTables()), new LinkedHashMap<>()); + return new ShardingSphereSchema(currentSchema.getName(), getToBeDroppedTables(reloadSchema, currentSchema), new LinkedList<>()); } /** * Get to be drop tables. * - * @param reloadTables reload tables - * @param currentTables current tables + * @param reloadSchema reload schema + * @param currentSchema current schema * @return to be dropped table */ - public static Map getToBeDroppedTables(final Map reloadTables, final Map currentTables) { - return currentTables.entrySet().stream().filter(entry -> !reloadTables.containsKey(entry.getKey())).collect(Collectors.toMap(Entry::getKey, Entry::getValue)); + public static Collection getToBeDroppedTables(final ShardingSphereSchema reloadSchema, final ShardingSphereSchema currentSchema) { + return currentSchema.getAllTables().stream().filter(each -> !reloadSchema.containsTable(each.getName().toLowerCase())).collect(Collectors.toList()); } /** diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchema.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchema.java index 94d5b3fd1fc74a..5966c8080598d7 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchema.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchema.java @@ -23,15 +23,14 @@ import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.Map.Entry; import java.util.concurrent.ConcurrentHashMap; /** * ShardingSphere schema. */ -@Getter public final class ShardingSphereSchema { + @Getter private final String name; private final Map tables; @@ -45,12 +44,12 @@ public ShardingSphereSchema(final String name) { views = new ConcurrentHashMap<>(); } - public ShardingSphereSchema(final String name, final Map tables, final Map views) { + public ShardingSphereSchema(final String name, final Collection tables, final Collection views) { this.name = name; this.tables = new ConcurrentHashMap<>(tables.size(), 1F); this.views = new ConcurrentHashMap<>(views.size(), 1F); - tables.forEach((key, value) -> this.tables.put(key.toLowerCase(), value)); - views.forEach((key, value) -> this.views.put(key.toLowerCase(), value)); + tables.forEach(each -> this.tables.put(each.getName().toLowerCase(), each)); + views.forEach(each -> this.views.put(each.getName().toLowerCase(), each)); } /** @@ -63,23 +62,32 @@ public Collection getAllTableNames() { } /** - * Get table. + * Get all tables. + * + * @return all tables + */ + public Collection getAllTables() { + return tables.values(); + } + + /** + * Judge whether contains table. * * @param tableName table name - * @return table + * @return contains table or not */ - public ShardingSphereTable getTable(final String tableName) { - return tables.get(tableName.toLowerCase()); + public boolean containsTable(final String tableName) { + return tables.containsKey(tableName.toLowerCase()); } /** - * Get view. + * Get table. * - * @param viewName view name - * @return view + * @param tableName table name + * @return table */ - public ShardingSphereView getView(final String viewName) { - return views.get(viewName.toLowerCase()); + public ShardingSphereTable getTable(final String tableName) { + return tables.get(tableName.toLowerCase()); } /** @@ -92,51 +100,59 @@ public void putTable(final ShardingSphereTable table) { } /** - * Add tables. + * Remove table. * - * @param tables tables + * @param tableName table name */ - public void putTables(final Map tables) { - for (Entry entry : tables.entrySet()) { - putTable(entry.getValue()); - } + public void removeTable(final String tableName) { + tables.remove(tableName.toLowerCase()); } /** - * Add view. + * Get all views. * - * @param view view + * @return all views */ - public void putView(final ShardingSphereView view) { - views.put(view.getName().toLowerCase(), view); + public Collection getAllViews() { + return views.values(); } /** - * Remove table. + * Judge whether contains view. * - * @param tableName table name + * @param viewName view name + * @return contains view or not */ - public void removeTable(final String tableName) { - tables.remove(tableName.toLowerCase()); + public boolean containsView(final String viewName) { + return views.containsKey(viewName.toLowerCase()); } /** - * Remove view. + * Get view. * * @param viewName view name + * @return view */ - public void removeView(final String viewName) { - views.remove(viewName.toLowerCase()); + public ShardingSphereView getView(final String viewName) { + return views.get(viewName.toLowerCase()); } /** - * Judge whether contains table. + * Add view. * - * @param tableName table name - * @return contains table or not + * @param view view */ - public boolean containsTable(final String tableName) { - return tables.containsKey(tableName.toLowerCase()); + public void putView(final ShardingSphereView view) { + views.put(view.getName().toLowerCase(), view); + } + + /** + * Remove view. + * + * @param viewName view name + */ + public void removeView(final String viewName) { + views.remove(viewName.toLowerCase()); } /** @@ -150,16 +166,6 @@ public boolean containsIndex(final String tableName, final String indexName) { return containsTable(tableName) && getTable(tableName).containsIndex(indexName); } - /** - * Judge whether contains view. - * - * @param viewName view name - * @return contains view or not - */ - public boolean containsView(final String viewName) { - return views.containsKey(viewName.toLowerCase()); - } - /** * Get all column names. * diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilder.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilder.java index 94085419010040..81d928444b4518 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilder.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilder.java @@ -94,10 +94,9 @@ private void initShardingTableStatisticsTable(final ShardingSphereSchemaData sch } private void initTables(final ShardingSphereSchema schema, final Collection tables, final ShardingSphereSchemaData schemaData) { - for (Entry entry : schema.getTables().entrySet()) { - if (tables.contains(entry.getValue().getName())) { - ShardingSphereTableData tableData = new ShardingSphereTableData(entry.getValue().getName()); - schemaData.putTable(entry.getKey(), tableData); + for (ShardingSphereTable each : schema.getAllTables()) { + if (tables.contains(each.getName().toLowerCase())) { + schemaData.putTable(each.getName().toLowerCase(), new ShardingSphereTableData(each.getName())); } } } diff --git a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/collector/tables/PgClassTableCollector.java b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/collector/tables/PgClassTableCollector.java index d58aee597ed0cb..d924c4c56956dc 100644 --- a/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/collector/tables/PgClassTableCollector.java +++ b/infra/common/src/main/java/org/apache/shardingsphere/infra/metadata/statistics/collector/tables/PgClassTableCollector.java @@ -60,11 +60,11 @@ public Optional collect(final String databaseName, fina private Collection collectForSchema(final Long oid, final Long relNamespace, final ShardingSphereSchema schema, final ShardingSphereTable table) { Collection result = new LinkedList<>(); - for (Entry entry : schema.getTables().entrySet()) { + for (ShardingSphereTable each : schema.getAllTables()) { Map columnValues = new CaseInsensitiveMap<>(4, 1F); columnValues.put("oid", oid); columnValues.put("relnamespace", relNamespace); - columnValues.put("relname", entry.getKey()); + columnValues.put("relname", each.getName()); columnValues.put("relkind", "r"); result.add(new ShardingSphereRowData(ShardingSphereTableDataCollectorUtils.createRowValue(columnValues, table))); } diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilderTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilderTest.java index 8fe0dbfa8f2555..a5d31b1c576b45 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilderTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/GenericSchemaBuilderTest.java @@ -24,7 +24,6 @@ import org.apache.shardingsphere.infra.database.core.metadata.data.model.TableMetaData; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; 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.rule.ShardingSphereRule; import org.apache.shardingsphere.infra.rule.attribute.RuleAttributes; import org.apache.shardingsphere.infra.rule.attribute.table.TableMapperRuleAttribute; @@ -75,14 +74,14 @@ void setUp() { void assertLoadWithExistedTableName() throws SQLException { Collection tableNames = Collections.singletonList("data_node_routed_table1"); when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material)); - assertFalse(GenericSchemaBuilder.build(tableNames, material).get(DefaultDatabase.LOGIC_NAME).getTables().isEmpty()); + assertFalse(GenericSchemaBuilder.build(tableNames, material).get(DefaultDatabase.LOGIC_NAME).getAllTables().isEmpty()); } @Test void assertLoadWithNotExistedTableName() throws SQLException { Collection tableNames = Collections.singletonList("invalid_table"); when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material)); - assertTrue(GenericSchemaBuilder.build(tableNames, material).get(DefaultDatabase.LOGIC_NAME).getTables().isEmpty()); + assertTrue(GenericSchemaBuilder.build(tableNames, material).get(DefaultDatabase.LOGIC_NAME).getAllTables().isEmpty()); } @Test @@ -91,7 +90,7 @@ void assertLoadAllTables() throws SQLException { when(MetaDataLoader.load(any())).thenReturn(createSchemaMetaDataMap(tableNames, material)); Map actual = GenericSchemaBuilder.build(tableNames, material); assertThat(actual.size(), is(1)); - assertTables(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, actual.values().iterator().next().getTables(), Collections.emptyMap()).getTables()); + assertTables(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, actual.values().iterator().next().getAllTables(), Collections.emptyList())); } private Map createSchemaMetaDataMap(final Collection tableNames, final GenericSchemaBuilderMaterial material) { @@ -103,9 +102,9 @@ private Map createSchemaMetaDataMap(final Collection actual) { - assertThat(actual.size(), is(2)); - assertTrue(actual.get("data_node_routed_table1").getAllColumns().isEmpty()); - assertTrue(actual.get("data_node_routed_table2").getAllColumns().isEmpty()); + private void assertTables(final ShardingSphereSchema actual) { + assertThat(actual.getAllTables().size(), is(2)); + assertTrue(actual.getTable("data_node_routed_table1").getAllColumns().isEmpty()); + assertTrue(actual.getTable("data_node_routed_table2").getAllColumns().isEmpty()); } } diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilderTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilderTest.java index d02be5381f3960..1092be90a81a05 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilderTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/builder/SystemSchemaBuilderTest.java @@ -39,19 +39,19 @@ void assertBuildForMySQL() { Map actualInformationSchema = SystemSchemaBuilder.build("information_schema", databaseType, configProps); assertThat(actualInformationSchema.size(), is(1)); assertTrue(actualInformationSchema.containsKey("information_schema")); - assertThat(actualInformationSchema.get("information_schema").getTables().size(), is(95)); + assertThat(actualInformationSchema.get("information_schema").getAllTables().size(), is(95)); Map actualMySQLSchema = SystemSchemaBuilder.build("mysql", databaseType, configProps); assertThat(actualMySQLSchema.size(), is(1)); assertTrue(actualMySQLSchema.containsKey("mysql")); - assertThat(actualMySQLSchema.get("mysql").getTables().size(), is(40)); + assertThat(actualMySQLSchema.get("mysql").getAllTables().size(), is(40)); Map actualPerformanceSchema = SystemSchemaBuilder.build("performance_schema", databaseType, configProps); assertThat(actualPerformanceSchema.size(), is(1)); assertTrue(actualPerformanceSchema.containsKey("performance_schema")); - assertThat(actualPerformanceSchema.get("performance_schema").getTables().size(), is(114)); + assertThat(actualPerformanceSchema.get("performance_schema").getAllTables().size(), is(114)); Map actualSysSchema = SystemSchemaBuilder.build("sys", databaseType, configProps); assertThat(actualSysSchema.size(), is(1)); assertTrue(actualSysSchema.containsKey("sys")); - assertThat(actualSysSchema.get("sys").getTables().size(), is(53)); + assertThat(actualSysSchema.get("sys").getAllTables().size(), is(53)); } @Test @@ -62,9 +62,9 @@ void assertBuildForPostgreSQL() { assertTrue(actual.containsKey("information_schema")); assertTrue(actual.containsKey("pg_catalog")); assertTrue(actual.containsKey("shardingsphere")); - assertThat(actual.get("information_schema").getTables().size(), is(69)); - assertThat(actual.get("pg_catalog").getTables().size(), is(134)); - assertThat(actual.get("shardingsphere").getTables().size(), is(2)); + assertThat(actual.get("information_schema").getAllTables().size(), is(69)); + assertThat(actual.get("pg_catalog").getAllTables().size(), is(134)); + assertThat(actual.get("shardingsphere").getAllTables().size(), is(2)); } @Test @@ -74,8 +74,8 @@ void assertBuildForOpenGaussSQL() { assertThat(actual.size(), is(16)); assertTrue(actual.containsKey("pg_catalog")); assertTrue(actual.containsKey("shardingsphere")); - assertThat(actual.get("information_schema").getTables().size(), is(66)); - assertThat(actual.get("pg_catalog").getTables().size(), is(240)); - assertThat(actual.get("shardingsphere").getTables().size(), is(2)); + assertThat(actual.get("information_schema").getAllTables().size(), is(66)); + assertThat(actual.get("pg_catalog").getAllTables().size(), is(240)); + assertThat(actual.get("shardingsphere").getAllTables().size(), is(2)); } } diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManagerTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManagerTest.java index 23330df3cdc87f..6d61b344d9f9e8 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManagerTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/manager/GenericSchemaManagerTest.java @@ -23,6 +23,7 @@ import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable; import org.junit.jupiter.api.Test; +import java.util.Collection; import java.util.Collections; import java.util.Map; @@ -34,42 +35,45 @@ class GenericSchemaManagerTest { @Test void assertGetToBeAddedTablesBySchemas() { - Map reloadSchemas = Collections.singletonMap("foo_schema", - new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("foo_table", new ShardingSphereTable("foo_table", - Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyMap())); - Map currentSchemas = Collections.singletonMap("foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyMap(), Collections.emptyMap())); + Map reloadSchemas = Collections.singletonMap("foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, + Collections.singleton(new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyList())); + Map currentSchemas = Collections.singletonMap( + "foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyList(), Collections.emptyList())); Map actual = GenericSchemaManager.getToBeAddedTablesBySchemas(reloadSchemas, currentSchemas); assertThat(actual.size(), is(1)); - assertThat(actual.get("foo_schema").getTables().size(), is(1)); - assertTrue(actual.get("foo_schema").getTables().containsKey("foo_table")); + assertThat(actual.get("foo_schema").getAllTables().size(), is(1)); + assertTrue(actual.get("foo_schema").containsTable("foo_tbl")); } @Test void assertGetToBeDroppedTablesBySchemas() { - Map currentSchemas = Collections.singletonMap("foo_schema", - new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("foo_table", new ShardingSphereTable("foo_table", - Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyMap())); - Map reloadSchemas = Collections.singletonMap("foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyMap(), Collections.emptyMap())); + Map currentSchemas = Collections.singletonMap("foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, + Collections.singleton(new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())), Collections.emptyList())); + Map reloadSchemas = Collections.singletonMap("foo_schema", + new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyList(), Collections.emptyList())); Map actual = GenericSchemaManager.getToBeDroppedTablesBySchemas(reloadSchemas, currentSchemas); assertThat(actual.size(), is(1)); - assertThat(actual.get("foo_schema").getTables().size(), is(1)); - assertTrue(actual.get("foo_schema").getTables().containsKey("foo_table")); + assertThat(actual.get("foo_schema").getAllTables().size(), is(1)); + assertTrue(actual.get("foo_schema").containsTable("foo_tbl")); } @Test void assertGetToBeAddedTables() { - Map actual = GenericSchemaManager.getToBeAddedTables(Collections.singletonMap("foo_table", - new ShardingSphereTable("", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), TableType.TABLE)), Collections.emptyMap()); + ShardingSphereSchema reloadSchema = new ShardingSphereSchema("foo_schema", + Collections.singleton(new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), TableType.TABLE)), Collections.emptyList()); + Collection actual = GenericSchemaManager.getToBeAddedTables(reloadSchema, new ShardingSphereSchema("foo_schema", Collections.emptyList(), Collections.emptyList())); assertThat(actual.size(), is(1)); - assertTrue(actual.containsKey("foo_table")); + assertThat(actual.iterator().next().getName(), is("foo_tbl")); } @Test void assertGetToBeDroppedTables() { - Map actual = GenericSchemaManager.getToBeDroppedTables(Collections.emptyMap(), Collections.singletonMap("foo_table", - new ShardingSphereTable("", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), TableType.TABLE))); + ShardingSphereSchema reloadSchema = new ShardingSphereSchema("foo_schema", Collections.emptyList(), Collections.emptyList()); + ShardingSphereSchema currentSchema = new ShardingSphereSchema("foo_schema", + Collections.singleton(new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), TableType.TABLE)), Collections.emptyList()); + Collection actual = GenericSchemaManager.getToBeDroppedTables(reloadSchema, currentSchema); assertThat(actual.size(), is(1)); - assertTrue(actual.containsKey("foo_table")); + assertThat(actual.iterator().next().getName(), is("foo_tbl")); } @Test diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchemaTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchemaTest.java index 9af047fc1800c8..84ce48d1f8e192 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchemaTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/model/ShardingSphereSchemaTest.java @@ -34,27 +34,30 @@ class ShardingSphereSchemaTest { @Test void assertGetAllTableNames() { - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", mock(ShardingSphereTable.class)), Collections.emptyMap()).getAllTableNames(), - is(new HashSet<>(Collections.singleton("tbl")))); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("tbl"); + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getAllTableNames(), is(new HashSet<>(Collections.singleton("tbl")))); } @Test void assertGetTable() { ShardingSphereTable table = mock(ShardingSphereTable.class); - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()).getTable("tbl"), is(table)); + when(table.getName()).thenReturn("tbl"); + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getTable("tbl"), is(table)); } @Test void assertGetView() { + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("tbl"); ShardingSphereView view = mock(ShardingSphereView.class); - assertThat( - new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", mock(ShardingSphereTable.class)), Collections.singletonMap("tbl_view", view)).getView("tbl_view"), - is(view)); + when(view.getName()).thenReturn("tbl_view"); + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.singleton(view)).getView("tbl_view"), is(view)); } @Test void assertPutTable() { - ShardingSphereSchema actual = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyMap(), Collections.emptyMap()); + ShardingSphereSchema actual = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.emptyList(), Collections.emptyList()); ShardingSphereTable table = mock(ShardingSphereTable.class); when(table.getName()).thenReturn("tbl"); actual.putTable(table); @@ -63,28 +66,32 @@ void assertPutTable() { @Test void assertRemoveTable() { - ShardingSphereSchema actual = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", mock(ShardingSphereTable.class)), Collections.emptyMap()); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("tbl"); + ShardingSphereSchema actual = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); actual.removeTable("tbl"); assertNull(actual.getTable("tbl")); } @Test void assertContainsTable() { - assertTrue(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", mock(ShardingSphereTable.class)), Collections.emptyMap()).containsTable("tbl")); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("tbl"); + assertTrue(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).containsTable("tbl")); } @Test void assertGetAllColumnNamesWhenContainsKey() { ShardingSphereTable table = new ShardingSphereTable("tbl", Collections.singletonList( new ShardingSphereColumn("col", 0, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList()); - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()).getAllColumnNames("tbl"), is(Collections.singletonList("col"))); + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getAllColumnNames("tbl"), is(Collections.singletonList("col"))); } @Test void assertGetAllColumnNamesWhenNotContainsKey() { ShardingSphereTable table = new ShardingSphereTable("tbl", Collections.singletonList( new ShardingSphereColumn("col", 0, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList()); - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl1", table), Collections.emptyMap()).getAllColumnNames("tbl2"), + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getAllColumnNames("tbl2"), is(Collections.emptyList())); } @@ -92,14 +99,14 @@ void assertGetAllColumnNamesWhenNotContainsKey() { void assertContainsIndex() { ShardingSphereTable table = new ShardingSphereTable( "tbl", Collections.emptyList(), Collections.singletonList(new ShardingSphereIndex("col_idx", Collections.emptyList(), false)), Collections.emptyList()); - assertTrue(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()).containsIndex("tbl", "col_idx")); + assertTrue(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).containsIndex("tbl", "col_idx")); } @Test void assertGetVisibleColumnNamesWhenContainsKey() { ShardingSphereTable table = new ShardingSphereTable("tbl", Collections.singletonList( new ShardingSphereColumn("col", 0, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList()); - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()).getVisibleColumnNames("tbl"), + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getVisibleColumnNames("tbl"), is(Collections.singletonList("col"))); } @@ -107,6 +114,6 @@ void assertGetVisibleColumnNamesWhenContainsKey() { void assertGetVisibleColumnNamesWhenNotContainsKey() { ShardingSphereTable table = new ShardingSphereTable("tbl", Collections.singletonList( new ShardingSphereColumn("col", 0, false, false, false, false, true, false)), Collections.emptyList(), Collections.emptyList()); - assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("tbl", table), Collections.emptyMap()).getVisibleColumnNames("tbl"), is(Collections.emptyList())); + assertThat(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()).getVisibleColumnNames("tbl"), is(Collections.emptyList())); } } diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/util/IndexMetaDataUtilsTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/util/IndexMetaDataUtilsTest.java index d75cdbacf0b956..ad0675381d61d2 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/util/IndexMetaDataUtilsTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/database/schema/util/IndexMetaDataUtilsTest.java @@ -92,8 +92,8 @@ void assertGetTableNames() { private ShardingSphereDatabase buildDatabase() { ShardingSphereTable table = new ShardingSphereTable( TABLE_NAME, Collections.emptyList(), Collections.singleton(new ShardingSphereIndex(INDEX_NAME, Collections.emptyList(), false)), Collections.emptyList()); - Map tables = Collections.singletonMap(TABLE_NAME, table); - Map schemas = Collections.singletonMap(DefaultDatabase.LOGIC_NAME, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap())); + Map schemas = Collections.singletonMap( + DefaultDatabase.LOGIC_NAME, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList())); return new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, mock(DatabaseType.class), mock(ResourceMetaData.class), mock(RuleMetaData.class), schemas); } } diff --git a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilderTest.java b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilderTest.java index 5057cb28ebf6cd..713b92c1be82f9 100644 --- a/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilderTest.java +++ b/infra/common/src/test/java/org/apache/shardingsphere/infra/metadata/statistics/builder/dialect/PostgreSQLShardingSphereStatisticsBuilderTest.java @@ -59,14 +59,9 @@ private Map mockDatabaseMap() { private Map mockSchemaMap() { ShardingSphereSchema schema = mock(ShardingSphereSchema.class); - Map tableMap = mockTableMap(); - when(schema.getTables()).thenReturn(tableMap); - return Collections.singletonMap("pg_catalog", schema); - } - - private Map mockTableMap() { ShardingSphereTable table = mock(ShardingSphereTable.class); when(table.getName()).thenReturn("pg_class"); - return Collections.singletonMap("pg_class", table); + when(schema.getAllTables()).thenReturn(Collections.singleton(table)); + return Collections.singletonMap("pg_catalog", schema); } } diff --git a/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutor.java b/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutor.java index cf7d81b121b6e7..e44cd6c5151690 100644 --- a/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutor.java +++ b/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutor.java @@ -67,7 +67,7 @@ private LocalDataQueryResultRow getRow(final ShardingSphereTable table, final Sh } private Collection getTables(final String schemaName, final ShowLogicalTablesStatement sqlStatement) { - Collection tables = database.getSchema(schemaName).getTables().values(); + Collection tables = database.getSchema(schemaName).getAllTables(); Collection filteredTables = filterByLike(tables, sqlStatement); return filteredTables.stream().sorted(Comparator.comparing(ShardingSphereTable::getName)).collect(Collectors.toList()); } diff --git a/infra/distsql-handler/src/test/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutorTest.java b/infra/distsql-handler/src/test/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutorTest.java index fa95d1ec71a3e3..39e49a4d2e428a 100644 --- a/infra/distsql-handler/src/test/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutorTest.java +++ b/infra/distsql-handler/src/test/java/org/apache/shardingsphere/distsql/handler/executor/rql/resource/ShowLogicalTablesExecutorTest.java @@ -17,7 +17,6 @@ package org.apache.shardingsphere.distsql.handler.executor.rql.resource; -import org.apache.groovy.util.Maps; import org.apache.shardingsphere.distsql.statement.rql.resource.ShowLogicalTablesStatement; import org.apache.shardingsphere.infra.database.core.metadata.database.enums.TableType; import org.apache.shardingsphere.infra.database.core.type.DatabaseType; @@ -35,9 +34,9 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import java.util.Arrays; import java.util.Collection; import java.util.Iterator; -import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -59,8 +58,8 @@ void setUp() { when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); ShardingSphereSchema schema = mock(ShardingSphereSchema.class); when(database.getSchema("foo_db")).thenReturn(schema); - Map tables = Maps.of("t_order", mockShardingSphereTable("t_order"), "t_order_item", mockShardingSphereTable("t_order_item")); - when(schema.getTables()).thenReturn(tables); + Collection tables = Arrays.asList(mockShardingSphereTable("t_order"), mockShardingSphereTable("t_order_item")); + when(schema.getAllTables()).thenReturn(tables); executor.setDatabase(database); } diff --git a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/context/ExecutionContextBuilderTest.java b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/context/ExecutionContextBuilderTest.java index ca4ff31c6039e4..043f84bfb3c34a 100644 --- a/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/context/ExecutionContextBuilderTest.java +++ b/infra/executor/src/test/java/org/apache/shardingsphere/infra/executor/sql/context/ExecutionContextBuilderTest.java @@ -40,6 +40,8 @@ import java.util.Collections; import java.util.HashMap; import java.util.LinkedHashSet; +import java.util.LinkedList; +import java.util.List; import java.util.Map; import static org.hamcrest.CoreMatchers.is; @@ -125,27 +127,27 @@ void assertBuildRouteSQLRewriteResultWithEmptyPrimaryKeyMeta() { } private Map buildDatabaseWithoutPrimaryKey() { - Map tables = new HashMap<>(3, 1F); - tables.put("logicName1", new ShardingSphereTable("logicName1", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), + List tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("logicName1", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.INTEGER, false, false, false, true, false, false)), Collections.emptySet(), Collections.emptyList())); - tables.put("t_other", new ShardingSphereTable("t_other", Collections.singletonList( + tables.add(new ShardingSphereTable("t_other", Collections.singletonList( new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptySet(), Collections.emptyList())); - return Collections.singletonMap("name", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap())); + return Collections.singletonMap("name", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } private Map buildDatabase() { - Map tables = new HashMap<>(3, 1F); - tables.put("logicName1", new ShardingSphereTable("logicName1", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("logicName1", Arrays.asList(new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.INTEGER, false, false, false, true, false, false)), Collections.emptySet(), Collections.emptyList())); - tables.put("logicName2", new ShardingSphereTable("logicName2", Arrays.asList(new ShardingSphereColumn("item_id", Types.INTEGER, true, false, false, true, false, false), + tables.add(new ShardingSphereTable("logicName2", Arrays.asList(new ShardingSphereColumn("item_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("order_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("c_date", Types.TIMESTAMP, false, false, false, true, false, false)), Collections.emptySet(), Collections.emptyList())); - tables.put("t_other", new ShardingSphereTable("t_other", Collections.singletonList( + tables.add(new ShardingSphereTable("t_other", Collections.singletonList( new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false)), Collections.emptySet(), Collections.emptyList())); - return Collections.singletonMap("name", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap())); + return Collections.singletonMap("name", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } } diff --git a/kernel/data-pipeline/scenario/cdc/core/src/test/java/org/apache/shardingsphere/data/pipeline/cdc/util/CDCSchemaTableUtilsTest.java b/kernel/data-pipeline/scenario/cdc/core/src/test/java/org/apache/shardingsphere/data/pipeline/cdc/util/CDCSchemaTableUtilsTest.java index 02174b6ae9dd6f..f93435dd978ffc 100644 --- a/kernel/data-pipeline/scenario/cdc/core/src/test/java/org/apache/shardingsphere/data/pipeline/cdc/util/CDCSchemaTableUtilsTest.java +++ b/kernel/data-pipeline/scenario/cdc/core/src/test/java/org/apache/shardingsphere/data/pipeline/cdc/util/CDCSchemaTableUtilsTest.java @@ -38,6 +38,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; class CDCSchemaTableUtilsTest { @@ -65,17 +66,19 @@ void assertParseTableExpression() { } private ShardingSphereSchema mockedPublicSchema() { - Map tables = new HashMap<>(2, 1F); - tables.put("t_order", mock(ShardingSphereTable.class)); - tables.put("t_order2", mock(ShardingSphereTable.class)); - return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); + ShardingSphereTable table1 = mock(ShardingSphereTable.class); + when(table1.getName()).thenReturn("t_order"); + ShardingSphereTable table2 = mock(ShardingSphereTable.class); + when(table2.getName()).thenReturn("t_order2"); + return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Arrays.asList(table1, table2), Collections.emptyList()); } private ShardingSphereSchema mockedTestSchema() { - Map tables = new HashMap<>(2, 1F); - tables.put("t_order_item", mock(ShardingSphereTable.class)); - tables.put("t_order_item2", mock(ShardingSphereTable.class)); - return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); + ShardingSphereTable table1 = mock(ShardingSphereTable.class); + when(table1.getName()).thenReturn("t_order_item"); + ShardingSphereTable table2 = mock(ShardingSphereTable.class); + when(table2.getName()).thenReturn("t_order_item2"); + return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Arrays.asList(table1, table2), Collections.emptyList()); } @Test diff --git a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistService.java b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistService.java index b0e6668498c04b..602af68f127ef6 100644 --- a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistService.java +++ b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistService.java @@ -152,7 +152,7 @@ public void persistReloadDatabaseByAlter(final String databaseName, final Shardi Map toBeDeletedSchemas = GenericSchemaManager.getToBeDroppedTablesBySchemas(reloadDatabase.getSchemas(), currentDatabase.getSchemas()); Map toBeAddedSchemas = GenericSchemaManager.getToBeAddedTablesBySchemas(reloadDatabase.getSchemas(), currentDatabase.getSchemas()); toBeAddedSchemas.forEach((key, value) -> databaseMetaDataFacade.getSchema().alterByRuleAltered(databaseName, value)); - toBeDeletedSchemas.forEach((key, value) -> databaseMetaDataFacade.getTable().drop(databaseName, key, value.getTables())); + toBeDeletedSchemas.forEach((key, value) -> databaseMetaDataFacade.getTable().drop(databaseName, key, value.getAllTables())); } /** @@ -166,6 +166,6 @@ public void persistReloadDatabaseByDrop(final String databaseName, final Shardin Map toBeAlterSchemas = GenericSchemaManager.getToBeDroppedTablesBySchemas(reloadDatabase.getSchemas(), currentDatabase.getSchemas()); Map toBeAddedSchemas = GenericSchemaManager.getToBeAddedTablesBySchemas(reloadDatabase.getSchemas(), currentDatabase.getSchemas()); toBeAddedSchemas.forEach((key, value) -> databaseMetaDataFacade.getSchema().alterByRuleDropped(databaseName, key, value)); - toBeAlterSchemas.forEach((key, value) -> databaseMetaDataFacade.getTable().drop(databaseName, key, value.getTables())); + toBeAlterSchemas.forEach((key, value) -> databaseMetaDataFacade.getTable().drop(databaseName, key, value.getAllTables())); } } diff --git a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistService.java b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistService.java index 8e7eaab2ca3d91..ce0cc30628be38 100644 --- a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistService.java +++ b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistService.java @@ -19,7 +19,6 @@ import org.apache.shardingsphere.infra.metadata.database.schema.manager.GenericSchemaManager; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; -import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable; import org.apache.shardingsphere.metadata.persist.node.DatabaseMetaDataNode; import org.apache.shardingsphere.metadata.persist.service.metadata.table.TableMetaDataPersistService; import org.apache.shardingsphere.metadata.persist.service.metadata.table.ViewMetaDataPersistService; @@ -27,6 +26,7 @@ import org.apache.shardingsphere.mode.spi.PersistRepository; import java.util.Collection; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.Map; import java.util.stream.Collectors; @@ -76,12 +76,12 @@ public void drop(final String databaseName, final String schemaName) { */ public void alterByRefresh(final String databaseName, final ShardingSphereSchema schema) { String schemaName = schema.getName().toLowerCase(); - if (schema.getTables().isEmpty() && schema.getViews().isEmpty()) { + if (schema.isEmpty()) { add(databaseName, schemaName); } - Map currentTables = tableMetaDataPersistService.load(databaseName, schemaName); - tableMetaDataPersistService.persist(databaseName, schemaName, GenericSchemaManager.getToBeAddedTables(schema.getTables(), currentTables)); - GenericSchemaManager.getToBeDroppedTables(schema.getTables(), currentTables).forEach((key, value) -> tableMetaDataPersistService.drop(databaseName, schemaName, key)); + ShardingSphereSchema currentSchema = new ShardingSphereSchema(schemaName, tableMetaDataPersistService.load(databaseName, schemaName), Collections.emptyList()); + tableMetaDataPersistService.persist(databaseName, schemaName, GenericSchemaManager.getToBeAddedTables(schema, currentSchema)); + GenericSchemaManager.getToBeDroppedTables(schema, currentSchema).forEach(each -> tableMetaDataPersistService.drop(databaseName, schemaName, each.getName())); } /** @@ -92,10 +92,10 @@ public void alterByRefresh(final String databaseName, final ShardingSphereSchema */ public void alterByRuleAltered(final String databaseName, final ShardingSphereSchema schema) { String schemaName = schema.getName().toLowerCase(); - if (schema.getTables().isEmpty() && schema.getViews().isEmpty()) { + if (schema.isEmpty()) { add(databaseName, schemaName); } - tableMetaDataPersistService.persist(databaseName, schemaName, schema.getTables()); + tableMetaDataPersistService.persist(databaseName, schemaName, schema.getAllTables()); } /** @@ -106,7 +106,7 @@ public void alterByRuleAltered(final String databaseName, final ShardingSphereSc * @param schema to be altered schema */ public void alterByRuleDropped(final String databaseName, final String schemaName, final ShardingSphereSchema schema) { - tableMetaDataPersistService.persist(databaseName, schemaName, schema.getTables()); + tableMetaDataPersistService.persist(databaseName, schemaName, schema.getAllTables()); } /** diff --git a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistService.java b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistService.java index 397d9a802d783f..0bb9c6fcbf6c07 100644 --- a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistService.java +++ b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistService.java @@ -29,11 +29,8 @@ import org.apache.shardingsphere.mode.spi.PersistRepository; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.stream.Collectors; /** @@ -53,9 +50,8 @@ public final class TableMetaDataPersistService { * @param schemaName to be loaded schema name * @return loaded tables */ - public Map load(final String databaseName, final String schemaName) { - List tableNames = repository.getChildrenKeys(TableMetaDataNode.getMetaDataTablesNode(databaseName, schemaName)); - return tableNames.stream().collect(Collectors.toMap(String::toLowerCase, each -> load(databaseName, schemaName, each), (a, b) -> b, () -> new LinkedHashMap<>(tableNames.size(), 1F))); + public Collection load(final String databaseName, final String schemaName) { + return repository.getChildrenKeys(TableMetaDataNode.getMetaDataTablesNode(databaseName, schemaName)).stream().map(each -> load(databaseName, schemaName, each)).collect(Collectors.toList()); } /** @@ -79,16 +75,14 @@ public ShardingSphereTable load(final String databaseName, final String schemaNa * @param schemaName to be persisted schema name * @param tables to be persisted tables */ - public void persist(final String databaseName, final String schemaName, final Map tables) { + public void persist(final String databaseName, final String schemaName, final Collection tables) { Collection metaDataVersions = new LinkedList<>(); - for (Entry entry : tables.entrySet()) { - String tableName = entry.getKey().toLowerCase(); + for (ShardingSphereTable each : tables) { + String tableName = each.getName().toLowerCase(); List versions = metaDataVersionPersistService.getVersions(TableMetaDataNode.getTableVersionsNode(databaseName, schemaName, tableName)); String nextActiveVersion = versions.isEmpty() ? MetaDataVersion.DEFAULT_VERSION : String.valueOf(Integer.parseInt(versions.get(0)) + 1); - if (null != entry.getValue()) { - repository.persist(TableMetaDataNode.getTableVersionNode(databaseName, schemaName, tableName, nextActiveVersion), - YamlEngine.marshal(new YamlTableSwapper().swapToYamlConfiguration(entry.getValue()))); - } + repository.persist( + TableMetaDataNode.getTableVersionNode(databaseName, schemaName, tableName, nextActiveVersion), YamlEngine.marshal(new YamlTableSwapper().swapToYamlConfiguration(each))); if (Strings.isNullOrEmpty(getActiveVersion(databaseName, schemaName, tableName))) { repository.persist(TableMetaDataNode.getTableActiveVersionNode(databaseName, schemaName, tableName), MetaDataVersion.DEFAULT_VERSION); } @@ -119,7 +113,7 @@ public void drop(final String databaseName, final String schemaName, final Strin * @param schemaName to be dropped schema name * @param tables to be dropped tables */ - public void drop(final String databaseName, final String schemaName, final Map tables) { - tables.forEach((key, value) -> drop(databaseName, schemaName, key)); + public void drop(final String databaseName, final String schemaName, final Collection tables) { + tables.forEach(each -> drop(databaseName, schemaName, each.getName())); } } diff --git a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistService.java b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistService.java index 68092d1b16a6ef..07f5c2cc937580 100644 --- a/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistService.java +++ b/kernel/metadata/core/src/main/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistService.java @@ -29,11 +29,8 @@ import org.apache.shardingsphere.mode.spi.PersistRepository; import java.util.Collection; -import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; -import java.util.Map; -import java.util.Map.Entry; import java.util.stream.Collectors; /** @@ -53,9 +50,8 @@ public final class ViewMetaDataPersistService { * @param schemaName schema name * @return loaded views */ - public Map load(final String databaseName, final String schemaName) { - List viewNames = repository.getChildrenKeys(ViewMetaDataNode.getMetaDataViewsNode(databaseName, schemaName)); - return viewNames.stream().collect(Collectors.toMap(String::toLowerCase, each -> load(databaseName, schemaName, each), (a, b) -> b, () -> new LinkedHashMap<>(viewNames.size(), 1F))); + public Collection load(final String databaseName, final String schemaName) { + return repository.getChildrenKeys(ViewMetaDataNode.getMetaDataViewsNode(databaseName, schemaName)).stream().map(each -> load(databaseName, schemaName, each)).collect(Collectors.toList()); } /** @@ -79,14 +75,14 @@ public ShardingSphereView load(final String databaseName, final String schemaNam * @param schemaName schema name * @param views views */ - public void persist(final String databaseName, final String schemaName, final Map views) { + public void persist(final String databaseName, final String schemaName, final Collection views) { Collection metaDataVersions = new LinkedList<>(); - for (Entry entry : views.entrySet()) { - String viewName = entry.getKey().toLowerCase(); + for (ShardingSphereView each : views) { + String viewName = each.getName().toLowerCase(); List versions = metaDataVersionPersistService.getVersions(ViewMetaDataNode.getViewVersionsNode(databaseName, schemaName, viewName)); String nextActiveVersion = versions.isEmpty() ? MetaDataVersion.DEFAULT_VERSION : String.valueOf(Integer.parseInt(versions.get(0)) + 1); repository.persist(ViewMetaDataNode.getViewVersionNode(databaseName, schemaName, viewName, nextActiveVersion), - YamlEngine.marshal(new YamlViewSwapper().swapToYamlConfiguration(entry.getValue()))); + YamlEngine.marshal(new YamlViewSwapper().swapToYamlConfiguration(each))); if (Strings.isNullOrEmpty(getActiveVersion(databaseName, schemaName, viewName))) { repository.persist(ViewMetaDataNode.getViewActiveVersionNode(databaseName, schemaName, viewName), MetaDataVersion.DEFAULT_VERSION); } diff --git a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistServiceTest.java b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistServiceTest.java index 72d6ab3c9636cb..a67484567a5e5c 100644 --- a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistServiceTest.java +++ b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/MetaDataPersistServiceTest.java @@ -151,7 +151,7 @@ void assertPersistReloadDatabaseByAlter() { when(GenericSchemaManager.getToBeAddedTablesBySchemas(any(), any())).thenReturn(Collections.singletonMap("to_be_added", toBeAddedSchema)); metaDataPersistService.persistReloadDatabaseByAlter("foo_db", mock(ShardingSphereDatabase.class), mock(ShardingSphereDatabase.class)); verify(databaseMetaDataFacade.getSchema()).alterByRuleAltered("foo_db", toBeAddedSchema); - verify(databaseMetaDataFacade.getTable()).drop("foo_db", "to_be_deleted", Collections.emptyMap()); + verify(databaseMetaDataFacade.getTable()).drop("foo_db", "to_be_deleted", Collections.emptyList()); } @Test @@ -162,6 +162,6 @@ void assertPersistReloadDatabaseByDrop() { when(GenericSchemaManager.getToBeAddedTablesBySchemas(any(), any())).thenReturn(Collections.singletonMap("to_be_altered", toBeAlterSchema)); metaDataPersistService.persistReloadDatabaseByDrop("foo_db", mock(ShardingSphereDatabase.class), mock(ShardingSphereDatabase.class)); verify(databaseMetaDataFacade.getSchema()).alterByRuleDropped("foo_db", "to_be_altered", toBeAlterSchema); - verify(databaseMetaDataFacade.getTable()).drop("foo_db", "to_be_deleted", Collections.emptyMap()); + verify(databaseMetaDataFacade.getTable()).drop("foo_db", "to_be_deleted", Collections.emptyList()); } } diff --git a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistServiceTest.java b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistServiceTest.java index fd3fea4faf08f5..abea1cc14cc7fb 100644 --- a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistServiceTest.java +++ b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/schema/SchemaMetaDataPersistServiceTest.java @@ -36,6 +36,8 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; +import static org.mockito.ArgumentMatchers.anyCollection; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; @@ -78,31 +80,36 @@ void assertDrop() { void assertAlterByRefreshWithoutTablesAndViews() { persistService.alterByRefresh("foo_db", new ShardingSphereSchema("foo_schema")); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyList()); } @Test void assertAlterByRefreshWithTables() { - Map tables = Collections.singletonMap("foo_tbl", mock(ShardingSphereTable.class)); - persistService.alterByRefresh("foo_db", new ShardingSphereSchema("foo_schema", tables, Collections.emptyMap())); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + persistService.alterByRefresh("foo_db", new ShardingSphereSchema("foo_schema", Collections.singleton(table), Collections.emptyList())); verify(repository, times(0)).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", tables); + verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.singletonList(table)); } @Test void assertAlterByRefreshWithViews() { - persistService.alterByRefresh("foo_db", new ShardingSphereSchema("foo_schema", Collections.emptyMap(), Collections.singletonMap("foo_view", mock(ShardingSphereView.class)))); + ShardingSphereView view = mock(ShardingSphereView.class); + when(view.getName()).thenReturn("foo_view"); + persistService.alterByRefresh("foo_db", new ShardingSphereSchema("foo_schema", Collections.emptyList(), Collections.singleton(view))); verify(repository, times(0)).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyList()); } @Test void assertLoad() { when(repository.getChildrenKeys("/metadata/foo_db/schemas")).thenReturn(Collections.singletonList("foo_schema")); ShardingSphereTable table = mock(ShardingSphereTable.class); - when(tableMetaDataPersistService.load("foo_db", "foo_schema")).thenReturn(Collections.singletonMap("foo_tbl", table)); + when(table.getName()).thenReturn("foo_tbl"); + when(tableMetaDataPersistService.load("foo_db", "foo_schema")).thenReturn(Collections.singleton(table)); ShardingSphereView view = mock(ShardingSphereView.class); - when(viewMetaDataPersistService.load("foo_db", "foo_schema")).thenReturn(Collections.singletonMap("foo_view", view)); + when(view.getName()).thenReturn("foo_view"); + when(viewMetaDataPersistService.load("foo_db", "foo_schema")).thenReturn(Collections.singleton(view)); Map actual = persistService.load("foo_db"); assertThat(actual.size(), is(1)); assertThat(actual.get("foo_schema").getTable("foo_tbl"), is(table)); @@ -113,27 +120,30 @@ void assertLoad() { void assertAlterSchemaByAlterConfigurationByRefresh() { persistService.alterByRuleAltered("foo_db", new ShardingSphereSchema("foo_schema")); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(tableMetaDataPersistService).persist(eq("foo_db"), eq("foo_schema"), anyCollection()); } @Test void assertAlterSchemaByAlterConfigurationWithNotEmptyTablesByRefresh() { - Map tables = Collections.singletonMap("foo_tbl", mock(ShardingSphereTable.class)); - persistService.alterByRuleAltered("foo_db", new ShardingSphereSchema("foo_schema", tables, Collections.emptyMap())); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + persistService.alterByRuleAltered("foo_db", new ShardingSphereSchema("foo_schema", Collections.singletonList(table), Collections.emptyList())); verify(repository, times(0)).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", tables); + verify(tableMetaDataPersistService).persist(eq("foo_db"), eq("foo_schema"), anyCollection()); } @Test void assertAlterSchemaByAlterConfigurationWithNotEmptyViewsByRefresh() { - persistService.alterByRuleAltered("foo_db", new ShardingSphereSchema("foo_schema", Collections.emptyMap(), Collections.singletonMap("foo_view", mock(ShardingSphereView.class)))); + ShardingSphereView view = mock(ShardingSphereView.class); + when(view.getName()).thenReturn("foo_view"); + persistService.alterByRuleAltered("foo_db", new ShardingSphereSchema("foo_schema", Collections.emptyList(), Collections.singleton(view))); verify(repository, times(0)).persist("/metadata/foo_db/schemas/foo_schema/tables", ""); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(tableMetaDataPersistService).persist(eq("foo_db"), eq("foo_schema"), anyCollection()); } @Test void assertAlterByRefreshByDropConfiguration() { persistService.alterByRuleDropped("foo_db", "foo_schema", mock(ShardingSphereSchema.class)); - verify(tableMetaDataPersistService).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(tableMetaDataPersistService).persist(eq("foo_db"), eq("foo_schema"), anyCollection()); } } diff --git a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistServiceTest.java b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistServiceTest.java index fc7d6d95806d3a..1113287ff88e2e 100644 --- a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistServiceTest.java +++ b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/TableMetaDataPersistServiceTest.java @@ -26,8 +26,8 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.Collection; import java.util.Collections; -import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -54,16 +54,18 @@ void assertLoad() { when(repository.getChildrenKeys("/metadata/foo_db/schemas/foo_schema/tables")).thenReturn(Collections.singletonList("foo_tbl")); when(repository.query("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/active_version")).thenReturn("0"); when(repository.query("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions/0")).thenReturn("{name: foo_tbl}"); - Map actual = persistService.load("foo_db", "foo_schema"); + Collection actual = persistService.load("foo_db", "foo_schema"); assertThat(actual.size(), is(1)); - assertThat(actual.get("foo_tbl").getName(), is("foo_tbl")); + assertThat(actual.iterator().next().getName(), is("foo_tbl")); } @Test void assertPersistWithoutVersion() { when(repository.query("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/active_version")).thenReturn("", "0"); - persistService.persist("foo_db", "foo_schema", Collections.singletonMap("foo_tbl", mock(ShardingSphereTable.class))); - verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions/0", "{}" + System.lineSeparator()); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + persistService.persist("foo_db", "foo_schema", Collections.singleton(table)); + verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions/0", "name: foo_tbl" + System.lineSeparator()); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/active_version", "0"); } @@ -71,8 +73,10 @@ void assertPersistWithoutVersion() { void assertPersistWithVersion() { when(repository.getChildrenKeys("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions")).thenReturn(Collections.singletonList("10")); when(repository.query("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/active_version")).thenReturn("10"); - persistService.persist("foo_db", "foo_schema", Collections.singletonMap("foo_tbl", mock(ShardingSphereTable.class))); - verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions/11", "{}" + System.lineSeparator()); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + persistService.persist("foo_db", "foo_schema", Collections.singleton(table)); + verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/versions/11", "name: foo_tbl" + System.lineSeparator()); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl/active_version", "11"); } @@ -84,7 +88,9 @@ void assertDropTable() { @Test void assertDropTables() { - persistService.drop("foo_db", "foo_schema", Collections.singletonMap("foo_tbl", mock(ShardingSphereTable.class))); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + persistService.drop("foo_db", "foo_schema", Collections.singleton(table)); verify(repository).delete("/metadata/foo_db/schemas/foo_schema/tables/foo_tbl"); } } diff --git a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistServiceTest.java b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistServiceTest.java index 2d597508fac383..6a1747d20e539e 100644 --- a/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistServiceTest.java +++ b/kernel/metadata/core/src/test/java/org/apache/shardingsphere/metadata/persist/service/metadata/table/ViewMetaDataPersistServiceTest.java @@ -26,8 +26,8 @@ import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import java.util.Collection; import java.util.Collections; -import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -54,16 +54,18 @@ void assertLoad() { when(repository.getChildrenKeys("/metadata/foo_db/schemas/foo_schema/views")).thenReturn(Collections.singletonList("foo_view")); when(repository.query("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version")).thenReturn("0"); when(repository.query("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/0")).thenReturn("{name: foo_view}"); - Map actual = persistService.load("foo_db", "foo_schema"); + Collection actual = persistService.load("foo_db", "foo_schema"); assertThat(actual.size(), is(1)); - assertThat(actual.get("foo_view").getName(), is("foo_view")); + assertThat(actual.iterator().next().getName(), is("foo_view")); } @Test void assertPersistWithoutVersion() { when(repository.query("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version")).thenReturn("", "0"); - persistService.persist("foo_db", "foo_schema", Collections.singletonMap("foo_view", mock(ShardingSphereView.class))); - verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/0", "{}" + System.lineSeparator()); + ShardingSphereView view = mock(ShardingSphereView.class); + when(view.getName()).thenReturn("foo_view"); + persistService.persist("foo_db", "foo_schema", Collections.singleton(view)); + verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/0", "name: foo_view" + System.lineSeparator()); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version", "0"); } @@ -71,8 +73,10 @@ void assertPersistWithoutVersion() { void assertPersistWithVersion() { when(repository.getChildrenKeys("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions")).thenReturn(Collections.singletonList("10")); when(repository.query("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version")).thenReturn("10"); - persistService.persist("foo_db", "foo_schema", Collections.singletonMap("foo_view", mock(ShardingSphereView.class))); - verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/11", "{}" + System.lineSeparator()); + ShardingSphereView view = mock(ShardingSphereView.class); + when(view.getName()).thenReturn("foo_view"); + persistService.persist("foo_db", "foo_schema", Collections.singleton(view)); + verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/versions/11", "name: foo_view" + System.lineSeparator()); verify(repository).persist("/metadata/foo_db/schemas/foo_schema/views/foo_view/active_version", "11"); } diff --git a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/constant/SingleOrder.java b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/constant/SingleOrder.java index b11706fa32c3f9..69d9cbd4a477d6 100644 --- a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/constant/SingleOrder.java +++ b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/constant/SingleOrder.java @@ -29,5 +29,5 @@ public final class SingleOrder { /** * Single order. */ - public static final int ORDER = 10; + public static final int ORDER = 5; } diff --git a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/SingleSQLRouter.java b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/SingleSQLRouter.java index e7fd34700a083e..24523813990457 100644 --- a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/SingleSQLRouter.java +++ b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/SingleSQLRouter.java @@ -17,6 +17,7 @@ package org.apache.shardingsphere.single.route; +import com.cedarsoftware.util.CaseInsensitiveSet; import org.apache.shardingsphere.infra.annotation.HighFrequencyInvocation; import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext; import org.apache.shardingsphere.infra.binder.context.type.TableAvailable; @@ -30,11 +31,11 @@ import org.apache.shardingsphere.infra.route.type.DecorateSQLRouter; import org.apache.shardingsphere.infra.route.type.EntranceSQLRouter; import org.apache.shardingsphere.infra.route.type.TableSQLRouter; +import org.apache.shardingsphere.infra.rule.attribute.table.TableMapperRuleAttribute; import org.apache.shardingsphere.infra.session.query.QueryContext; import org.apache.shardingsphere.single.constant.SingleOrder; -import org.apache.shardingsphere.single.route.engine.SingleRouteEngineFactory; +import org.apache.shardingsphere.single.route.engine.SingleRouteEngine; import org.apache.shardingsphere.single.rule.SingleRule; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTableStatement; import java.util.Collection; import java.util.Collections; @@ -52,19 +53,24 @@ public RouteContext createRouteContext(final QueryContext queryContext, final Ru if (1 == database.getResourceMetaData().getStorageUnits().size()) { return createSingleDataSourceRouteContext(rule, database, queryContext); } - RouteContext result = new RouteContext(); - Collection singleTables = getSingleTables(database, rule, result, queryContext.getSqlStatementContext()); - SingleRouteEngineFactory.newInstance(singleTables, queryContext.getSqlStatementContext().getSqlStatement(), queryContext.getHintValueContext()) - .ifPresent(optional -> optional.route(result, rule)); - return result; + SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); + RouteContext routeContext = new RouteContext(); + Collection singleTables = getSingleTables(database, rule, sqlStatementContext); + if (singleTables.isEmpty()) { + return routeContext; + } + return new SingleRouteEngine(singleTables, sqlStatementContext.getSqlStatement(), queryContext.getHintValueContext()).route(routeContext, rule); } @Override public void decorateRouteContext(final RouteContext routeContext, final QueryContext queryContext, final ShardingSphereDatabase database, final SingleRule rule, final Collection tableNames, final ConfigurationProperties props) { - Collection singleTables = getSingleTables(database, rule, routeContext, queryContext.getSqlStatementContext()); - SingleRouteEngineFactory.newInstance(singleTables, queryContext.getSqlStatementContext().getSqlStatement(), queryContext.getHintValueContext()) - .ifPresent(optional -> optional.route(routeContext, rule)); + SQLStatementContext sqlStatementContext = queryContext.getSqlStatementContext(); + Collection singleTables = getSingleTables(database, rule, sqlStatementContext); + if (singleTables.isEmpty()) { + return; + } + new SingleRouteEngine(singleTables, sqlStatementContext.getSqlStatement(), queryContext.getHintValueContext()).route(routeContext, rule); } private RouteContext createSingleDataSourceRouteContext(final SingleRule rule, final ShardingSphereDatabase database, final QueryContext queryContext) { @@ -86,9 +92,24 @@ private Collection createTableMappers(final Collection tabl return result; } - private Collection getSingleTables(final ShardingSphereDatabase database, final SingleRule rule, final RouteContext routeContext, final SQLStatementContext sqlStatementContext) { + private Collection getSingleTables(final ShardingSphereDatabase database, final SingleRule rule, final SQLStatementContext sqlStatementContext) { Collection qualifiedTables = rule.getQualifiedTables(sqlStatementContext, database); - return routeContext.getRouteUnits().isEmpty() && sqlStatementContext.getSqlStatement() instanceof CreateTableStatement ? qualifiedTables : rule.getSingleTables(qualifiedTables); + Collection distributedTableNames = getDistributedTableNames(database); + Collection result = new LinkedList<>(); + for (QualifiedTable each : qualifiedTables) { + if (!distributedTableNames.contains(each.getTableName())) { + result.add(each); + } + } + return result; + } + + private Collection getDistributedTableNames(final ShardingSphereDatabase database) { + Collection result = new CaseInsensitiveSet<>(); + for (TableMapperRuleAttribute each : database.getRuleMetaData().getAttributes(TableMapperRuleAttribute.class)) { + result.addAll(each.getDistributedTableNames()); + } + return result; } @Override diff --git a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngine.java b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngine.java index 64de553484a1ea..4223fbc364a107 100644 --- a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngine.java +++ b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngine.java @@ -17,19 +17,126 @@ package org.apache.shardingsphere.single.route.engine; +import lombok.RequiredArgsConstructor; +import org.apache.shardingsphere.infra.datanode.DataNode; +import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; +import org.apache.shardingsphere.infra.exception.dialect.exception.syntax.table.TableExistsException; +import org.apache.shardingsphere.infra.exception.generic.UnsupportedSQLOperationException; +import org.apache.shardingsphere.infra.hint.HintValueContext; +import org.apache.shardingsphere.infra.metadata.database.schema.QualifiedTable; import org.apache.shardingsphere.infra.route.context.RouteContext; +import org.apache.shardingsphere.infra.route.context.RouteMapper; +import org.apache.shardingsphere.infra.route.context.RouteUnit; +import org.apache.shardingsphere.infra.rule.attribute.datanode.MutableDataNodeRuleAttribute; +import org.apache.shardingsphere.single.exception.SingleTableNotFoundException; import org.apache.shardingsphere.single.rule.SingleRule; +import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; +import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTableStatement; +import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DDLStatement; +import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement; + +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedList; +import java.util.Map; +import java.util.Map.Entry; +import java.util.Optional; +import java.util.function.Function; +import java.util.stream.Collectors; /** * Single route engine. */ -public interface SingleRouteEngine { +@RequiredArgsConstructor +public final class SingleRouteEngine { + + private final Collection singleTables; + + private final SQLStatement sqlStatement; + + private final HintValueContext hintValueContext; /** * Route. * * @param routeContext route context * @param singleRule single rule + * @return route context */ - void route(RouteContext routeContext, SingleRule singleRule); + public RouteContext route(final RouteContext routeContext, final SingleRule singleRule) { + if (routeContext.getRouteUnits().isEmpty() || sqlStatement instanceof SelectStatement) { + routeStatement(routeContext, singleRule); + } else { + RouteContext newRouteContext = new RouteContext(); + routeStatement(newRouteContext, singleRule); + combineRouteContext(routeContext, newRouteContext); + } + return routeContext; + } + + private void routeStatement(final RouteContext routeContext, final SingleRule rule) { + if (sqlStatement instanceof DDLStatement) { + routeDDLStatement(routeContext, rule); + } else { + boolean allTablesInSameComputeNode = rule.isAllTablesInSameComputeNode(getDataNodes(routeContext), singleTables); + ShardingSpherePreconditions.checkState(allTablesInSameComputeNode, () -> new UnsupportedSQLOperationException("all tables must be in the same compute node")); + fillRouteContext(rule, routeContext, singleTables); + } + } + + private Collection getDataNodes(final RouteContext routeContext) { + Collection result = new LinkedList<>(); + for (Collection each : routeContext.getOriginalDataNodes()) { + result.addAll(each); + } + return result; + } + + private void routeDDLStatement(final RouteContext routeContext, final SingleRule rule) { + if (sqlStatement instanceof CreateTableStatement) { + QualifiedTable table = singleTables.iterator().next(); + Optional dataNode = rule.getAttributes().getAttribute(MutableDataNodeRuleAttribute.class).findTableDataNode(table.getSchemaName(), table.getTableName()); + boolean containsIfNotExists = ((CreateTableStatement) sqlStatement).isIfNotExists(); + if (dataNode.isPresent()) { + routeDDLStatementWithExistTable(routeContext, containsIfNotExists, dataNode.get(), table); + } else { + String dataSourceName = rule.assignNewDataSourceName(); + routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper(dataSourceName, dataSourceName), Collections.singleton(new RouteMapper(table.getTableName(), table.getTableName())))); + } + } else { + fillRouteContext(rule, routeContext, singleTables); + } + } + + private void routeDDLStatementWithExistTable(final RouteContext routeContext, final boolean containsIfNotExists, final DataNode dataNode, final QualifiedTable table) { + if (containsIfNotExists || hintValueContext.isSkipMetadataValidate()) { + String dataSourceName = dataNode.getDataSourceName(); + routeContext.getRouteUnits() + .add(new RouteUnit(new RouteMapper(dataSourceName, dataSourceName), Collections.singleton(new RouteMapper(table.getTableName(), table.getTableName())))); + } else { + throw new TableExistsException(table.getTableName()); + } + } + + private void fillRouteContext(final SingleRule singleRule, final RouteContext routeContext, final Collection logicTables) { + for (QualifiedTable each : logicTables) { + String tableName = each.getTableName(); + DataNode dataNode = singleRule.getAttributes().getAttribute(MutableDataNodeRuleAttribute.class).findTableDataNode(each.getSchemaName(), tableName) + .orElseThrow(() -> new SingleTableNotFoundException(tableName)); + String dataSource = dataNode.getDataSourceName(); + routeContext.putRouteUnit(new RouteMapper(dataSource, dataSource), Collections.singletonList(new RouteMapper(tableName, tableName))); + } + } + + private void combineRouteContext(final RouteContext routeContext, final RouteContext newRouteContext) { + Map dataSourceRouteUnits = getDataSourceRouteUnits(newRouteContext); + routeContext.getRouteUnits().removeIf(each -> !dataSourceRouteUnits.containsKey(each.getDataSourceMapper().getLogicName())); + for (Entry entry : dataSourceRouteUnits.entrySet()) { + routeContext.putRouteUnit(entry.getValue().getDataSourceMapper(), entry.getValue().getTableMappers()); + } + } + + private Map getDataSourceRouteUnits(final RouteContext newRouteContext) { + return newRouteContext.getRouteUnits().stream().collect(Collectors.toMap(each -> each.getDataSourceMapper().getLogicName(), Function.identity())); + } } diff --git a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactory.java b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactory.java deleted file mode 100644 index cb8dd5bc3b52f4..00000000000000 --- a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactory.java +++ /dev/null @@ -1,47 +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.single.route.engine; - -import lombok.AccessLevel; -import lombok.NoArgsConstructor; -import org.apache.shardingsphere.infra.hint.HintValueContext; -import org.apache.shardingsphere.infra.metadata.database.schema.QualifiedTable; -import org.apache.shardingsphere.single.route.engine.standard.SingleStandardRouteEngine; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; - -import java.util.Collection; -import java.util.Optional; - -/** - * Single route engine factory. - */ -@NoArgsConstructor(access = AccessLevel.PRIVATE) -public final class SingleRouteEngineFactory { - - /** - * Create new instance of single route engine. - * - * @param singleTables single tables - * @param sqlStatement SQL statement - * @param hintValueContext hint value context - * @return created instance - */ - public static Optional newInstance(final Collection singleTables, final SQLStatement sqlStatement, final HintValueContext hintValueContext) { - return singleTables.isEmpty() ? Optional.empty() : Optional.of(new SingleStandardRouteEngine(singleTables, sqlStatement, hintValueContext)); - } -} diff --git a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/standard/SingleStandardRouteEngine.java b/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/standard/SingleStandardRouteEngine.java deleted file mode 100644 index 02ea6cfef44b9f..00000000000000 --- a/kernel/single/core/src/main/java/org/apache/shardingsphere/single/route/engine/standard/SingleStandardRouteEngine.java +++ /dev/null @@ -1,136 +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.single.route.engine.standard; - -import lombok.RequiredArgsConstructor; -import org.apache.shardingsphere.infra.datanode.DataNode; -import org.apache.shardingsphere.infra.exception.core.ShardingSpherePreconditions; -import org.apache.shardingsphere.infra.exception.dialect.exception.syntax.table.TableExistsException; -import org.apache.shardingsphere.infra.exception.generic.UnsupportedSQLOperationException; -import org.apache.shardingsphere.infra.hint.HintValueContext; -import org.apache.shardingsphere.infra.metadata.database.schema.QualifiedTable; -import org.apache.shardingsphere.infra.route.context.RouteContext; -import org.apache.shardingsphere.infra.route.context.RouteMapper; -import org.apache.shardingsphere.infra.route.context.RouteUnit; -import org.apache.shardingsphere.infra.rule.attribute.datanode.MutableDataNodeRuleAttribute; -import org.apache.shardingsphere.single.exception.SingleTableNotFoundException; -import org.apache.shardingsphere.single.route.engine.SingleRouteEngine; -import org.apache.shardingsphere.single.rule.SingleRule; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateTableStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.DDLStatement; -import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement; - -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedList; -import java.util.Map; -import java.util.Map.Entry; -import java.util.Optional; -import java.util.function.Function; -import java.util.stream.Collectors; - -/** - * Single standard route engine. - */ -@RequiredArgsConstructor -public final class SingleStandardRouteEngine implements SingleRouteEngine { - - private final Collection singleTables; - - private final SQLStatement sqlStatement; - - private final HintValueContext hintValueContext; - - @Override - public void route(final RouteContext routeContext, final SingleRule singleRule) { - if (routeContext.getRouteUnits().isEmpty() || sqlStatement instanceof SelectStatement) { - routeStatement(routeContext, singleRule); - } else { - RouteContext newRouteContext = new RouteContext(); - routeStatement(newRouteContext, singleRule); - combineRouteContext(routeContext, newRouteContext); - } - } - - private void routeStatement(final RouteContext routeContext, final SingleRule rule) { - if (sqlStatement instanceof DDLStatement) { - routeDDLStatement(routeContext, rule); - } else { - boolean allTablesInSameComputeNode = rule.isAllTablesInSameComputeNode(getDataNodes(routeContext), singleTables); - ShardingSpherePreconditions.checkState(allTablesInSameComputeNode, () -> new UnsupportedSQLOperationException("all tables must be in the same compute node")); - fillRouteContext(rule, routeContext, singleTables); - } - } - - private Collection getDataNodes(final RouteContext routeContext) { - Collection result = new LinkedList<>(); - for (Collection each : routeContext.getOriginalDataNodes()) { - result.addAll(each); - } - return result; - } - - private void routeDDLStatement(final RouteContext routeContext, final SingleRule rule) { - if (sqlStatement instanceof CreateTableStatement) { - QualifiedTable table = singleTables.iterator().next(); - Optional dataNode = rule.getAttributes().getAttribute(MutableDataNodeRuleAttribute.class).findTableDataNode(table.getSchemaName(), table.getTableName()); - boolean containsIfNotExists = ((CreateTableStatement) sqlStatement).isIfNotExists(); - if (dataNode.isPresent()) { - routeDDLStatementWithExistTable(routeContext, containsIfNotExists, dataNode.get(), table); - } else { - String dataSourceName = rule.assignNewDataSourceName(); - routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper(dataSourceName, dataSourceName), Collections.singleton(new RouteMapper(table.getTableName(), table.getTableName())))); - } - } else { - fillRouteContext(rule, routeContext, singleTables); - } - } - - private void routeDDLStatementWithExistTable(final RouteContext routeContext, final boolean containsIfNotExists, final DataNode dataNode, final QualifiedTable table) { - if (containsIfNotExists || hintValueContext.isSkipMetadataValidate()) { - String dataSourceName = dataNode.getDataSourceName(); - routeContext.getRouteUnits() - .add(new RouteUnit(new RouteMapper(dataSourceName, dataSourceName), Collections.singleton(new RouteMapper(table.getTableName(), table.getTableName())))); - } else { - throw new TableExistsException(table.getTableName()); - } - } - - private void fillRouteContext(final SingleRule singleRule, final RouteContext routeContext, final Collection logicTables) { - for (QualifiedTable each : logicTables) { - String tableName = each.getTableName(); - DataNode dataNode = singleRule.getAttributes().getAttribute(MutableDataNodeRuleAttribute.class).findTableDataNode(each.getSchemaName(), tableName) - .orElseThrow(() -> new SingleTableNotFoundException(tableName)); - String dataSource = dataNode.getDataSourceName(); - routeContext.putRouteUnit(new RouteMapper(dataSource, dataSource), Collections.singletonList(new RouteMapper(tableName, tableName))); - } - } - - private void combineRouteContext(final RouteContext routeContext, final RouteContext newRouteContext) { - Map dataSourceRouteUnits = getDataSourceRouteUnits(newRouteContext); - routeContext.getRouteUnits().removeIf(each -> !dataSourceRouteUnits.containsKey(each.getDataSourceMapper().getLogicName())); - for (Entry entry : dataSourceRouteUnits.entrySet()) { - routeContext.putRouteUnit(entry.getValue().getDataSourceMapper(), entry.getValue().getTableMappers()); - } - } - - private Map getDataSourceRouteUnits(final RouteContext newRouteContext) { - return newRouteContext.getRouteUnits().stream().collect(Collectors.toMap(each -> each.getDataSourceMapper().getLogicName(), Function.identity())); - } -} diff --git a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/SingleSQLRouterTest.java b/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/SingleSQLRouterTest.java index fa0beb370a4e4f..41dd0a61f9093b 100644 --- a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/SingleSQLRouterTest.java +++ b/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/SingleSQLRouterTest.java @@ -58,7 +58,6 @@ import java.util.Arrays; import java.util.Collections; import java.util.HashMap; -import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.List; @@ -69,6 +68,7 @@ import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -197,7 +197,8 @@ void assertDecorateRouteContextWithReadwriteSplittingDataSource() { ShardingSphereDatabase database = new ShardingSphereDatabase(DefaultDatabase.LOGIC_NAME, mock(DatabaseType.class), mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), new RuleMetaData(Collections.singleton(rule)), Collections.emptyMap()); sqlRouter.decorateRouteContext(routeContext, createQueryContext(), database, rule, Collections.singletonList("t_order"), new ConfigurationProperties(new Properties())); - assertThat(routeContext.getActualDataSourceNames(), is(new HashSet<>(Arrays.asList("write_ds", "readwrite_ds")))); + assertThat(routeContext.getActualDataSourceNames().size(), is(1)); + assertTrue(Arrays.asList("write_ds", "readwrite_ds").contains(routeContext.getActualDataSourceNames().iterator().next())); } @Test @@ -207,11 +208,10 @@ void assertDecorateRouteContextWithMultiDataSource() throws SQLException { routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper("ds_0", "ds_0"), Collections.emptyList())); routeContext.getRouteUnits().add(new RouteUnit(new RouteMapper("ds_1", "ds_1"), Collections.emptyList())); SingleSQLRouter sqlRouter = (SingleSQLRouter) OrderedSPILoader.getServices(SQLRouter.class, Collections.singleton(rule)).get(rule); - sqlRouter.decorateRouteContext( - routeContext, createQueryContext(), mockDatabaseWithMultipleResources(), rule, Collections.singletonList("t_order"), new ConfigurationProperties(new Properties())); - Iterator routedDataSourceNames = routeContext.getActualDataSourceNames().iterator(); - assertThat(routedDataSourceNames.next(), is("ds_1")); - assertThat(routedDataSourceNames.next(), is("ds_0")); + sqlRouter.decorateRouteContext(routeContext, createQueryContext(), mockDatabaseWithMultipleResources(), rule, Collections.singletonList("t_order"), + new ConfigurationProperties(new Properties())); + assertThat(routeContext.getActualDataSourceNames().size(), is(1)); + assertTrue(Arrays.asList("ds_0", "ds_1").contains(routeContext.getActualDataSourceNames().iterator().next())); } private QueryContext createQueryContext() { diff --git a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactoryTest.java b/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactoryTest.java deleted file mode 100644 index d81bb51ccf9a3c..00000000000000 --- a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/SingleRouteEngineFactoryTest.java +++ /dev/null @@ -1,42 +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.single.route.engine; - -import org.apache.shardingsphere.infra.hint.HintValueContext; -import org.apache.shardingsphere.infra.metadata.database.schema.QualifiedTable; -import org.apache.shardingsphere.sql.parser.statement.core.statement.SQLStatement; -import org.junit.jupiter.api.Test; - -import java.util.Collections; - -import static org.junit.jupiter.api.Assertions.assertFalse; -import static org.junit.jupiter.api.Assertions.assertTrue; -import static org.mockito.Mockito.mock; - -class SingleRouteEngineFactoryTest { - - @Test - void assertNewInstanceWithNotEmptySingleTables() { - assertTrue(SingleRouteEngineFactory.newInstance(Collections.singleton(new QualifiedTable("demo_ds", "t_order")), mock(SQLStatement.class), mock(HintValueContext.class)).isPresent()); - } - - @Test - void assertNewInstanceWithEmptySingleTableNameAndOtherStatement() { - assertFalse(SingleRouteEngineFactory.newInstance(Collections.emptyList(), mock(SQLStatement.class), mock(HintValueContext.class)).isPresent()); - } -} diff --git a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleStandardRouteEngineTest.java b/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleRouteEngineTest.java similarity index 89% rename from kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleStandardRouteEngineTest.java rename to kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleRouteEngineTest.java index 4f52e8efe31a8a..14751984b2dd45 100644 --- a/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleStandardRouteEngineTest.java +++ b/kernel/single/core/src/test/java/org/apache/shardingsphere/single/route/engine/engine/SingleRouteEngineTest.java @@ -30,7 +30,7 @@ import org.apache.shardingsphere.infra.rule.attribute.RuleAttributes; import org.apache.shardingsphere.infra.rule.attribute.datanode.DataNodeRuleAttribute; import org.apache.shardingsphere.single.config.SingleRuleConfiguration; -import org.apache.shardingsphere.single.route.engine.standard.SingleStandardRouteEngine; +import org.apache.shardingsphere.single.route.engine.SingleRouteEngine; import org.apache.shardingsphere.single.rule.SingleRule; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment; import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.TableNameSegment; @@ -61,11 +61,11 @@ import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; -class SingleStandardRouteEngineTest { +class SingleRouteEngineTest { @Test void assertRouteInSameDataSource() throws SQLException { - SingleStandardRouteEngine engine = new SingleStandardRouteEngine(mockQualifiedTables(), null, mock(HintValueContext.class)); + SingleRouteEngine engine = new SingleRouteEngine(mockQualifiedTables(), null, mock(HintValueContext.class)); SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new MySQLDatabaseType(), createDataSourceMap(), Collections.emptyList()); singleRule.getAttributes().getAttribute(DataNodeRuleAttribute.class).getAllDataNodes().put("t_order", Collections.singleton(mockDataNode("t_order"))); singleRule.getAttributes().getAttribute(DataNodeRuleAttribute.class).getAllDataNodes().put("t_order_item", Collections.singleton(mockDataNode("t_order_item"))); @@ -96,7 +96,7 @@ private Collection mockQualifiedTables() { @Test void assertRouteWithoutSingleRule() throws SQLException { - SingleStandardRouteEngine engine = new SingleStandardRouteEngine(mockQualifiedTables(), new MySQLCreateTableStatement(false), mock(HintValueContext.class)); + SingleRouteEngine engine = new SingleRouteEngine(mockQualifiedTables(), new MySQLCreateTableStatement(false), mock(HintValueContext.class)); SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(), DefaultDatabase.LOGIC_NAME, new MySQLDatabaseType(), createDataSourceMap(), Collections.emptyList()); RouteContext routeContext = new RouteContext(); engine.route(routeContext, singleRule); @@ -111,7 +111,7 @@ void assertRouteWithoutSingleRule() throws SQLException { @Test void assertRouteWithDefaultSingleRule() throws SQLException { - SingleStandardRouteEngine engine = new SingleStandardRouteEngine(mockQualifiedTables(), new MySQLCreateTableStatement(false), mock(HintValueContext.class)); + SingleRouteEngine engine = new SingleRouteEngine(mockQualifiedTables(), new MySQLCreateTableStatement(false), mock(HintValueContext.class)); SingleRule singleRule = new SingleRule(new SingleRuleConfiguration(Collections.emptyList(), "ds_0"), DefaultDatabase.LOGIC_NAME, new MySQLDatabaseType(), createDataSourceMap(), Collections.emptyList()); RouteContext routeContext = new RouteContext(); @@ -137,15 +137,15 @@ private Map createDataSourceMap() throws SQLException { @Test void assertRouteDuplicateSingleTable() { - SingleStandardRouteEngine engine = - new SingleStandardRouteEngine(Collections.singleton(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "t_order")), mockStatement(false), mock(HintValueContext.class)); + SingleRouteEngine engine = + new SingleRouteEngine(Collections.singleton(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "t_order")), mockStatement(false), mock(HintValueContext.class)); assertThrows(TableExistsException.class, () -> engine.route(new RouteContext(), mockSingleRule())); } @Test void assertRouteIfNotExistsDuplicateSingleTable() { - SingleStandardRouteEngine engine = - new SingleStandardRouteEngine(Collections.singleton(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "t_order")), mockStatement(true), mock(HintValueContext.class)); + SingleRouteEngine engine = + new SingleRouteEngine(Collections.singleton(new QualifiedTable(DefaultDatabase.LOGIC_NAME, "t_order")), mockStatement(true), mock(HintValueContext.class)); assertDoesNotThrow(() -> engine.route(new RouteContext(), mockSingleRule())); } diff --git a/kernel/single/distsql/handler/src/main/java/org/apache/shardingsphere/single/distsql/handler/update/UnloadSingleTableExecutor.java b/kernel/single/distsql/handler/src/main/java/org/apache/shardingsphere/single/distsql/handler/update/UnloadSingleTableExecutor.java index bf62b88c3871b6..4302b72872e939 100644 --- a/kernel/single/distsql/handler/src/main/java/org/apache/shardingsphere/single/distsql/handler/update/UnloadSingleTableExecutor.java +++ b/kernel/single/distsql/handler/src/main/java/org/apache/shardingsphere/single/distsql/handler/update/UnloadSingleTableExecutor.java @@ -72,7 +72,7 @@ private void checkTables(final UnloadSingleTableStatement sqlStatement) { private Collection getAllTableNames(final ShardingSphereDatabase database) { String defaultSchemaName = new DatabaseTypeRegistry(database.getProtocolType()).getDefaultSchemaName(database.getName()); - return database.getSchema(defaultSchemaName).getTables().values().stream().map(ShardingSphereTable::getName).collect(Collectors.toList()); + return database.getSchema(defaultSchemaName).getAllTables().stream().map(ShardingSphereTable::getName).collect(Collectors.toList()); } private void checkTableExist(final Collection allTables, final String tableName) { 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 bc44ef0d702be7..c5e4e585567d69 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 @@ -266,7 +266,7 @@ private void registerTableScanExecutor(final Schema sqlFederationSchema, final D EnumerableScanExecutor scanExecutor = new EnumerableScanExecutor(prepareEngine, jdbcExecutor, callback, optimizerContext, executorContext, federationContext, metaData.getGlobalRuleMetaData(), statistics); // TODO register only the required tables - for (ShardingSphereTable each : metaData.getDatabase(databaseName).getSchema(schemaName).getTables().values()) { + for (ShardingSphereTable each : metaData.getDatabase(databaseName).getSchema(schemaName).getAllTables()) { Table table = sqlFederationSchema.getTable(each.getName()); if (table instanceof SQLFederationTable) { ((SQLFederationTable) table).setScanExecutor(scanExecutor); diff --git a/kernel/sql-federation/optimizer/src/main/java/org/apache/shardingsphere/sqlfederation/optimizer/metadata/schema/SQLFederationSchema.java b/kernel/sql-federation/optimizer/src/main/java/org/apache/shardingsphere/sqlfederation/optimizer/metadata/schema/SQLFederationSchema.java index abdbcfb60cfef0..73e1f141ef3407 100644 --- a/kernel/sql-federation/optimizer/src/main/java/org/apache/shardingsphere/sqlfederation/optimizer/metadata/schema/SQLFederationSchema.java +++ b/kernel/sql-federation/optimizer/src/main/java/org/apache/shardingsphere/sqlfederation/optimizer/metadata/schema/SQLFederationSchema.java @@ -51,8 +51,8 @@ public SQLFederationSchema(final String schemaName, final ShardingSphereSchema s } private Map createTableMap(final ShardingSphereSchema schema, final DatabaseType protocolType, final JavaTypeFactory javaTypeFactory) { - Map result = new CaseInsensitiveMap<>(schema.getTables().size(), 1F); - for (ShardingSphereTable each : schema.getTables().values()) { + Map result = new CaseInsensitiveMap<>(schema.getAllTables().size(), 1F); + for (ShardingSphereTable each : schema.getAllTables()) { if (schema.containsView(each.getName())) { result.put(each.getName(), getViewTable(schema, each, protocolType, javaTypeFactory)); } else { diff --git a/kernel/sql-federation/optimizer/src/test/java/org/apache/shardingsphere/sqlfederation/optimizer/it/SQLStatementCompilerIT.java b/kernel/sql-federation/optimizer/src/test/java/org/apache/shardingsphere/sqlfederation/optimizer/it/SQLStatementCompilerIT.java index ea98d7a4d471b4..d9c24fdaf017da 100644 --- a/kernel/sql-federation/optimizer/src/test/java/org/apache/shardingsphere/sqlfederation/optimizer/it/SQLStatementCompilerIT.java +++ b/kernel/sql-federation/optimizer/src/test/java/org/apache/shardingsphere/sqlfederation/optimizer/it/SQLStatementCompilerIT.java @@ -49,9 +49,9 @@ import java.io.IOException; import java.sql.Types; import java.util.Arrays; +import java.util.Collection; import java.util.Collections; -import java.util.HashMap; -import java.util.Map; +import java.util.LinkedList; import java.util.Properties; import java.util.stream.Stream; @@ -69,20 +69,20 @@ class SQLStatementCompilerIT { @BeforeEach void init() { - Map tables = new HashMap<>(12, 1F); - tables.put("t_order_federate", createOrderFederationTableMetaData()); - tables.put("t_user_info", createUserInfoTableMetaData()); - tables.put("t_order", createTOrderTableMetaData()); - tables.put("t_order_item", createTOrderItemTableMetaData()); - tables.put("t_single_table", createTSingleTableMetaData()); - tables.put("t_order_federate_sharding", createTOrderFederateShardingMetaData()); - tables.put("t_order_item_federate_sharding", createTOrderItemFederateShardingMetaData()); - tables.put("t_merchant", createTMerchantMetaData()); - tables.put("t_product", createTProductMetaData()); - tables.put("t_product_detail", createTProductDetailMetaData()); - tables.put("multi_types_first", createMultiTypesFirstTableMetaData()); - tables.put("multi_types_second", createMultiTypesSecondTableMetaData()); - sqlStatementCompiler = new SQLStatementCompiler(createSqlToRelConverter(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()))); + Collection tables = new LinkedList<>(); + tables.add(createOrderFederationTableMetaData()); + tables.add(createUserInfoTableMetaData()); + tables.add(createTOrderTableMetaData()); + tables.add(createTOrderItemTableMetaData()); + tables.add(createTSingleTableMetaData()); + tables.add(createTOrderFederateShardingMetaData()); + tables.add(createTOrderItemFederateShardingMetaData()); + tables.add(createTMerchantMetaData()); + tables.add(createTProductMetaData()); + tables.add(createTProductDetailMetaData()); + tables.add(createMultiTypesFirstTableMetaData()); + tables.add(createMultiTypesSecondTableMetaData()); + sqlStatementCompiler = new SQLStatementCompiler(createSqlToRelConverter(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList()))); } private ShardingSphereTable createOrderFederationTableMetaData() { diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java index 8fd5f189df8fd9..2d01b34e15eedf 100644 --- a/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java +++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/manager/ContextManager.java @@ -127,7 +127,7 @@ public Map getStorageUnits(final String databaseName) { public void reloadSchema(final ShardingSphereDatabase database, final String schemaName, final String dataSourceName) { try { ShardingSphereSchema reloadedSchema = loadSchema(database, schemaName, dataSourceName); - if (reloadedSchema.getTables().isEmpty()) { + if (reloadedSchema.getAllTables().isEmpty()) { database.dropSchema(schemaName); persistServiceFacade.getMetaDataPersistService().getDatabaseMetaDataFacade().getSchema().drop(database.getName(), schemaName); } else { @@ -146,7 +146,7 @@ private ShardingSphereSchema loadSchema(final ShardingSphereDatabase database, f Collections.singletonMap(dataSourceName, database.getResourceMetaData().getStorageUnits().get(dataSourceName).getDataSource()), database.getRuleMetaData().getRules(), metaDataContexts.get().getMetaData().getProps(), schemaName); ShardingSphereSchema result = GenericSchemaBuilder.build(material).get(schemaName); - result.getViews().putAll(persistServiceFacade.getMetaDataPersistService().getDatabaseMetaDataFacade().getView().load(database.getName(), schemaName)); + persistServiceFacade.getMetaDataPersistService().getDatabaseMetaDataFacade().getView().load(database.getName(), schemaName).forEach(result::putView); return result; } @@ -189,8 +189,7 @@ public void reloadTable(final ShardingSphereDatabase database, final String sche private void persistTable(final ShardingSphereDatabase database, final String schemaName, final String tableName, final GenericSchemaBuilderMaterial material) throws SQLException { ShardingSphereSchema schema = GenericSchemaBuilder.build(Collections.singleton(tableName), material).getOrDefault(schemaName, new ShardingSphereSchema(schemaName)); - persistServiceFacade.getMetaDataPersistService().getDatabaseMetaDataFacade().getTable() - .persist(database.getName(), schemaName, Collections.singletonMap(tableName, schema.getTable(tableName))); + persistServiceFacade.getMetaDataPersistService().getDatabaseMetaDataFacade().getTable().persist(database.getName(), schemaName, Collections.singleton(schema.getTable(tableName))); } /** diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextManager.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextManager.java index b556082f375b04..61c5ecb25907b0 100644 --- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextManager.java +++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextManager.java @@ -123,7 +123,7 @@ public void forceRefreshDatabaseMetaData(final ShardingSphereDatabase database) if (schema.isEmpty()) { metaDataPersistService.getDatabaseMetaDataFacade().getSchema().add(database.getName(), schemaName); } - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(database.getName(), schemaName, schema.getTables()); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(database.getName(), schemaName, schema.getAllTables()); }); } catch (final SQLException ex) { log.error("Refresh database meta data: {} failed", database.getName(), ex); diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsFactory.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsFactory.java index 122372c7b7851f..99e9cd6d74df2c 100644 --- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsFactory.java +++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/MetaDataContextsFactory.java @@ -242,7 +242,7 @@ private static void persistMetaData(final MetaDataContexts metaDataContexts, fin if (schema.isEmpty()) { persistService.getDatabaseMetaDataFacade().getSchema().add(each.getName(), schemaName); } - persistService.getDatabaseMetaDataFacade().getTable().persist(each.getName(), schemaName, schema.getTables()); + persistService.getDatabaseMetaDataFacade().getTable().persist(each.getName(), schemaName, schema.getAllTables()); })); for (Entry databaseDataEntry : metaDataContexts.getStatistics().getDatabaseData().entrySet()) { for (Entry schemaDataEntry : databaseDataEntry.getValue().getSchemaData().entrySet()) { diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/DatabaseRuleConfigurationManager.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/DatabaseRuleConfigurationManager.java index f6f66a4d80e0ad..390c2a1d1c12b3 100644 --- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/DatabaseRuleConfigurationManager.java +++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/DatabaseRuleConfigurationManager.java @@ -115,7 +115,7 @@ private void refreshMetadata(final String databaseName, final ShardingSphereData private Map buildShardingSphereSchemas(final ShardingSphereDatabase database) { Map result = new LinkedHashMap<>(database.getSchemas().size(), 1F); - database.getSchemas().forEach((key, value) -> result.put(key, new ShardingSphereSchema(key, value.getTables(), value.getViews()))); + database.getSchemas().forEach((key, value) -> result.put(key, new ShardingSphereSchema(key, value.getAllTables(), value.getAllViews()))); return result; } } diff --git a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/StorageUnitManager.java b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/StorageUnitManager.java index 1c55b920b4b836..a6a38f29d8dee4 100644 --- a/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/StorageUnitManager.java +++ b/mode/core/src/main/java/org/apache/shardingsphere/mode/metadata/manager/StorageUnitManager.java @@ -121,8 +121,8 @@ private Map buildShardingSphereDatabase(final Sh private Map buildSchemas(final ShardingSphereDatabase originalDatabase) { Map result = new LinkedHashMap<>(originalDatabase.getSchemas().size(), 1F); - originalDatabase.getSchemas().keySet().forEach(schemaName -> result.put(schemaName.toLowerCase(), new ShardingSphereSchema( - schemaName, originalDatabase.getSchema(schemaName).getTables(), metaDataPersistService.getDatabaseMetaDataFacade().getView().load(originalDatabase.getName(), schemaName)))); + originalDatabase.getSchemas().keySet().forEach(schemaName -> result.put(schemaName.toLowerCase(), new ShardingSphereSchema(schemaName, originalDatabase.getSchema(schemaName).getAllTables(), + metaDataPersistService.getDatabaseMetaDataFacade().getView().load(originalDatabase.getName(), schemaName)))); return result; } diff --git a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java index 5797530910f85b..3cb6770fd7d42f 100644 --- a/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java +++ b/mode/core/src/test/java/org/apache/shardingsphere/mode/manager/ContextManagerTest.java @@ -33,6 +33,7 @@ import org.apache.shardingsphere.infra.metadata.database.resource.unit.StorageUnit; import org.apache.shardingsphere.infra.metadata.database.rule.RuleMetaData; 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.rule.ShardingSphereRule; import org.apache.shardingsphere.infra.rule.attribute.RuleAttributes; import org.apache.shardingsphere.infra.rule.attribute.datanode.MutableDataNodeRuleAttribute; @@ -50,6 +51,9 @@ import org.mockito.junit.jupiter.MockitoSettings; import org.mockito.quality.Strictness; +import java.sql.Connection; +import java.sql.ResultSet; +import java.sql.SQLException; import java.util.Collections; import java.util.HashMap; import java.util.Optional; @@ -79,7 +83,7 @@ class ContextManagerTest { private ContextManager contextManager; @BeforeEach - void setUp() { + void setUp() throws SQLException { when(metaDataContexts.getMetaData().getProps()).thenReturn(new ConfigurationProperties(new Properties())); ShardingSphereDatabase database = mockDatabase(); when(metaDataContexts.getMetaData().containsDatabase("foo_db")).thenReturn(true); @@ -90,7 +94,7 @@ void setUp() { contextManager = new ContextManager(metaDataContexts, computeNodeInstanceContext, mock(PersistRepository.class)); } - private ShardingSphereDatabase mockDatabase() { + private ShardingSphereDatabase mockDatabase() throws SQLException { ShardingSphereDatabase result = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(result.getName()).thenReturn("foo_db"); when(result.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); @@ -100,9 +104,17 @@ private ShardingSphereDatabase mockDatabase() { when(rule.getAttributes()).thenReturn(new RuleAttributes(ruleAttribute)); when(result.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.singleton(rule))); when(result.containsSchema("foo_schema")).thenReturn(true); - when(result.getSchemas()).thenReturn(new HashMap<>(Collections.singletonMap("foo_schema", new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME)))); + ShardingSphereTable table = mock(ShardingSphereTable.class); + when(table.getName()).thenReturn("foo_tbl"); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(table), Collections.emptyList()); + when(result.getSchemas()).thenReturn(new HashMap<>(Collections.singletonMap("foo_schema", schema))); StorageUnit storageUnit = mock(StorageUnit.class, RETURNS_DEEP_STUBS); when(storageUnit.getStorageType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); + Connection connection = mock(Connection.class, RETURNS_DEEP_STUBS); + ResultSet resultSet = mock(ResultSet.class); + when(resultSet.next()).thenReturn(true, false); + when(connection.getMetaData().getTables(null, null, "foo_tbl", null)).thenReturn(resultSet); + when(storageUnit.getDataSource()).thenReturn(new MockedDataSource(connection)); when(result.getResourceMetaData().getStorageUnits()).thenReturn(Collections.singletonMap("foo_ds", storageUnit)); return result; } @@ -139,7 +151,7 @@ void assertGetStorageUnits() { } @Test - void assertReloadSchema() { + void assertReloadSchema() throws SQLException { when(metaDataContexts.getMetaData().getDatabase("foo_db").getName()).thenReturn("foo_db"); ShardingSphereDatabase database = mockDatabase(); contextManager.reloadSchema(database, "foo_schema", "foo_ds"); @@ -147,16 +159,16 @@ void assertReloadSchema() { } @Test - void assertReloadTable() { + void assertReloadTable() throws SQLException { ShardingSphereDatabase database = mockDatabase(); - contextManager.reloadTable(database, "foo_schema", "foo_table"); + contextManager.reloadTable(database, "foo_schema", "foo_tbl"); assertTrue(contextManager.getMetaDataContexts().getMetaData().getDatabase("foo_db").getResourceMetaData().getStorageUnits().containsKey("foo_ds")); } @Test - void assertReloadTableWithDataSourceName() { + void assertReloadTableWithDataSourceName() throws SQLException { ShardingSphereDatabase database = mockDatabase(); - contextManager.reloadTable(database, "foo_schema", "foo_ds", "foo_table"); + contextManager.reloadTable(database, "foo_schema", "foo_ds", "foo_tbl"); assertTrue(contextManager.getMetaDataContexts().getMetaData().getDatabase("foo_db").getResourceMetaData().getStorageUnits().containsKey("foo_ds")); } diff --git a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/manager/SchemaMetaDataManagerTest.java b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/manager/SchemaMetaDataManagerTest.java index 11a304d6974c5e..0e1483ebb7831a 100644 --- a/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/manager/SchemaMetaDataManagerTest.java +++ b/mode/core/src/test/java/org/apache/shardingsphere/mode/metadata/manager/SchemaMetaDataManagerTest.java @@ -158,7 +158,7 @@ void assertAlterSchemaForTableAltered() { ShardingSphereColumn toBeChangedColumn = new ShardingSphereColumn("foo_col", Types.VARCHAR, false, false, false, true, false, false); ShardingSphereTable toBeChangedTable = new ShardingSphereTable("foo_tbl", Collections.singleton(toBeChangedColumn), Collections.emptyList(), Collections.emptyList()); schemaMetaDataManager.alterSchema("foo_db", "foo_schema", toBeChangedTable, null); - ShardingSphereTable table = metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").getTables().get("foo_tbl"); + ShardingSphereTable table = metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").getTable("foo_tbl"); assertThat(table.getAllColumns().size(), is(1)); assertTrue(table.containsColumn("foo_col")); } @@ -197,19 +197,19 @@ void assertAlterSchemaForNothingTableDropped() { void assertAlterSchemaForTableDropped() { when(metaDataContexts.getMetaData().getDatabase("foo_db").getSchemas()).thenReturn(Collections.singletonMap("foo_schema", createToBeAlteredSchema())); schemaMetaDataManager.alterSchema("foo_db", "foo_schema", "foo_tbl", null); - assertFalse(metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").getTables().containsKey("foo_tbl")); + assertFalse(metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").containsTable("foo_tbl")); } @Test void assertAlterSchemaForViewDropped() { when(metaDataContexts.getMetaData().getDatabase("foo_db").getSchemas()).thenReturn(Collections.singletonMap("foo_schema", createToBeAlteredSchema())); schemaMetaDataManager.alterSchema("foo_db", "foo_schema", "foo_view", null); - assertFalse(metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").getViews().containsKey("foo_view")); + assertFalse(metaDataContexts.getMetaData().getDatabase("foo_db").getSchema("foo_schema").containsView("foo_view")); } private ShardingSphereSchema createToBeAlteredSchema() { ShardingSphereTable beforeChangedTable = new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList()); - ShardingSphereView beforeChangedView = new ShardingSphereView("foo_tbl", ""); - return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singletonMap("foo_tbl", beforeChangedTable), Collections.singletonMap("foo_view", beforeChangedView)); + ShardingSphereView beforeChangedView = new ShardingSphereView("foo_view", ""); + return new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, Collections.singleton(beforeChangedTable), Collections.singleton(beforeChangedView)); } } diff --git a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistService.java b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistService.java index afc9124493577f..903d86224aa0e1 100644 --- a/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistService.java +++ b/mode/type/cluster/core/src/main/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistService.java @@ -17,14 +17,12 @@ package org.apache.shardingsphere.mode.manager.cluster.persist; -import org.apache.groovy.util.Maps; import org.apache.shardingsphere.infra.config.rule.RuleConfiguration; import org.apache.shardingsphere.infra.datasource.pool.destroyer.DataSourcePoolDestroyer; import org.apache.shardingsphere.infra.datasource.pool.props.domain.DataSourcePoolProperties; import org.apache.shardingsphere.infra.metadata.database.resource.node.StorageNode; 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.model.ShardingSphereView; import org.apache.shardingsphere.infra.metadata.database.schema.pojo.AlterSchemaMetaDataPOJO; import org.apache.shardingsphere.infra.metadata.database.schema.pojo.AlterSchemaPOJO; import org.apache.shardingsphere.infra.metadata.version.MetaDataVersion; @@ -95,8 +93,8 @@ public void alterSchema(final AlterSchemaPOJO alterSchemaPOJO) { if (schema.isEmpty()) { metaDataPersistService.getDatabaseMetaDataFacade().getSchema().add(databaseName, alterSchemaPOJO.getRenameSchemaName()); } - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, alterSchemaPOJO.getRenameSchemaName(), schema.getTables()); - metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, alterSchemaPOJO.getRenameSchemaName(), schema.getViews()); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, alterSchemaPOJO.getRenameSchemaName(), schema.getAllTables()); + metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, alterSchemaPOJO.getRenameSchemaName(), schema.getAllViews()); metaDataPersistService.getDatabaseMetaDataFacade().getSchema().drop(databaseName, schemaName); } @@ -109,11 +107,9 @@ public void dropSchema(final String databaseName, final Collection schem public void alterSchemaMetaData(final AlterSchemaMetaDataPOJO alterSchemaMetaDataPOJO) { String databaseName = alterSchemaMetaDataPOJO.getDatabaseName(); String schemaName = alterSchemaMetaDataPOJO.getSchemaName(); - Map tables = alterSchemaMetaDataPOJO.getAlteredTables().stream().collect(Collectors.toMap(ShardingSphereTable::getName, table -> table)); - Map views = alterSchemaMetaDataPOJO.getAlteredViews().stream().collect(Collectors.toMap(ShardingSphereView::getName, view -> view)); DatabaseMetaDataPersistFacade databaseMetaDataFacade = metaDataPersistService.getDatabaseMetaDataFacade(); - databaseMetaDataFacade.getTable().persist(databaseName, schemaName, tables); - databaseMetaDataFacade.getView().persist(databaseName, schemaName, views); + databaseMetaDataFacade.getTable().persist(databaseName, schemaName, alterSchemaMetaDataPOJO.getAlteredTables()); + databaseMetaDataFacade.getView().persist(databaseName, schemaName, alterSchemaMetaDataPOJO.getAlteredViews()); alterSchemaMetaDataPOJO.getDroppedTables().forEach(each -> databaseMetaDataFacade.getTable().drop(databaseName, schemaName, each)); alterSchemaMetaDataPOJO.getDroppedViews().forEach(each -> databaseMetaDataFacade.getView().delete(databaseName, schemaName, each)); } @@ -259,7 +255,7 @@ public void alterProperties(final Properties props) { @Override public void createTable(final String databaseName, final String schemaName, final ShardingSphereTable table, final String logicDataSourceName) { - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, Maps.of(table.getName(), table)); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, Collections.singleton(table)); } @Override diff --git a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistServiceTest.java b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistServiceTest.java index 670042b24ab91a..47feac6319c605 100644 --- a/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistServiceTest.java +++ b/mode/type/cluster/core/src/test/java/org/apache/shardingsphere/mode/manager/cluster/persist/ClusterMetaDataManagerPersistServiceTest.java @@ -18,7 +18,6 @@ package org.apache.shardingsphere.mode.manager.cluster.persist; import lombok.SneakyThrows; -import org.apache.groovy.util.Maps; import org.apache.shardingsphere.infra.config.rule.RuleConfiguration; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema; import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable; @@ -98,7 +97,8 @@ void assertCreateSchema() { @Test void assertAlterNotEmptySchema() { - assertAlterSchema(mock(ShardingSphereSchema.class)); + ShardingSphereSchema schema = mock(ShardingSphereSchema.class); + assertAlterSchema(schema); verify(metaDataPersistService.getDatabaseMetaDataFacade().getSchema(), times(0)).add("foo_db", "bar_schema"); } @@ -113,8 +113,8 @@ void assertAlterEmptySchema() { private void assertAlterSchema(final ShardingSphereSchema schema) { when(metaDataContextManager.getMetaDataContexts().get().getMetaData().getDatabase("foo_db").getSchema("foo_schema")).thenReturn(schema); metaDataManagerPersistService.alterSchema(new AlterSchemaPOJO("foo_db", "foo_schema", "bar_schema", Collections.singleton("foo_ds"))); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "bar_schema", Collections.emptyMap()); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getView()).persist("foo_db", "bar_schema", Collections.emptyMap()); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getView()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); verify(metaDataPersistService.getDatabaseMetaDataFacade().getSchema()).drop("foo_db", "foo_schema"); } @@ -127,8 +127,8 @@ void assertDropSchema() { @Test void assertAlterSchemaMetaData() { metaDataManagerPersistService.alterSchemaMetaData(new AlterSchemaMetaDataPOJO("foo_db", "foo_schema", Collections.singleton("foo_ds"))); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Collections.emptyMap()); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getView()).persist("foo_db", "foo_schema", Collections.emptyMap()); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Collections.emptyList()); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getView()).persist("foo_db", "foo_schema", Collections.emptyList()); } @Test @@ -189,9 +189,8 @@ void assertAlterProperties() { @Test void assertCreateTable() { ShardingSphereTable table = mock(ShardingSphereTable.class); - when(table.getName()).thenReturn("foo_tbl"); metaDataManagerPersistService.createTable("foo_db", "foo_schema", table, "foo_ds"); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Maps.of("foo_tbl", table)); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Collections.singleton(table)); } @Test diff --git a/mode/type/standalone/core/src/main/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistService.java b/mode/type/standalone/core/src/main/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistService.java index febe330f39b953..09abed96a5adae 100644 --- a/mode/type/standalone/core/src/main/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistService.java +++ b/mode/type/standalone/core/src/main/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistService.java @@ -18,7 +18,6 @@ package org.apache.shardingsphere.mode.manager.standalone.persist; import com.google.common.base.Strings; -import org.apache.groovy.util.Maps; import org.apache.shardingsphere.infra.config.rule.RuleConfiguration; import org.apache.shardingsphere.infra.datasource.pool.props.domain.DataSourcePoolProperties; import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData; @@ -56,10 +55,8 @@ import java.util.HashSet; import java.util.LinkedList; import java.util.Map; -import java.util.Map.Entry; import java.util.Optional; import java.util.Properties; -import java.util.stream.Collectors; /** * Standalone meta data manager persist service. @@ -114,8 +111,8 @@ public void alterSchema(final AlterSchemaPOJO alterSchemaPOJO) { if (alteredSchema.isEmpty()) { metaDataPersistService.getDatabaseMetaDataFacade().getSchema().add(databaseName, alteredSchemaName); } - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, alteredSchemaName, alteredSchema.getTables()); - metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, alteredSchemaName, alteredSchema.getViews()); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, alteredSchemaName, alteredSchema.getAllTables()); + metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, alteredSchemaName, alteredSchema.getAllViews()); metaDataPersistService.getDatabaseMetaDataFacade().getSchema().drop(databaseName, alterSchemaPOJO.getSchemaName()); } @@ -133,34 +130,34 @@ private void addDataNode(final ShardingSphereDatabase database, final String log }); } - private void addDataNode(final ShardingSphereDatabase database, final String logicDataSourceName, final String schemaName, final Map toBeAddedTables, - final Map toBeAddedViews) { + private void addDataNode(final ShardingSphereDatabase database, final String logicDataSourceName, final String schemaName, final Collection toBeAddedTables, + final Collection toBeAddedViews) { addTablesToDataNode(database, schemaName, logicDataSourceName, toBeAddedTables); addViewsToDataNode(database, schemaName, logicDataSourceName, toBeAddedTables, toBeAddedViews); } - private void addTablesToDataNode(final ShardingSphereDatabase database, final String schemaName, final String logicDataSourceName, final Map toBeAddedTables) { - for (Entry entry : toBeAddedTables.entrySet()) { - if (!Strings.isNullOrEmpty(logicDataSourceName) && TableRefreshUtils.isSingleTable(entry.getKey(), database)) { - database.getRuleMetaData().getAttributes(MutableDataNodeRuleAttribute.class).forEach(rule -> rule.put(logicDataSourceName, schemaName, entry.getKey())); + private void addTablesToDataNode(final ShardingSphereDatabase database, final String schemaName, final String logicDataSourceName, final Collection toBeAddedTables) { + for (ShardingSphereTable each : toBeAddedTables) { + if (!Strings.isNullOrEmpty(logicDataSourceName) && TableRefreshUtils.isSingleTable(each.getName(), database)) { + database.getRuleMetaData().getAttributes(MutableDataNodeRuleAttribute.class).forEach(rule -> rule.put(logicDataSourceName, schemaName, each.getName())); } - database.getSchema(schemaName).putTable(entry.getValue()); + database.getSchema(schemaName).putTable(each); } } private void addViewsToDataNode(final ShardingSphereDatabase database, final String schemaName, final String logicDataSourceName, - final Map toBeAddedTables, final Map toBeAddedViews) { - for (Entry entry : toBeAddedViews.entrySet()) { - if (!Strings.isNullOrEmpty(logicDataSourceName) && TableRefreshUtils.isSingleTable(entry.getKey(), database)) { - database.getRuleMetaData().getAttributes(MutableDataNodeRuleAttribute.class).forEach(each -> each.put(logicDataSourceName, schemaName, entry.getKey())); + final Collection toBeAddedTables, final Collection toBeAddedViews) { + for (ShardingSphereView view : toBeAddedViews) { + if (!Strings.isNullOrEmpty(logicDataSourceName) && TableRefreshUtils.isSingleTable(view.getName(), database)) { + database.getRuleMetaData().getAttributes(MutableDataNodeRuleAttribute.class).forEach(each -> each.put(logicDataSourceName, schemaName, view.getName())); } - Optional.ofNullable(toBeAddedTables.get(entry.getKey().toLowerCase())).ifPresent(optional -> database.getSchema(schemaName).putTable(optional)); - database.getSchema(schemaName).putView(entry.getValue()); + toBeAddedTables.stream().filter(each -> each.getName().toLowerCase().equals(view.getName())).findFirst().ifPresent(optional -> database.getSchema(schemaName).putTable(optional)); + database.getSchema(schemaName).putView(view); } } private void removeSchemaMetaData(final ShardingSphereDatabase database, final String schemaName) { - ShardingSphereSchema schema = new ShardingSphereSchema(schemaName, database.getSchema(schemaName).getTables(), database.getSchema(schemaName).getViews()); + ShardingSphereSchema schema = new ShardingSphereSchema(schemaName, database.getSchema(schemaName).getAllTables(), database.getSchema(schemaName).getAllViews()); database.dropSchema(schemaName); removeDataNode(database.getRuleMetaData().getAttributes(MutableDataNodeRuleAttribute.class), Collections.singletonList(schemaName), schema.getAllTableNames()); } @@ -197,7 +194,7 @@ public void dropSchema(final String databaseName, final Collection schem ShardingSphereMetaData metaData = metaDataContextManager.getMetaDataContexts().get().getMetaData(); ShardingSphereDatabase database = metaData.getDatabase(databaseName); for (String each : schemaNames) { - ShardingSphereSchema schema = new ShardingSphereSchema(each, database.getSchema(each).getTables(), database.getSchema(each).getViews()); + ShardingSphereSchema schema = new ShardingSphereSchema(each, database.getSchema(each).getAllTables(), database.getSchema(each).getAllViews()); database.dropSchema(each); Optional.of(schema).ifPresent(optional -> tobeRemovedTables.addAll(optional.getAllTableNames())); tobeRemovedSchemas.add(each.toLowerCase()); @@ -212,13 +209,11 @@ public void alterSchemaMetaData(final AlterSchemaMetaDataPOJO alterSchemaMetaDat String schemaName = alterSchemaMetaDataPOJO.getSchemaName(); ShardingSphereMetaData metaData = metaDataContextManager.getMetaDataContexts().get().getMetaData(); ShardingSphereDatabase database = metaData.getDatabase(databaseName); - Map tables = alterSchemaMetaDataPOJO.getAlteredTables().stream().collect(Collectors.toMap(ShardingSphereTable::getName, table -> table)); - Map views = alterSchemaMetaDataPOJO.getAlteredViews().stream().collect(Collectors.toMap(ShardingSphereView::getName, view -> view)); - addDataNode(database, alterSchemaMetaDataPOJO.getLogicDataSourceName(), schemaName, tables, views); + addDataNode(database, alterSchemaMetaDataPOJO.getLogicDataSourceName(), schemaName, alterSchemaMetaDataPOJO.getAlteredTables(), alterSchemaMetaDataPOJO.getAlteredViews()); removeDataNode(database, schemaName, alterSchemaMetaDataPOJO.getDroppedTables(), alterSchemaMetaDataPOJO.getDroppedViews()); metaData.getGlobalRuleMetaData().getRules().forEach(each -> ((GlobalRule) each).refresh(metaData.getDatabases(), GlobalRuleChangedType.SCHEMA_CHANGED)); - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, tables); - metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, schemaName, views); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, alterSchemaMetaDataPOJO.getAlteredTables()); + metaDataPersistService.getDatabaseMetaDataFacade().getView().persist(databaseName, schemaName, alterSchemaMetaDataPOJO.getAlteredViews()); alterSchemaMetaDataPOJO.getDroppedTables().forEach(each -> metaDataPersistService.getDatabaseMetaDataFacade().getTable().drop(databaseName, schemaName, each)); alterSchemaMetaDataPOJO.getDroppedViews().forEach(each -> metaDataPersistService.getDatabaseMetaDataFacade().getView().delete(databaseName, schemaName, each)); } @@ -237,7 +232,7 @@ public void registerStorageUnits(final String databaseName, final Map ((GlobalRule) each).refresh(metaData.getDatabases(), GlobalRuleChangedType.SCHEMA_CHANGED)); - metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, Maps.of(table.getName(), table)); + metaDataPersistService.getDatabaseMetaDataFacade().getTable().persist(databaseName, schemaName, Collections.singleton(table)); } @Override diff --git a/mode/type/standalone/core/src/test/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistServiceTest.java b/mode/type/standalone/core/src/test/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistServiceTest.java index 059bafaf5f84f4..4952148407a372 100644 --- a/mode/type/standalone/core/src/test/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistServiceTest.java +++ b/mode/type/standalone/core/src/test/java/org/apache/shardingsphere/mode/manager/standalone/persist/StandaloneMetaDataManagerPersistServiceTest.java @@ -18,7 +18,6 @@ package org.apache.shardingsphere.mode.manager.standalone.persist; import lombok.SneakyThrows; -import org.apache.groovy.util.Maps; import org.apache.shardingsphere.infra.config.props.ConfigurationProperties; import org.apache.shardingsphere.infra.config.rule.RuleConfiguration; import org.apache.shardingsphere.infra.database.core.metadata.database.enums.TableType; @@ -51,12 +50,12 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.Optional; import java.util.Properties; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyCollection; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.RETURNS_DEEP_STUBS; import static org.mockito.Mockito.mock; @@ -112,8 +111,8 @@ void assertAlterSchemaWithEmptyAlteredSchema() { when(metaDataPersistService.getDatabaseMetaDataFacade()).thenReturn(databaseMetaDataFacade); metaDataManagerPersistService.alterSchema(new AlterSchemaPOJO("foo_db", "foo_schema", "bar_schema", Collections.singleton("foo_ds"))); verify(databaseMetaDataFacade.getSchema(), times(0)).add("foo_db", "bar_schema"); - verify(databaseMetaDataFacade.getTable()).persist("foo_db", "bar_schema", new HashMap<>()); - verify(databaseMetaDataFacade.getView()).persist("foo_db", "bar_schema", new HashMap<>()); + verify(databaseMetaDataFacade.getTable()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); + verify(databaseMetaDataFacade.getView()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); verify(databaseMetaDataFacade.getSchema()).drop("foo_db", "foo_schema"); } @@ -131,8 +130,8 @@ void assertAlterSchemaWithNotEmptyAlteredSchema() { when(metaDataPersistService.getDatabaseMetaDataFacade()).thenReturn(databaseMetaDataFacade); metaDataManagerPersistService.alterSchema(new AlterSchemaPOJO("foo_db", "foo_schema", "bar_schema", Collections.singleton("foo_ds"))); verify(databaseMetaDataFacade.getSchema()).add("foo_db", "bar_schema"); - verify(databaseMetaDataFacade.getTable()).persist("foo_db", "bar_schema", new HashMap<>()); - verify(databaseMetaDataFacade.getView()).persist("foo_db", "bar_schema", new HashMap<>()); + verify(databaseMetaDataFacade.getTable()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); + verify(databaseMetaDataFacade.getView()).persist(eq("foo_db"), eq("bar_schema"), anyCollection()); verify(databaseMetaDataFacade.getSchema()).drop("foo_db", "foo_schema"); } @@ -151,7 +150,7 @@ void assertAlterSchemaMetaData() { DatabaseMetaDataPersistFacade databaseMetaDataFacade = mock(DatabaseMetaDataPersistFacade.class, RETURNS_DEEP_STUBS); when(metaDataPersistService.getDatabaseMetaDataFacade()).thenReturn(databaseMetaDataFacade); metaDataManagerPersistService.alterSchemaMetaData(new AlterSchemaMetaDataPOJO("foo_db", "foo_schema", Collections.singleton("foo_ds"))); - verify(databaseMetaDataFacade.getTable()).persist("foo_db", "foo_schema", new HashMap<>()); + verify(databaseMetaDataFacade.getTable()).persist("foo_db", "foo_schema", new LinkedList<>()); } @Test @@ -232,7 +231,7 @@ void assertAlterProperties() { void assertCreateTable() { ShardingSphereTable table = new ShardingSphereTable("foo_tbl", Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), TableType.TABLE); metaDataManagerPersistService.createTable("foo_db", "foo_schema", table, "foo_ds"); - verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Maps.of("foo_tbl", table)); + verify(metaDataPersistService.getDatabaseMetaDataFacade().getTable()).persist("foo_db", "foo_schema", Collections.singleton(table)); } @Test diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java index ee923a390f4a7e..32aa3e020b6b02 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryBackendHandlerTest.java @@ -50,7 +50,6 @@ import java.util.Collection; import java.util.Collections; -import java.util.Map; import static org.junit.jupiter.api.Assertions.assertDoesNotThrow; import static org.junit.jupiter.api.Assertions.assertThrows; @@ -91,15 +90,15 @@ void assertExecute() { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getName()).thenReturn("foo_db"); when(database.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); - when(database.getSchema("foo_db")).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTableMap(), Collections.emptyMap())); + when(database.getSchema("foo_db")).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTables(), Collections.emptyList())); when(ProxyContext.getInstance().getContextManager().getDatabase("foo_db")).thenReturn(database); assertDoesNotThrow(() -> new DistSQLQueryBackendHandler(createSqlStatement(), mock(ConnectionSession.class, RETURNS_DEEP_STUBS)).execute()); } - private Map createTableMap() { + private Collection createTables() { Collection columns = Collections.singletonList(new ShardingSphereColumn("order_id", 0, false, false, false, true, false, false)); Collection indexes = Collections.singletonList(new ShardingSphereIndex("primary", Collections.emptyList(), false)); - return Collections.singletonMap("t_order", new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); + return Collections.singleton(new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); } private ShowTableMetaDataStatement createSqlStatement() { diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowTableMetaDataExecutorTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowTableMetaDataExecutorTest.java index 57a50b9087e066..710d1bd78b111d 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowTableMetaDataExecutorTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ShowTableMetaDataExecutorTest.java @@ -39,7 +39,6 @@ import java.util.Collection; import java.util.Collections; import java.util.Iterator; -import java.util.Map; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.MatcherAssert.assertThat; @@ -78,14 +77,14 @@ private ShardingSphereDatabase mockDatabase() { ShardingSphereDatabase result = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(result.getProtocolType()).thenReturn(TypedSPILoader.getService(DatabaseType.class, "FIXTURE")); when(result.getName()).thenReturn("foo_db"); - when(result.getSchema("foo_db")).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTableMap(), Collections.emptyMap())); + when(result.getSchema("foo_db")).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTables(), Collections.emptyList())); return result; } - private Map createTableMap() { + private Collection createTables() { Collection columns = Collections.singletonList(new ShardingSphereColumn("order_id", 0, false, false, false, true, false, false)); Collection indexes = Collections.singletonList(new ShardingSphereIndex("primary", Collections.emptyList(), false)); - return Collections.singletonMap("t_order", new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); + return Collections.singleton(new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); } private ShowTableMetaDataStatement createSqlStatement() { diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportMetaDataExecutorTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportMetaDataExecutorTest.java index fb70225ba8a3f6..8a194212844ad4 100644 --- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportMetaDataExecutorTest.java +++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/updatable/ImportMetaDataExecutorTest.java @@ -129,7 +129,7 @@ private ContextManager mockContextManager(final String feature) { .thenReturn(new ConfigurationProperties(PropertiesBuilder.build(new Property(ConfigurationPropertyKey.PROXY_FRONTEND_DATABASE_PROTOCOL_TYPE.getKey(), "MySQL")))); if (null != feature) { ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); - when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTables(), Collections.emptyMap())); + when(database.getSchema(DefaultDatabase.LOGIC_NAME)).thenReturn(new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, createTables(), Collections.emptyList())); Map storageUnits = createStorageUnits(); when(database.getResourceMetaData().getStorageUnits()).thenReturn(storageUnits); when(result.getMetaDataContexts().getMetaData().getDatabases()).thenReturn(Collections.singletonMap(feature, database)); @@ -149,9 +149,9 @@ private Map createStorageUnits() { return result; } - private Map createTables() { + private Collection createTables() { Collection columns = Collections.singleton(new ShardingSphereColumn("order_id", 0, false, false, false, true, false, false)); Collection indexes = Collections.singleton(new ShardingSphereIndex("primary", Collections.emptyList(), false)); - return Collections.singletonMap("t_order", new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); + return Collections.singletonList(new ShardingSphereTable("t_order", columns, indexes, Collections.emptyList())); } } diff --git a/proxy/backend/type/mysql/src/main/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutor.java b/proxy/backend/type/mysql/src/main/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutor.java index d0c3a332c7ddfc..20f68183d38e52 100644 --- a/proxy/backend/type/mysql/src/main/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutor.java +++ b/proxy/backend/type/mysql/src/main/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutor.java @@ -99,7 +99,7 @@ private Collection getTables(final String databaseName) { if (null == ProxyContext.getInstance().getContextManager().getDatabase(databaseName).getSchema(databaseName)) { return Collections.emptyList(); } - Collection tables = ProxyContext.getInstance().getContextManager().getDatabase(databaseName).getSchema(databaseName).getTables().values(); + Collection tables = ProxyContext.getInstance().getContextManager().getDatabase(databaseName).getSchema(databaseName).getAllTables(); Collection filteredTables = filterByLike(tables); return filteredTables.stream().sorted(Comparator.comparing(ShardingSphereTable::getName)).collect(Collectors.toList()); } diff --git a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java index d6b0330bda60f2..86fa671fee2db6 100644 --- a/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java +++ b/proxy/backend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/backend/mysql/handler/admin/executor/ShowTablesExecutorTest.java @@ -51,8 +51,10 @@ import org.mockito.quality.Strictness; import java.sql.SQLException; +import java.util.Collection; import java.util.Collections; import java.util.HashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Optional; import java.util.Properties; @@ -204,12 +206,12 @@ private ContextManager mockContextManager(final Map getDatabases() { - Map tables = new HashMap<>(4, 1F); - tables.put("t_account", new ShardingSphereTable("t_account", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_bak", new ShardingSphereTable("t_account_bak", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_detail", new ShardingSphereTable("t_account_detail", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - tables.put("t_test", new ShardingSphereTable("T_TEST", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); - ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_account", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); + tables.add(new ShardingSphereTable("t_account_bak", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); + tables.add(new ShardingSphereTable("t_account_detail", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); + tables.add(new ShardingSphereTable("T_TEST", Collections.emptyList(), Collections.emptyList(), Collections.emptyList())); + ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList()); ShardingSphereDatabase database = mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS); when(database.getSchema(String.format(DATABASE_PATTERN, 0))).thenReturn(schema); when(database.isComplete()).thenReturn(true); 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 210d89cb4e2870..30327ee5d773b8 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 @@ -137,7 +137,7 @@ private Map createShardingSphereDatabaseMap() { new ShardingSphereColumn("datfrozenxid64", 1111, false, false, false, true, false, false), new ShardingSphereColumn("datminmxid", 1111, false, false, false, true, false, false)); ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, - Collections.singletonMap("pg_database", new ShardingSphereTable("pg_database", columns, Collections.emptyList(), Collections.emptyList())), Collections.emptyMap()); + Collections.singleton(new ShardingSphereTable("pg_database", columns, Collections.emptyList(), Collections.emptyList())), Collections.emptyList()); result.put("sharding_db", new ShardingSphereDatabase("sharding_db", TypedSPILoader.getService(DatabaseType.class, "openGauss"), mock(ResourceMetaData.class, RETURNS_DEEP_STUBS), mock(RuleMetaData.class), Collections.singletonMap("pg_catalog", schema))); return result; diff --git a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareExecutorTest.java b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareExecutorTest.java index 9580dd3958ec34..33d77217b1be5f 100644 --- a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareExecutorTest.java +++ b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareExecutorTest.java @@ -233,7 +233,7 @@ private ContextManager mockContextManager() { new ShardingSphereColumn("name", Types.VARCHAR, false, false, false, false, false, false), new ShardingSphereColumn("age", Types.SMALLINT, false, false, false, false, true, false)), Collections.emptyList(), Collections.emptyList()); ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME); - schema.getTables().put("user", table); + schema.putTable(table); ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", TypedSPILoader.getService(DatabaseType.class, "MySQL"), new ResourceMetaData(Collections.emptyMap()), new RuleMetaData(Collections.emptyList()), Collections.singletonMap("foo_db", schema)); when(result.getMetaDataContexts().getMetaData().getDatabase("foo_db")).thenReturn(database); diff --git a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareParameterMarkerExtractorTest.java b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareParameterMarkerExtractorTest.java index c994839b59be35..11820bfea4437c 100644 --- a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareParameterMarkerExtractorTest.java +++ b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/binary/prepare/MySQLComStmtPrepareParameterMarkerExtractorTest.java @@ -56,7 +56,7 @@ private ShardingSphereSchema prepareSchema() { new ShardingSphereColumn("name", Types.VARCHAR, false, false, false, false, false, false), new ShardingSphereColumn("age", Types.SMALLINT, false, false, false, false, true, false)), Collections.emptyList(), Collections.emptyList()); ShardingSphereSchema result = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME); - result.getTables().put("user", table); + result.putTable(table); return result; } } diff --git a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/text/query/MySQLComQueryPacketExecutorTest.java b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/text/query/MySQLComQueryPacketExecutorTest.java index e8af9da9113b7a..6e9fed9b0425ba 100644 --- a/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/text/query/MySQLComQueryPacketExecutorTest.java +++ b/proxy/frontend/type/mysql/src/test/java/org/apache/shardingsphere/proxy/frontend/mysql/command/query/text/query/MySQLComQueryPacketExecutorTest.java @@ -172,7 +172,7 @@ private MetaDataContexts mockMetaDataContexts() { ShardingSphereTable table = new ShardingSphereTable("t", Arrays.asList(new ShardingSphereColumn("id", Types.BIGINT, true, false, false, false, true, false), new ShardingSphereColumn("v", Types.INTEGER, false, false, false, false, true, false)), Collections.emptyList(), Collections.emptyList()); ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME); - schema.getTables().put("t", table); + schema.putTable(table); ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", TypedSPILoader.getService(DatabaseType.class, "MySQL"), new ResourceMetaData(Collections.emptyMap()), new RuleMetaData(Collections.emptyList()), Collections.singletonMap("foo_db", schema)); when(result.getMetaData().getDatabase("foo_db")).thenReturn(database); diff --git a/proxy/frontend/type/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/extended/parse/PostgreSQLComParseExecutorTest.java b/proxy/frontend/type/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/extended/parse/PostgreSQLComParseExecutorTest.java index cb307da06d2538..f9b8649f2c47f0 100644 --- a/proxy/frontend/type/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/extended/parse/PostgreSQLComParseExecutorTest.java +++ b/proxy/frontend/type/postgresql/src/test/java/org/apache/shardingsphere/proxy/frontend/postgresql/command/query/extended/parse/PostgreSQLComParseExecutorTest.java @@ -197,8 +197,8 @@ private ContextManager mockContextManager() { new ShardingSphereColumn("c", Types.VARCHAR, false, false, false, false, true, false), new ShardingSphereColumn("pad", Types.VARCHAR, false, false, false, false, true, false)), Collections.emptyList(), Collections.emptyList()); ShardingSphereSchema schema = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME); - schema.getTables().put("t_test", testTable); - schema.getTables().put("sbtest1", sbTestTable); + schema.putTable(testTable); + schema.putTable(sbTestTable); ShardingSphereDatabase database = new ShardingSphereDatabase("foo_db", TypedSPILoader.getService(DatabaseType.class, "PostgreSQL"), new ResourceMetaData(Collections.emptyMap()), new RuleMetaData(Collections.emptyList()), Collections.singletonMap("public", schema)); when(result.getMetaDataContexts().getMetaData().getDatabase("foo_db")).thenReturn(database); diff --git a/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/migration/AbstractMigrationE2EIT.java b/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/migration/AbstractMigrationE2EIT.java index 1742dd6e4aca21..f6b4f4e489bb92 100644 --- a/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/migration/AbstractMigrationE2EIT.java +++ b/test/e2e/operation/pipeline/src/test/java/org/apache/shardingsphere/test/e2e/data/pipeline/cases/migration/AbstractMigrationE2EIT.java @@ -75,7 +75,7 @@ protected void addMigrationTargetResource(final PipelineContainerComposer contai .replace("${ds2}", containerComposer.getActualJdbcUrlTemplate(PipelineContainerComposer.DS_2, true)) .replace("${ds3}", containerComposer.getActualJdbcUrlTemplate(PipelineContainerComposer.DS_3, true)) .replace("${ds4}", containerComposer.getActualJdbcUrlTemplate(PipelineContainerComposer.DS_4, true)); - containerComposer.proxyExecuteWithLog(addTargetResource, 0); + containerComposer.proxyExecuteWithLog(addTargetResource, 15); Awaitility.await().ignoreExceptions().atMost(60L, TimeUnit.SECONDS).pollInterval(3L, TimeUnit.SECONDS).until(() -> 3 == containerComposer.showStorageUnitsName().size()); } diff --git a/test/e2e/sql/src/test/resources/cases/dql/e2e-dql-select-join.xml b/test/e2e/sql/src/test/resources/cases/dql/e2e-dql-select-join.xml index 6a6da2083b08bf..952981fc24da89 100644 --- a/test/e2e/sql/src/test/resources/cases/dql/e2e-dql-select-join.xml +++ b/test/e2e/sql/src/test/resources/cases/dql/e2e-dql-select-join.xml @@ -87,6 +87,16 @@ + + + + + + + + + + diff --git a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtils.java b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtils.java index db968f5b4bd0db..eb3b1038854634 100644 --- a/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtils.java +++ b/test/it/pipeline/src/test/java/org/apache/shardingsphere/test/it/data/pipeline/core/util/PipelineContextUtils.java @@ -77,7 +77,6 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import java.util.Set; @@ -134,18 +133,18 @@ private static ClusterPersistRepository getClusterPersistRepository(final Cluste } private static MetaDataContexts renewMetaDataContexts(final MetaDataContexts old, final MetaDataPersistService persistService) { - Map tables = new HashMap<>(3, 1F); - tables.put("t_order", new ShardingSphereTable("t_order", Arrays.asList( + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_order", Arrays.asList( new ShardingSphereColumn("order_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_order_item", new ShardingSphereTable("t_order_item", Arrays.asList( + tables.add(new ShardingSphereTable("t_order_item", Arrays.asList( new ShardingSphereColumn("item_id", Types.INTEGER, true, false, false, true, false, false), new ShardingSphereColumn("order_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - old.getMetaData().getDatabase("logic_db").getSchema("logic_db").putTables(tables); + tables.forEach(each -> old.getMetaData().getDatabase("logic_db").getSchema("logic_db").putTable(each)); return MetaDataContextsFactory.create(persistService, old.getMetaData()); } diff --git a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/EncryptSQLRewriterIT.java b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/EncryptSQLRewriterIT.java index 0577556d620559..c26e709edd650a 100644 --- a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/EncryptSQLRewriterIT.java +++ b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/EncryptSQLRewriterIT.java @@ -44,7 +44,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Map.Entry; import java.util.Objects; @@ -66,38 +66,37 @@ protected YamlRootConfiguration createRootConfiguration(final SQLRewriteEngineTe @Override protected Map mockSchemas(final String schemaName) { - Map tables = new LinkedHashMap<>(); - tables.put("t_account", new ShardingSphereTable("t_account", Arrays.asList( + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_account", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("certificate_number", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_bak", new ShardingSphereTable("t_account_bak", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_bak", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("certificate_number", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_detail", new ShardingSphereTable("t_account_detail", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_detail", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("certificate_number", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_order", new ShardingSphereTable("t_order", Arrays.asList( + tables.add(new ShardingSphereTable("t_order", Arrays.asList( new ShardingSphereColumn("ORDER_ID", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("USER_ID", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("CONTENT", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_user", new ShardingSphereTable("t_user", Arrays.asList( + tables.add(new ShardingSphereTable("t_user", Arrays.asList( new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("user_name", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("email", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("telephone", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("creation_date", Types.DATE, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - ShardingSphereSchema result = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); - return Collections.singletonMap(schemaName, result); + return Collections.singletonMap(schemaName, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } @Override diff --git a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/MixSQLRewriterIT.java b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/MixSQLRewriterIT.java index 4323f00242301c..ee9562b969b09c 100644 --- a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/MixSQLRewriterIT.java +++ b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/MixSQLRewriterIT.java @@ -38,7 +38,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Objects; @@ -53,25 +53,24 @@ protected YamlRootConfiguration createRootConfiguration(final SQLRewriteEngineTe @Override protected Map mockSchemas(final String schemaName) { - Map tables = new LinkedHashMap<>(); - tables.put("t_account", new ShardingSphereTable("t_account", Arrays.asList( + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_account", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, true, true, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.singletonList(new ShardingSphereIndex("index_name", Collections.emptyList(), false)), Collections.emptyList())); - tables.put("t_account_bak", new ShardingSphereTable("t_account_bak", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_bak", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, true, true, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_detail", new ShardingSphereTable("t_account_detail", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_detail", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("password", Types.VARCHAR, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - ShardingSphereSchema result = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); - return Collections.singletonMap(schemaName, result); + return Collections.singletonMap(schemaName, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } @Override diff --git a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/ShardingSQLRewriterIT.java b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/ShardingSQLRewriterIT.java index 7a573f87942db0..e2e7e938b1b8df 100644 --- a/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/ShardingSQLRewriterIT.java +++ b/test/it/rewriter/src/test/java/org/apache/shardingsphere/test/it/rewrite/engine/scenario/ShardingSQLRewriterIT.java @@ -41,7 +41,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.Collections; -import java.util.LinkedHashMap; +import java.util.LinkedList; import java.util.Map; import java.util.Objects; import java.util.Optional; @@ -66,46 +66,45 @@ protected void mockRules(final Collection rules, final Strin @Override protected Map mockSchemas(final String schemaName) { - Map tables = new LinkedHashMap<>(); - tables.put("t_account", new ShardingSphereTable("t_account", Arrays.asList( + Collection tables = new LinkedList<>(); + tables.add(new ShardingSphereTable("t_account", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, true, true, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.singletonList(new ShardingSphereIndex("status_idx_exist", Collections.emptyList(), false)), Collections.emptyList())); - tables.put("t_account_detail", new ShardingSphereTable("t_account_detail", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_detail", Arrays.asList( new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("amount", Types.DECIMAL, false, false, false, true, false, false), new ShardingSphereColumn("status", Types.TINYINT, false, false, false, false, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_user", new ShardingSphereTable("t_user", Arrays.asList( + tables.add(new ShardingSphereTable("t_user", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("content", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_user_extend", new ShardingSphereTable("t_user_extend", Arrays.asList( + tables.add(new ShardingSphereTable("t_user_extend", Arrays.asList( new ShardingSphereColumn("user_id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("content", Types.VARCHAR, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_single", new ShardingSphereTable("t_single", Arrays.asList( + tables.add(new ShardingSphereTable("t_single", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false)), Collections.singletonList(new ShardingSphereIndex("single_id_idx", Collections.emptyList(), false)), Collections.emptyList())); - tables.put("t_single_extend", new ShardingSphereTable("t_single_extend", Collections.singletonList( + tables.add(new ShardingSphereTable("t_single_extend", Collections.singletonList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_config", new ShardingSphereTable("t_config", Arrays.asList( + tables.add(new ShardingSphereTable("t_config", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false)), Collections.singletonList(new ShardingSphereIndex("broadcast_id_idx", Collections.emptyList(), false)), Collections.emptyList())); - tables.put("T_ROLE", new ShardingSphereTable("T_ROLE", Arrays.asList( + tables.add(new ShardingSphereTable("T_ROLE", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("ROLE_ID", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("T_ROLE_ADMIN", new ShardingSphereTable("T_ROLE_ADMIN", Arrays.asList( + tables.add(new ShardingSphereTable("T_ROLE_ADMIN", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("ROLE_ID", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - tables.put("t_account_view", new ShardingSphereTable("t_account_view", Arrays.asList( + tables.add(new ShardingSphereTable("t_account_view", Arrays.asList( new ShardingSphereColumn("id", Types.INTEGER, false, false, false, true, false, false), new ShardingSphereColumn("account_id", Types.INTEGER, false, false, false, true, false, false)), Collections.emptyList(), Collections.emptyList())); - ShardingSphereSchema result = new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyMap()); - return Collections.singletonMap(schemaName, result); + return Collections.singletonMap(schemaName, new ShardingSphereSchema(DefaultDatabase.LOGIC_NAME, tables, Collections.emptyList())); } @Override diff --git a/test/it/rewriter/src/test/resources/scenario/sharding/case/ddl/create-table.xml b/test/it/rewriter/src/test/resources/scenario/sharding/case/ddl/create-table.xml index 842faf0edb15ea..c277252794350f 100644 --- a/test/it/rewriter/src/test/resources/scenario/sharding/case/ddl/create-table.xml +++ b/test/it/rewriter/src/test/resources/scenario/sharding/case/ddl/create-table.xml @@ -21,68 +21,83 @@ + + + + + + + + - + + + - + + + + + +