未验证 提交 efef6e4d 编写于 作者: M ma-xiao-guang-64 提交者: GitHub

Merge pull request #1 from shardingjdbc/dev

更新代码
......@@ -8,6 +8,7 @@
1. [ISSUE #609](https://github.com/shardingjdbc/sharding-jdbc/issues/609) 支持MySQL的SHOW语句
1. [ISSUE #610](https://github.com/shardingjdbc/sharding-jdbc/issues/610) 优化不包含表的DQL
1. [ISSUE #611](https://github.com/shardingjdbc/sharding-jdbc/issues/611) 支持MySQL的DESC语句
1. [ISSUE #652](https://github.com/shardingjdbc/sharding-jdbc/issues/652) Spring Boot Starter 2.x支持
### 缺陷修正
1. [ISSUE #646](https://github.com/shardingjdbc/sharding-jdbc/issues/646) 当SELECT ITEMS中的别名与GROUP BY或ORDER BY的真实列名对应时,无需补列
......
......@@ -58,6 +58,7 @@ public final class UpdateSetItemsClauseParser implements SQLClauseParser {
parseSetColumn(updateStatement);
lexerEngine.skipIfEqual(Symbol.EQ, Symbol.COLON_EQ);
parseSetValue(updateStatement);
skipsDoubleColon();
}
private void parseSetColumn(final DMLStatement updateStatement) {
......@@ -79,4 +80,10 @@ public final class UpdateSetItemsClauseParser implements SQLClauseParser {
private void parseSetValue(final DMLStatement updateStatement) {
basicExpressionParser.parse(updateStatement);
}
private void skipsDoubleColon() {
if (lexerEngine.skipIfEqual(Symbol.DOUBLE_COLON)) {
lexerEngine.nextToken();
}
}
}
......@@ -17,6 +17,11 @@
package io.shardingjdbc.core.merger;
import io.shardingjdbc.core.merger.dal.DALMergeEngineTest;
import io.shardingjdbc.core.merger.dal.show.ShowCreateTableMergedResultTest;
import io.shardingjdbc.core.merger.dal.show.ShowDatabasesMergedResultTest;
import io.shardingjdbc.core.merger.dal.show.ShowOtherMergedResultTest;
import io.shardingjdbc.core.merger.dal.show.ShowTablesMergedResultTest;
import io.shardingjdbc.core.merger.dql.DQLMergeEngineTest;
import io.shardingjdbc.core.merger.dql.common.DecoratorMergedResultTest;
import io.shardingjdbc.core.merger.dql.common.MemoryMergedResultTest;
......@@ -32,6 +37,8 @@ import io.shardingjdbc.core.merger.dql.orderby.CompareUtilTest;
import io.shardingjdbc.core.merger.dql.orderby.OrderByStreamMergedResultTest;
import io.shardingjdbc.core.merger.dql.orderby.OrderByValueTest;
import io.shardingjdbc.core.merger.dql.pagination.LimitDecoratorMergedResultTest;
import io.shardingjdbc.core.merger.dql.pagination.RowNumberDecoratorMergedResultTest;
import io.shardingjdbc.core.merger.dql.pagination.TopAndRowNumberDecoratorMergedResultTest;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
......@@ -51,7 +58,15 @@ import org.junit.runners.Suite;
GroupByStreamMergedResultTest.class,
GroupByMemoryMergedResultTest.class,
AllAggregationTests.class,
LimitDecoratorMergedResultTest.class
LimitDecoratorMergedResultTest.class,
RowNumberDecoratorMergedResultTest.class,
TopAndRowNumberDecoratorMergedResultTest.class,
DALMergeEngineTest.class,
ShowCreateTableMergedResultTest.class,
ShowDatabasesMergedResultTest.class,
ShowOtherMergedResultTest.class,
ShowTablesMergedResultTest.class,
MergeEngineFactoryTest.class
})
public class AllMergerTests {
}
/*
* 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 io.shardingjdbc.core.merger;
import com.google.common.collect.Lists;
import io.shardingjdbc.core.merger.dal.DALMergeEngine;
import io.shardingjdbc.core.merger.dql.DQLMergeEngine;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.parsing.parser.sql.SQLStatement;
import io.shardingjdbc.core.parsing.parser.sql.dal.DALStatement;
import io.shardingjdbc.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class MergeEngineFactoryTest {
private List<QueryResult> queryResults;
@Before
public void setUp() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
when(resultSetMetaData.getColumnCount()).thenReturn(1);
when(resultSetMetaData.getColumnLabel(1)).thenReturn("label");
List<ResultSet> resultSets = Lists.newArrayList(resultSet);
queryResults = new ArrayList<>(resultSets.size());
queryResults.add(new TestQueryResult(resultSets.get(0)));
}
@Test
public void assertNewInstanceWithSelectStatement() throws SQLException {
SQLStatement selectStatement = new SelectStatement();
assertThat(MergeEngineFactory.newInstance(null, queryResults, selectStatement), instanceOf(DQLMergeEngine.class));
}
@Test
public void assertNewInstanceWithDALStatement() throws SQLException {
SQLStatement dalStatement = new DALStatement();
assertThat(MergeEngineFactory.newInstance(null, queryResults, dalStatement), instanceOf(DALMergeEngine.class));
}
@Test(expected = UnsupportedOperationException.class)
public void assertNewInstanceWithOtherStatement() throws SQLException {
SQLStatement insertStatement = new InsertStatement();
MergeEngineFactory.newInstance(null, queryResults, insertStatement);
}
}
/*
* 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 io.shardingjdbc.core.merger.dal;
import io.shardingjdbc.core.merger.QueryResult;
import io.shardingjdbc.core.merger.dal.show.ShowCreateTableMergedResult;
import io.shardingjdbc.core.merger.dal.show.ShowDatabasesMergedResult;
import io.shardingjdbc.core.merger.dal.show.ShowOtherMergedResult;
import io.shardingjdbc.core.merger.dal.show.ShowTablesMergedResult;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.parsing.parser.dialect.mysql.statement.ShowCreateTableStatement;
import io.shardingjdbc.core.parsing.parser.dialect.mysql.statement.ShowDatabasesStatement;
import io.shardingjdbc.core.parsing.parser.dialect.mysql.statement.ShowOtherStatement;
import io.shardingjdbc.core.parsing.parser.dialect.mysql.statement.ShowTablesStatement;
import io.shardingjdbc.core.parsing.parser.sql.dal.DALStatement;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Collections;
import java.util.List;
import static org.hamcrest.CoreMatchers.instanceOf;
import static org.junit.Assert.assertThat;
import static org.mockito.Mockito.mock;
public final class DALMergeEngineTest {
private List<QueryResult> queryResults;
@Before
public void setUp() {
ResultSet resultSet = mock(ResultSet.class);
queryResults = Collections.<QueryResult>singletonList(new TestQueryResult(resultSet));
}
@Test
public void assertMergeForShowDatabasesStatement() throws SQLException {
DALStatement dalStatement = new ShowDatabasesStatement();
DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement);
assertThat(dalMergeEngine.merge(), instanceOf(ShowDatabasesMergedResult.class));
}
@Test
public void assertMergeForShowShowTablesStatement() throws SQLException {
DALStatement dalStatement = new ShowTablesStatement();
DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement);
assertThat(dalMergeEngine.merge(), instanceOf(ShowTablesMergedResult.class));
}
@Test
public void assertMergeForShowCreateTableStatement() throws SQLException {
DALStatement dalStatement = new ShowCreateTableStatement();
DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement);
assertThat(dalMergeEngine.merge(), instanceOf(ShowCreateTableMergedResult.class));
}
@Test
public void assertMergeForShowOtherStatement() throws SQLException {
DALStatement dalStatement = new ShowOtherStatement();
DALMergeEngine dalMergeEngine = new DALMergeEngine(null, queryResults, dalStatement);
assertThat(dalMergeEngine.merge(), instanceOf(ShowOtherMergedResult.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 io.shardingjdbc.core.merger.dal.show;
import com.google.common.collect.Lists;
import io.shardingjdbc.core.api.algorithm.fixture.TestComplexKeysShardingAlgorithm;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.ComplexShardingStrategyConfiguration;
import io.shardingjdbc.core.merger.QueryResult;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.rule.ShardingRule;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class ShowCreateTableMergedResultTest {
private ShardingRule shardingRule;
private List<QueryResult> queryResults;
private ResultSet resultSet;
@Before
public void setUp() throws SQLException {
TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration();
tableRuleConfig.setLogicTable("table");
tableRuleConfig.setActualDataNodes("ds.table_${0..2}");
tableRuleConfig.setTableShardingStrategyConfig(new ComplexShardingStrategyConfiguration("field1, field2, field3", new TestComplexKeysShardingAlgorithm()));
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig);
shardingRule = new ShardingRule(shardingRuleConfig, Lists.newArrayList("ds"));
resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
when(resultSetMetaData.getColumnCount()).thenReturn(2);
List<ResultSet> resultSets = Lists.newArrayList(resultSet);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, false);
}
queryResults = new ArrayList<>(resultSets.size());
for (ResultSet each : resultSets) {
queryResults.add(new TestQueryResult(each));
}
}
@Test
public void assertNextForEmptyQueryResult() throws SQLException {
ShowCreateTableMergedResult showCreateTableMergedResult = new ShowCreateTableMergedResult(shardingRule, new ArrayList<QueryResult>());
assertFalse(showCreateTableMergedResult.next());
}
@Test
public void assertNextForTableRuleIsPresentForBackQuotes() throws SQLException {
when(resultSet.getObject(1)).thenReturn("table_0");
when(resultSet.getObject(2)).thenReturn("CREATE TABLE `t_order` (\n"
+ " `id` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `order_id` int(11) NOT NULL COMMENT,\n"
+ " `user_id` int(11) NOT NULL COMMENT,\n"
+ " `status` tinyint(4) NOT NULL DEFAULT '1',\n"
+ " `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n"
+ " PRIMARY KEY (`id`)\n"
+ ") ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
ShowCreateTableMergedResult showCreateTableMergedResult = new ShowCreateTableMergedResult(shardingRule, queryResults);
assertTrue(showCreateTableMergedResult.next());
}
@Test
public void assertNextForTableRuleIsPresentForNoBackQuotes() throws SQLException {
when(resultSet.getObject(1)).thenReturn("table_0");
when(resultSet.getObject(2)).thenReturn("CREATE TABLE t_order (\n"
+ " `id` int(11) NOT NULL AUTO_INCREMENT,\n"
+ " `order_id` int(11) NOT NULL COMMENT,\n"
+ " `user_id` int(11) NOT NULL COMMENT,\n"
+ " `status` tinyint(4) NOT NULL DEFAULT '1',\n"
+ " `created_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,\n"
+ " PRIMARY KEY (`id`)\n"
+ ") ENGINE=InnoDB AUTO_INCREMENT=121 DEFAULT CHARSET=utf8 COLLATE=utf8_bin");
ShowCreateTableMergedResult showCreateTableMergedResult = new ShowCreateTableMergedResult(shardingRule, queryResults);
assertTrue(showCreateTableMergedResult.next());
}
@Test
public void assertNextForTableRuleIsNotPresent() throws SQLException {
when(resultSet.getObject(1)).thenReturn("table_3");
ShowCreateTableMergedResult showCreateTableMergedResult = new ShowCreateTableMergedResult(shardingRule, queryResults);
assertFalse(showCreateTableMergedResult.next());
}
}
/*
* 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 io.shardingjdbc.core.merger.dal.show;
import io.shardingjdbc.core.constant.ShardingConstant;
import org.junit.Before;
import org.junit.Test;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Calendar;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
public final class ShowDatabasesMergedResultTest {
private ShowDatabasesMergedResult showDatabasesMergedResult;
@Before
public void setUp() {
showDatabasesMergedResult = new ShowDatabasesMergedResult();
}
@Test
public void assertNext() {
assertTrue(showDatabasesMergedResult.next());
assertFalse(showDatabasesMergedResult.next());
}
@Test
public void assertGetValueWithColumnIndex() {
assertThat(showDatabasesMergedResult.getValue(1, Object.class).toString(), is(ShardingConstant.LOGIC_SCHEMA_NAME));
}
@Test
public void assertGetValueWithColumnLabel() {
assertThat(showDatabasesMergedResult.getValue("label", Object.class).toString(), is(ShardingConstant.LOGIC_SCHEMA_NAME));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnIndex() throws SQLException {
showDatabasesMergedResult.getCalendarValue(1, Object.class, Calendar.getInstance());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnLabel() throws SQLException {
showDatabasesMergedResult.getCalendarValue("label", Object.class, Calendar.getInstance());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnIndex() throws SQLException {
showDatabasesMergedResult.getInputStream(1, "Ascii");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnLabel() throws SQLException {
showDatabasesMergedResult.getInputStream("label", "Ascii");
}
@Test
public void assertWasNull() {
assertFalse(showDatabasesMergedResult.wasNull());
}
}
/*
* 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 io.shardingjdbc.core.merger.dal.show;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.InputStream;
import java.io.Reader;
import java.math.BigDecimal;
import java.net.MalformedURLException;
import java.net.URL;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLXML;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Collection;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public final class ShowOtherMergedResultTest {
@Mock
private ResultSet resultSet;
private ShowOtherMergedResult showOtherMergedResult;
@Before
public void setUp() {
showOtherMergedResult = new ShowOtherMergedResult(new TestQueryResult(resultSet));
}
@Test
public void assertNext() throws SQLException {
when(resultSet.next()).thenReturn(true, false);
assertThat(showOtherMergedResult.next(), is(true));
assertThat(showOtherMergedResult.next(), is(false));
}
@Test
public void assertGetValueWithColumnIndexWithObject() throws SQLException {
when(resultSet.getObject(1)).thenReturn("1");
assertThat(showOtherMergedResult.getValue(1, Object.class).toString(), is("1"));
}
@Test
public void assertGetValueWithColumnIndexWithBoolean() throws SQLException {
when(resultSet.getBoolean(1)).thenReturn(true);
assertTrue((Boolean) showOtherMergedResult.getValue(1, boolean.class));
}
@Test
public void assertGetValueWithColumnIndexWithByte() throws SQLException {
when(resultSet.getByte(1)).thenReturn((byte) 1);
assertThat((byte) showOtherMergedResult.getValue(1, byte.class), is((byte) 1));
}
@Test
public void assertGetValueWithColumnIndexWithShort() throws SQLException {
when(resultSet.getShort(1)).thenReturn((short) 1);
assertThat((short) showOtherMergedResult.getValue(1, short.class), is((short) 1));
}
@Test
public void assertGetValueWithColumnIndexWithInt() throws SQLException {
when(resultSet.getInt(1)).thenReturn(1);
assertThat((int) showOtherMergedResult.getValue(1, int.class), is(1));
}
@Test
public void assertGetValueWithColumnIndexWithLong() throws SQLException {
when(resultSet.getLong(1)).thenReturn(1L);
assertThat((long) showOtherMergedResult.getValue(1, long.class), is(1L));
}
@Test
public void assertGetValueWithColumnIndexWithFloat() throws SQLException {
when(resultSet.getFloat(1)).thenReturn(1F);
assertThat((float) showOtherMergedResult.getValue(1, float.class), is(1F));
}
@Test
public void assertGetValueWithColumnIndexWithDouble() throws SQLException {
when(resultSet.getDouble(1)).thenReturn(1D);
assertThat((double) showOtherMergedResult.getValue(1, double.class), is(1D));
}
@Test
public void assertGetValueWithColumnIndexWithString() throws SQLException {
when(resultSet.getString(1)).thenReturn("1");
assertThat((String) showOtherMergedResult.getValue(1, String.class), is("1"));
}
@Test
public void assertGetValueWithColumnIndexWithBigDecimal() throws SQLException {
when(resultSet.getBigDecimal(1)).thenReturn(new BigDecimal("1"));
assertThat((BigDecimal) showOtherMergedResult.getValue(1, BigDecimal.class), is(new BigDecimal("1")));
}
@Test
public void assertGetValueWithColumnIndexWithByteArray() throws SQLException {
when(resultSet.getBytes(1)).thenReturn(new byte[] {(byte) 1});
assertThat((byte[]) showOtherMergedResult.getValue(1, byte[].class), is(new byte[] {(byte) 1}));
}
@Test
public void assertGetValueWithColumnIndexWithDate() throws SQLException {
when(resultSet.getDate(1)).thenReturn(new Date(0L));
assertThat((Date) showOtherMergedResult.getValue(1, Date.class), is(new Date(0L)));
}
@Test
public void assertGetValueWithColumnIndexWithTime() throws SQLException {
when(resultSet.getTime(1)).thenReturn(new Time(0L));
assertThat((Time) showOtherMergedResult.getValue(1, Time.class), is(new Time(0L)));
}
@Test
public void assertGetValueWithColumnIndexWithTimestamp() throws SQLException {
when(resultSet.getTimestamp(1)).thenReturn(new Timestamp(0L));
assertThat((Timestamp) showOtherMergedResult.getValue(1, Timestamp.class), is(new Timestamp(0L)));
}
@Test
public void assertGetValueWithColumnIndexWithURL() throws SQLException, MalformedURLException {
when(resultSet.getURL(1)).thenReturn(new URL("http://xxx.xxx"));
assertThat((URL) showOtherMergedResult.getValue(1, URL.class), is(new URL("http://xxx.xxx")));
}
@Test
public void assertGetValueWithColumnIndexWithBlob() throws SQLException {
Blob blob = mock(Blob.class);
when(resultSet.getBlob(1)).thenReturn(blob);
assertThat((Blob) showOtherMergedResult.getValue(1, Blob.class), is(blob));
}
@Test
public void assertGetValueWithColumnIndexWithClob() throws SQLException {
Clob clob = mock(Clob.class);
when(resultSet.getClob(1)).thenReturn(clob);
assertThat((Clob) showOtherMergedResult.getValue(1, Clob.class), is(clob));
}
@Test
public void assertGetValueWithColumnIndexWithSQLXML() throws SQLException {
SQLXML sqlxml = mock(SQLXML.class);
when(resultSet.getSQLXML(1)).thenReturn(sqlxml);
assertThat((SQLXML) showOtherMergedResult.getValue(1, SQLXML.class), is(sqlxml));
}
@Test
public void assertGetValueWithColumnIndexWithReader() throws SQLException {
Reader reader = mock(Reader.class);
when(resultSet.getCharacterStream(1)).thenReturn(reader);
assertThat((Reader) showOtherMergedResult.getValue(1, Reader.class), is(reader));
}
@Test
public void assertGetValueWithColumnIndexWithOtherObject() throws SQLException {
when(resultSet.getObject(1)).thenReturn("1");
assertThat((String) showOtherMergedResult.getValue(1, Collection.class), is("1"));
}
@Test
public void assertGetValueWithColumnLabelWithObject() throws SQLException {
when(resultSet.getObject("label")).thenReturn("1");
assertThat(showOtherMergedResult.getValue("label", Object.class).toString(), is("1"));
}
@Test
public void assertGetValueWithColumnLabelWithBoolean() throws SQLException {
when(resultSet.getBoolean("label")).thenReturn(true);
assertTrue((Boolean) showOtherMergedResult.getValue("label", boolean.class));
}
@Test
public void assertGetValueWithColumnLabelWithByte() throws SQLException {
when(resultSet.getByte("label")).thenReturn((byte) 1);
assertThat((byte) showOtherMergedResult.getValue("label", byte.class), is((byte) 1));
}
@Test
public void assertGetValueWithColumnLabelWithShort() throws SQLException {
when(resultSet.getShort("label")).thenReturn((short) 1);
assertThat((short) showOtherMergedResult.getValue("label", short.class), is((short) 1));
}
@Test
public void assertGetValueWithColumnLabelWithInt() throws SQLException {
when(resultSet.getInt("label")).thenReturn(1);
assertThat((int) showOtherMergedResult.getValue("label", int.class), is(1));
}
@Test
public void assertGetValueWithColumnLabelWithLong() throws SQLException {
when(resultSet.getLong("label")).thenReturn(1L);
assertThat((long) showOtherMergedResult.getValue("label", long.class), is(1L));
}
@Test
public void assertGetValueWithColumnLabelWithFloat() throws SQLException {
when(resultSet.getFloat("label")).thenReturn(1F);
assertThat((float) showOtherMergedResult.getValue("label", float.class), is(1F));
}
@Test
public void assertGetValueWithColumnLabelWithDouble() throws SQLException {
when(resultSet.getDouble("label")).thenReturn(1D);
assertThat((double) showOtherMergedResult.getValue("label", double.class), is(1D));
}
@Test
public void assertGetValueWithColumnLabelWithString() throws SQLException {
when(resultSet.getString("label")).thenReturn("1");
assertThat((String) showOtherMergedResult.getValue("label", String.class), is("1"));
}
@Test
public void assertGetValueWithColumnLabelWithBigDecimal() throws SQLException {
when(resultSet.getBigDecimal("label")).thenReturn(new BigDecimal("1"));
assertThat((BigDecimal) showOtherMergedResult.getValue("label", BigDecimal.class), is(new BigDecimal("1")));
}
@Test
public void assertGetValueWithColumnLabelWithByteArray() throws SQLException {
when(resultSet.getBytes("label")).thenReturn(new byte[] {(byte) 1});
assertThat((byte[]) showOtherMergedResult.getValue("label", byte[].class), is(new byte[] {(byte) 1}));
}
@Test
public void assertGetValueWithColumnLabelWithDate() throws SQLException {
when(resultSet.getDate("label")).thenReturn(new Date(0L));
assertThat((Date) showOtherMergedResult.getValue("label", Date.class), is(new Date(0L)));
}
@Test
public void assertGetValueWithColumnLabelWithTime() throws SQLException {
when(resultSet.getTime("label")).thenReturn(new Time(0L));
assertThat((Time) showOtherMergedResult.getValue("label", Time.class), is(new Time(0L)));
}
@Test
public void assertGetValueWithColumnLabelWithTimestamp() throws SQLException {
when(resultSet.getTimestamp("label")).thenReturn(new Timestamp(0L));
assertThat((Timestamp) showOtherMergedResult.getValue("label", Timestamp.class), is(new Timestamp(0L)));
}
@Test
public void assertGetValueWithColumnLabelWithURL() throws SQLException, MalformedURLException {
when(resultSet.getURL("label")).thenReturn(new URL("http://xxx.xxx"));
assertThat((URL) showOtherMergedResult.getValue("label", URL.class), is(new URL("http://xxx.xxx")));
}
@Test
public void assertGetValueWithColumnLabelWithBlob() throws SQLException {
Blob blob = mock(Blob.class);
when(resultSet.getBlob("label")).thenReturn(blob);
assertThat((Blob) showOtherMergedResult.getValue("label", Blob.class), is(blob));
}
@Test
public void assertGetValueWithColumnLabelWithClob() throws SQLException {
Clob clob = mock(Clob.class);
when(resultSet.getClob("label")).thenReturn(clob);
assertThat((Clob) showOtherMergedResult.getValue("label", Clob.class), is(clob));
}
@Test
public void assertGetValueWithColumnLabelWithSQLXML() throws SQLException {
SQLXML sqlxml = mock(SQLXML.class);
when(resultSet.getSQLXML("label")).thenReturn(sqlxml);
assertThat((SQLXML) showOtherMergedResult.getValue("label", SQLXML.class), is(sqlxml));
}
@Test
public void assertGetValueWithColumnLabelWithReader() throws SQLException {
Reader reader = mock(Reader.class);
when(resultSet.getCharacterStream("label")).thenReturn(reader);
assertThat((Reader) showOtherMergedResult.getValue("label", Reader.class), is(reader));
}
@Test
public void assertGetValueWithColumnLabelWithOtherObject() throws SQLException {
when(resultSet.getObject("label")).thenReturn("1");
assertThat((String) showOtherMergedResult.getValue("label", Collection.class), is("1"));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnIndexWithDate() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Date) showOtherMergedResult.getCalendarValue(1, Date.class, calendar), is(new Date(0L)));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnIndexWithTime() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Time) showOtherMergedResult.getCalendarValue(1, Time.class, calendar), is(new Time(0L)));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnIndexWithTimestamp() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Timestamp) showOtherMergedResult.getCalendarValue(1, Timestamp.class, calendar), is(new Timestamp(0L)));
}
@Test(expected = SQLException.class)
public void assertGetCalendarValueWithColumnIndexWithInvalidType() throws SQLException {
showOtherMergedResult.getCalendarValue(1, Object.class, Calendar.getInstance());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnLabelWithDate() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Date) showOtherMergedResult.getCalendarValue("label", Date.class, calendar), is(new Date(0L)));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnLabelWithTime() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Time) showOtherMergedResult.getCalendarValue("label", Time.class, calendar), is(new Time(0L)));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetCalendarValueWithColumnLabelWithTimestamp() throws SQLException {
Calendar calendar = Calendar.getInstance();
assertThat((Timestamp) showOtherMergedResult.getCalendarValue("label", Timestamp.class, calendar), is(new Timestamp(0L)));
}
@Test(expected = SQLException.class)
public void assertGetCalendarValueWithColumnLabelWithInvalidType() throws SQLException {
showOtherMergedResult.getCalendarValue("label", Object.class, Calendar.getInstance());
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnIndexWithAscii() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream(1, "Ascii"), is(inputStream));
}
@SuppressWarnings("deprecation")
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnIndexWithUnicode() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream(1, "Unicode"), is(inputStream));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnIndexWithBinary() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream(1, "Binary"), is(inputStream));
}
@Test(expected = SQLException.class)
public void assertGetInputStreamWithColumnIndexWithInvalidType() throws SQLException {
showOtherMergedResult.getInputStream(1, "Invalid");
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnLabelWithAscii() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream("label", "Ascii"), is(inputStream));
}
@SuppressWarnings("deprecation")
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnLabelWithUnicode() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream("label", "Unicode"), is(inputStream));
}
@Test(expected = SQLFeatureNotSupportedException.class)
public void assertGetInputStreamWithColumnLabelWithBinary() throws SQLException {
InputStream inputStream = mock(InputStream.class);
assertThat(showOtherMergedResult.getInputStream("label", "Binary"), is(inputStream));
}
@Test(expected = SQLException.class)
public void assertGetInputStreamWithColumnLabelWithInvalidType() throws SQLException {
showOtherMergedResult.getInputStream("label", "Invalid");
}
@Test
public void assertWasNull() {
assertFalse(showOtherMergedResult.wasNull());
}
}
/*
* 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 io.shardingjdbc.core.merger.dal.show;
import com.google.common.collect.Lists;
import io.shardingjdbc.core.api.algorithm.fixture.TestComplexKeysShardingAlgorithm;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.ComplexShardingStrategyConfiguration;
import io.shardingjdbc.core.merger.QueryResult;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.rule.ShardingRule;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class ShowTablesMergedResultTest {
private ShardingRule shardingRule;
private List<QueryResult> queryResults;
private ResultSet resultSet;
@Before
public void setUp() throws SQLException {
TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration();
tableRuleConfig.setLogicTable("table");
tableRuleConfig.setActualDataNodes("ds.table_${0..2}");
tableRuleConfig.setTableShardingStrategyConfig(new ComplexShardingStrategyConfiguration("field1, field2, field3", new TestComplexKeysShardingAlgorithm()));
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig);
shardingRule = new ShardingRule(shardingRuleConfig, Lists.newArrayList("ds"));
resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
when(resultSetMetaData.getColumnCount()).thenReturn(1);
List<ResultSet> resultSets = Lists.newArrayList(resultSet);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, false);
}
queryResults = new ArrayList<>(resultSets.size());
for (ResultSet each : resultSets) {
queryResults.add(new TestQueryResult(each));
}
}
@Test
public void assertNextForEmptyQueryResult() throws SQLException {
ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, new ArrayList<QueryResult>());
assertFalse(showTablesMergedResult.next());
}
@Test
public void assertNextForActualTableNameInTableRule() throws SQLException {
when(resultSet.getObject(1)).thenReturn("table_0");
ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults);
assertTrue(showTablesMergedResult.next());
}
@Test
public void assertNextForActualTableNameNotInTableRule() throws SQLException {
when(resultSet.getObject(1)).thenReturn("table_3");
ShowTablesMergedResult showTablesMergedResult = new ShowTablesMergedResult(shardingRule, queryResults);
assertTrue(showTablesMergedResult.next());
}
}
......@@ -28,6 +28,8 @@ import io.shardingjdbc.core.merger.dql.groupby.GroupByStreamMergedResult;
import io.shardingjdbc.core.merger.dql.iterator.IteratorStreamMergedResult;
import io.shardingjdbc.core.merger.dql.orderby.OrderByStreamMergedResult;
import io.shardingjdbc.core.merger.dql.pagination.LimitDecoratorMergedResult;
import io.shardingjdbc.core.merger.dql.pagination.RowNumberDecoratorMergedResult;
import io.shardingjdbc.core.merger.dql.pagination.TopAndRowNumberDecoratorMergedResult;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.parsing.parser.context.OrderItem;
import io.shardingjdbc.core.parsing.parser.context.limit.Limit;
......@@ -74,7 +76,7 @@ public final class DQLMergeEngineTest {
}
@Test
public void assertBuildIteratorStreamMergedResultWithLimit() throws SQLException {
public void assertBuildIteratorStreamMergedResultWithMySQLLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.MySQL));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
......@@ -82,6 +84,24 @@ public final class DQLMergeEngineTest {
assertThat(((LimitDecoratorMergedResult) actual).getMergedResult(), instanceOf(IteratorStreamMergedResult.class));
}
@Test
public void assertBuildIteratorStreamMergedResultWithOracleLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.Oracle));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(RowNumberDecoratorMergedResult.class));
assertThat(((RowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(IteratorStreamMergedResult.class));
}
@Test
public void assertBuildIteratorStreamMergedResultWithSQLServerLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.SQLServer));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(TopAndRowNumberDecoratorMergedResult.class));
assertThat(((TopAndRowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(IteratorStreamMergedResult.class));
}
@Test
public void assertBuildOrderByStreamMergedResult() throws SQLException {
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
......@@ -90,7 +110,7 @@ public final class DQLMergeEngineTest {
}
@Test
public void assertBuildOrderByStreamMergedResultWithLimit() throws SQLException {
public void assertBuildOrderByStreamMergedResultWithMySQLLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.MySQL));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
......@@ -99,6 +119,26 @@ public final class DQLMergeEngineTest {
assertThat(((LimitDecoratorMergedResult) actual).getMergedResult(), instanceOf(OrderByStreamMergedResult.class));
}
@Test
public void assertBuildOrderByStreamMergedResultWithOracleLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.Oracle));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(RowNumberDecoratorMergedResult.class));
assertThat(((RowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(OrderByStreamMergedResult.class));
}
@Test
public void assertBuildOrderByStreamMergedResultWithSQLServerLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.SQLServer));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(TopAndRowNumberDecoratorMergedResult.class));
assertThat(((TopAndRowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(OrderByStreamMergedResult.class));
}
@Test
public void assertBuildGroupByStreamMergedResult() throws SQLException {
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
......@@ -108,7 +148,7 @@ public final class DQLMergeEngineTest {
}
@Test
public void assertBuildGroupByStreamMergedResultWithLimit() throws SQLException {
public void assertBuildGroupByStreamMergedResultWithMySQLLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.MySQL));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
......@@ -118,6 +158,28 @@ public final class DQLMergeEngineTest {
assertThat(((LimitDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByStreamMergedResult.class));
}
@Test
public void assertBuildGroupByStreamMergedResultWithOracleLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.Oracle));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(RowNumberDecoratorMergedResult.class));
assertThat(((RowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByStreamMergedResult.class));
}
@Test
public void assertBuildGroupByStreamMergedResultWithSQLServerLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.SQLServer));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
selectStatement.getOrderByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(TopAndRowNumberDecoratorMergedResult.class));
assertThat(((TopAndRowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByStreamMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResult() throws SQLException {
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
......@@ -126,7 +188,7 @@ public final class DQLMergeEngineTest {
}
@Test
public void assertBuildGroupByMemoryMergedResultWithLimit() throws SQLException {
public void assertBuildGroupByMemoryMergedResultWithMySQLLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.MySQL));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
......@@ -135,6 +197,28 @@ public final class DQLMergeEngineTest {
assertThat(((LimitDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResultWithOracleLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.Oracle));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
selectStatement.getOrderByItems().add(new OrderItem(2, OrderDirection.DESC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(RowNumberDecoratorMergedResult.class));
assertThat(((RowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResultWithSQLServerLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.SQLServer));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC));
selectStatement.getGroupByItems().add(new OrderItem(1, OrderDirection.ASC, OrderDirection.ASC));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(TopAndRowNumberDecoratorMergedResult.class));
assertThat(((TopAndRowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResultWithAggregationOnly() throws SQLException {
selectStatement.getItems().add(new AggregationSelectItem(AggregationType.COUNT, "(*)", Optional.<String>absent()));
......@@ -143,7 +227,7 @@ public final class DQLMergeEngineTest {
}
@Test
public void assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithLimit() throws SQLException {
public void assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithMySQLLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.MySQL));
selectStatement.getItems().add(new AggregationSelectItem(AggregationType.COUNT, "(*)", Optional.<String>absent()));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
......@@ -151,4 +235,24 @@ public final class DQLMergeEngineTest {
assertThat(actual, instanceOf(LimitDecoratorMergedResult.class));
assertThat(((LimitDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithOracleLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.Oracle));
selectStatement.getItems().add(new AggregationSelectItem(AggregationType.COUNT, "(*)", Optional.<String>absent()));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(RowNumberDecoratorMergedResult.class));
assertThat(((RowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
@Test
public void assertBuildGroupByMemoryMergedResultWithAggregationOnlyWithSQLServerLimit() throws SQLException {
selectStatement.setLimit(new Limit(DatabaseType.SQLServer));
selectStatement.getItems().add(new AggregationSelectItem(AggregationType.COUNT, "(*)", Optional.<String>absent()));
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertThat(actual, instanceOf(TopAndRowNumberDecoratorMergedResult.class));
assertThat(((TopAndRowNumberDecoratorMergedResult) actual).getMergedResult(), instanceOf(GroupByMemoryMergedResult.class));
}
}
......@@ -44,6 +44,7 @@ import java.util.Collection;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
......@@ -420,4 +421,9 @@ public final class StreamMergedResultTest {
public void assertGetInputStreamWithColumnLabelWithInvalidType() throws SQLException {
streamMergedResult.getInputStream("label", "Invalid");
}
@Test
public void assertWasNull() {
assertFalse(streamMergedResult.wasNull());
}
}
......@@ -32,6 +32,7 @@ import java.util.Arrays;
import java.util.List;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertFalse;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
......@@ -53,4 +54,25 @@ public final class GroupByValueTest {
List<?> expected = Arrays.asList("1", "3");
assertTrue(actual.equals(expected));
}
@Test
public void assertGroupByValueEquals() throws SQLException {
GroupByValue groupByValue1 = new GroupByValue(new TestQueryResult(resultSet),
Arrays.asList(new OrderItem(1, OrderDirection.ASC, OrderDirection.ASC), new OrderItem(3, OrderDirection.DESC, OrderDirection.ASC)));
GroupByValue groupByValue2 = new GroupByValue(new TestQueryResult(resultSet),
Arrays.asList(new OrderItem(1, OrderDirection.ASC, OrderDirection.ASC), new OrderItem(3, OrderDirection.DESC, OrderDirection.ASC)));
assertTrue(groupByValue1.equals(groupByValue2));
assertTrue(groupByValue2.equals(groupByValue1));
assertTrue(groupByValue1.hashCode() == groupByValue2.hashCode());
}
@Test
public void assertGroupByValueNotEquals() throws SQLException {
GroupByValue groupByValue1 = new GroupByValue(new TestQueryResult(resultSet),
Arrays.asList(new OrderItem(1, OrderDirection.ASC, OrderDirection.ASC), new OrderItem(3, OrderDirection.DESC, OrderDirection.ASC)));
GroupByValue groupByValue2 = new GroupByValue(new TestQueryResult(resultSet),
Arrays.asList(new OrderItem(3, OrderDirection.ASC, OrderDirection.ASC), new OrderItem(1, OrderDirection.DESC, OrderDirection.ASC)));
assertFalse(groupByValue1.equals(groupByValue2));
assertFalse(groupByValue1.hashCode() == groupByValue2.hashCode());
}
}
......@@ -44,8 +44,6 @@ public final class LimitDecoratorMergedResultTest {
private DQLMergeEngine mergeEngine;
private List<ResultSet> resultSets;
private List<QueryResult> queryResults;
private SelectStatement selectStatement;
......@@ -55,7 +53,10 @@ public final class LimitDecoratorMergedResultTest {
ResultSet resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class));
List<ResultSet> resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class));
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
queryResults = new ArrayList<>(resultSets.size());
for (ResultSet each : resultSets) {
queryResults.add(new TestQueryResult(each));
......@@ -68,9 +69,6 @@ public final class LimitDecoratorMergedResultTest {
Limit limit = new Limit(DatabaseType.MySQL);
limit.setOffset(new LimitValue(Integer.MAX_VALUE, -1, true));
selectStatement.setLimit(limit);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertFalse(actual.next());
......@@ -81,45 +79,20 @@ public final class LimitDecoratorMergedResultTest {
Limit limit = new Limit(DatabaseType.MySQL);
limit.setOffset(new LimitValue(2, -1, true));
selectStatement.setLimit(limit);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
for (int i = 0; i < 6; i++) {
assertTrue(actual.next());
}
assertFalse(actual.next());
}
@Test
public void assertNextWithRewriteRowCount() throws SQLException {
public void assertNextWithRowCount() throws SQLException {
Limit limit = new Limit(DatabaseType.MySQL);
limit.setOffset(new LimitValue(2, -1, true));
limit.setRowCount(new LimitValue(2, -1, false));
selectStatement.setLimit(limit);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertFalse(actual.next());
}
@Test
public void assertNextWithNotRewriteRowCount() throws SQLException {
Limit limit = new Limit(DatabaseType.Oracle);
limit.setOffset(new LimitValue(2, -1, true));
limit.setRowCount(new LimitValue(4, -1, false));
selectStatement.setLimit(limit);
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
......
/*
* 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 io.shardingjdbc.core.merger.dql.pagination;
import com.google.common.collect.Lists;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.core.merger.MergedResult;
import io.shardingjdbc.core.merger.QueryResult;
import io.shardingjdbc.core.merger.dql.DQLMergeEngine;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.parsing.parser.context.limit.Limit;
import io.shardingjdbc.core.parsing.parser.context.limit.LimitValue;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class RowNumberDecoratorMergedResultTest {
private DQLMergeEngine mergeEngine;
private List<QueryResult> queryResults;
private SelectStatement selectStatement;
@Before
public void setUp() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
List<ResultSet> resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class));
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
queryResults = new ArrayList<>(resultSets.size());
for (ResultSet each : resultSets) {
queryResults.add(new TestQueryResult(each));
}
selectStatement = new SelectStatement();
}
@Test
public void assertNextForSkipAll() throws SQLException {
Limit limit = new Limit(DatabaseType.Oracle);
limit.setOffset(new LimitValue(Integer.MAX_VALUE, -1, true));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertFalse(actual.next());
}
@Test
public void assertNextWithoutOffsetWithoutRowCount() throws SQLException {
Limit limit = new Limit(DatabaseType.Oracle);
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
for (int i = 0; i < 8; i++) {
assertTrue(actual.next());
}
assertFalse(actual.next());
}
@Test
public void assertNextForRowCountBoundOpendedFalse() throws SQLException {
Limit limit = new Limit(DatabaseType.Oracle);
limit.setOffset(new LimitValue(2, -1, true));
limit.setRowCount(new LimitValue(4, -1, false));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertFalse(actual.next());
}
@Test
public void assertNextForRowCountBoundOpendedTrue() throws SQLException {
Limit limit = new Limit(DatabaseType.Oracle);
limit.setOffset(new LimitValue(2, -1, true));
limit.setRowCount(new LimitValue(4, -1, true));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
assertFalse(actual.next());
}
}
/*
* 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 io.shardingjdbc.core.merger.dql.pagination;
import com.google.common.collect.Lists;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.core.merger.MergedResult;
import io.shardingjdbc.core.merger.QueryResult;
import io.shardingjdbc.core.merger.dql.DQLMergeEngine;
import io.shardingjdbc.core.merger.fixture.TestQueryResult;
import io.shardingjdbc.core.parsing.parser.context.limit.Limit;
import io.shardingjdbc.core.parsing.parser.context.limit.LimitValue;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import org.junit.Before;
import org.junit.Test;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public final class TopAndRowNumberDecoratorMergedResultTest {
private DQLMergeEngine mergeEngine;
private List<QueryResult> queryResults;
private SelectStatement selectStatement;
@Before
public void setUp() throws SQLException {
ResultSet resultSet = mock(ResultSet.class);
ResultSetMetaData resultSetMetaData = mock(ResultSetMetaData.class);
when(resultSet.getMetaData()).thenReturn(resultSetMetaData);
List<ResultSet> resultSets = Lists.newArrayList(resultSet, mock(ResultSet.class), mock(ResultSet.class), mock(ResultSet.class));
for (ResultSet each : resultSets) {
when(each.next()).thenReturn(true, true, false);
}
queryResults = new ArrayList<>(resultSets.size());
for (ResultSet each : resultSets) {
queryResults.add(new TestQueryResult(each));
}
selectStatement = new SelectStatement();
}
@Test
public void assertNextForSkipAll() throws SQLException {
Limit limit = new Limit(DatabaseType.SQLServer);
limit.setOffset(new LimitValue(Integer.MAX_VALUE, -1, true));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertFalse(actual.next());
}
@Test
public void assertNextWithoutOffsetWithRowCount() throws SQLException {
Limit limit = new Limit(DatabaseType.SQLServer);
limit.setRowCount(new LimitValue(5, -1, false));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
for (int i = 0; i < 5; i++) {
assertTrue(actual.next());
}
assertFalse(actual.next());
}
@Test
public void assertNextWithOffsetWithoutRowCount() throws SQLException {
Limit limit = new Limit(DatabaseType.SQLServer);
limit.setOffset(new LimitValue(2, -1, true));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
for (int i = 0; i < 7; i++) {
assertTrue(actual.next());
}
assertFalse(actual.next());
}
@Test
public void assertNextWithOffsetBoundOpendedFalse() throws SQLException {
Limit limit = new Limit(DatabaseType.SQLServer);
limit.setOffset(new LimitValue(2, -1, false));
limit.setRowCount(new LimitValue(4, -1, false));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertFalse(actual.next());
}
@Test
public void assertNextWithOffsetBoundOpendedTrue() throws SQLException {
Limit limit = new Limit(DatabaseType.SQLServer);
limit.setOffset(new LimitValue(2, -1, true));
limit.setRowCount(new LimitValue(4, -1, false));
selectStatement.setLimit(limit);
mergeEngine = new DQLMergeEngine(queryResults, selectStatement);
MergedResult actual = mergeEngine.merge();
assertTrue(actual.next());
assertTrue(actual.next());
assertTrue(actual.next());
assertFalse(actual.next());
}
}
......@@ -19,7 +19,6 @@ package io.shardingjdbc.core.rewrite;
import io.shardingjdbc.core.api.config.ShardingRuleConfiguration;
import io.shardingjdbc.core.api.config.TableRuleConfiguration;
import io.shardingjdbc.core.api.config.strategy.NoneShardingStrategyConfiguration;
import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.core.rewrite.placeholder.IndexPlaceholder;
import io.shardingjdbc.core.rewrite.placeholder.SchemaPlaceholder;
......@@ -27,7 +26,11 @@ import io.shardingjdbc.core.rewrite.placeholder.TablePlaceholder;
import io.shardingjdbc.core.rule.ShardingRule;
import org.junit.Test;
import java.util.*;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
......@@ -76,8 +79,8 @@ public final class SQLBuilderTest {
sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x"));
sqlBuilder.appendLiterals(" ON ");
sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x"));
sqlBuilder.appendLiterals(" ('cloumn')");
assertThat(sqlBuilder.toSQL(Collections.<String, String>emptyMap(), null), is("CREATE INDEX index_name ON table_x ('cloumn')"));
sqlBuilder.appendLiterals(" ('column')");
assertThat(sqlBuilder.toSQL(Collections.<String, String>emptyMap(), null), is("CREATE INDEX index_name ON table_x ('column')"));
}
@Test
......@@ -87,10 +90,10 @@ public final class SQLBuilderTest {
sqlBuilder.appendPlaceholder(new IndexPlaceholder("index_name", "table_x"));
sqlBuilder.appendLiterals(" ON ");
sqlBuilder.appendPlaceholder(new TablePlaceholder("table_x"));
sqlBuilder.appendLiterals(" ('cloumn')");
sqlBuilder.appendLiterals(" ('column')");
Map<String, String> tableTokens = new HashMap<>(1, 1);
tableTokens.put("table_x", "table_x_1");
assertThat(sqlBuilder.toSQL(tableTokens, null), is("CREATE INDEX index_name_table_x_1 ON table_x_1 ('cloumn')"));
assertThat(sqlBuilder.toSQL(tableTokens, null), is("CREATE INDEX index_name_table_x_1 ON table_x_1 ('column')"));
}
@Test(expected = ShardingJdbcException.class)
......@@ -121,8 +124,7 @@ public final class SQLBuilderTest {
ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration();
TableRuleConfiguration tableRuleConfig = createTableRuleConfig();
shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig);
ShardingRule actual = new ShardingRule(shardingRuleConfig, createDataSourceNames());
return actual;
return new ShardingRule(shardingRuleConfig, createDataSourceNames());
}
private Collection<String> createDataSourceNames() {
......
......@@ -33,4 +33,21 @@
</condition>
</conditions>
</parser-result>
<parser-result sql-case-id="assertUpdateWithGeoInPostgreSQL" parameters="'2017-06-07' 100 200 '{&quot;rule2&quot;:&quot;null2&quot;}' 3 5 7 200">
<tables>
<table name="t_place" />
</tables>
<tokens>
<table-token begin-position="7" original-literals="t_place" />
</tokens>
<conditions>
<condition column-name="user_new_id" table-name="t_place" operator="EQUAL">
<value index="6" literal="7" type="int" />
</condition>
<condition column-name="guid" table-name="t_place" operator="EQUAL">
<value index="7" literal="200" type="int"/>
</condition>
</conditions>
</parser-result>
</parser-result-sets>
......@@ -25,6 +25,12 @@ shardingRule:
shardingColumns: user_id, order_id, item_id
algorithmClassName: io.shardingjdbc.core.api.algorithm.fixture.TestComplexKeysShardingAlgorithm
keyGeneratorColumnName: item_id
t_place:
actualDataNodes: db${0..1}.t_place
tableStrategy:
complex:
shardingColumns: user_new_id, guid
algorithmClassName: io.shardingjdbc.core.api.algorithm.fixture.TestComplexKeysShardingAlgorithm
bindingTables:
- t_order, t_order_item
defaultKeyGeneratorClass: io.shardingjdbc.core.keygen.fixture.IncrementKeyGenerator
......@@ -17,6 +17,18 @@
package io.shardingjdbc.spring.boot;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import com.google.common.base.Preconditions;
import io.shardingjdbc.core.api.MasterSlaveDataSourceFactory;
import io.shardingjdbc.core.api.ShardingDataSourceFactory;
......@@ -24,14 +36,7 @@ import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.core.util.DataSourceUtil;
import io.shardingjdbc.spring.boot.masterslave.SpringBootMasterSlaveRuleConfigurationProperties;
import io.shardingjdbc.spring.boot.sharding.SpringBootShardingRuleConfigurationProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;
import io.shardingjdbc.spring.boot.util.PropertyUtil;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.LinkedHashMap;
......@@ -72,12 +77,13 @@ public class SpringBootConfiguration implements EnvironmentAware {
setDataSourceMap(environment);
}
@SuppressWarnings("unchecked")
private void setDataSourceMap(final Environment environment) {
RelaxedPropertyResolver propertyResolver = new RelaxedPropertyResolver(environment, "sharding.jdbc.datasource.");
String dataSources = propertyResolver.getProperty("names");
String prefix = "sharding.jdbc.datasource.";
String dataSources = environment.getProperty(prefix + "names");
for (String each : dataSources.split(",")) {
try {
Map<String, Object> dataSourceProps = propertyResolver.getSubProperties(each + ".");
Map<String, Object> dataSourceProps = PropertyUtil.handle(environment, prefix + each, Map.class);
Preconditions.checkState(!dataSourceProps.isEmpty(), "Wrong datasource properties!");
DataSource dataSource = DataSourceUtil.getDataSource(dataSourceProps.get("type").toString(), dataSourceProps);
dataSourceMap.put(each, dataSource);
......
/*
* 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 io.shardingjdbc.spring.boot.util;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import org.springframework.core.env.Environment;
import org.springframework.core.env.PropertyResolver;
import io.shardingjdbc.core.exception.ShardingJdbcException;
public class PropertyUtil {
private static int springBootVersion = 1;
static {
try {
Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
} catch (ClassNotFoundException e) {
springBootVersion = 2;
}
}
/**
* Spring Boot 1.x is compatible with Spring Boot 2.x by Using Java Reflect.
* @param environment : the environment context
* @param prefix : the prefix part of property key
* @param targetClass : the target class type of result
* @param <T> : refer to @param targetClass
* @return T
*/
@SuppressWarnings("unchecked")
public static <T> T handle(final Environment environment, final String prefix, final Class<T> targetClass) {
switch (springBootVersion) {
case 1:
return (T) v1(environment, prefix, targetClass);
default:
return (T) v2(environment, prefix, targetClass);
}
}
private static Object v1(final Environment environment, final String prefix, final Class<?> targetClass) {
try {
Class<?> resolverClass = Class.forName("org.springframework.boot.bind.RelaxedPropertyResolver");
Constructor<?> resolverConstructor = resolverClass.getDeclaredConstructor(PropertyResolver.class);
Method getSubPropertiesMethod = resolverClass.getDeclaredMethod("getSubProperties", String.class);
Object resolverObject = resolverConstructor.newInstance(environment);
String prefixParam = prefix.endsWith(".") ? prefix : prefix + ".";
return getSubPropertiesMethod.invoke(resolverObject, prefixParam);
} catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
| IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
throw new ShardingJdbcException(ex.getMessage(), ex);
}
}
private static Object v2(final Environment environment, final String prefix, final Class<?> targetClass) {
try {
Class<?> binderClass = Class.forName("org.springframework.boot.context.properties.bind.Binder");
Method getMethod = binderClass.getDeclaredMethod("get", Environment.class);
Method bindMethod = binderClass.getDeclaredMethod("bind", String.class, Class.class);
Object binderObject = getMethod.invoke(null, environment);
String prefixParam = prefix.endsWith(".") ? prefix.substring(0, prefix.length() - 1) : prefix;
Object bindResultObject = bindMethod.invoke(binderObject, prefixParam, targetClass);
Method resultGetMethod = bindResultObject.getClass().getDeclaredMethod("get");
return resultGetMethod.invoke(bindResultObject);
} catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException
| IllegalArgumentException | InvocationTargetException ex) {
throw new ShardingJdbcException(ex.getMessage(), ex);
}
}
}
......@@ -17,7 +17,7 @@
package io.shardingjdbc.proxy;
import io.shardingjdbc.proxy.transport.ShardingProxy;
import io.shardingjdbc.proxy.frontend.ShardingProxy;
/**
* Sharding-Proxy Bootstrap.
......
/*
* 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 io.shardingjdbc.proxy.config;
import io.shardingjdbc.core.exception.ShardingJdbcException;
import io.shardingjdbc.core.rule.ShardingRule;
import io.shardingjdbc.core.yaml.sharding.YamlShardingConfiguration;
import lombok.Getter;
import javax.sql.DataSource;
import java.io.File;
import java.io.IOException;
import java.util.Collections;
import java.util.Map;
/**
* Sharding rule registry.
*
* @author zhangliang
*/
@Getter
public final class ShardingRuleRegistry {
private static final ShardingRuleRegistry INSTANCE = new ShardingRuleRegistry();
private final Map<String, DataSource> dataSourceMap;
private final ShardingRule shardingRule;
private ShardingRuleRegistry() {
YamlShardingConfiguration yamlShardingConfig;
try {
yamlShardingConfig = YamlShardingConfiguration.unmarshal(new File(getClass().getResource("/conf/sharding-config.yaml").getFile()));
} catch (IOException ex) {
throw new ShardingJdbcException(ex);
}
dataSourceMap = yamlShardingConfig.getDataSources();
shardingRule = yamlShardingConfig.getShardingRule(Collections.<String>emptyList());
}
/**
* Get instance of sharding rule registry.
*
* @return instance of sharding rule registry
*/
public static ShardingRuleRegistry getInstance() {
return INSTANCE;
}
}
......@@ -15,7 +15,7 @@
* </p>
*/
package io.shardingjdbc.proxy.transport;
package io.shardingjdbc.proxy.frontend;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
......@@ -27,7 +27,7 @@ import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.proxy.transport.common.codec.PacketCodecFactory;
import io.shardingjdbc.proxy.transport.common.handler.DatabaseProxyHandlerFactory;
import io.shardingjdbc.proxy.frontend.common.handler.FrontendHandlerFactory;
/**
* Sharding-Proxy.
......@@ -55,7 +55,7 @@ public final class ShardingProxy {
ChannelPipeline pipeline = socketChannel.pipeline();
// TODO load database type from yaml or startup arguments
pipeline.addLast(PacketCodecFactory.createPacketCodecInstance(DatabaseType.MySQL));
pipeline.addLast(DatabaseProxyHandlerFactory.createDatabaseProxyHandlerInstance(DatabaseType.MySQL));
pipeline.addLast(FrontendHandlerFactory.createFrontendHandlerInstance(DatabaseType.MySQL));
}
});
ChannelFuture future = bootstrap.bind(port).sync();
......
......@@ -15,18 +15,18 @@
* </p>
*/
package io.shardingjdbc.proxy.transport.common.handler;
package io.shardingjdbc.proxy.frontend.common.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
/**
* Database proxy handler.
* Frontend handler.
*
* @author zhangliang
*/
public abstract class DatabaseProxyHandler extends ChannelInboundHandlerAdapter {
public abstract class FrontendHandler extends ChannelInboundHandlerAdapter {
private boolean authorized;
......
......@@ -15,31 +15,31 @@
* </p>
*/
package io.shardingjdbc.proxy.transport.common.handler;
package io.shardingjdbc.proxy.frontend.common.handler;
import io.shardingjdbc.core.constant.DatabaseType;
import io.shardingjdbc.proxy.transport.mysql.handler.MySQLProxyHandler;
import io.shardingjdbc.proxy.frontend.mysql.handler.MySQLFrontendHandler;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
/**
* Database proxy handler factory.
* Frontend handler factory.
*
* @author zhangliang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class DatabaseProxyHandlerFactory {
public final class FrontendHandlerFactory {
/**
* Create database proxy handler instance.
* Create frontend handler instance.
*
* @param databaseType database type
* @return database proxy handler instance
* @return frontend handler instance
*/
public static DatabaseProxyHandler createDatabaseProxyHandlerInstance(final DatabaseType databaseType) {
public static FrontendHandler createFrontendHandlerInstance(final DatabaseType databaseType) {
switch (databaseType) {
case MySQL:
return new MySQLProxyHandler();
return new MySQLFrontendHandler();
default:
throw new UnsupportedOperationException(String.format("Cannot support database type '%s'", databaseType));
}
......
......@@ -15,12 +15,12 @@
* </p>
*/
package io.shardingjdbc.proxy.transport.mysql.handler;
package io.shardingjdbc.proxy.frontend.mysql.handler;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.shardingjdbc.proxy.constant.StatusFlag;
import io.shardingjdbc.proxy.transport.common.handler.DatabaseProxyHandler;
import io.shardingjdbc.proxy.frontend.common.handler.FrontendHandler;
import io.shardingjdbc.proxy.transport.mysql.packet.MySQLPacketPayload;
import io.shardingjdbc.proxy.transport.mysql.packet.MySQLSentPacket;
import io.shardingjdbc.proxy.transport.mysql.packet.command.CommandPacket;
......@@ -32,11 +32,11 @@ import io.shardingjdbc.proxy.transport.mysql.packet.handshake.HandshakeResponse4
import io.shardingjdbc.proxy.transport.mysql.packet.generic.OKPacket;
/**
* MySQL proxy handler.
* MySQL frontend handler.
*
* @author zhangliang
*/
public final class MySQLProxyHandler extends DatabaseProxyHandler {
public final class MySQLFrontendHandler extends FrontendHandler {
private AuthPluginData authPluginData;
......
<?xml version="1.0" encoding="UTF-8"?>
<sql-cases>
<sql-case id="assertUpdateWithAlias" value="UPDATE t_order AS o SET o.status = %s WHERE o.order_id = %s AND o.user_id = %s" db-types="MySQL,H2"/>
<sql-case id="assertUpdateWithAlias" value="UPDATE t_order AS o SET o.status = %s WHERE o.order_id = %s AND o.user_id = %s" db-types="MySQL,H2" />
<sql-case id="assertUpdateWithoutAlias" value="UPDATE t_order SET status = %s WHERE order_id = %s AND user_id = %s" />
<sql-case id="assertUpdateWithGeoInPostgreSQL" value="UPDATE t_place SET start_time = %s, status = 0, start_point = ST_GeographyFromText('SRID=4326;POINT('||%s||' '||%s||')'), rule = %s::jsonb, discount_type = %s, order_type = %s WHERE user_new_id = %s AND guid = %s" db-types="PostgreSQL" />
</sql-cases>
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册