You are viewing a plain text version of this content. The canonical link for it is here.
Posted to notifications@shardingsphere.apache.org by zh...@apache.org on 2026/10/29 16:52:13 UTC
(shardingsphere) branch master updated: Fix database resolution for PREVIEW without USE (#40417)
This is an automated email from the ASF dual-hosted git repository.
terrymanu pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/shardingsphere.git
The following commit(s) were added to refs/heads/master by this push:
new 858b475a189 Fix database resolution for PREVIEW without USE (#40417)
858b475a189 is described below
commit 858b475a1892a65102126834da91441aae77a7c8
Author: Liang Zhang <zh...@apache.org>
AuthorDate: Fri Oct 30 00:52:07 2026 +0800
Fix database resolution for PREVIEW without USE (#40417)
---
.../dml/from/type/SimpleTableSegmentBinder.java | 2 +-
.../from/type/SimpleTableSegmentBinderTest.java | 11 ++
.../handler/executor/preview/PreviewExecutor.java | 18 ++--
.../DistSQLQueryProxyBackendHandlerTest.java | 53 ++++++++++
.../handler/distsql/rul/PreviewExecutorTest.java | 112 ++++++++++++++++++---
5 files changed, 170 insertions(+), 26 deletions(-)
diff --git a/infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinder.java b/infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinder.java
index 418dfce2d50..a3b5d20b1bc 100644
--- a/infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinder.java
+++ b/infra/binder/core/src/main/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinder.java
@@ -134,7 +134,7 @@ public final class SimpleTableSegmentBinder {
Optional<OwnerSegment> owner = dialectDatabaseMetaData.getSchemaOption().getDefaultSchema().isPresent() ? segment.getOwner().flatMap(OwnerSegment::getOwner) : segment.getOwner();
IdentifierValue result = ownerDatabaseName.orElseGet(() -> new IdentifierValue(owner.map(optional -> optional.getIdentifier().getValue()).orElse(binderContext.getCurrentDatabaseName())));
ShardingSpherePreconditions.checkNotNull(result.getValue(), NoDatabaseSelectedException::new);
- if (binderContext.getHintValueContext().isSkipMetadataValidate() && !binderContext.getMetaData().containsDatabase(result)) {
+ if (binderContext.getHintValueContext().isSkipMetadataValidate() && null != binderContext.getCurrentDatabaseName() && !binderContext.getMetaData().containsDatabase(result)) {
return new IdentifierValue(binderContext.getCurrentDatabaseName());
}
ShardingSpherePreconditions.checkState(binderContext.getMetaData().containsDatabase(result), () -> new UnknownDatabaseException(result.getValue()));
diff --git a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinderTest.java b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinderTest.java
index 4b7e845f7e4..9ab3854cd03 100644
--- a/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinderTest.java
+++ b/infra/binder/core/src/test/java/org/apache/shardingsphere/infra/binder/engine/segment/dml/from/type/SimpleTableSegmentBinderTest.java
@@ -21,6 +21,7 @@ import com.cedarsoftware.util.CaseInsensitiveMap.CaseInsensitiveString;
import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import org.apache.shardingsphere.database.connector.core.type.DatabaseType;
+import org.apache.shardingsphere.database.exception.core.exception.syntax.database.UnknownDatabaseException;
import org.apache.shardingsphere.infra.binder.engine.segment.dml.from.context.TableSegmentBinderContext;
import org.apache.shardingsphere.infra.binder.engine.segment.dml.from.context.type.SimpleTableSegmentBinderContext;
import org.apache.shardingsphere.infra.binder.engine.statement.SQLStatementBinderContext;
@@ -81,6 +82,16 @@ class SimpleTableSegmentBinderTest {
assertTrue(((SimpleTableSegmentBinderContext) tableBinderContexts.values().iterator().next()).isSkipColumnBind());
}
+ @Test
+ void assertBindUnknownOwnerWithoutCurrentDatabase() {
+ SimpleTableSegment simpleTableSegment = new SimpleTableSegment(new TableNameSegment(11, 19, new IdentifierValue("foo_table")));
+ simpleTableSegment.setOwner(new OwnerSegment(0, 9, new IdentifierValue("unknown_db")));
+ HintValueContext hintValueContext = new HintValueContext();
+ hintValueContext.setSkipMetadataValidate(true);
+ SQLStatementBinderContext binderContext = new SQLStatementBinderContext(createMetaData(), null, hintValueContext, SelectStatement.builder().databaseType(databaseType).build());
+ assertThrows(UnknownDatabaseException.class, () -> SimpleTableSegmentBinder.bind(simpleTableSegment, binderContext, LinkedHashMultimap.create()));
+ }
+
@Test
void assertBindWithDBLinkContainsDBLink() {
SimpleTableSegment simpleTableSegment = new SimpleTableSegment(new TableNameSegment(0, 10, new IdentifierValue("t_not_exists")));
diff --git a/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/preview/PreviewExecutor.java b/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/preview/PreviewExecutor.java
index 2399d5adaad..3929a9a4f46 100644
--- a/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/preview/PreviewExecutor.java
+++ b/infra/distsql-handler/src/main/java/org/apache/shardingsphere/distsql/handler/executor/preview/PreviewExecutor.java
@@ -21,7 +21,6 @@ import com.google.common.base.Preconditions;
import lombok.Setter;
import org.apache.shardingsphere.distsql.handler.context.DistSQLConnectionContext;
import org.apache.shardingsphere.distsql.handler.executor.aware.DistSQLExecutorConnectionContextAware;
-import org.apache.shardingsphere.distsql.handler.executor.aware.DistSQLExecutorDatabaseAware;
import org.apache.shardingsphere.distsql.handler.executor.preview.spi.PreviewExecutionUnitGenerator;
import org.apache.shardingsphere.distsql.handler.executor.spi.query.DistSQLQueryExecutor;
import org.apache.shardingsphere.distsql.statement.type.rul.sql.PreviewStatement;
@@ -55,9 +54,7 @@ import java.util.stream.Collectors;
* Preview executor.
*/
@Setter
-public final class PreviewExecutor implements DistSQLQueryExecutor<PreviewStatement>, DistSQLExecutorDatabaseAware, DistSQLExecutorConnectionContextAware {
-
- private ShardingSphereDatabase database;
+public final class PreviewExecutor implements DistSQLQueryExecutor<PreviewStatement>, DistSQLExecutorConnectionContextAware {
private DistSQLConnectionContext connectionContext;
@@ -70,19 +67,21 @@ public final class PreviewExecutor implements DistSQLQueryExecutor<PreviewStatem
public Collection<LocalDataQueryResultRow> getRows(final PreviewStatement sqlStatement, final ContextManager contextManager) {
ShardingSphereMetaData metaData = contextManager.getMetaDataContexts().getMetaData();
String toBePreviewedSQL = sqlStatement.getSql();
- SQLStatement toBePreviewedStatement = metaData.getGlobalRuleMetaData().getSingleRule(SQLParserRule.class).getSQLParserEngine(database.getProtocolType()).parse(toBePreviewedSQL, false);
+ SQLStatement toBePreviewedStatement =
+ metaData.getGlobalRuleMetaData().getSingleRule(SQLParserRule.class).getSQLParserEngine(connectionContext.getProtocolType()).parse(toBePreviewedSQL, false);
HintValueContext hintValueContext = connectionContext.getQueryContext().getHintValueContext();
hintValueContext.setSkipMetadataValidate(true);
String currentDatabaseName = connectionContext.getQueryContext().getConnectionContext().getCurrentDatabaseName().orElse(null);
SQLStatementContext toBePreviewedStatementContext = new SQLBindEngine(metaData, currentDatabaseName, hintValueContext).bind(toBePreviewedStatement);
- QueryContext queryContext = new QueryContext(
- toBePreviewedStatementContext, toBePreviewedSQL, Collections.emptyList(), hintValueContext, connectionContext.getQueryContext().getConnectionContext(), metaData);
if (toBePreviewedStatementContext.getSqlStatement().getAttributes().findAttribute(CursorSQLStatementAttribute.class).isPresent()
&& toBePreviewedStatementContext instanceof CursorHeldSQLStatementContext) {
setUpCursorDefinition((CursorHeldSQLStatementContext) toBePreviewedStatementContext);
}
+ QueryContext queryContext = new QueryContext(
+ toBePreviewedStatementContext, toBePreviewedSQL, Collections.emptyList(), hintValueContext, connectionContext.getQueryContext().getConnectionContext(), metaData);
+ ShardingSphereDatabase database = queryContext.getUsedDatabaseNames().size() > 1 ? contextManager.getDatabase(currentDatabaseName) : queryContext.getUsedDatabase();
ShardingSpherePreconditions.checkState(database.isComplete(), () -> new EmptyRuleException(database.getName()));
- Collection<ExecutionUnit> executionUnits = getExecutionUnits(contextManager, metaData, queryContext);
+ Collection<ExecutionUnit> executionUnits = getExecutionUnits(contextManager, metaData, queryContext, database);
return executionUnits.stream().map(each -> new LocalDataQueryResultRow(each.getDataSourceName(), each.getSqlUnit().getSql())).collect(Collectors.toList());
}
@@ -97,7 +96,8 @@ public final class PreviewExecutor implements DistSQLQueryExecutor<PreviewStatem
toBePreviewedStatementContext.setCursorStatementContext(cursorStatementContext);
}
- private Collection<ExecutionUnit> getExecutionUnits(final ContextManager contextManager, final ShardingSphereMetaData metaData, final QueryContext queryContext) {
+ private Collection<ExecutionUnit> getExecutionUnits(final ContextManager contextManager, final ShardingSphereMetaData metaData, final QueryContext queryContext,
+ final ShardingSphereDatabase database) {
for (PreviewExecutionUnitGenerator each : ShardingSphereServiceLoader.getServiceInstances(PreviewExecutionUnitGenerator.class)) {
Optional<Collection<ExecutionUnit>> result = each.generate(database, queryContext, contextManager, connectionContext);
if (result.isPresent()) {
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryProxyBackendHandlerTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryProxyBackendHandlerTest.java
index 5bd4fd09519..40dc3e2b3b7 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryProxyBackendHandlerTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/DistSQLQueryProxyBackendHandlerTest.java
@@ -25,8 +25,14 @@ import org.apache.shardingsphere.distsql.statement.DistSQLStatement;
import org.apache.shardingsphere.distsql.statement.type.ral.queryable.QueryableRALStatement;
import org.apache.shardingsphere.distsql.statement.type.ral.queryable.export.ExportDatabaseConfigurationStatement;
import org.apache.shardingsphere.distsql.statement.type.ral.queryable.show.ShowTableMetaDataStatement;
+import org.apache.shardingsphere.distsql.statement.type.rul.sql.PreviewStatement;
import org.apache.shardingsphere.infra.config.mode.ModeConfiguration;
import org.apache.shardingsphere.infra.config.props.ConfigurationProperties;
+import org.apache.shardingsphere.infra.connection.kernel.KernelProcessor;
+import org.apache.shardingsphere.infra.executor.sql.context.ExecutionContext;
+import org.apache.shardingsphere.infra.executor.sql.context.ExecutionUnit;
+import org.apache.shardingsphere.infra.executor.sql.context.SQLUnit;
+import org.apache.shardingsphere.infra.hint.HintValueContext;
import org.apache.shardingsphere.infra.instance.ComputeNodeInstanceContext;
import org.apache.shardingsphere.infra.merge.result.impl.local.LocalDataQueryResultRow;
import org.apache.shardingsphere.infra.metadata.ShardingSphereMetaData;
@@ -38,11 +44,17 @@ import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSp
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereSchema;
import org.apache.shardingsphere.infra.metadata.database.schema.model.ShardingSphereTable;
import org.apache.shardingsphere.infra.metadata.statistics.ShardingSphereStatistics;
+import org.apache.shardingsphere.infra.route.context.RouteContext;
+import org.apache.shardingsphere.infra.session.connection.ConnectionContext;
+import org.apache.shardingsphere.infra.session.query.QueryContext;
import org.apache.shardingsphere.infra.spi.exception.ServiceProviderNotFoundException;
import org.apache.shardingsphere.infra.spi.type.typed.TypedSPILoader;
import org.apache.shardingsphere.mode.manager.ContextManager;
import org.apache.shardingsphere.mode.metadata.MetaDataContexts;
import org.apache.shardingsphere.mode.spi.repository.PersistRepository;
+import org.apache.shardingsphere.parser.rule.SQLParserRule;
+import org.apache.shardingsphere.parser.rule.builder.DefaultSQLParserRuleConfigurationBuilder;
+import org.apache.shardingsphere.proxy.backend.distsql.DistSQLStatementContext;
import org.apache.shardingsphere.proxy.backend.response.data.QueryResponseRow;
import org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
@@ -50,7 +62,9 @@ import org.apache.shardingsphere.sql.parser.statement.core.segment.dal.FromDatab
import org.apache.shardingsphere.sql.parser.statement.core.segment.generic.DatabaseSegment;
import org.apache.shardingsphere.sql.parser.statement.core.statement.attribute.SQLStatementAttributes;
import org.apache.shardingsphere.sql.parser.statement.core.value.identifier.IdentifierValue;
+import org.apache.shardingsphere.sqlfederation.engine.SQLFederationEngine;
import org.junit.jupiter.api.Test;
+import org.mockito.MockedConstruction;
import org.mockito.MockedStatic;
import java.sql.SQLException;
@@ -65,8 +79,10 @@ import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
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;
+import static org.mockito.Mockito.mockConstruction;
import static org.mockito.Mockito.mockStatic;
import static org.mockito.Mockito.when;
@@ -110,6 +126,43 @@ class DistSQLQueryProxyBackendHandlerTest {
assertDoesNotThrow(() -> new DistSQLQueryProxyBackendHandler(createSqlStatement(), mock(), mock(ConnectionSession.class, RETURNS_DEEP_STUBS), contextManager).execute());
}
+ @Test
+ void assertExecutePreviewWithQualifiedTableAndNoDatabase() throws SQLException {
+ DatabaseType mysqlDatabaseType = TypedSPILoader.getService(DatabaseType.class, "MySQL");
+ ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
+ when(database.getName()).thenReturn("foo_db");
+ when(database.isComplete()).thenReturn(true);
+ when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.emptyList()));
+ when(database.getDefaultSchemaName()).thenReturn("foo_db");
+ when(database.getSchema(any(IdentifierValue.class))).thenReturn(new ShardingSphereSchema("foo_db", mysqlDatabaseType));
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(Collections.singleton(database), mock(),
+ new RuleMetaData(Collections.singleton(new SQLParserRule(new DefaultSQLParserRuleConfigurationBuilder().build()))), new ConfigurationProperties(new Properties()));
+ ContextManager contextManager = mock(ContextManager.class, RETURNS_DEEP_STUBS);
+ when(contextManager.getMetaDataContexts().getMetaData()).thenReturn(metaData);
+ ConnectionContext connectionContext = new ConnectionContext(Collections::emptyList);
+ ConnectionSession connectionSession = mock(ConnectionSession.class, RETURNS_DEEP_STUBS);
+ when(connectionSession.getProtocolType()).thenReturn(mysqlDatabaseType);
+ PreviewStatement sqlStatement = new PreviewStatement("SELECT 1 FROM foo_db.foo_table FOR UPDATE");
+ QueryContext queryContext = new QueryContext(new DistSQLStatementContext(sqlStatement), "PREVIEW " + sqlStatement.getSql(), Collections.emptyList(),
+ new HintValueContext(), connectionContext, metaData);
+ ExecutionUnit executionUnit = new ExecutionUnit("foo_ds", new SQLUnit("SELECT 1 FROM foo_table FOR UPDATE", Collections.emptyList()));
+ ExecutionContext executionContext = new ExecutionContext(mock(QueryContext.class), Collections.singletonList(executionUnit), mock(RouteContext.class));
+ try (
+ MockedConstruction<SQLFederationEngine> ignoredFederationEngine = mockConstruction(SQLFederationEngine.class, (mock, context) -> {
+ assertThat(context.arguments().get(0), is("foo_db"));
+ when(mock.decide(any(QueryContext.class), any(RuleMetaData.class))).thenReturn(false);
+ });
+ MockedConstruction<KernelProcessor> ignoredKernelProcessor = mockConstruction(KernelProcessor.class,
+ (mock, context) -> when(mock.generateExecutionContext(any(QueryContext.class), any(RuleMetaData.class), any(ConfigurationProperties.class))).thenReturn(executionContext))) {
+ DistSQLQueryProxyBackendHandler handler = new DistSQLQueryProxyBackendHandler(sqlStatement, queryContext, connectionSession, contextManager);
+ handler.execute();
+ assertTrue(handler.next());
+ assertThat(handler.getRowData().getData(), contains("foo_ds", "SELECT 1 FROM foo_table FOR UPDATE"));
+ assertFalse(connectionContext.getCurrentDatabaseName().isPresent());
+ assertFalse(handler.next());
+ }
+ }
+
private Collection<ShardingSphereTable> createTables() {
Collection<ShardingSphereColumn> columns = Collections.singletonList(new ShardingSphereColumn("order_id", 0, false, false, false, true, false, false));
Collection<ShardingSphereIndex> indexes = Collections.singletonList(new ShardingSphereIndex("primary", Collections.emptyList(), false));
diff --git a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/rul/PreviewExecutorTest.java b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/rul/PreviewExecutorTest.java
index 5430ab919e9..ac720535800 100644
--- a/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/rul/PreviewExecutorTest.java
+++ b/proxy/backend/core/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/rul/PreviewExecutorTest.java
@@ -18,6 +18,8 @@
package org.apache.shardingsphere.proxy.backend.handler.distsql.rul;
import org.apache.shardingsphere.database.connector.core.type.DatabaseType;
+import org.apache.shardingsphere.database.exception.core.exception.syntax.database.NoDatabaseSelectedException;
+import org.apache.shardingsphere.database.exception.core.exception.syntax.database.UnknownDatabaseException;
import org.apache.shardingsphere.database.exception.core.exception.syntax.sql.DialectSQLParsingException;
import org.apache.shardingsphere.distsql.handler.context.DistSQLConnectionContext;
import org.apache.shardingsphere.distsql.handler.executor.preview.PreviewExecutor;
@@ -49,6 +51,7 @@ import org.apache.shardingsphere.infra.metadata.database.resource.ResourceMetaDa
import org.apache.shardingsphere.infra.metadata.database.resource.node.StorageNode;
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.route.context.RouteContext;
import org.apache.shardingsphere.infra.rule.ShardingSphereRule;
import org.apache.shardingsphere.infra.session.connection.ConnectionContext;
@@ -66,6 +69,8 @@ import org.apache.shardingsphere.sqlfederation.context.SQLFederationContext;
import org.apache.shardingsphere.sqlfederation.engine.SQLFederationEngine;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.CsvSource;
import org.mockito.MockedConstruction;
import org.mockito.invocation.InvocationOnMock;
@@ -83,7 +88,9 @@ import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.sameInstance;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
@@ -102,16 +109,21 @@ class PreviewExecutorTest {
private ContextManager contextManager;
+ private ConnectionContext connectionContext;
+
@BeforeEach
void setUp() {
- contextManager = mockContextManager();
+ contextManager = mockContextManager(mockCompleteDatabase());
+ connectionContext = new ConnectionContext(Collections::emptyList);
+ connectionContext.setCurrentDatabaseName("foo_db");
+ executor.setConnectionContext(mockConnectionContext(new HintValueContext(), connectionContext, mock(DatabaseConnectionManager.class)));
}
- private ContextManager mockContextManager() {
+ private ContextManager mockContextManager(final ShardingSphereDatabase... databases) {
ContextManager result = mock(ContextManager.class, RETURNS_DEEP_STUBS);
Collection<ShardingSphereRule> rules = Collections.singleton(new SQLParserRule(new DefaultSQLParserRuleConfigurationBuilder().build()));
- when(result.getMetaDataContexts().getMetaData()).thenReturn(
- new ShardingSphereMetaData(Collections.emptyList(), mock(), new RuleMetaData(rules), new ConfigurationProperties(new Properties())));
+ ShardingSphereMetaData metaData = new ShardingSphereMetaData(Arrays.asList(databases), mock(), new RuleMetaData(rules), new ConfigurationProperties(new Properties()));
+ when(result.getMetaDataContexts().getMetaData()).thenReturn(metaData);
return result;
}
@@ -122,34 +134,100 @@ class PreviewExecutorTest {
@Test
void assertGetRowsWithInvalidSQL() {
- ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
- when(database.getProtocolType()).thenReturn(databaseType);
- executor.setDatabase(database);
assertThrows(DialectSQLParsingException.class, () -> executor.getRows(new PreviewStatement("invalid sql"), contextManager));
}
@Test
void assertGetRowsWithIncompleteDatabase() {
ShardingSphereDatabase database = mock(ShardingSphereDatabase.class);
- when(database.getProtocolType()).thenReturn(databaseType);
when(database.getName()).thenReturn("foo_db");
- executor.setDatabase(database);
+ when(database.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.emptyList()));
+ contextManager = mockContextManager(database);
HintValueContext hintValueContext = new HintValueContext();
- executor.setConnectionContext(mockConnectionContext(hintValueContext, new ConnectionContext(Collections::emptyList), mock(DatabaseConnectionManager.class)));
+ executor.setConnectionContext(mockConnectionContext(hintValueContext, connectionContext, mock(DatabaseConnectionManager.class)));
assertThrows(EmptyRuleException.class, () -> executor.getRows(new PreviewStatement("SELECT 1"), contextManager));
assertTrue(hintValueContext.isSkipMetadataValidate());
}
+ @ParameterizedTest(name = "{0}, current database: {1}")
+ @CsvSource({"SELECT 1,", "SELECT 1 FROM foo_db.foo_table,", "SELECT 1 FROM foo_db.foo_table FOR UPDATE,", "SELECT 1 FROM foo_table,foo_db"})
+ void assertGetRowsWithDatabaseResolution(final String sql, final String currentDatabaseName) {
+ connectionContext = new ConnectionContext(Collections::emptyList);
+ connectionContext.setCurrentDatabaseName(currentDatabaseName);
+ executor.setConnectionContext(mockConnectionContext(new HintValueContext(), connectionContext, mock(DatabaseConnectionManager.class)));
+ ShardingSphereDatabase database = contextManager.getMetaDataContexts().getMetaData().getDatabase("foo_db");
+ ExecutionContext executionContext = new ExecutionContext(mock(QueryContext.class), Collections.singletonList(createExecutionUnit("foo_ds", "SELECT 1")), mock(RouteContext.class));
+ try (
+ MockedConstruction<SQLFederationEngine> ignoredFederationEngine = mockConstruction(SQLFederationEngine.class, (mock, context) -> {
+ assertThat(context.arguments().get(0), is("foo_db"));
+ when(mock.decide(any(QueryContext.class), any(RuleMetaData.class))).thenReturn(false);
+ });
+ MockedConstruction<KernelProcessor> ignoredKernelProcessor = mockConstruction(KernelProcessor.class,
+ (mock, context) -> when(mock.generateExecutionContext(any(QueryContext.class), any(RuleMetaData.class), any(ConfigurationProperties.class)))
+ .thenAnswer(invocation -> {
+ QueryContext actualQueryContext = invocation.getArgument(0);
+ assertThat(actualQueryContext.getUsedDatabase(), sameInstance(database));
+ return executionContext;
+ }))) {
+ assertThat(executor.getRows(new PreviewStatement(sql), contextManager).iterator().next().getCell(1), is("foo_ds"));
+ assertThat(connectionContext.getCurrentDatabaseName(), is(Optional.ofNullable(currentDatabaseName)));
+ }
+ }
+
+ @Test
+ void assertGetRowsWithNoDatabaseSelected() {
+ connectionContext = new ConnectionContext(Collections::emptyList);
+ executor.setConnectionContext(mockConnectionContext(new HintValueContext(), connectionContext, mock(DatabaseConnectionManager.class)));
+ assertThrows(NoDatabaseSelectedException.class, () -> executor.getRows(new PreviewStatement("SELECT 1 FROM foo_table"), contextManager));
+ }
+
+ @Test
+ void assertGetRowsWithUnknownDatabase() {
+ connectionContext.setCurrentDatabaseName("unknown_db");
+ assertThrows(UnknownDatabaseException.class, () -> executor.getRows(new PreviewStatement("SELECT 1"), contextManager));
+ }
+
+ @Test
+ void assertGetRowsWithUnknownQualifiedDatabase() {
+ connectionContext = new ConnectionContext(Collections::emptyList);
+ executor.setConnectionContext(mockConnectionContext(new HintValueContext(), connectionContext, mock(DatabaseConnectionManager.class)));
+ assertThrows(UnknownDatabaseException.class, () -> executor.getRows(new PreviewStatement("SELECT 1 FROM unknown_db.foo_table"), contextManager));
+ }
+
+ @Test
+ void assertGetRowsWithMultipleDatabasesWithFederation() {
+ ShardingSphereDatabase database = mockCompleteDatabase();
+ ShardingSphereDatabase otherDatabase = mockCompleteDatabase();
+ when(otherDatabase.getName()).thenReturn("bar_db");
+ contextManager = mockContextManager(database, otherDatabase);
+ when(contextManager.getDatabase("foo_db")).thenReturn(database);
+ AtomicReference<String> actualSchemaName = new AtomicReference<>();
+ try (
+ MockedConstruction<DriverExecutionPrepareEngine> ignoredPrepareEngine = mockConstruction(DriverExecutionPrepareEngine.class);
+ MockedConstruction<SQLFederationEngine> ignoredFederationEngine = mockConstruction(SQLFederationEngine.class, (mock, context) -> {
+ configureSQLFederationEngine(mock, context, actualSchemaName);
+ when(mock.decide(any(QueryContext.class), any(RuleMetaData.class))).thenAnswer(invocation -> {
+ QueryContext actualQueryContext = invocation.getArgument(0);
+ assertThat(actualQueryContext.getUsedDatabaseNames(), containsInAnyOrder("foo_db", "bar_db"));
+ return true;
+ });
+ })) {
+ assertThat(executor.getRows(new PreviewStatement("SELECT 1 FROM foo_db.foo_table, bar_db.bar_table"), contextManager).iterator().next().getCell(1), is("bar_ds"));
+ assertThat(actualSchemaName.get(), is("foo_db"));
+ }
+ }
+
@Test
void assertGetRowsWithCursorAttributeAndNotCursorHeld() {
HintValueContext hintValueContext = new HintValueContext();
ShardingSphereDatabase database = mockCompleteDatabase();
when(database.getDefaultSchemaName()).thenReturn("foo_default_schema");
- executor.setDatabase(database);
- executor.setConnectionContext(mockConnectionContext(hintValueContext, new ConnectionContext(Collections::emptyList), mock(DatabaseConnectionManager.class)));
+ contextManager = mockContextManager(database);
+ executor.setConnectionContext(mockConnectionContext(hintValueContext, connectionContext, mock(DatabaseConnectionManager.class)));
SQLStatement sqlStatement = mockSQLStatement(new CursorSQLStatementAttribute(null));
SQLStatementContext sqlStatementContext = mock(SQLStatementContext.class, RETURNS_DEEP_STUBS);
when(sqlStatementContext.getSqlStatement()).thenReturn(sqlStatement);
+ when(sqlStatementContext.getTablesContext().getDatabaseNames()).thenReturn(Collections.emptyList());
when(sqlStatementContext.getTablesContext().getSchemaName()).thenReturn(Optional.empty());
ExecutionContext executionContext = new ExecutionContext(mock(QueryContext.class), Collections.singletonList(createExecutionUnit("foo_ds", "SELECT 1")), mock(RouteContext.class));
try (
@@ -170,8 +248,7 @@ class PreviewExecutorTest {
@Test
void assertGetRowsWithCursorHeldAndNoCursorName() {
HintValueContext hintValueContext = new HintValueContext();
- executor.setDatabase(mockCompleteDatabase());
- executor.setConnectionContext(mockConnectionContext(hintValueContext, new ConnectionContext(Collections::emptyList), mock(DatabaseConnectionManager.class)));
+ executor.setConnectionContext(mockConnectionContext(hintValueContext, connectionContext, mock(DatabaseConnectionManager.class)));
SQLStatement sqlStatement = mockSQLStatement(new CursorSQLStatementAttribute(null));
CursorHeldSQLStatementContext cursorHeldSQLStatementContext = new CursorHeldSQLStatementContext(sqlStatement);
ExecutionContext executionContext = new ExecutionContext(mock(QueryContext.class), Collections.singletonList(createExecutionUnit("foo_ds", "SELECT 1")), mock(RouteContext.class));
@@ -189,14 +266,14 @@ class PreviewExecutorTest {
@Test
void assertGetRowsWithCursorHeldAndCursorNameWithFederation() {
- ConnectionContext connectionContext = new ConnectionContext(Collections::emptyList);
+ connectionContext = new ConnectionContext(Collections::emptyList);
CursorStatementContext cursorStatementContext = mock(CursorStatementContext.class);
TablesContext tablesContext = mock(TablesContext.class);
when(tablesContext.getSchemaName()).thenReturn(Optional.of("foo_schema"));
+ when(tablesContext.getDatabaseNames()).thenReturn(Collections.singleton("foo_db"));
when(cursorStatementContext.getTablesContext()).thenReturn(tablesContext);
connectionContext.getCursorContext().getCursorStatementContexts().put("foo_cursor", cursorStatementContext);
HintValueContext hintValueContext = new HintValueContext();
- executor.setDatabase(mockCompleteDatabase());
executor.setConnectionContext(mockConnectionContext(hintValueContext, connectionContext, mock(DatabaseConnectionManager.class)));
SQLStatement sqlStatement = mockSQLStatement(new CursorSQLStatementAttribute(new CursorNameSegment(0, 0, new IdentifierValue("FOO_CURSOR"))));
CursorHeldSQLStatementContext cursorHeldSQLStatementContext = new CursorHeldSQLStatementContext(sqlStatement);
@@ -219,6 +296,8 @@ class PreviewExecutorTest {
when(result.isComplete()).thenReturn(true);
when(result.getResourceMetaData()).thenReturn(createResourceMetaData());
when(result.getRuleMetaData()).thenReturn(new RuleMetaData(Collections.emptyList()));
+ when(result.getDefaultSchemaName()).thenReturn("foo_db");
+ when(result.getSchema(any(IdentifierValue.class))).thenReturn(new ShardingSphereSchema("foo_db", databaseType));
return result;
}
@@ -269,6 +348,7 @@ class PreviewExecutorTest {
}
private void configureSQLFederationEngine(final SQLFederationEngine federationEngine, final MockedConstruction.Context context, final AtomicReference<String> actualSchemaName) {
+ assertThat(context.arguments().get(0), is("foo_db"));
actualSchemaName.set(context.arguments().get(1).toString());
when(federationEngine.decide(any(QueryContext.class), any(RuleMetaData.class))).thenReturn(true);
doAnswer(this::executePreviewCallback).when(federationEngine).executeQuery(any(), any(), any(SQLFederationContext.class));