This is an automated email from the ASF dual-hosted git repository.
panjuan 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 7f339d77da8 Refactor ExportDatabaseConfigurationHandler (#23935)
7f339d77da8 is described below
commit 7f339d77da81c80e8827549f13046b66240db312
Author: Raigor <[email protected]>
AuthorDate: Thu Feb 2 17:33:26 2023 +0800
Refactor ExportDatabaseConfigurationHandler (#23935)
* Refactor ExportDatabaseConfigurationHandler.
* Refactor ExportDatabaseConfigurationHandler.
---
.../distsql/ral/RALBackendHandlerFactory.java | 3 -
...va => ExportDatabaseConfigurationExecutor.java} | 42 ++--
....distsql.handler.ral.query.QueryableRALExecutor | 3 +-
.../ExportDatabaseConfigurationExecutorTest.java | 139 +++++++++++++
.../ExportDatabaseConfigurationHandlerTest.java | 222 ---------------------
5 files changed, 156 insertions(+), 253 deletions(-)
diff --git
a/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/RALBackendHandlerFactory.java
b/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/RALBackendHandlerFactory.java
index 4a57e6fc9ad..a8953fb8b32 100644
---
a/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/RALBackendHandlerFactory.java
+++
b/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/RALBackendHandlerFactory.java
@@ -28,7 +28,6 @@ import
org.apache.shardingsphere.distsql.parser.statement.ral.HintRALStatement;
import
org.apache.shardingsphere.distsql.parser.statement.ral.QueryableGlobalRuleRALStatement;
import org.apache.shardingsphere.distsql.parser.statement.ral.RALStatement;
import
org.apache.shardingsphere.distsql.parser.statement.ral.UpdatableGlobalRuleRALStatement;
-import
org.apache.shardingsphere.distsql.parser.statement.ral.queryable.ExportDatabaseConfigurationStatement;
import
org.apache.shardingsphere.distsql.parser.statement.ral.queryable.ShowTableMetaDataStatement;
import
org.apache.shardingsphere.distsql.parser.statement.ral.scaling.QueryableScalingRALStatement;
import
org.apache.shardingsphere.distsql.parser.statement.ral.scaling.UpdatableScalingRALStatement;
@@ -49,7 +48,6 @@ import
org.apache.shardingsphere.proxy.backend.handler.ProxyBackendHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.hint.HintRALBackendHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.migration.query.QueryableScalingRALBackendHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.migration.update.UpdatableScalingRALBackendHandler;
-import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ExportDatabaseConfigurationHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowStatusFromReadwriteSplittingRulesHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowTableMetaDataHandler;
import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.updatable.AlterReadwriteSplittingStorageUnitStatusStatementHandler;
@@ -92,7 +90,6 @@ public final class RALBackendHandlerFactory {
HANDLERS.put(ImportDatabaseConfigurationStatement.class,
ImportDatabaseConfigurationHandler.class);
HANDLERS.put(ShowStatusFromReadwriteSplittingRulesStatement.class,
ShowStatusFromReadwriteSplittingRulesHandler.class);
HANDLERS.put(ShowTableMetaDataStatement.class,
ShowTableMetaDataHandler.class);
- HANDLERS.put(ExportDatabaseConfigurationStatement.class,
ExportDatabaseConfigurationHandler.class);
}
/**
diff --git
a/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandler.java
b/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutor.java
similarity index 81%
rename from
proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandler.java
rename to
proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutor.java
index 64107e0b651..d02cffd8b68 100644
---
a/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandler.java
+++
b/proxy/backend/src/main/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutor.java
@@ -17,10 +17,8 @@
package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable;
-import com.google.common.base.Strings;
import
org.apache.shardingsphere.dbdiscovery.api.config.DatabaseDiscoveryRuleConfiguration;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.NoDatabaseSelectedException;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.UnknownDatabaseException;
+import
org.apache.shardingsphere.distsql.handler.ral.query.DatabaseRequiredQueryableRALExecutor;
import
org.apache.shardingsphere.distsql.parser.statement.ral.queryable.ExportDatabaseConfigurationStatement;
import org.apache.shardingsphere.encrypt.api.config.EncryptRuleConfiguration;
import org.apache.shardingsphere.infra.config.rule.RuleConfiguration;
@@ -32,10 +30,7 @@ import
org.apache.shardingsphere.infra.util.spi.type.ordered.OrderedSPILoader;
import org.apache.shardingsphere.infra.util.yaml.YamlEngine;
import
org.apache.shardingsphere.infra.yaml.config.swapper.rule.YamlRuleConfigurationSwapper;
import org.apache.shardingsphere.mask.api.config.MaskRuleConfiguration;
-import org.apache.shardingsphere.mode.manager.ContextManager;
-import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
import org.apache.shardingsphere.proxy.backend.exception.FileIOException;
-import
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.AbstractQueryableRALBackendHandler;
import
org.apache.shardingsphere.readwritesplitting.api.ReadwriteSplittingRuleConfiguration;
import org.apache.shardingsphere.shadow.api.config.ShadowRuleConfiguration;
import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
@@ -50,41 +45,29 @@ import java.util.Collections;
import java.util.Map.Entry;
/**
- * Export database configuration handler.
+ * Export database configuration executor.
*/
-public final class ExportDatabaseConfigurationHandler extends
AbstractQueryableRALBackendHandler<ExportDatabaseConfigurationStatement> {
+public final class ExportDatabaseConfigurationExecutor implements
DatabaseRequiredQueryableRALExecutor<ExportDatabaseConfigurationStatement> {
@Override
- protected Collection<String> getColumnNames() {
+ public Collection<String> getColumnNames() {
return Collections.singleton("result");
}
@Override
- protected Collection<LocalDataQueryResultRow> getRows(final ContextManager
contextManager) {
- String exportedData = generateExportData(getDatabaseName());
- if (getSqlStatement().getFilePath().isPresent()) {
- String filePath = getSqlStatement().getFilePath().get();
+ public Collection<LocalDataQueryResultRow> getRows(final
ShardingSphereDatabase database, final ExportDatabaseConfigurationStatement
sqlStatement) {
+ String exportedData = generateExportData(database);
+ if (sqlStatement.getFilePath().isPresent()) {
+ String filePath = sqlStatement.getFilePath().get();
exportToFile(filePath, exportedData);
return Collections.singleton(new
LocalDataQueryResultRow(String.format("Successfully exported to:'%s'",
filePath)));
}
return Collections.singleton(new
LocalDataQueryResultRow(exportedData));
}
- private String getDatabaseName() {
- String result = getSqlStatement().getDatabase().isPresent() ?
getSqlStatement().getDatabase().get().getIdentifier().getValue() :
getConnectionSession().getDatabaseName();
- if (Strings.isNullOrEmpty(result)) {
- throw new NoDatabaseSelectedException();
- }
- if (!ProxyContext.getInstance().databaseExists(result)) {
- throw new UnknownDatabaseException(result);
- }
- return result;
- }
-
- private String generateExportData(final String databaseName) {
+ private String generateExportData(final ShardingSphereDatabase database) {
StringBuilder result = new StringBuilder();
- ShardingSphereDatabase database =
ProxyContext.getInstance().getDatabase(databaseName);
- appendDatabaseName(databaseName, result);
+ appendDatabaseName(database.getName(), result);
appendDataSourceConfigurations(database, result);
appendRuleConfigurations(database.getRuleMetaData().getConfigurations(),
result);
return result.toString();
@@ -159,4 +142,9 @@ public final class ExportDatabaseConfigurationHandler
extends AbstractQueryableR
throw new FileIOException(ex);
}
}
+
+ @Override
+ public String getType() {
+ return ExportDatabaseConfigurationStatement.class.getName();
+ }
}
diff --git
a/proxy/backend/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.query.QueryableRALExecutor
b/proxy/backend/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.query.QueryableRALExecutor
index 743044a4df3..d3b5bc44025 100644
---
a/proxy/backend/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.query.QueryableRALExecutor
+++
b/proxy/backend/src/main/resources/META-INF/services/org.apache.shardingsphere.distsql.handler.ral.query.QueryableRALExecutor
@@ -18,6 +18,7 @@
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowComputeNodesExecutor
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowComputeNodeInfoExecutor
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowComputeNodeModeExecutor
+org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ExportDatabaseConfigurationExecutor
+org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ConvertYamlConfigurationExecutor
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowDistVariableExecutor
org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ShowDistVariablesExecutor
-org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable.ConvertYamlConfigurationExecutor
diff --git
a/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutorTest.java
b/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutorTest.java
new file mode 100644
index 00000000000..c04ac93a139
--- /dev/null
+++
b/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationExecutorTest.java
@@ -0,0 +1,139 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You under the Apache License, Version 2.0
+ * (the "License"); you may not use this file except in compliance with
+ * the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable;
+
+import lombok.SneakyThrows;
+import
org.apache.shardingsphere.distsql.parser.statement.ral.queryable.ExportDatabaseConfigurationStatement;
+import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
+import
org.apache.shardingsphere.infra.merge.result.impl.local.LocalDataQueryResultRow;
+import
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
+import org.apache.shardingsphere.proxy.backend.util.ProxyContextRestorer;
+import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
+import
org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
+import
org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration;
+import
org.apache.shardingsphere.sharding.api.config.strategy.sharding.NoneShardingStrategyConfiguration;
+import
org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
+import
org.apache.shardingsphere.sql.parser.sql.common.segment.generic.DatabaseSegment;
+import
org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue;
+import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
+import org.apache.shardingsphere.test.util.PropertiesBuilder;
+import org.apache.shardingsphere.test.util.PropertiesBuilder.Property;
+import org.junit.Test;
+
+import javax.sql.DataSource;
+import java.io.BufferedReader;
+import java.io.FileReader;
+import java.io.IOException;
+import java.sql.SQLException;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Properties;
+
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+public final class ExportDatabaseConfigurationExecutorTest extends
ProxyContextRestorer {
+
+ private final ShardingSphereDatabase database =
mock(ShardingSphereDatabase.class, RETURNS_DEEP_STUBS);
+
+ @Test
+ public void assertGetColumns() {
+ Collection<String> columns = new
ExportDatabaseConfigurationExecutor().getColumnNames();
+ assertThat(columns.size(), is(1));
+ assertThat(columns.iterator().next(), is("result"));
+ }
+
+ @Test
+ public void assertExecute() throws SQLException {
+ when(database.getName()).thenReturn("normal_db");
+
when(database.getResourceMetaData().getDataSources()).thenReturn(createDataSourceMap());
+
when(database.getRuleMetaData().getConfigurations()).thenReturn(Collections.singleton(createShardingRuleConfiguration()));
+ Collection<LocalDataQueryResultRow> actual = new
ExportDatabaseConfigurationExecutor().getRows(database, new
ExportDatabaseConfigurationStatement(mock(DatabaseSegment.class), null));
+ assertThat(actual.size(), is(1));
+ LocalDataQueryResultRow row = actual.iterator().next();
+ assertThat(row.getCell(1), is(loadExpectedRow()));
+ }
+
+ @Test
+ public void assertExecuteWithEmptyDatabase() {
+ when(database.getName()).thenReturn("empty_db");
+
when(database.getResourceMetaData().getDataSources()).thenReturn(Collections.emptyMap());
+
when(database.getRuleMetaData().getConfigurations()).thenReturn(Collections.emptyList());
+ ExportDatabaseConfigurationStatement sqlStatement = new
ExportDatabaseConfigurationStatement(new DatabaseSegment(0, 0, new
IdentifierValue("empty_db")), null);
+ Collection<LocalDataQueryResultRow> actual = new
ExportDatabaseConfigurationExecutor().getRows(database, sqlStatement);
+ assertThat(actual.size(), is(1));
+ LocalDataQueryResultRow row = actual.iterator().next();
+ assertThat(row.getCell(1), is("databaseName: empty_db" +
System.lineSeparator()));
+ }
+
+ private Map<String, DataSource> createDataSourceMap() {
+ Map<String, DataSource> result = new LinkedHashMap<>(2, 1);
+ result.put("ds_0", createDataSource("demo_ds_0"));
+ result.put("ds_1", createDataSource("demo_ds_1"));
+ return result;
+ }
+
+ private DataSource createDataSource(final String name) {
+ MockedDataSource result = new MockedDataSource();
+ result.setUrl(String.format("jdbc:mock://127.0.0.1/%s", name));
+ result.setUsername("root");
+ result.setPassword("");
+ result.setMaxPoolSize(50);
+ result.setMinPoolSize(1);
+ return result;
+ }
+
+ private ShardingRuleConfiguration createShardingRuleConfiguration() {
+ ShardingRuleConfiguration result = new ShardingRuleConfiguration();
+ result.getTables().add(createTableRuleConfiguration());
+ result.setDefaultDatabaseShardingStrategy(new
StandardShardingStrategyConfiguration("order_id", "ds_inline"));
+ result.setDefaultTableShardingStrategy(new
NoneShardingStrategyConfiguration());
+ result.getKeyGenerators().put("snowflake", new
AlgorithmConfiguration("SNOWFLAKE", new Properties()));
+ result.getShardingAlgorithms().put("ds_inline", new
AlgorithmConfiguration("INLINE", PropertiesBuilder.build(new
Property("algorithm-expression", "ds_${order_id % 2}"))));
+ return result;
+ }
+
+ private ShardingTableRuleConfiguration createTableRuleConfiguration() {
+ ShardingTableRuleConfiguration result = new
ShardingTableRuleConfiguration("t_order", "ds_${0..1}.t_order_${0..1}");
+ result.setKeyGenerateStrategy(new
KeyGenerateStrategyConfiguration("order_id", "snowflake"));
+ return result;
+ }
+
+ @SneakyThrows(IOException.class)
+ private String loadExpectedRow() {
+ StringBuilder result = new StringBuilder();
+ String fileName =
Objects.requireNonNull(ExportDatabaseConfigurationExecutorTest.class.getResource("/expected/export-database-configuration.yaml")).getFile();
+ try (
+ FileReader fileReader = new FileReader(fileName);
+ BufferedReader reader = new BufferedReader(fileReader)) {
+ String line;
+ while (null != (line = reader.readLine())) {
+ if (!line.startsWith("#") && !"".equals(line.trim())) {
+ result.append(line).append(System.lineSeparator());
+ }
+ }
+ }
+ return result.toString();
+ }
+}
diff --git
a/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandlerTest.java
b/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandlerTest.java
deleted file mode 100644
index b97101855cf..00000000000
---
a/proxy/backend/src/test/java/org/apache/shardingsphere/proxy/backend/handler/distsql/ral/queryable/ExportDatabaseConfigurationHandlerTest.java
+++ /dev/null
@@ -1,222 +0,0 @@
-/*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements. See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License. You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.apache.shardingsphere.proxy.backend.handler.distsql.ral.queryable;
-
-import lombok.SneakyThrows;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.NoDatabaseSelectedException;
-import
org.apache.shardingsphere.dialect.exception.syntax.database.UnknownDatabaseException;
-import
org.apache.shardingsphere.distsql.parser.statement.ral.queryable.ExportDatabaseConfigurationStatement;
-import org.apache.shardingsphere.infra.config.algorithm.AlgorithmConfiguration;
-import
org.apache.shardingsphere.infra.metadata.database.ShardingSphereDatabase;
-import
org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereColumn;
-import
org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereIndex;
-import
org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereSchema;
-import
org.apache.shardingsphere.infra.metadata.database.schema.decorator.model.ShardingSphereTable;
-import org.apache.shardingsphere.mode.manager.ContextManager;
-import org.apache.shardingsphere.proxy.backend.context.ProxyContext;
-import
org.apache.shardingsphere.proxy.backend.response.header.query.QueryHeader;
-import
org.apache.shardingsphere.proxy.backend.response.header.query.QueryResponseHeader;
-import org.apache.shardingsphere.proxy.backend.session.ConnectionSession;
-import org.apache.shardingsphere.proxy.backend.util.ProxyContextRestorer;
-import org.apache.shardingsphere.sharding.api.config.ShardingRuleConfiguration;
-import
org.apache.shardingsphere.sharding.api.config.rule.ShardingTableRuleConfiguration;
-import
org.apache.shardingsphere.sharding.api.config.strategy.keygen.KeyGenerateStrategyConfiguration;
-import
org.apache.shardingsphere.sharding.api.config.strategy.sharding.NoneShardingStrategyConfiguration;
-import
org.apache.shardingsphere.sharding.api.config.strategy.sharding.StandardShardingStrategyConfiguration;
-import
org.apache.shardingsphere.sql.parser.sql.common.segment.generic.DatabaseSegment;
-import
org.apache.shardingsphere.sql.parser.sql.common.value.identifier.IdentifierValue;
-import org.apache.shardingsphere.test.fixture.jdbc.MockedDataSource;
-import org.apache.shardingsphere.test.util.PropertiesBuilder;
-import org.apache.shardingsphere.test.util.PropertiesBuilder.Property;
-import org.junit.Before;
-import org.junit.Test;
-
-import javax.sql.DataSource;
-import java.io.BufferedReader;
-import java.io.FileReader;
-import java.io.IOException;
-import java.sql.SQLException;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.LinkedHashMap;
-import java.util.Map;
-import java.util.Objects;
-import java.util.Properties;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.RETURNS_DEEP_STUBS;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public final class ExportDatabaseConfigurationHandlerTest extends
ProxyContextRestorer {
-
- @Before
- public void init() {
- ContextManager contextManager = mock(ContextManager.class,
RETURNS_DEEP_STUBS);
- Map<String, ShardingSphereDatabase> databases = createDatabases();
-
when(contextManager.getMetaDataContexts().getMetaData().getDatabases()).thenReturn(databases);
-
when(contextManager.getMetaDataContexts().getMetaData().containsDatabase("normal_db")).thenReturn(true);
-
when(contextManager.getMetaDataContexts().getMetaData().containsDatabase("empty_db")).thenReturn(true);
-
when(contextManager.getMetaDataContexts().getMetaData().getDatabase("normal_db")).thenReturn(databases.get("normal_db"));
-
when(contextManager.getMetaDataContexts().getMetaData().getDatabase("empty_db")).thenReturn(databases.get("empty_db"));
- ProxyContext.init(contextManager);
- }
-
- private Map<String, ShardingSphereDatabase> createDatabases() {
- Map<String, ShardingSphereDatabase> result = new HashMap<>(2, 1);
- result.put("normal_db", createNormalDatabase());
- result.put("empty_db", createEmptyDatabase());
- return result;
- }
-
- private ShardingSphereDatabase createNormalDatabase() {
- ShardingSphereDatabase result = mock(ShardingSphereDatabase.class,
RETURNS_DEEP_STUBS);
-
when(result.getResourceMetaData().getDataSources()).thenReturn(createDataSourceMap());
-
when(result.getRuleMetaData().getConfigurations()).thenReturn(Collections.singleton(createShardingRuleConfiguration()));
- when(result.getSchema("normal_db")).thenReturn(new
ShardingSphereSchema(createTables(), Collections.emptyMap()));
- return result;
- }
-
- private Map<String, DataSource> createDataSourceMap() {
- Map<String, DataSource> result = new LinkedHashMap<>(2, 1);
- result.put("ds_0", createDataSource("demo_ds_0"));
- result.put("ds_1", createDataSource("demo_ds_1"));
- return result;
- }
-
- private DataSource createDataSource(final String name) {
- MockedDataSource result = new MockedDataSource();
- result.setUrl(String.format("jdbc:mock://127.0.0.1/%s", name));
- result.setUsername("root");
- result.setPassword("");
- result.setMaxPoolSize(50);
- result.setMinPoolSize(1);
- return result;
- }
-
- private ShardingRuleConfiguration createShardingRuleConfiguration() {
- ShardingRuleConfiguration result = new ShardingRuleConfiguration();
- result.getTables().add(createTableRuleConfiguration());
- result.setDefaultDatabaseShardingStrategy(new
StandardShardingStrategyConfiguration("order_id", "ds_inline"));
- result.setDefaultTableShardingStrategy(new
NoneShardingStrategyConfiguration());
- result.getKeyGenerators().put("snowflake", new
AlgorithmConfiguration("SNOWFLAKE", new Properties()));
- result.getShardingAlgorithms().put("ds_inline", new
AlgorithmConfiguration("INLINE", PropertiesBuilder.build(new
Property("algorithm-expression", "ds_${order_id % 2}"))));
- return result;
- }
-
- private ShardingTableRuleConfiguration createTableRuleConfiguration() {
- ShardingTableRuleConfiguration result = new
ShardingTableRuleConfiguration("t_order", "ds_${0..1}.t_order_${0..1}");
- result.setKeyGenerateStrategy(new
KeyGenerateStrategyConfiguration("order_id", "snowflake"));
- return result;
- }
-
- private Map<String, ShardingSphereTable> createTables() {
- Collection<ShardingSphereColumn> columns = Collections.singleton(new
ShardingSphereColumn("order_id", 0, false, false, false, true, false));
- Collection<ShardingSphereIndex> indexes = Collections.singleton(new
ShardingSphereIndex("primary"));
- return Collections.singletonMap("t_order", new
ShardingSphereTable("t_order", columns, indexes, Collections.emptyList()));
- }
-
- private ShardingSphereDatabase createEmptyDatabase() {
- ShardingSphereDatabase result = mock(ShardingSphereDatabase.class,
RETURNS_DEEP_STUBS);
-
when(result.getResourceMetaData().getDataSources()).thenReturn(Collections.emptyMap());
-
when(result.getRuleMetaData().getConfigurations()).thenReturn(Collections.emptyList());
- return result;
- }
-
- @Test
- public void assertExecute() throws SQLException {
- ExportDatabaseConfigurationHandler handler = new
ExportDatabaseConfigurationHandler();
- handler.init(new ExportDatabaseConfigurationStatement(new
DatabaseSegment(0, 0, new IdentifierValue("normal_db")), null),
mock(ConnectionSession.class));
- assertQueryResponseHeader((QueryResponseHeader) handler.execute());
- assertTrue(handler.next());
- assertRowData(handler.getRowData().getData());
- assertFalse(handler.next());
- }
-
- private void assertQueryResponseHeader(final QueryResponseHeader actual) {
- assertThat(actual.getQueryHeaders().size(), is(1));
- assertQueryHeader(actual.getQueryHeaders().get(0));
- }
-
- private void assertQueryHeader(final QueryHeader actual) {
- assertThat(actual.getSchema(), is(""));
- assertThat(actual.getTable(), is(""));
- assertThat(actual.getColumnLabel(), is("result"));
- assertThat(actual.getColumnName(), is("result"));
- assertThat(actual.getColumnType(), is(1));
- assertThat(actual.getColumnTypeName(), is("CHAR"));
- assertThat(actual.getColumnLength(), is(255));
- assertThat(actual.getDecimals(), is(0));
- assertFalse(actual.isSigned());
- assertFalse(actual.isPrimaryKey());
- assertFalse(actual.isNotNull());
- assertFalse(actual.isAutoIncrement());
- }
-
- private void assertRowData(final Collection<Object> actual) {
- assertThat(actual.size(), is(1));
- assertThat(actual.iterator().next(), is(loadExpectedRow()));
- }
-
- @SneakyThrows(IOException.class)
- private String loadExpectedRow() {
- StringBuilder result = new StringBuilder();
- String fileName =
Objects.requireNonNull(ExportDatabaseConfigurationHandlerTest.class.getResource("/expected/export-database-configuration.yaml")).getFile();
- try (
- FileReader fileReader = new FileReader(fileName);
- BufferedReader reader = new BufferedReader(fileReader)) {
- String line;
- while (null != (line = reader.readLine())) {
- if (!line.startsWith("#") && !"".equals(line.trim())) {
- result.append(line).append(System.lineSeparator());
- }
- }
- }
- return result.toString();
- }
-
- @Test
- public void assertExecuteWithEmptyDatabase() throws SQLException {
- ExportDatabaseConfigurationHandler handler = new
ExportDatabaseConfigurationHandler();
- handler.init(new ExportDatabaseConfigurationStatement(new
DatabaseSegment(0, 0, new IdentifierValue("empty_db")), null),
mock(ConnectionSession.class));
- assertQueryResponseHeader((QueryResponseHeader) handler.execute());
- assertTrue(handler.next());
- Collection<Object> rowData = handler.getRowData().getData();
- assertThat(rowData.size(), is(1));
- assertThat(rowData.iterator().next(), is("databaseName: empty_db" +
System.lineSeparator()));
- assertFalse(handler.next());
- }
-
- @Test(expected = UnknownDatabaseException.class)
- public void assertExecuteWithNotExistedDatabase() {
- ExportDatabaseConfigurationHandler handler = new
ExportDatabaseConfigurationHandler();
- handler.init(new ExportDatabaseConfigurationStatement(new
DatabaseSegment(0, 0, new IdentifierValue("not_exist_db")), null),
mock(ConnectionSession.class));
- handler.execute();
- }
-
- @Test(expected = NoDatabaseSelectedException.class)
- public void assertExecuteWithNoDatabaseSelected() {
- ExportDatabaseConfigurationHandler handler = new
ExportDatabaseConfigurationHandler();
- handler.init(new ExportDatabaseConfigurationStatement(null, null),
mock(ConnectionSession.class));
- handler.execute();
- }
-}