提交 fb04f0db 编写于 作者: T terrymanu

remove dynamic table feature

上级 9a0a0a2e
......@@ -48,8 +48,6 @@ public final class ShardingJdbcDataSourceBeanDefinitionParserTag {
public static final String LOGIC_TABLES_ATTRIBUTE = "logic-tables";
public static final String DYNAMIC_TABLE_ATTRIBUTE = "dynamic";
public static final String ACTUAL_TABLES_ATTRIBUTE = "actual-tables";
public static final String DATA_SOURCE_NAMES_ATTRIBUTE = "data-source-names";
......
......@@ -107,10 +107,6 @@ public class ShardingJdbcDataSourceBeanDefinitionParser extends AbstractBeanDefi
private BeanDefinition parseTableRuleConfig(final Element tableElement) {
BeanDefinitionBuilder factory = BeanDefinitionBuilder.rootBeanDefinition(TableRuleConfig.class);
factory.addPropertyValue("logicTable", tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.LOGIC_TABLE_ATTRIBUTE));
String dynamic = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.DYNAMIC_TABLE_ATTRIBUTE);
if (!Strings.isNullOrEmpty(dynamic)) {
factory.addPropertyValue("dynamic", dynamic);
}
String actualTables = tableElement.getAttribute(ShardingJdbcDataSourceBeanDefinitionParserTag.ACTUAL_TABLES_ATTRIBUTE);
if (!Strings.isNullOrEmpty(actualTables)) {
factory.addPropertyValue("actualTables", actualTables);
......
......@@ -19,7 +19,6 @@ package com.dangdang.ddframe.rdb.sharding;
import com.dangdang.ddframe.rdb.sharding.spring.GenerateKeyDBUnitTest;
import com.dangdang.ddframe.rdb.sharding.spring.cases.WithNamespaceAlgorithmClassTest;
import com.dangdang.ddframe.rdb.sharding.spring.cases.WithNamespaceAlgorithmExpressionForDynamicTest;
import com.dangdang.ddframe.rdb.sharding.spring.cases.WithNamespaceAlgorithmExpressionTest;
import com.dangdang.ddframe.rdb.sharding.spring.cases.WithNamespaceBindingTablesTest;
import com.dangdang.ddframe.rdb.sharding.spring.cases.WithNamespaceDefaultStrategyTest;
......@@ -37,7 +36,6 @@ import org.junit.runners.Suite.SuiteClasses;
WithNamespaceAlgorithmClassTest.class,
WithNamespaceDifferentTablesTest.class,
WithNamespaceAlgorithmExpressionTest.class,
WithNamespaceAlgorithmExpressionForDynamicTest.class,
WithNamespaceDefaultStrategyTest.class,
WithNamespaceBindingTablesTest.class,
WithNamespaceDifferentTablesTest.class,
......
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.spring.cases;
import com.dangdang.ddframe.rdb.sharding.spring.AbstractShardingBothDataBasesAndTablesSpringDBUnitTest;
import org.springframework.test.context.ContextConfiguration;
@ContextConfiguration(locations = "classpath:META-INF/rdb/withNamespaceAlgorithmExpressionForDynamic.xml")
public final class WithNamespaceAlgorithmExpressionForDynamicTest extends AbstractShardingBothDataBasesAndTablesSpringDBUnitTest {
}
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:rdb="http://www.dangdang.com/schema/ddframe/rdb"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.dangdang.com/schema/ddframe/rdb
http://www.dangdang.com/schema/ddframe/rdb/rdb.xsd
">
<import resource="datasource/dataSource.xml" />
<rdb:strategy id="databaseStrategy" type="inline" sharding-columns="user_id" algorithm-expression="dbtbl_${user_id % 2}"/>
<rdb:strategy id="orderTableStrategy" type="inline" sharding-columns="order_id" algorithm-expression="t_order_${order_id % 4}"/>
<rdb:strategy id="orderItemTableStrategy" type="inline" sharding-columns="order_id" algorithm-expression="t_order_item_${order_id % 4}"/>
<rdb:data-source id="shardingDataSource">
<rdb:sharding-rule data-sources="dbtbl_0,dbtbl_1" default-data-source="dbtbl_0">
<rdb:table-rules>
<rdb:table-rule logic-table="t_order" dynamic="true" database-strategy="databaseStrategy" table-strategy="orderTableStrategy"/>
<rdb:table-rule logic-table="t_order_item" dynamic="true" database-strategy="databaseStrategy" table-strategy="orderItemTableStrategy"/>
</rdb:table-rules>
</rdb:sharding-rule>
</rdb:data-source>
</beans>
......@@ -16,8 +16,6 @@ public class YamlTableRuleConfig {
private String logicTable;
private boolean dynamic;
private String actualTables;
private String dataSourceNames;
......@@ -39,7 +37,6 @@ public class YamlTableRuleConfig {
Preconditions.checkNotNull(logicTable, "Logic table cannot be null.");
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable(logicTable);
tableRuleConfig.setDynamic(dynamic);
tableRuleConfig.setActualTables(actualTables);
tableRuleConfig.setLogicTable(logicTable);
if (null != databaseStrategy) {
......
......@@ -22,13 +22,10 @@ import com.dangdang.ddframe.rdb.sharding.exception.ShardingJdbcException;
import com.dangdang.ddframe.rdb.sharding.jdbc.core.ShardingContext;
import com.dangdang.ddframe.rdb.sharding.jdbc.core.datasource.ShardingDataSource;
import com.dangdang.ddframe.rdb.sharding.rule.BindingTableRule;
import com.dangdang.ddframe.rdb.sharding.rule.DynamicDataNode;
import com.dangdang.ddframe.rdb.sharding.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.rule.TableRule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.dbcp.BasicDataSource;
import org.h2.Driver;
import org.junit.Ignore;
import org.junit.Test;
import javax.sql.DataSource;
......@@ -43,9 +40,7 @@ import java.util.Map;
import static org.hamcrest.Matchers.hasItems;
import static org.hamcrest.core.Is.is;
import static org.hamcrest.core.IsCollectionContaining.hasItem;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.fail;
@Slf4j
public class YamlShardingDataSourceTest {
......@@ -67,34 +62,6 @@ public class YamlShardingDataSourceTest {
assertThat(shardingRule.getTableRules().size(), is(1));
}
@Test
@Ignore
public void assertDynamic() throws IOException, ReflectiveOperationException, URISyntaxException, SQLException {
Map<String, DataSource> dataSourceMap = new HashMap<>(1);
dataSourceMap.put("ds", createDataSource());
ShardingRule shardingRule = getShardingRule(dataSourceMap, "/config/config-dynamic.yaml");
int i = 0;
for (TableRule each : shardingRule.getTableRules()) {
i++;
assertThat(each.getActualDataNodes().size(), is(2));
assertThat(each.getActualDataNodes(), hasItem(new DynamicDataNode("db0")));
assertThat(each.getActualDataNodes(), hasItem(new DynamicDataNode("db1")));
switch (i) {
case 1:
assertThat(each.getLogicTable(), is("config"));
break;
case 2:
assertThat(each.getLogicTable(), is("t_order"));
break;
case 3:
assertThat(each.getLogicTable(), is("t_order_item"));
break;
default:
fail();
}
}
}
@Test(expected = ShardingJdbcException.class)
public void assertClassNotFound() throws IOException, NoSuchFieldException, IllegalAccessException, URISyntaxException, SQLException {
getShardingRule("/config/config-classNotFound.yaml");
......
......@@ -43,8 +43,6 @@ public class TableRuleConfig {
private String logicTable;
private boolean dynamic;
private String actualTables;
private String dataSourceNames;
......@@ -70,6 +68,6 @@ public class TableRuleConfig {
ShardingStrategy databaseShardingStrategy = null == databaseShardingStrategyConfig ? null : databaseShardingStrategyConfig.build();
ShardingStrategy tableShardingStrategy = null == tableShardingStrategyConfig ? null : tableShardingStrategyConfig.build();
KeyGenerator keyGenerator = !Strings.isNullOrEmpty(keyGeneratorColumnName) && !Strings.isNullOrEmpty(keyGeneratorClass) ? KeyGeneratorFactory.newInstance(keyGeneratorClass) : null;
return new TableRule(logicTable, dynamic, actualTables, dataSourceNames, dataSourceMap, databaseShardingStrategy, tableShardingStrategy, keyGeneratorColumnName, keyGenerator);
return new TableRule(logicTable, actualTables, dataSourceNames, dataSourceMap, databaseShardingStrategy, tableShardingStrategy, keyGeneratorColumnName, keyGenerator);
}
}
......@@ -36,7 +36,6 @@ import lombok.RequiredArgsConstructor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
......@@ -123,10 +122,7 @@ public final class SimpleRoutingEngine implements RoutingEngine {
}
private Collection<DataNode> routeTables(final TableRule tableRule, final String routedDataSource, final List<ShardingValue> tableShardingValues) {
if (tableShardingValues.isEmpty() && tableRule.isDynamic()) {
throw new UnsupportedOperationException("Dynamic table should contain sharding value.");
}
Collection<String> availableTargetTables = tableRule.isDynamic() ? Collections.<String>emptyList() : tableRule.getActualTableNames(routedDataSource);
Collection<String> availableTargetTables = tableRule.getActualTableNames(routedDataSource);
Collection<String> routedTables = tableShardingValues.isEmpty() ? availableTargetTables
: shardingRule.getTableShardingStrategy(tableRule).doSharding(availableTargetTables, tableShardingValues);
Preconditions.checkState(!routedTables.isEmpty(), "no table route info");
......
......@@ -65,9 +65,6 @@ public final class BindingTableRule {
public String getBindingActualTable(final String dataSource, final String logicTable, final String otherActualTable) {
int index = -1;
for (TableRule each : tableRules) {
if (each.isDynamic()) {
throw new UnsupportedOperationException("Dynamic table cannot support Binding table.");
}
index = each.findActualTableIndex(dataSource, otherActualTable);
if (-1 != index) {
break;
......
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.rule;
/**
* Dynamic Sharding data unit node.
*
* <p>Dynamic data node do not need configure actual tables, it will get actual tables depended on sharding algorithm.</p>
*
* @author zhangliang
*/
public final class DynamicDataNode extends DataNode {
private static final String DYNAMIC_TABLE_PLACEHOLDER = "SHARDING_JDBC DYNAMIC_TABLE_PLACEHOLDER";
/**
* Constructs a data node with data source name, actual table is unnecessary.
*
* @param dataSourceName data source name
*/
public DynamicDataNode(final String dataSourceName) {
super(dataSourceName, DYNAMIC_TABLE_PLACEHOLDER);
}
}
......@@ -128,7 +128,7 @@ public final class ShardingRule {
config.setLogicTable(logicTableName);
config.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfig());
config.setTableShardingStrategyConfig(new NoneShardingStrategyConfig());
return new TableRule(logicTableName, false, null, null, defaultDataSourceMap, null, null, null, null);
return new TableRule(logicTableName, null, null, defaultDataSourceMap, null, null, null, null);
}
/**
......
......@@ -41,8 +41,6 @@ public final class TableRule {
private final String logicTable;
private final boolean dynamic;
private final List<DataNode> actualDataNodes;
private final ShardingStrategy databaseShardingStrategy;
......@@ -53,13 +51,10 @@ public final class TableRule {
private final KeyGenerator keyGenerator;
public TableRule(final String logicTable, final boolean dynamic, final List<String> actualTables, final List<String> actualDataSources, final Map<String, DataSource> dataSourceMap,
public TableRule(final String logicTable, final List<String> actualTables, final List<String> actualDataSources, final Map<String, DataSource> dataSourceMap,
final ShardingStrategy databaseShardingStrategy, final ShardingStrategy tableShardingStrategy, final String generateKeyColumn, final KeyGenerator keyGenerator) {
this.logicTable = logicTable;
this.dynamic = dynamic;
if (dynamic) {
actualDataNodes = generateDataNodes(dataSourceMap);
} else if (null == actualTables || actualTables.isEmpty()) {
if (null == actualTables || actualTables.isEmpty()) {
actualDataNodes = generateDataNodes(Collections.singletonList(logicTable), dataSourceMap, actualDataSources);
} else {
actualDataNodes = generateDataNodes(actualTables, dataSourceMap, actualDataSources);
......@@ -70,14 +65,6 @@ public final class TableRule {
this.keyGenerator = keyGenerator;
}
private List<DataNode> generateDataNodes(final Map<String, DataSource> dataSourceMap) {
List<DataNode> result = new ArrayList<>(dataSourceMap.size());
for (String each : dataSourceMap.keySet()) {
result.add(new DynamicDataNode(each));
}
return result;
}
private List<DataNode> generateDataNodes(final List<String> actualTables, final Map<String, DataSource> dataSourceMap, final Collection<String> actualDataSourceNames) {
Collection<String> dataSourceNames = getDataSourceNames(dataSourceMap, actualDataSourceNames);
List<DataNode> result = new ArrayList<>(actualTables.size() * (dataSourceNames.isEmpty() ? 1 : dataSourceNames.size()));
......
......@@ -120,9 +120,6 @@ public abstract class AbstractSQLAssertTest extends AbstractSQLTest {
//CHECKSTYLE:OFF
} catch (final Exception ex) {
//CHECKSTYLE:ON
if (null != ex.getMessage() && ex.getMessage().startsWith("Dynamic table")) {
continue;
}
ex.printStackTrace();
throw new RuntimeException(ex);
}
......
......@@ -19,7 +19,6 @@ package com.dangdang.ddframe.rdb.integrate;
import com.dangdang.ddframe.rdb.integrate.type.ms.MasterSlaveOnlyTest;
import com.dangdang.ddframe.rdb.integrate.type.sharding.NullableShardingTableOnlyTest;
import com.dangdang.ddframe.rdb.integrate.type.sharding.ShardingDatabaseAndTableDynamicTest;
import com.dangdang.ddframe.rdb.integrate.type.sharding.ShardingDatabaseAndTableTest;
import com.dangdang.ddframe.rdb.integrate.type.sharding.ShardingDatabaseOnlyTest;
import com.dangdang.ddframe.rdb.integrate.type.sharding.ShardingMasterSlaveTest;
......@@ -36,7 +35,6 @@ import org.junit.runners.Suite.SuiteClasses;
ShardingMasterSlaveTest.class,
MasterSlaveOnlyTest.class,
ShardingDatabaseAndTableTest.class,
ShardingDatabaseAndTableDynamicTest.class,
NullableShardingTableOnlyTest.class,
AllHintDatabaseOnlyTests.class
})
......
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.integrate.fixture;
import com.dangdang.ddframe.rdb.sharding.api.strategy.PreciseShardingValue;
import com.dangdang.ddframe.rdb.sharding.routing.strategy.standard.PreciseShardingAlgorithm;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
@RequiredArgsConstructor
public final class PreciseDynamicModuloTableShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> availableTargetNames, final PreciseShardingValue<Integer> shardingValue) {
return "t_order_" + shardingValue.getValue() % 10;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.integrate.fixture;
import com.dangdang.ddframe.rdb.sharding.api.strategy.RangeShardingValue;
import com.dangdang.ddframe.rdb.sharding.routing.strategy.standard.RangeShardingAlgorithm;
import com.google.common.collect.Range;
import lombok.RequiredArgsConstructor;
import java.util.Collection;
import java.util.LinkedHashSet;
@RequiredArgsConstructor
public final class RangeDynamicModuloTableShardingAlgorithm implements RangeShardingAlgorithm<Integer> {
@Override
public Collection<String> doSharding(final Collection<String> availableTargetNames, final RangeShardingValue<Integer> shardingValue) {
Collection<String> result = new LinkedHashSet<>(availableTargetNames.size());
Range<Integer> range = shardingValue.getValueRange();
for (Integer i = range.lowerEndpoint(); i <= range.upperEndpoint(); i++) {
result.add("t_order_" + i % 10);
}
return result;
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.integrate.type.sharding;
import com.dangdang.ddframe.rdb.common.base.AbstractSQLAssertTest;
import com.dangdang.ddframe.rdb.common.env.ShardingTestStrategy;
import com.dangdang.ddframe.rdb.integrate.fixture.PreciseDynamicModuloTableShardingAlgorithm;
import com.dangdang.ddframe.rdb.integrate.fixture.PreciseModuloDatabaseShardingAlgorithm;
import com.dangdang.ddframe.rdb.integrate.fixture.RangeDynamicModuloTableShardingAlgorithm;
import com.dangdang.ddframe.rdb.integrate.fixture.RangeModuloDatabaseShardingAlgorithm;
import com.dangdang.ddframe.rdb.integrate.jaxb.SQLShardingRule;
import com.dangdang.ddframe.rdb.sharding.api.config.ShardingRuleConfig;
import com.dangdang.ddframe.rdb.sharding.api.config.TableRuleConfig;
import com.dangdang.ddframe.rdb.sharding.api.config.strategy.StandardShardingStrategyConfig;
import com.dangdang.ddframe.rdb.sharding.constant.DatabaseType;
import com.dangdang.ddframe.rdb.sharding.jdbc.core.datasource.ShardingDataSource;
import org.junit.AfterClass;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class ShardingDatabaseAndTableDynamicTest extends AbstractSQLAssertTest {
private static boolean isShutdown;
private static Map<DatabaseType, ShardingDataSource> shardingDataSources = new HashMap<>();
public ShardingDatabaseAndTableDynamicTest(final String testCaseName, final String sql, final DatabaseType type, final List<SQLShardingRule> sqlShardingRules) {
super(testCaseName, sql, type, sqlShardingRules);
}
@Override
protected ShardingTestStrategy getShardingStrategy() {
return ShardingTestStrategy.dbtbl;
}
@Override
protected List<String> getInitDataSetFiles() {
return Arrays.asList(
"integrate/dataset/sharding/dbtbl/init/dbtbl_0.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_1.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_2.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_3.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_4.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_5.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_6.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_7.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_8.xml",
"integrate/dataset/sharding/dbtbl/init/dbtbl_9.xml");
}
@Override
protected final Map<DatabaseType, ShardingDataSource> getDataSources() throws SQLException {
if (!shardingDataSources.isEmpty() && !isShutdown) {
return shardingDataSources;
}
isShutdown = false;
Map<DatabaseType, Map<String, DataSource>> dataSourceMap = createDataSourceMap();
for (Entry<DatabaseType, Map<String, DataSource>> each : dataSourceMap.entrySet()) {
ShardingRuleConfig shardingRuleConfig = new ShardingRuleConfig();
TableRuleConfig orderTableRuleConfig = new TableRuleConfig();
orderTableRuleConfig.setLogicTable("t_order");
orderTableRuleConfig.setDynamic(true);
shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig);
TableRuleConfig orderItemTableRuleConfig = new TableRuleConfig();
orderItemTableRuleConfig.setLogicTable("t_order_item");
orderItemTableRuleConfig.setDynamic(true);
shardingRuleConfig.getTableRuleConfigs().add(orderItemTableRuleConfig);
shardingRuleConfig.getBindingTableGroups().add("t_order, t_order_item");
StandardShardingStrategyConfig databaseShardingStrategyConfig = new StandardShardingStrategyConfig();
databaseShardingStrategyConfig.setShardingColumn("user_id");
databaseShardingStrategyConfig.setPreciseAlgorithmClassName(PreciseModuloDatabaseShardingAlgorithm.class.getName());
databaseShardingStrategyConfig.setRangeAlgorithmClassName(RangeModuloDatabaseShardingAlgorithm.class.getName());
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(databaseShardingStrategyConfig);
StandardShardingStrategyConfig tableShardingStrategyConfig = new StandardShardingStrategyConfig();
tableShardingStrategyConfig.setShardingColumn("order_id");
tableShardingStrategyConfig.setPreciseAlgorithmClassName(PreciseDynamicModuloTableShardingAlgorithm.class.getName());
tableShardingStrategyConfig.setRangeAlgorithmClassName(RangeDynamicModuloTableShardingAlgorithm.class.getName());
shardingRuleConfig.setDefaultTableShardingStrategyConfig(tableShardingStrategyConfig);
shardingDataSources.put(each.getKey(), new ShardingDataSource(shardingRuleConfig.build(each.getValue())));
}
return shardingDataSources;
}
@AfterClass
public static void clear() {
isShutdown = true;
if (!shardingDataSources.isEmpty()) {
for (ShardingDataSource each : shardingDataSources.values()) {
each.close();
}
}
}
}
......@@ -118,9 +118,6 @@ public class ShardingTableOnlyTest extends AbstractSQLAssertTest {
//CHECKSTYLE:OFF
} catch (final Exception ex) {
//CHECKSTYLE:ON
if (null != ex.getMessage() && ex.getMessage().startsWith("Dynamic table")) {
continue;
}
ex.printStackTrace();
throw new RuntimeException(ex);
}
......
......@@ -41,29 +41,22 @@ public final class ShardingStrategyTest {
private final Collection<String> targets = Sets.newHashSet("1", "2", "3");
@Test
public void assertDoStaticShardingWithoutShardingColumns() {
public void assertDoShardingWithoutShardingColumns() {
NoneShardingStrategy strategy = new NoneShardingStrategy();
assertThat(strategy.doSharding(targets, Collections.<ShardingValue>emptySet()), is(targets));
}
@Test
public void assertDoStaticShardingForBetweenSingleKey() {
public void assertDoShardingForBetweenSingleKey() {
StandardShardingStrategy strategy = new StandardShardingStrategy("column", new TestPreciseShardingAlgorithm(), new TestRangeShardingAlgorithm());
assertThat(strategy.doSharding(targets, Collections.<ShardingValue>singletonList(new RangeShardingValue<>("logicTable", "column", Range.open("1", "3")))),
is((Collection<String>) Sets.newHashSet("1", "2", "3")));
}
@Test
public void assertDoStaticShardingForMultipleKeys() {
public void assertDoShardingForMultipleKeys() {
ComplexShardingStrategy strategy = new ComplexShardingStrategy(Collections.singletonList("column"), new TestComplexKeysShardingAlgorithm());
assertThat(strategy.doSharding(targets, Collections.<ShardingValue>singletonList(new PreciseShardingValue<>("logicTable", "column", "1"))),
is((Collection<String>) Sets.newHashSet("1", "2", "3")));
}
@Test
public void assertDoDynamicShardingForBetweenSingleKey() {
StandardShardingStrategy strategy = new StandardShardingStrategy("column", new TestPreciseShardingAlgorithm(), new TestRangeShardingAlgorithm());
assertThat(strategy.doSharding(Collections.<String>emptyList(), Collections.<ShardingValue>singletonList(new RangeShardingValue<>("logicTable", "column", Range.open("1", "3")))),
is((Collection<String>) Sets.newHashSet("1", "2", "3")));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.dangdang.ddframe.rdb.sharding.api.config.ShardingRuleConfig;
import com.dangdang.ddframe.rdb.sharding.api.config.TableRuleConfig;
import com.dangdang.ddframe.rdb.sharding.api.config.strategy.StandardShardingStrategyConfig;
import com.dangdang.ddframe.rdb.sharding.rule.ShardingRule;
import com.dangdang.ddframe.rdb.sharding.constant.DatabaseType;
import com.dangdang.ddframe.rdb.sharding.jdbc.core.ShardingContext;
import com.dangdang.ddframe.rdb.sharding.routing.fixture.OrderAttrShardingAlgorithm;
import com.dangdang.ddframe.rdb.sharding.routing.fixture.PreciseOrderShardingAlgorithm;
import com.dangdang.ddframe.rdb.sharding.routing.fixture.RangeOrderShardingAlgorithm;
import com.google.common.base.Function;
import com.google.common.collect.Collections2;
import lombok.AccessLevel;
import lombok.Getter;
import org.junit.Before;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public abstract class AbstractBaseRouteSqlTest {
@Getter(AccessLevel.PROTECTED)
private ShardingRule shardingRule;
@Before
public void setRouteRuleContext() throws SQLException {
ShardingRuleConfig shardingRuleConfig = new ShardingRuleConfig();
TableRuleConfig orderTableRuleConfig = new TableRuleConfig();
orderTableRuleConfig.setLogicTable("order");
orderTableRuleConfig.setActualTables("order_0, order_1");
shardingRuleConfig.getTableRuleConfigs().add(orderTableRuleConfig);
TableRuleConfig orderItemTableRuleConfig = new TableRuleConfig();
orderItemTableRuleConfig.setLogicTable("order_item");
orderItemTableRuleConfig.setActualTables("order_item_0, order_item_1");
shardingRuleConfig.getTableRuleConfigs().add(orderItemTableRuleConfig);
TableRuleConfig orderAttrTableRuleConfig = new TableRuleConfig();
orderAttrTableRuleConfig.setLogicTable("order_attr");
orderAttrTableRuleConfig.setActualTables("ds_0.order_attr_a, ds_1.order_attr_b");
StandardShardingStrategyConfig orderShardingStrategyConfig = new StandardShardingStrategyConfig();
orderShardingStrategyConfig.setShardingColumn("order_id");
orderShardingStrategyConfig.setPreciseAlgorithmClassName(OrderAttrShardingAlgorithm.class.getName());
orderAttrTableRuleConfig.setTableShardingStrategyConfig(orderShardingStrategyConfig);
shardingRuleConfig.getTableRuleConfigs().add(orderAttrTableRuleConfig);
shardingRuleConfig.getBindingTableGroups().add("order, order_item");
StandardShardingStrategyConfig defaultShardingStrategyConfig = new StandardShardingStrategyConfig();
defaultShardingStrategyConfig.setShardingColumn("order_id");
defaultShardingStrategyConfig.setPreciseAlgorithmClassName(PreciseOrderShardingAlgorithm.class.getName());
defaultShardingStrategyConfig.setRangeAlgorithmClassName(RangeOrderShardingAlgorithm.class.getName());
shardingRuleConfig.setDefaultDatabaseShardingStrategyConfig(defaultShardingStrategyConfig);
shardingRuleConfig.setDefaultTableShardingStrategyConfig(defaultShardingStrategyConfig);
Map<String, DataSource> dataSourceMap = new HashMap<>();
dataSourceMap.put("ds_0", null);
dataSourceMap.put("ds_1", null);
shardingRule = shardingRuleConfig.build(dataSourceMap);
}
protected void assertSingleTargetWithoutParameter(final String originSql, final String targetDataSource, final String targetSQL) {
assertMultipleTargetsWithoutParameter(originSql, 1, Collections.singletonList(targetDataSource), Collections.singletonList(targetSQL));
}
protected void assertMultipleTargetsWithoutParameter(final String originSql, final int expectedSize, final Collection<String> targetDataSources, final Collection<String> targetSQLs) {
ShardingContext shardingContext = new ShardingContext(getShardingRule(), DatabaseType.MySQL, null, false);
SQLRouteResult actual = new StatementRoutingEngine(shardingContext).route(originSql);
assertThat(actual.getExecutionUnits().size(), is(expectedSize));
Set<String> actualDataSources = new HashSet<>(Collections2.transform(actual.getExecutionUnits(), new Function<SQLExecutionUnit, String>() {
@Override
public String apply(final SQLExecutionUnit input) {
return input.getDataSource();
}
}));
assertThat(actualDataSources, hasItems(targetDataSources.toArray(new String[targetDataSources.size()])));
Collection<String> actualSQLs = Collections2.transform(actual.getExecutionUnits(), new Function<SQLExecutionUnit, String>() {
@Override
public String apply(final SQLExecutionUnit input) {
return input.getSql();
}
});
assertThat(actualSQLs, hasItems(targetSQLs.toArray(new String[targetSQLs.size()])));
}
protected void assertSingleTargetWithParameters(final String originSql, final List<Object> parameters, final String targetDataSource, final String targetSQL) {
assertMultipleTargetsWithParameters(originSql, parameters, 1, Collections.singletonList(targetDataSource), Collections.singletonList(targetSQL));
}
protected void assertMultipleTargetsWithParameters(
final String originSql, final List<Object> parameters, final int expectedSize, final Collection<String> targetDataSources, final Collection<String> targetSQLs) {
ShardingContext shardingContext = new ShardingContext(getShardingRule(), DatabaseType.MySQL, null, false);
SQLRouteResult actual = new PreparedStatementRoutingEngine(originSql, shardingContext).route(parameters);
assertThat(actual.getExecutionUnits().size(), is(expectedSize));
Set<String> actualDataSources = new HashSet<>(Collections2.transform(actual.getExecutionUnits(), new Function<SQLExecutionUnit, String>() {
@Override
public String apply(final SQLExecutionUnit input) {
return input.getDataSource();
}
}));
assertThat(actualDataSources, hasItems(targetDataSources.toArray(new String[targetDataSources.size()])));
Collection<String> actualSQLs = Collections2.transform(actual.getExecutionUnits(), new Function<SQLExecutionUnit, String>() {
@Override
public String apply(final SQLExecutionUnit input) {
return input.getSql();
}
});
assertThat(actualSQLs, hasItems(targetSQLs.toArray(new String[targetSQLs.size()])));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.dangdang.ddframe.rdb.sharding.api.HintManager;
import com.dangdang.ddframe.rdb.sharding.constant.ShardingOperator;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
public abstract class AbstractDynamicRouteSqlTest extends AbstractBaseRouteSqlTest {
protected void assertSingleTargetWithoutParameter(final List<ShardingValuePair> shardingValuePairs, final String originSql, final String targetDataSource, final String targetSQL) {
assertMultipleTargetsWithoutParameter(shardingValuePairs, originSql, 1, Collections.singletonList(targetDataSource), Collections.singletonList(targetSQL));
}
protected void assertSingleTargetWithParameters(
final List<ShardingValuePair> shardingValuePairs, final String originSql, final List<Object> parameters, final String targetDataSource, final String targetSQL) {
assertMultipleTargetsWithParameters(shardingValuePairs, originSql, parameters, 1, Collections.singletonList(targetDataSource), Collections.singletonList(targetSQL));
}
protected void assertMultipleTargetsWithoutParameter(final List<ShardingValuePair> shardingValuePairs, final String originSql, final int expectedSize,
final Collection<String> targetDataSources, final Collection<String> targetSQLs) {
try (HintManager hintManager = HintManager.getInstance()) {
for (ShardingValuePair each : shardingValuePairs) {
hintManager.addDatabaseShardingValue(each.logicTable, "order_id", each.shardingOperator, each.shardingValue);
hintManager.addTableShardingValue(each.logicTable, "order_id", each.shardingOperator, each.shardingValue);
}
assertMultipleTargetsWithoutParameter(originSql, expectedSize, targetDataSources, targetSQLs);
}
}
protected void assertMultipleTargetsWithParameters(final List<ShardingValuePair> shardingValuePairs, final String originSql, final List<Object> parameters, final int expectedSize,
final Collection<String> targetDataSources, final Collection<String> targetSQLs) {
try (HintManager hintManager = HintManager.getInstance()) {
for (ShardingValuePair each : shardingValuePairs) {
hintManager.addDatabaseShardingValue(each.logicTable, "order_id", each.shardingOperator, each.shardingValue);
hintManager.addTableShardingValue(each.logicTable, "order_id", each.shardingOperator, each.shardingValue);
}
assertMultipleTargetsWithParameters(originSql, parameters, expectedSize, targetDataSources, targetSQLs);
}
}
protected static class ShardingValuePair {
private final String logicTable;
private final ShardingOperator shardingOperator;
private final Integer[] shardingValue;
protected ShardingValuePair(final String logicTable, final Integer... shardingValue) {
this(logicTable, ShardingOperator.EQUAL, shardingValue);
}
protected ShardingValuePair(final String logicTable, final ShardingOperator shardingOperator, final Integer... shardingValue) {
this.logicTable = logicTable;
this.shardingOperator = shardingOperator;
this.shardingValue = shardingValue;
}
}
}
......@@ -21,12 +21,6 @@ import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SelectSingleTableTest.class,
SelectBindingTableTest.class,
SelectMixedTablesTest.class,
DMLTest.class,
DatabaseTest.class
})
@Suite.SuiteClasses(DatabaseTest.class)
public class AllRoutingTests {
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
public final class DMLTest extends AbstractDynamicRouteSqlTest {
@Test
public void assertInsert() {
assertSingleTargetWithoutParameter("insert into `order` (order_id, name) value (1,'test')", "ds_1", "insert into order_1 (order_id, name) value (1,'test')");
assertSingleTargetWithParameters("insert into `order` (order_id, name) value (?,?)", Arrays.<Object>asList(2, "test"), "ds_0", "insert into order_0 (order_id, name) value (?,?)");
assertSingleTargetWithParameters(
Lists.newArrayList(new ShardingValuePair("order", 2)), "insert into `order` value (?,?)", Arrays.<Object>asList(2, "test"), "ds_0", "insert into order_0 value (?,?)");
}
@Test
public void assertUpdate() {
assertSingleTargetWithoutParameter("update `order` set name = 'test' where order_id = 1", "ds_1", "update order_1 set name = 'test' where order_id = 1");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "update `order` set name = 'test'", "ds_1", "update order_1 set name = 'test'");
assertSingleTargetWithParameters("update `order` set name = ? where order_id = ?", Arrays.<Object>asList("test", 2), "ds_0", "update order_0 set name = ? where order_id = ?");
assertSingleTargetWithParameters(
Lists.newArrayList(new ShardingValuePair("order", 2)), "update `order` set name = ?", Collections.<Object>singletonList("test"), "ds_0", "update order_0 set name = ?");
}
@Test
public void assertDelete() {
assertSingleTargetWithoutParameter("delete from `order` where order_id = 1", "ds_1", "delete from order_1 where order_id = 1");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "delete from `order`", "ds_1", "delete from order_1");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 2)), "delete from `order`", "ds_0", "delete from order_0");
assertSingleTargetWithParameters("delete from `order` where order_id = ?", Collections.<Object>singletonList(2), "ds_0", "delete from order_0 where order_id = ?");
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
public final class SelectBindingTableTest extends AbstractDynamicRouteSqlTest {
@Test
public void assertSelectWithBindingJoin() {
assertSingleTargetWithoutParameter("select * from order o inner join order_item i on o.order_id = i.order_id where o.order_id = 1", "ds_1",
"select * from order_1 o inner join order_item_1 i on o.order_id = i.order_id where o.order_id = 1");
assertSingleTargetWithoutParameter("select * from order o join order_item i on o.order_id = i.order_id where o.order_id = 1", "ds_1",
"select * from order_1 o join order_item_1 i on o.order_id = i.order_id where o.order_id = 1");
assertSingleTargetWithoutParameter("select * from order o join order_item i using (order_id) where o.order_id = 1", "ds_1",
"select * from order_1 o join order_item_1 i using (order_id) where o.order_id = 1");
assertSingleTargetWithoutParameter("select * from order o, order_item i where o.order_id = i.order_id and o.order_id = 1", "ds_1",
"select * from order_1 o, order_item_1 i where o.order_id = i.order_id and o.order_id = 1");
assertSingleTargetWithParameters("select * from order o, order_item i where o.order_id = i.order_id and o.order_id = ?", Collections.<Object>singletonList(1), "ds_1",
"select * from order_1 o, order_item_1 i where o.order_id = i.order_id and o.order_id = ?");
}
@Test
public void assertSelectWithBindingJoinDynamic() {
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "select * from order o inner join order_item i on o.order_id = i.order_id", "ds_1",
"select * from order_1 o inner join order_item_1 i on o.order_id = i.order_id");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "select * from order o join order_item i on o.order_id = i.order_id", "ds_1",
"select * from order_1 o join order_item_1 i on o.order_id = i.order_id");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "select * from order o join order_item i using (order_id)", "ds_1",
"select * from order_1 o join order_item_1 i using (order_id)");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1)), "select * from order o, order_item i where o.order_id = i.order_id", "ds_1",
"select * from order_1 o, order_item_1 i where o.order_id = i.order_id");
}
@Test
public void assertSelectWithRouteAllPartitions() {
assertMultipleTargetsWithoutParameter("select * from order o inner join order_item i on o.order_id = i.order_id", 4, Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_0 o inner join order_item_0 i on o.order_id = i.order_id", "select * from order_1 o inner join order_item_1 i on o.order_id = i.order_id"));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.dangdang.ddframe.rdb.sharding.exception.ShardingJdbcException;
import com.google.common.collect.Lists;
import org.junit.Test;
import java.util.Arrays;
public final class SelectMixedTablesTest extends AbstractDynamicRouteSqlTest {
@Test
public void assertBindingTableWithUnBoundTable() {
assertSingleTargetWithoutParameter("select * from order o join order_item i join order_attr a using(order_id) where o.order_id = 1", "ds_1",
"select * from order_1 o join order_item_1 i join order_attr_b a using(order_id) where o.order_id = 1");
assertSingleTargetWithoutParameter(Lists.newArrayList(new ShardingValuePair("order", 1), new ShardingValuePair("order_attr", 1)),
"select * from order o join order_item i join order_attr a using(order_id)", "ds_1",
"select * from order_1 o join order_item_1 i join order_attr_b a using(order_id)");
}
@Test
public void assertConditionFromRelationship() {
assertSingleTargetWithoutParameter("select * from order o join order_attr a using(order_id) where o.order_id = 1", "ds_1",
"select * from order_1 o join order_attr_b a using(order_id) where o.order_id = 1");
assertSingleTargetWithoutParameter(
Lists.newArrayList(new ShardingValuePair("order", 1), new ShardingValuePair("order_attr", 1)), "select * from order o join order_attr a using(order_id)", "ds_1",
"select * from order_1 o join order_attr_b a using(order_id)");
}
@Test
public void assertSelectWithCartesianProductAllPartitions() {
assertMultipleTargetsWithoutParameter("select * from order o, order_attr a", 4, Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_0 o, order_attr_a a", "select * from order_1 o, order_attr_a a",
"select * from order_0 o, order_attr_b a", "select * from order_1 o, order_attr_b a"));
}
@Test(expected = ShardingJdbcException.class)
public void assertSelectTableWithoutRules() {
assertSingleTargetWithoutParameter("select * from aaa, bbb, ccc", null, null);
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing;
import com.dangdang.ddframe.rdb.sharding.constant.ShardingOperator;
import org.junit.Ignore;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public final class SelectSingleTableTest extends AbstractDynamicRouteSqlTest {
@Test
public void assertGroupBy() {
assertSingleTargetWithoutParameter("select sum(qty) from order where order_id = 1 group by tenant_id", "ds_1",
"select sum(qty) , tenant_id AS GROUP_BY_DERIVED_0 from order_1 where order_id = 1 group by tenant_id ORDER BY GROUP_BY_DERIVED_0 ASC ");
// assertMultipleTargetsWithoutParameters("select sum(qty) from order group by tenant_id", 4, Arrays.asList("ds_0", "ds_1"),
// Arrays.asList("select sum(qty) , tenant_id as sharding_gen_1 from order_0 group by tenant_id", "select sum(qty) , tenant_id as sharding_gen_1 from order_1 group by tenant_id"));
}
@Test
public void assertSingleSelect() {
assertSingleTargetWithoutParameter("select * from order where order_id = 1", "ds_1", "select * from order_1 where order_id = 1");
assertSingleTargetWithoutParameter(Collections.singletonList(new ShardingValuePair("order", 1)), "select * from order", "ds_1", "select * from order_1");
assertSingleTargetWithoutParameter(Collections.singletonList(new ShardingValuePair("order", 2)), "select * from order", "ds_0", "select * from order_0");
assertSingleTargetWithParameters("select * from order where order_id = ?", Collections.<Object>singletonList(2), "ds_0", "select * from order_0 where order_id = ?");
}
@Test
public void assertSelectWithAlias() {
assertSingleTargetWithoutParameter("select * from order a where a.order_id = 2", "ds_0", "select * from order_0 a where a.order_id = 2");
assertSingleTargetWithoutParameter("select * from order A where a.order_id = 2", "ds_0", "select * from order_0 A where a.order_id = 2");
assertSingleTargetWithoutParameter("select * from order a where A.order_id = 2", "ds_0", "select * from order_0 a where A.order_id = 2");
assertSingleTargetWithoutParameter(Collections.singletonList(new ShardingValuePair("order", 2)), "select * from order a", "ds_0", "select * from order_0 a");
assertSingleTargetWithoutParameter(Collections.singletonList(new ShardingValuePair("order", 2)), "select * from order A", "ds_0", "select * from order_0 A");
assertSingleTargetWithoutParameter(Collections.singletonList(new ShardingValuePair("order", 2)), "select * from order a", "ds_0", "select * from order_0 a");
}
@Test
public void assertSelectWithTableNameAsAlias() {
assertSingleTargetWithoutParameter("select * from order where order.order_id = 10", "ds_0", "select * from order_0 where order_0.order_id = 10");
}
@Test
public void assertSelectWithIn() {
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?)", Arrays.<Object>asList(1, 2, 100), 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?)", "select * from order_1 where order_id in (?,?,?)"));
assertMultipleTargetsWithoutParameter(Collections.singletonList(new ShardingValuePair("order", ShardingOperator.IN, 1, 2, 100)), "select * from order", 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0", "select * from order_1"));
}
@Test
@Ignore
// TODO or
public void assertSelectWithInAndIntersection() {
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?) or order_id in (?,?)", Arrays.<Object>asList(1, 2, 100, 2), 4,
Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_1 where order_id in (?,?) or order_id in (?,?)", "select * from order_1 where order_id in (?, ?) or order_id in (?, ?)"));
}
@Test
public void assertSelectWithBetween() {
assertMultipleTargetsWithParameters("select * from order where order_id between ? and ?", Arrays.<Object>asList(1, 100), 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id between ? and ?", "select * from order_1 where order_id between ? and ?"));
assertMultipleTargetsWithoutParameter(Collections.singletonList(new ShardingValuePair("order", ShardingOperator.BETWEEN, 1, 100)), "select * from order", 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0", "select * from order_1"));
}
@Test
@Ignore
// TODO or
public void assertSelectWithBetweenAndIntersection() {
assertMultipleTargetsWithParameters("select * from order where order_id between ? and ? or order_id between ? and ? ", Arrays.<Object>asList(1, 50, 29, 100), 4,
Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_0 where order_id between ? and ? or order_id between ? and ? ",
"select * from order_1 where order_id between ? and ? or order_id between ? and ? "));
}
@Test
public void assertSingleSelectLimit() {
assertSingleTargetWithoutParameter("select * from order where order_id = 1 limit 5", "ds_1", "select * from order_1 where order_id = 1 limit 5");
assertSingleTargetWithoutParameter("select * from order where order_id = 1 limit 2,5", "ds_1", "select * from order_1 where order_id = 1 limit 2,5");
assertSingleTargetWithoutParameter("select * from order where order_id = 1 limit 5 offset 2", "ds_1", "select * from order_1 where order_id = 1 limit 5 offset 2");
List<Object> parameters = Arrays.<Object>asList(2, 4, 5);
assertSingleTargetWithParameters("select * from order where order_id = ? limit ?,?", parameters, "ds_0", "select * from order_0 where order_id = ? limit ?,?");
assertThat(parameters, is(Arrays.<Object>asList(2, 4, 5)));
parameters = Arrays.<Object>asList(2, 4, 5);
assertSingleTargetWithParameters("select * from order where order_id = ? limit ? offset ?", parameters, "ds_0", "select * from order_0 where order_id = ? limit ? offset ?");
assertThat(parameters, is(Arrays.<Object>asList(2, 4, 5)));
parameters = Arrays.<Object>asList(2, 5);
assertSingleTargetWithParameters("select * from order where order_id = ? limit ?", parameters, "ds_0", "select * from order_0 where order_id = ? limit ?");
assertThat(parameters, is(Arrays.<Object>asList(2, 5)));
parameters = Arrays.<Object>asList(2, 5);
assertSingleTargetWithParameters("select * from order where order_id = ? limit ?,10", parameters, "ds_0", "select * from order_0 where order_id = ? limit ?,10");
assertThat(parameters, is(Arrays.<Object>asList(2, 5)));
parameters = Arrays.<Object>asList(2, 5);
assertSingleTargetWithParameters("select * from order where order_id = ? limit 10,?", parameters, "ds_0", "select * from order_0 where order_id = ? limit 10,?");
assertThat(parameters, is(Arrays.<Object>asList(2, 5)));
}
@Test
public void assertSelectInLimit() {
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit 5", Arrays.<Object>asList(1, 2, 100), 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit 5", "select * from order_1 where order_id in (?,?,?) limit 5"));
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit 2,5", Arrays.<Object>asList(1, 2, 100), 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit 0,7", "select * from order_1 where order_id in (?,?,?) limit 0,7"));
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit 5 offset 2", Arrays.<Object>asList(1, 2, 100), 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit 7 offset 0", "select * from order_1 where order_id in (?,?,?) limit 7 offset 0"));
List<Object> parameters = Arrays.<Object>asList(1, 2, 100, 5);
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit ?", parameters, 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit ?", "select * from order_1 where order_id in (?,?,?) limit ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 5)));
parameters = Arrays.<Object>asList(1, 2, 100, 2, 5);
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit ?,?", parameters, 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit ?,?", "select * from order_1 where order_id in (?,?,?) limit ?,?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 0, 7)));
parameters = Arrays.<Object>asList(1, 2, 100, 5, 2);
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit ? offset ?", parameters, 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit ? offset ?", "select * from order_1 where order_id in (?,?,?) limit ? offset ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 7, 0)));
parameters = Arrays.<Object>asList(1, 2, 100, 5);
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit 2,?", parameters, 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit 0,?", "select * from order_1 where order_id in (?,?,?) limit 0,?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 7)));
parameters = Arrays.<Object>asList(1, 2, 100, 2);
assertMultipleTargetsWithParameters("select * from order where order_id in (?,?,?) limit ?,5", parameters, 4,
Arrays.asList("ds_0", "ds_1"), Arrays.asList("select * from order_0 where order_id in (?,?,?) limit ?,7", "select * from order_1 where order_id in (?,?,?) limit ?,7"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 0)));
}
@Test
@Ignore
public void assertSelectOrLimit() {
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit 5", Arrays.<Object>asList(1, 2, 100), 2,
Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit 5", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit 5"));
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit 2,5", Arrays.<Object>asList(1, 2, 100), 2,
Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit 0, 7", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit 0, 7"));
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit 5 offset 2", Arrays.<Object>asList(1, 2, 100), 2,
Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit 0, 7", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit 0, 7"));
List<Object> parameters = Arrays.<Object>asList(1, 2, 100, 5);
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit ?", parameters, 2, Arrays.asList("ds_0", "ds_1"),
Arrays.asList("select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit ?", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 5)));
parameters = Arrays.<Object>asList(1, 2, 100, 2, 5);
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit ?,?", parameters, 2, Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit ?, ?", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit ?, ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 0, 7)));
parameters = Arrays.<Object>asList(1, 2, 100, 5, 2);
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit ? offset ?", parameters, 2, Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit ?, ?", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit ?, ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 0, 7)));
parameters = Arrays.<Object>asList(1, 2, 100, 5);
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit 2,?", parameters, 2, Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit 0, ?", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit 0, ?"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 7)));
parameters = Arrays.<Object>asList(1, 2, 100, 2);
assertMultipleTargetsWithParameters("select * from order where order_id = ? or order_id = ? or order_id = ? limit ?,5", parameters, 2, Arrays.asList("ds_0", "ds_1"), Arrays.asList(
"select * from order_0 where order_id = ? or order_id = ? or order_id = ? limit ?, 7", "select * from order_1 where order_id = ? or order_id = ? or order_id = ? limit ?, 7"));
assertThat(parameters, is(Arrays.<Object>asList(1, 2, 100, 0)));
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.routing.fixture;
import com.dangdang.ddframe.rdb.sharding.api.strategy.PreciseShardingValue;
import com.dangdang.ddframe.rdb.sharding.routing.strategy.standard.PreciseShardingAlgorithm;
import java.util.Collection;
public final class OrderAttrShardingAlgorithm implements PreciseShardingAlgorithm<Integer> {
@Override
public String doSharding(final Collection<String> tables, final PreciseShardingValue<Integer> shardingValue) {
String suffix = shardingValue.getValue() % 2 == 0 ? "_a" : "_b";
for (String each : tables) {
if (each.endsWith(suffix)) {
return each;
}
}
return null;
}
}
......@@ -25,7 +25,6 @@ import org.junit.runners.Suite;
ShardingRuleTest.class,
TableRuleTest.class,
DataNodeTest.class,
DynamicDataNodeTest.class,
BindingTableRuleTest.class
})
public class AllRuleTests {
......
......@@ -53,11 +53,6 @@ public final class BindingTableRuleTest {
createBindingTableRule().getBindingActualTable("no_ds", "subLogicTable", "table_1");
}
@Test(expected = UnsupportedOperationException.class)
public void assertGetBindingActualTablesFailureWhenIsDynamicTable() {
createDynamicBindingTableRule().getBindingActualTable("no_ds", "subLogicTable", "table_1");
}
@Test
public void assertGetAllLogicTables() {
assertThat(createBindingTableRule().getAllLogicTables(), is((Collection<String>) Arrays.asList("logicTable", "subLogicTable")));
......@@ -96,22 +91,4 @@ public final class BindingTableRuleTest {
result.put("ds2", null);
return result;
}
private BindingTableRule createDynamicBindingTableRule() {
return new BindingTableRule(Arrays.asList(createDynamicTableRule(), createDynamicSubTableRule()));
}
private TableRule createDynamicTableRule() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("logicTable");
tableRuleConfig.setDynamic(true);
return tableRuleConfig.build(createDataSourceMap());
}
private TableRule createDynamicSubTableRule() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("subLogicTable");
tableRuleConfig.setDynamic(true);
return tableRuleConfig.build(createDataSourceMap());
}
}
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed 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.
* </p>
*/
package com.dangdang.ddframe.rdb.sharding.rule;
import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
public final class DynamicDataNodeTest {
@Test
public void assertGetTableName() {
assertThat(new DynamicDataNode("ds").getTableName(), is("SHARDING_JDBC DYNAMIC_TABLE_PLACEHOLDER"));
}
}
......@@ -38,60 +38,6 @@ import static org.junit.Assert.assertTrue;
public final class TableRuleTest {
@Test
public void assertTableRuleForDynamicWithoutAnyStrategies() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("logicTable");
tableRuleConfig.setDynamic(true);
TableRule actual = tableRuleConfig.build(createDataSourceMap());
assertDynamicTable(actual);
assertNull(actual.getDatabaseShardingStrategy());
assertNull(actual.getTableShardingStrategy());
}
@Test
public void assertTableRuleForDynamicWithDatabaseStrategy() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("logicTable");
tableRuleConfig.setDynamic(true);
tableRuleConfig.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfig());
TableRule actual = tableRuleConfig.build(createDataSourceMap());
assertDynamicTable(actual);
assertNotNull(actual.getDatabaseShardingStrategy());
assertNull(actual.getTableShardingStrategy());
}
@Test
public void assertTableRuleForDynamicWithTableStrategy() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("logicTable");
tableRuleConfig.setDynamic(true);
tableRuleConfig.setTableShardingStrategyConfig(new NoneShardingStrategyConfig());
TableRule actual = tableRuleConfig.build(createDataSourceMap());
assertDynamicTable(actual);
assertNull(actual.getDatabaseShardingStrategy());
assertNotNull(actual.getTableShardingStrategy());
}
@Test
public void assertTableRuleForDynamicWithAllStrategies() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
tableRuleConfig.setLogicTable("logicTable");
tableRuleConfig.setDynamic(true);
tableRuleConfig.setDatabaseShardingStrategyConfig(new NoneShardingStrategyConfig());
tableRuleConfig.setTableShardingStrategyConfig(new NoneShardingStrategyConfig());
TableRule actual = tableRuleConfig.build(createDataSourceMap());
assertDynamicTable(actual);
assertNotNull(actual.getDatabaseShardingStrategy());
assertNotNull(actual.getTableShardingStrategy());
}
private void assertDynamicTable(final TableRule actual) {
assertThat(actual.getActualDataNodes().size(), is(2));
assertTrue(actual.getActualDataNodes().contains(new DynamicDataNode("ds0")));
assertTrue(actual.getActualDataNodes().contains(new DynamicDataNode("ds1")));
}
@Test
public void assertTableRuleWithoutDataNode() {
TableRuleConfig tableRuleConfig = new TableRuleConfig();
......
......@@ -19,9 +19,9 @@ import static org.junit.Assert.assertThat;
public final class ShardingRuleConfigConverterTest {
private final String commonShardingRuleConfigJson = "{\"tableRuleConfigs\":[{\"logicTable\":\"t_order\",\"dynamic\":false,\"actualTables\":\"t_order_${[0, 1]}\","
private final String commonShardingRuleConfigJson = "{\"tableRuleConfigs\":[{\"logicTable\":\"t_order\",\"actualTables\":\"t_order_${[0, 1]}\","
+ "\"databaseShardingStrategyConfig\":{},\"tableShardingStrategyConfig\":{}},"
+ "{\"logicTable\":\"t_order_item\",\"dynamic\":false,\"actualTables\":\"t_order_item_${[0, 1]}\","
+ "{\"logicTable\":\"t_order_item\",\"actualTables\":\"t_order_item_${[0, 1]}\","
+ "\"databaseShardingStrategyConfig\":{},\"tableShardingStrategyConfig\":{}}"
+ "],\"bindingTableGroups\":[\"t_order, t_order_item\"],\"defaultDatabaseShardingStrategyConfig\":{},";
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册