Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix alter view exception when config sharding rule and binding table rule #32700

Merged
merged 8 commits into from
Aug 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@

package org.apache.shardingsphere.sharding.merge.dal.show;

import com.cedarsoftware.util.CaseInsensitiveMap;
import org.apache.shardingsphere.infra.binder.context.statement.SQLStatementContext;
import org.apache.shardingsphere.infra.datanode.DataNode;
import org.apache.shardingsphere.infra.executor.sql.execute.result.query.QueryResult;
Expand All @@ -26,12 +27,17 @@
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.infra.metadata.database.schema.util.IndexMetaDataUtils;
import org.apache.shardingsphere.sharding.rule.BindingTableRule;
import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.sharding.rule.ShardingTable;

import java.sql.SQLException;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;

/**
* Merged result for show create table.
Expand All @@ -47,6 +53,7 @@ public ShowCreateTableMergedResult(final ShardingRule shardingRule,
protected void setCellValue(final MemoryQueryResultRow memoryResultSetRow, final String logicTableName, final String actualTableName,
final ShardingSphereTable table, final ShardingRule shardingRule) {
memoryResultSetRow.setCell(2, memoryResultSetRow.getCell(2).toString().replaceFirst(actualTableName, logicTableName));
setViewCellValue(memoryResultSetRow, logicTableName, actualTableName, shardingRule);
for (ShardingSphereIndex each : table.getIndexValues()) {
String actualIndexName = IndexMetaDataUtils.getActualIndexName(each.getName(), actualTableName);
memoryResultSetRow.setCell(2, memoryResultSetRow.getCell(2).toString().replace(actualIndexName, each.getName()));
Expand All @@ -63,4 +70,20 @@ protected void setCellValue(final MemoryQueryResultRow memoryResultSetRow, final
}
}
}

private void setViewCellValue(final MemoryQueryResultRow memoryResultSetRow, final String logicTableName, final String actualTableName, final ShardingRule shardingRule) {
Optional<ShardingTable> shardingTable = shardingRule.findShardingTable(logicTableName);
Optional<BindingTableRule> bindingTableRule = shardingRule.findBindingTableRule(logicTableName);
if (shardingTable.isPresent() && bindingTableRule.isPresent()) {
Collection<DataNode> actualDataNodes = shardingTable.get().getActualDataNodes().stream().filter(each -> each.getTableName().equalsIgnoreCase(actualTableName)).collect(Collectors.toList());
Map<String, String> logicAndActualTablesFromBindingTables = new CaseInsensitiveMap<>();
for (DataNode each : actualDataNodes) {
logicAndActualTablesFromBindingTables
.putAll(shardingRule.getLogicAndActualTablesFromBindingTable(each.getDataSourceName(), logicTableName, actualTableName, bindingTableRule.get().getAllLogicTables()));
}
for (Entry<String, String> entry : logicAndActualTablesFromBindingTables.entrySet()) {
memoryResultSetRow.setCell(2, memoryResultSetRow.getCell(2).toString().replaceFirst(entry.getValue(), entry.getKey()));
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
import org.apache.shardingsphere.sql.parser.statement.core.segment.ddl.index.IndexSegment;
import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment;

import java.util.Arrays;
import java.util.Collection;

/**
Expand Down Expand Up @@ -105,4 +106,22 @@ protected boolean isRouteUnitDataNodeDifferentSize(final ShardingRule shardingRu
protected boolean isSchemaContainsIndex(final ShardingSphereSchema schema, final IndexSegment index) {
return schema.getAllTableNames().stream().anyMatch(each -> schema.getTable(each).containsIndex(index.getIndexName().getIdentifier().getValue()));
}

/**
* Judge whether sharding tables not binding with view.
*
* @param tableSegments table segments
* @param shardingRule sharding rule
* @param viewName view name
* @return sharding tables not binding with view or not
*/
protected boolean isShardingTablesNotBindingWithView(final Collection<SimpleTableSegment> tableSegments, final ShardingRule shardingRule, final String viewName) {
for (SimpleTableSegment each : tableSegments) {
String logicTable = each.getTableName().getIdentifier().getValue();
if (shardingRule.isShardingTable(logicTable) && !shardingRule.isAllBindingTables(Arrays.asList(viewName, logicTable))) {
return true;
}
}
return false;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,14 @@
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.sharding.exception.metadata.EngagedViewException;
import org.apache.shardingsphere.sharding.exception.syntax.RenamedViewWithoutSameConfigurationException;
import org.apache.shardingsphere.sharding.route.engine.validator.ddl.ShardingDDLStatementValidator;
import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.sql.parser.statement.core.util.TableExtractor;
import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment;
import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.AlterViewStatement;
import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement;
import org.apache.shardingsphere.sql.parser.statement.core.util.TableExtractor;

import java.util.Arrays;
import java.util.List;
Expand All @@ -45,19 +46,23 @@ public void preValidate(final ShardingRule shardingRule, final SQLStatementConte
final List<Object> params, final ShardingSphereDatabase database, final ConfigurationProperties props) {
AlterViewStatement alterViewStatement = (AlterViewStatement) sqlStatementContext.getSqlStatement();
Optional<SelectStatement> selectStatement = alterViewStatement.getSelectStatement();
if (selectStatement.isPresent()) {
TableExtractor extractor = new TableExtractor();
extractor.extractTablesFromSelect(selectStatement.get());
validateShardingTable(shardingRule, "ALTER VIEW", extractor.getRewriteTables());
}
String originView = alterViewStatement.getView().getTableName().getIdentifier().getValue();
selectStatement.ifPresent(optional -> validateAlterViewShardingTables(shardingRule, optional, originView));
Optional<SimpleTableSegment> renamedView = alterViewStatement.getRenameView();
if (renamedView.isPresent()) {
String targetView = renamedView.get().getTableName().getIdentifier().getValue();
String originView = alterViewStatement.getView().getTableName().getIdentifier().getValue();
validateBroadcastShardingView(shardingRule, originView, targetView);
}
}

private void validateAlterViewShardingTables(final ShardingRule shardingRule, final SelectStatement selectStatement, final String viewName) {
TableExtractor extractor = new TableExtractor();
extractor.extractTablesFromSelect(selectStatement);
if (isShardingTablesNotBindingWithView(extractor.getRewriteTables(), shardingRule, viewName)) {
throw new EngagedViewException("sharding");
}
}

private void validateBroadcastShardingView(final ShardingRule shardingRule, final String originView, final String targetView) {
ShardingSpherePreconditions.checkState(!shardingRule.isShardingTable(originView) && !shardingRule.isShardingTable(targetView)
|| shardingRule.isAllBindingTables(Arrays.asList(originView, targetView)), () -> new RenamedViewWithoutSameConfigurationException(originView, targetView));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,13 @@
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedCreateViewException;
import org.apache.shardingsphere.sharding.route.engine.validator.ddl.ShardingDDLStatementValidator;
import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.sql.parser.statement.core.util.TableExtractor;
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.segment.generic.table.SimpleTableSegment;
import org.apache.shardingsphere.sql.parser.statement.core.statement.ddl.CreateViewStatement;
import org.apache.shardingsphere.sql.parser.statement.core.statement.dml.SelectStatement;
import org.apache.shardingsphere.sql.parser.statement.core.util.TableExtractor;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;

Expand All @@ -50,7 +49,8 @@ public void preValidate(final ShardingRule shardingRule, final SQLStatementConte
TableExtractor extractor = new TableExtractor();
extractor.extractTablesFromSelect(((CreateViewStatement) sqlStatementContext.getSqlStatement()).getSelect());
Collection<SimpleTableSegment> tableSegments = extractor.getRewriteTables();
if (isShardingTablesWithoutBinding(shardingRule, sqlStatementContext, tableSegments)) {
String viewName = ((CreateViewStatement) sqlStatementContext.getSqlStatement()).getView().getTableName().getIdentifier().getValue();
if (isShardingTablesNotBindingWithView(tableSegments, shardingRule, viewName)) {
throw new EngagedViewException("sharding");
}
}
Expand All @@ -64,23 +64,6 @@ public void postValidate(final ShardingRule shardingRule, final SQLStatementCont
}
}

private boolean isShardingTablesWithoutBinding(final ShardingRule shardingRule, final SQLStatementContext sqlStatementContext,
final Collection<SimpleTableSegment> tableSegments) {
for (SimpleTableSegment each : tableSegments) {
String logicTable = each.getTableName().getIdentifier().getValue();
if (shardingRule.isShardingTable(logicTable) && !isBindingTables(
shardingRule, ((CreateViewStatement) sqlStatementContext.getSqlStatement()).getView().getTableName().getIdentifier().getValue(), logicTable)) {
return true;
}
}
return false;
}

private boolean isBindingTables(final ShardingRule shardingRule, final String logicViewName, final String logicTable) {
Collection<String> bindTables = Arrays.asList(logicTable, logicViewName);
return shardingRule.isAllBindingTables(bindTables);
}

private boolean isContainsNotSupportedViewStatement(final SelectStatement selectStatement, final RouteContext routeContext) {
if (routeContext.getRouteUnits().size() <= 1) {
return false;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
import org.apache.shardingsphere.infra.database.core.DefaultDatabase;
import org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
import org.apache.shardingsphere.sharding.exception.syntax.UnsupportedShardingOperationException;
import org.apache.shardingsphere.sharding.exception.metadata.EngagedViewException;
import org.apache.shardingsphere.sharding.route.engine.validator.ddl.impl.ShardingAlterViewStatementValidator;
import org.apache.shardingsphere.sharding.rule.ShardingRule;
import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.table.SimpleTableSegment;
Expand Down Expand Up @@ -54,6 +54,7 @@ void assertPreValidateAlterViewForMySQL() {
MySQLSelectStatement selectStatement = new MySQLSelectStatement();
selectStatement.setFrom(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order"))));
MySQLAlterViewStatement sqlStatement = new MySQLAlterViewStatement();
sqlStatement.setView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_view"))));
sqlStatement.setSelect(selectStatement);
SQLStatementContext sqlStatementContext = new AlterViewStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
Expand All @@ -66,20 +67,21 @@ void assertPreValidateAlterViewWithShardingTableForMySQL() {
MySQLSelectStatement selectStatement = new MySQLSelectStatement();
selectStatement.setFrom(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order"))));
MySQLAlterViewStatement sqlStatement = new MySQLAlterViewStatement();
sqlStatement.setView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_view"))));
sqlStatement.setSelect(selectStatement);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
SQLStatementContext sqlStatementContext = new AlterViewStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME);
when(shardingRule.isShardingTable("t_order")).thenReturn(true);
assertThrows(UnsupportedShardingOperationException.class,
assertThrows(EngagedViewException.class,
() -> new ShardingAlterViewStatementValidator().preValidate(shardingRule, sqlStatementContext, Collections.emptyList(), database, mock(ConfigurationProperties.class)));
}

@Test
void assertPreValidateAlterRenamedView() {
OpenGaussAlterViewStatement selectStatement = new OpenGaussAlterViewStatement();
selectStatement.setView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order"))));
selectStatement.setRenameView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_new"))));
SQLStatementContext sqlStatementContext = new AlterViewStatementContext(selectStatement, DefaultDatabase.LOGIC_NAME);
OpenGaussAlterViewStatement sqlStatement = new OpenGaussAlterViewStatement();
sqlStatement.setView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_view"))));
sqlStatement.setRenameView(new SimpleTableSegment(new TableNameSegment(0, 0, new IdentifierValue("t_order_new"))));
SQLStatementContext sqlStatementContext = new AlterViewStatementContext(sqlStatement, DefaultDatabase.LOGIC_NAME);
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
assertDoesNotThrow(() -> new ShardingAlterViewStatementValidator().preValidate(shardingRule, sqlStatementContext, Collections.emptyList(), database, mock(ConfigurationProperties.class)));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!--
~ 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.
-->

<dataset>
<metadata>
<column name="View" />
<column name="Create View" />
<column name="character_set_client" />
<column name="collation_connection" />
</metadata>
<row values="t_order_sharding_view, CREATE ALGORITHM=UNDEFINED DEFINER=`test_user`@`%` SQL SECURITY DEFINER VIEW `t_order_sharding_view` AS select `o`.`order_id` AS `order_id`,`o`.`user_id` AS `user_id`,`o`.`status` AS `status`,`o`.`merchant_id` AS `merchant_id`,`o`.`remark` AS `remark`,`o`.`creation_date` AS `creation_date` from (`t_order` `o` join `t_order_item` `i` on((`o`.`order_id` = `i`.`order_id`))), utf8mb4, utf8mb4_0900_ai_ci" />
</dataset>
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<!--
~ 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.
-->

<dataset>
<metadata>
<column name="View" />
<column name="Create View" />
<column name="character_set_client" />
<column name="collation_connection" />
</metadata>
<row values="t_order_sharding_view, CREATE ALGORITHM=UNDEFINED DEFINER=`test_user`@`%` SQL SECURITY DEFINER VIEW `t_order_sharding_view` AS select `o`.`order_id` AS `order_id`,`o`.`user_id` AS `user_id`,`o`.`status` AS `status`,`o`.`merchant_id` AS `merchant_id`,`o`.`remark` AS `remark`,`o`.`creation_date` AS `creation_date` from (`t_order` `o` join `t_order_item` `i` on((`o`.`order_id` = `i`.`order_id`))), utf8mb4, utf8mb4_0900_ai_ci" />
</dataset>
Loading