未验证 提交 464cc925 编写于 作者: G guangyuan 提交者: GitHub

Merge pull request #1 from apache/dev

merge
-Xmx1024m -XX:MaxPermSize=256m
......@@ -12,6 +12,6 @@ jdk:
before_script:
- echo "MAVEN_OPTS='-Xmx1024m -XX:MaxPermSize=256m'" > ~/.mavenrc
script:
- mvn clean install cobertura:cobertura coveralls:report -DrepoToken="${COVERALLS_REPO_TOKEN}" -Dmaven.javadoc.skip=true
- mvn clean install cobertura:cobertura coveralls:report -DrepoToken=${COVERALLS_REPO_TOKEN} -Dmaven.javadoc.skip=true
install: travis_wait 30 mvn install --quiet
......@@ -2,7 +2,8 @@
### API Changes
1. Optimize and delete API and configuration item of sharding logicIndex.
1. Optimize and delete API and configuration item of sharding logic index.
1. Update the API of encryption to support the encrypted and plain data coexistence.
### New Features
......
此差异已折叠。
......@@ -39,7 +39,8 @@ pipeline {
}
stage('Build & Test') {
tools {
maven 'maven-3.2.1'
// use at least Apache Maven 3.3.1 to have .mvn/jvm.config support
maven 'Maven 3.6.0'
jdk 'JDK 1.8 (latest)'
}
steps {
......@@ -47,8 +48,7 @@ pipeline {
ssBuildBadge.setStatus('running')
try {
sh '''
echo "MAVEN_OPTS='-Xmx1024m -XX:MaxPermSize=256m'" > ~/.mavenrc
mvn clean install cobertura:cobertura coveralls:report -DrepoToken=${COVERALLS_REPO_TOKEN} -Prelease
mvn clean verify cobertura:cobertura coveralls:report -DrepoToken=${COVERALLS_REPO_TOKEN} -Prelease
'''
ssBuildBadge.setStatus('passing')
} catch (Exception err) {
......
......@@ -746,6 +746,7 @@
<exclude>**/.git/**</exclude>
<!-- CI files -->
<exclude>**/.travis.yml</exclude>
<exclude>**/.mvn/jvm.config</exclude>
<!-- GitHub files -->
<exclude>**/.github/**</exclude>
<!-- document files -->
......
......@@ -17,6 +17,8 @@
package org.apache.shardingsphere.core.rule;
import org.apache.shardingsphere.api.config.RuleConfiguration;
/**
* Base rule.
*
......@@ -24,4 +26,11 @@ package org.apache.shardingsphere.core.rule;
* @author panjuan
*/
public interface BaseRule {
/**
* Get rule configuration.
*
* @return rule configuration
*/
RuleConfiguration getRuleConfiguration();
}
......@@ -17,15 +17,28 @@
package org.apache.shardingsphere.core.rule;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.Getter;
import org.apache.shardingsphere.api.config.encrypt.EncryptColumnRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.core.strategy.encrypt.EncryptEngine;
import org.apache.shardingsphere.api.config.encrypt.EncryptorRuleConfiguration;
import org.apache.shardingsphere.core.spi.algorithm.encrypt.ShardingEncryptorServiceLoader;
import org.apache.shardingsphere.core.strategy.encrypt.EncryptTable;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import org.apache.shardingsphere.spi.encrypt.ShardingQueryAssistedEncryptor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Encrypt rule.
......@@ -35,27 +48,29 @@ import java.util.Collection;
@Getter
public final class EncryptRule implements BaseRule {
private final EncryptEngine encryptEngine;
private final Map<String, ShardingEncryptor> encryptors = new LinkedHashMap<>();
private EncryptRuleConfiguration encryptRuleConfig;
private final Map<String, EncryptTable> tables = new LinkedHashMap<>();
private EncryptRuleConfiguration ruleConfiguration;
public EncryptRule() {
encryptEngine = new EncryptEngine();
encryptRuleConfig = new EncryptRuleConfiguration();
ruleConfiguration = new EncryptRuleConfiguration();
}
public EncryptRule(final EncryptRuleConfiguration encryptRuleConfiguration) {
this.encryptRuleConfig = encryptRuleConfiguration;
this.ruleConfiguration = encryptRuleConfiguration;
Preconditions.checkArgument(isValidEncryptRuleConfig(), "Invalid encrypt column configurations in EncryptTableRuleConfigurations.");
encryptEngine = new EncryptEngine(encryptRuleConfiguration);
initEncryptors(encryptRuleConfiguration.getEncryptors());
initTables(encryptRuleConfiguration.getTables());
}
private boolean isValidEncryptRuleConfig() {
return (encryptRuleConfig.getEncryptors().isEmpty() && encryptRuleConfig.getTables().isEmpty()) || isValidEncryptTableConfig();
return (ruleConfiguration.getEncryptors().isEmpty() && ruleConfiguration.getTables().isEmpty()) || isValidEncryptTableConfig();
}
private boolean isValidEncryptTableConfig() {
for (EncryptTableRuleConfiguration table : encryptRuleConfig.getTables().values()) {
for (EncryptTableRuleConfiguration table : ruleConfiguration.getTables().values()) {
for (EncryptColumnRuleConfiguration column : table.getColumns().values()) {
if (!isValidColumnConfig(column)) {
return false;
......@@ -66,15 +81,266 @@ public final class EncryptRule implements BaseRule {
}
private boolean isValidColumnConfig(final EncryptColumnRuleConfiguration column) {
return !Strings.isNullOrEmpty(column.getEncryptor()) && !Strings.isNullOrEmpty(column.getCipherColumn()) && encryptRuleConfig.getEncryptors().keySet().contains(column.getEncryptor());
return !Strings.isNullOrEmpty(column.getEncryptor()) && !Strings.isNullOrEmpty(column.getCipherColumn()) && ruleConfiguration.getEncryptors().keySet().contains(column.getEncryptor());
}
private void initEncryptors(final Map<String, EncryptorRuleConfiguration> encryptors) {
ShardingEncryptorServiceLoader serviceLoader = new ShardingEncryptorServiceLoader();
for (Entry<String, EncryptorRuleConfiguration> each : encryptors.entrySet()) {
this.encryptors.put(each.getKey(), createShardingEncryptor(serviceLoader, each.getValue()));
}
}
private ShardingEncryptor createShardingEncryptor(final ShardingEncryptorServiceLoader serviceLoader, final EncryptorRuleConfiguration encryptorRuleConfiguration) {
ShardingEncryptor encryptor = serviceLoader.newService(encryptorRuleConfiguration.getType(), encryptorRuleConfiguration.getProperties());
encryptor.init();
return encryptor;
}
private void initTables(final Map<String, EncryptTableRuleConfiguration> tables) {
for (Entry<String, EncryptTableRuleConfiguration> entry : tables.entrySet()) {
this.tables.put(entry.getKey(), new EncryptTable(entry.getValue()));
}
}
/**
* Get encrypt table names.
* Get logic column.
*
* @param logicTable logic table
* @param cipherColumn cipher column
* @return logic column
*/
public String getLogicColumn(final String logicTable, final String cipherColumn) {
return tables.get(logicTable).getLogicColumn(cipherColumn);
}
/**
* Get logic columns.
*
* @param logicTable logic table
* @return logic columns
*/
public Collection<String> getLogicColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyList();
}
return tables.get(logicTable).getLogicColumns();
}
/**
* Get plain column.
*
* @param logicTable logic table name
* @param logicColumn logic column name
* @return plain column
*/
public Optional<String> getPlainColumn(final String logicTable, final String logicColumn) {
if (!tables.containsKey(logicTable)) {
return Optional.absent();
}
return tables.get(logicTable).getPlainColumn(logicColumn);
}
private Collection<String> getPlainColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyList();
}
return tables.get(logicTable).getPlainColumns();
}
/**
* Is has plain column or not.
*
* @param logicTable logic table name
* @return has plain column or not
*/
public boolean isHasPlainColumn(final String logicTable) {
return tables.containsKey(logicTable) && tables.get(logicTable).isHasPlainColumn();
}
/**
* Get cipher column.
*
* @param logicTable logic table name
* @param logicColumn logic column name
* @return cipher column
*/
public String getCipherColumn(final String logicTable, final String logicColumn) {
return tables.get(logicTable).getCipherColumn(logicColumn);
}
/**
* Get cipher columns.
*
* @param logicTable logic table name
* @return cipher columns
*/
public Collection<String> getCipherColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyList();
}
return tables.get(logicTable).getCipherColumns();
}
/**
* Is cipher column or not.
*
* @param tableName table name
* @param columnName column name
* @return cipher column or not
*/
public boolean isCipherColumn(final String tableName, final String columnName) {
return tables.keySet().contains(tableName) && tables.get(tableName).getCipherColumns().contains(columnName);
}
/**
* Get assisted query column.
*
* @param logicTable logic table name
* @param logicColumn column name
* @return assisted query column
*/
public Optional<String> getAssistedQueryColumn(final String logicTable, final String logicColumn) {
if (!tables.containsKey(logicTable)) {
return Optional.absent();
}
return tables.get(logicTable).getAssistedQueryColumn(logicColumn);
}
/**
* Get assisted query columns.
*
* @param logicTable logic table
* @return assisted query columns
*/
public Collection<String> getAssistedQueryColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyList();
}
return tables.get(logicTable).getAssistedQueryColumns();
}
/**
* Is has query assisted column or not.
*
* @param logicTable logic table name
* @return has query assisted column or not
*/
public boolean isHasQueryAssistedColumn(final String logicTable) {
return tables.containsKey(logicTable) && tables.get(logicTable).isHasQueryAssistedColumn();
}
/**
* Get assisted query and plain columns.
*
* @param logicTable logic table name
* @return assisted query and plain columns
*/
public Collection<String> getAssistedQueryAndPlainColumns(final String logicTable) {
Collection<String> result = new LinkedList<>();
result.addAll(getAssistedQueryColumns(logicTable));
result.addAll(getPlainColumns(logicTable));
return result;
}
/**
* Get assisted query and plain column count.
*
* @param logicTable logic table name
* @return assisted query and plain column count
*/
public Integer getAssistedQueryAndPlainColumnCount(final String logicTable) {
return getAssistedQueryColumns(logicTable).size() + getPlainColumns(logicTable).size();
}
/**
* Get logic and cipher columns.
*
* @param logicTable logic table
* @return logic and cipher columns
*/
public Map<String, String> getLogicAndCipherColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyMap();
}
return tables.get(logicTable).getLogicAndCipherColumns();
}
/**
* Get logic and plain columns.
*
* @param logicTable logic table
* @return logic and plain columns
*/
public Map<String, String> getLogicAndPlainColumns(final String logicTable) {
if (!tables.containsKey(logicTable)) {
return Collections.emptyMap();
}
return tables.get(logicTable).getLogicAndPlainColumns();
}
/**
* Get encrypt assisted column values.
*
* @param logicTable logic table
* @param logicColumn logic column
* @param originalColumnValues original column values
* @return assisted column values
*/
public List<Object> getEncryptAssistedColumnValues(final String logicTable, final String logicColumn, final List<Object> originalColumnValues) {
final Optional<ShardingEncryptor> shardingEncryptor = getShardingEncryptor(logicTable, logicColumn);
Preconditions.checkArgument(shardingEncryptor.isPresent() && shardingEncryptor.get() instanceof ShardingQueryAssistedEncryptor,
String.format("Can not find ShardingQueryAssistedEncryptor by %s.%s.", logicTable, logicColumn));
return Lists.transform(originalColumnValues, new Function<Object, Object>() {
@Override
public Object apply(final Object input) {
return ((ShardingQueryAssistedEncryptor) shardingEncryptor.get()).queryAssistedEncrypt(input.toString());
}
});
}
/**
* get encrypt column values.
*
* @param logicTable logic table
* @param logicColumn logic column
* @param originalColumnValues original column values
* @return encrypt column values
*/
public List<Object> getEncryptColumnValues(final String logicTable, final String logicColumn, final List<Object> originalColumnValues) {
final Optional<ShardingEncryptor> shardingEncryptor = getShardingEncryptor(logicTable, logicColumn);
Preconditions.checkArgument(shardingEncryptor.isPresent(), String.format("Can not find ShardingQueryAssistedEncryptor by %s.%s.", logicTable, logicColumn));
return Lists.transform(originalColumnValues, new Function<Object, Object>() {
@Override
public Object apply(final Object input) {
return String.valueOf(shardingEncryptor.get().encrypt(input.toString()));
}
});
}
/**
* Get sharding encryptor.
*
* @param logicTable logic table name
* @param logicColumn column name
* @return optional of sharding encryptor
*/
public Optional<ShardingEncryptor> getShardingEncryptor(final String logicTable, final String logicColumn) {
if (!tables.containsKey(logicTable)) {
return Optional.absent();
}
Optional<String> encryptor = tables.get(logicTable).getShardingEncryptor(logicColumn);
return encryptor.isPresent() ? Optional.of(encryptors.get(encryptor.get())) : Optional.<ShardingEncryptor>absent();
}
/**
* Get encrypt table names.
*
* @return encrypt table names
*/
public Collection<String> getEncryptTableNames() {
return encryptEngine.getEncryptTableNames();
return tables.keySet();
}
}
......@@ -42,14 +42,14 @@ public class MasterSlaveRule implements BaseRule {
private final MasterSlaveLoadBalanceAlgorithm loadBalanceAlgorithm;
private final MasterSlaveRuleConfiguration masterSlaveRuleConfiguration;
private final MasterSlaveRuleConfiguration ruleConfiguration;
public MasterSlaveRule(final String name, final String masterDataSourceName, final Collection<String> slaveDataSourceNames, final MasterSlaveLoadBalanceAlgorithm loadBalanceAlgorithm) {
this.name = name;
this.masterDataSourceName = masterDataSourceName;
this.slaveDataSourceNames = slaveDataSourceNames;
this.loadBalanceAlgorithm = null == loadBalanceAlgorithm ? new MasterSlaveLoadBalanceAlgorithmServiceLoader().newService() : loadBalanceAlgorithm;
masterSlaveRuleConfiguration = new MasterSlaveRuleConfiguration(name, masterDataSourceName, slaveDataSourceNames,
ruleConfiguration = new MasterSlaveRuleConfiguration(name, masterDataSourceName, slaveDataSourceNames,
new LoadBalanceStrategyConfiguration(this.loadBalanceAlgorithm.getType(), this.loadBalanceAlgorithm.getProperties()));
}
......@@ -58,7 +58,7 @@ public class MasterSlaveRule implements BaseRule {
masterDataSourceName = config.getMasterDataSourceName();
slaveDataSourceNames = config.getSlaveDataSourceNames();
loadBalanceAlgorithm = createMasterSlaveLoadBalanceAlgorithm(config.getLoadBalanceStrategyConfiguration());
masterSlaveRuleConfiguration = config;
ruleConfiguration = config;
}
private MasterSlaveLoadBalanceAlgorithm createMasterSlaveLoadBalanceAlgorithm(final LoadBalanceStrategyConfiguration loadBalanceStrategyConfiguration) {
......
......@@ -52,7 +52,7 @@ import java.util.TreeSet;
@Getter
public class ShardingRule implements BaseRule {
private final ShardingRuleConfiguration shardingRuleConfig;
private final ShardingRuleConfiguration ruleConfiguration;
private final ShardingDataSourceNames shardingDataSourceNames;
......@@ -75,7 +75,7 @@ public class ShardingRule implements BaseRule {
public ShardingRule(final ShardingRuleConfiguration shardingRuleConfig, final Collection<String> dataSourceNames) {
Preconditions.checkArgument(null != shardingRuleConfig, "ShardingRuleConfig cannot be null.");
Preconditions.checkArgument(null != dataSourceNames && !dataSourceNames.isEmpty(), "Data sources cannot be empty.");
this.shardingRuleConfig = shardingRuleConfig;
this.ruleConfiguration = shardingRuleConfig;
shardingDataSourceNames = new ShardingDataSourceNames(shardingRuleConfig, dataSourceNames);
tableRules = createTableRules(shardingRuleConfig);
bindingTableRules = createBindingTableRules(shardingRuleConfig.getBindingTableGroups());
......@@ -139,7 +139,7 @@ public class ShardingRule implements BaseRule {
}
private EncryptRule createEncryptRule(final EncryptRuleConfiguration encryptRuleConfig) {
return null == encryptRuleConfig ? new EncryptRule() : new EncryptRule(shardingRuleConfig.getEncryptRuleConfig());
return null == encryptRuleConfig ? new EncryptRule() : new EncryptRule(ruleConfiguration.getEncryptRuleConfig());
}
/**
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.strategy.encrypt;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;
import lombok.NoArgsConstructor;
import org.apache.shardingsphere.api.config.encrypt.EncryptRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptorRuleConfiguration;
import org.apache.shardingsphere.core.spi.algorithm.encrypt.ShardingEncryptorServiceLoader;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import org.apache.shardingsphere.spi.encrypt.ShardingQueryAssistedEncryptor;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
/**
* Encryptor engine.
*
* @author panjuan
*/
@NoArgsConstructor
public final class EncryptEngine {
private final Map<String, ShardingEncryptor> encryptors = new LinkedHashMap<>();
private final Map<String, EncryptTable> tables = new LinkedHashMap<>();
public EncryptEngine(final EncryptRuleConfiguration encryptRuleConfiguration) {
initEncryptors(encryptRuleConfiguration.getEncryptors());
initTables(encryptRuleConfiguration.getTables());
}
private void initEncryptors(final Map<String, EncryptorRuleConfiguration> encryptors) {
ShardingEncryptorServiceLoader serviceLoader = new ShardingEncryptorServiceLoader();
for (Entry<String, EncryptorRuleConfiguration> each : encryptors.entrySet()) {
this.encryptors.put(each.getKey(), createShardingEncryptor(serviceLoader, each.getValue()));
}
}
private ShardingEncryptor createShardingEncryptor(final ShardingEncryptorServiceLoader serviceLoader, final EncryptorRuleConfiguration encryptorRuleConfiguration) {
ShardingEncryptor encryptor = serviceLoader.newService(encryptorRuleConfiguration.getType(), encryptorRuleConfiguration.getProperties());
encryptor.init();
return encryptor;
}
private void initTables(final Map<String, EncryptTableRuleConfiguration> tables) {
for (Entry<String, EncryptTableRuleConfiguration> entry : tables.entrySet()) {
this.tables.put(entry.getKey(), new EncryptTable(entry.getValue()));
}
}
/**
* Get sharding encryptor.
*
* @param logicTableName logic table name
* @param logicColumnName column name
* @return optional of sharding encryptor
*/
public Optional<ShardingEncryptor> getShardingEncryptor(final String logicTableName, final String logicColumnName) {
if (!tables.containsKey(logicTableName)) {
return Optional.absent();
}
Optional<String> encryptor = tables.get(logicTableName).getShardingEncryptor(logicColumnName);
return encryptor.isPresent() ? Optional.of(encryptors.get(encryptor.get())) : Optional.<ShardingEncryptor>absent();
}
/**
* Is has sharding query assisted encryptor or not.
*
* @param logicTableName logic table name
* @return has sharding query assisted encryptor or not
*/
public boolean isHasShardingQueryAssistedEncryptor(final String logicTableName) {
return tables.containsKey(logicTableName) && tables.get(logicTableName).isHasShardingQueryAssistedEncryptor();
}
/**
* Get encrypt table names.
*
* @return encrypt table names
*/
public Collection<String> getEncryptTableNames() {
return tables.keySet();
}
/**
* Get plain column.
*
* @param logicTableName logic table name
* @param logicColumnName logic column name
* @return plain column
*/
public Optional<String> getPlainColumn(final String logicTableName, final String logicColumnName) {
return tables.get(logicTableName).getPlainColumn(logicColumnName);
}
/**
* Get cipher column.
*
* @param logicTableName logic table name
* @param logicColumnName logic column name
* @return cipher column
*/
public String getCipherColumn(final String logicTableName, final String logicColumnName) {
return tables.get(logicTableName).getCipherColumn(logicColumnName);
}
/**
* Get assisted query column.
*
* @param logicTableName logic table name
* @param logicColumnName column name
* @return assisted query column
*/
public Optional<String> getAssistedQueryColumn(final String logicTableName, final String logicColumnName) {
if (!tables.containsKey(logicTableName)) {
return Optional.absent();
}
return tables.get(logicTableName).getAssistedQueryColumn(logicColumnName);
}
/**
* Get assisted query columns.
*
* @param logicTableName logic table name
* @return assisted query columns
*/
public Collection<String> getAssistedQueryColumns(final String logicTableName) {
if (!tables.containsKey(logicTableName)) {
return Collections.emptyList();
}
return tables.get(logicTableName).getAssistedQueryColumns();
}
/**
* Get assisted query column count.
*
* @param logicTableName logic table name
* @return assisted query column count
*/
public Integer getAssistedQueryColumnCount(final String logicTableName) {
return getAssistedQueryColumns(logicTableName).size();
}
/**
* Get encrypt assisted column values.
*
* @param logicTable logic table
* @param logicColumn logic column
* @param originalColumnValues original column values
* @return assisted column values
*/
public List<Object> getEncryptAssistedColumnValues(final String logicTable, final String logicColumn, final List<Object> originalColumnValues) {
final Optional<ShardingEncryptor> shardingEncryptor = getShardingEncryptor(logicTable, logicColumn);
Preconditions.checkArgument(shardingEncryptor.isPresent() && shardingEncryptor.get() instanceof ShardingQueryAssistedEncryptor,
String.format("Can not find ShardingQueryAssistedEncryptor by %s.%s.", logicTable, logicColumn));
return Lists.transform(originalColumnValues, new Function<Object, Object>() {
@Override
public Object apply(final Object input) {
return ((ShardingQueryAssistedEncryptor) shardingEncryptor.get()).queryAssistedEncrypt(input.toString());
}
});
}
/**
* get encrypt column values.
*
* @param logicTable logic table
* @param logicColumn logic column
* @param originalColumnValues original column values
* @return encrypt column values
*/
public List<Object> getEncryptColumnValues(final String logicTable, final String logicColumn, final List<Object> originalColumnValues) {
final Optional<ShardingEncryptor> shardingEncryptor = getShardingEncryptor(logicTable, logicColumn);
Preconditions.checkArgument(shardingEncryptor.isPresent(), String.format("Can not find ShardingQueryAssistedEncryptor by %s.%s.", logicTable, logicColumn));
return Lists.transform(originalColumnValues, new Function<Object, Object>() {
@Override
public Object apply(final Object input) {
return String.valueOf(shardingEncryptor.get().encrypt(input.toString()));
}
});
}
}
......@@ -22,11 +22,13 @@ import com.google.common.base.Optional;
import com.google.common.collect.Maps;
import org.apache.shardingsphere.api.config.encrypt.EncryptColumnRuleConfiguration;
import org.apache.shardingsphere.api.config.encrypt.EncryptTableRuleConfiguration;
import org.apache.shardingsphere.core.exception.ShardingException;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Map.Entry;
/**
* Encryptor strategy.
......@@ -48,40 +50,99 @@ public final class EncryptTable {
}
/**
* Get sharding encryptor.
* Get logic column.
*
* @param cipherColumn cipher column
* @return logic column
*/
public String getLogicColumn(final String cipherColumn) {
for (Entry<String, EncryptColumn> entry : columns.entrySet()) {
if (entry.getValue().getCipherColumn().equals(cipherColumn)) {
return entry.getKey();
}
}
throw new ShardingException("Can not find logic column by %s.", cipherColumn);
}
/**
* Get logic columns.
*
* @param logicColumnName column name
* @return optional of sharding encryptor
* @return logic column
*/
public Optional<String> getShardingEncryptor(final String logicColumnName) {
return columns.containsKey(logicColumnName) ? Optional.of(columns.get(logicColumnName).getEncryptor()) : Optional.<String>absent();
public Collection<String> getLogicColumns() {
return columns.keySet();
}
/**
* Is has sharding query assisted encryptor or not.
* Get plain column.
*
* @param logicColumn logic column name
* @return plain column
*/
public Optional<String> getPlainColumn(final String logicColumn) {
return columns.keySet().contains(logicColumn) ? columns.get(logicColumn).getPlainColumn() : Optional.<String>absent();
}
/**
* Get plain columns.
*
* @return has sharding query assisted encryptor or not
* @return plain columns
*/
public boolean isHasShardingQueryAssistedEncryptor() {
public Collection<String> getPlainColumns() {
Collection<String> result = new LinkedList<>();
for (EncryptColumn each : columns.values()) {
if (each.getAssistedQueryColumn().isPresent()) {
if (each.getPlainColumn().isPresent()) {
result.add(each.getPlainColumn().get());
}
}
return result;
}
/**
* Is has plain column or not.
*
* @return has plain column or not
*/
public boolean isHasPlainColumn() {
for (EncryptColumn each : columns.values()) {
if (each.getPlainColumn().isPresent()) {
return true;
}
}
return false;
}
/**
* Get cipher column.
*
* @param logicColumn logic column name
* @return cipher column
*/
public String getCipherColumn(final String logicColumn) {
return columns.get(logicColumn).getCipherColumn();
}
/**
* Get cipher columns.
*
* @return cipher columns
*/
public Collection<String> getCipherColumns() {
Collection<String> result = new LinkedList<>();
for (EncryptColumn each : columns.values()) {
result.add(each.getCipherColumn());
}
return result;
}
/**
* Get assisted query column.
*
* @param logicColumnName column name
* @param logicColumn column name
* @return assisted query column
*/
public Optional<String> getAssistedQueryColumn(final String logicColumnName) {
if (!columns.containsKey(logicColumnName)) {
return Optional.absent();
}
return columns.get(logicColumnName).getAssistedQueryColumn();
public Optional<String> getAssistedQueryColumn(final String logicColumn) {
return columns.containsKey(logicColumn) ? columns.get(logicColumn).getAssistedQueryColumn() : Optional.<String>absent();
}
/**
......@@ -100,22 +161,59 @@ public final class EncryptTable {
}
/**
* Get plain column.
*
* @param logicColumnName logic column name
* @return plain column
* Is has query assisted column or not.
*
* @return has query assisted column or not
*/
public boolean isHasQueryAssistedColumn() {
for (EncryptColumn each : columns.values()) {
if (each.getAssistedQueryColumn().isPresent()) {
return true;
}
}
return false;
}
/**
* Get sharding encryptor.
*
* @param logicColumn column name
* @return optional of sharding encryptor
*/
public Optional<String> getPlainColumn(final String logicColumnName) {
return columns.get(logicColumnName).getPlainColumn();
public Optional<String> getShardingEncryptor(final String logicColumn) {
return columns.containsKey(logicColumn) ? Optional.of(columns.get(logicColumn).getEncryptor()) : Optional.<String>absent();
}
/**
* Get cipher column.
* Get logic and cipher columns.
*
* @param logicColumnName logic column name
* @return cipher column
* @return logic and cipher columns
*/
public String getCipherColumn(final String logicColumnName) {
return columns.get(logicColumnName).getCipherColumn();
public Map<String, String> getLogicAndCipherColumns() {
return Maps.transformValues(columns, new Function<EncryptColumn, String>() {
@Override
public String apply(final EncryptColumn input) {
return input.getCipherColumn();
}
});
}
/**
* Get logic and plain columns.
*
* @return logic and plain columns
*/
public Map<String, String> getLogicAndPlainColumns() {
return Maps.transformValues(columns, new Function<EncryptColumn, String>() {
@Override
public String apply(final EncryptColumn input) {
if (input.getPlainColumn().isPresent()) {
return input.getPlainColumn().get();
}
throw new ShardingException("Plain column is null.");
}
});
}
}
......@@ -328,14 +328,14 @@ public final class ShardingRuleTest {
ShardingRule actual = createMaximumShardingRule();
assertThat(actual.getShardingLogicTableNames(Arrays.asList("LOGIC_TABLE", "BROADCAST_TABLE")), CoreMatchers.<Collection<String>>is(Collections.singletonList("LOGIC_TABLE")));
}
@Test(expected = IllegalArgumentException.class)
public void assertConstructShardingRuleWithNullShardingRuleConfiguration() {
new ShardingRule(null, createDataSourceNames());
}
@Test(expected = IllegalArgumentException.class)
public void assertConstructShardingRuleWithNullDataSourceNames(){
public void assertConstructShardingRuleWithNullDataSourceNames() {
ShardingRuleConfiguration shardingRuleConfiguration = new ShardingRuleConfiguration();
TableRuleConfiguration tableRuleConfiguration = createTableRuleConfiguration("LOGIC_TABLE", "ms_ds_${0..1}.table_${0..2}");
shardingRuleConfiguration.getTableRuleConfigs().add(tableRuleConfiguration);
......
......@@ -71,7 +71,7 @@ public abstract class BaseShardingEngine {
result.getRouteUnits().addAll(HintManager.isDatabaseShardingOnly() ? convert(sql, clonedParameters, result) : rewriteAndConvert(sql, clonedParameters, result));
if (shardingProperties.getValue(ShardingPropertiesConstant.SQL_SHOW)) {
boolean showSimple = shardingProperties.getValue(ShardingPropertiesConstant.SQL_SIMPLE);
SQLLogger.logSQL(sql, showSimple, result.getOptimizedStatement().getSQLStatement(), result.getRouteUnits());
SQLLogger.logSQL(sql, showSimple, result.getOptimizedStatement(), result.getRouteUnits());
}
return result;
}
......
......@@ -17,14 +17,12 @@
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.collect.Multimap;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationDistinctSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationSelectItem;
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedHashMap;
......@@ -50,8 +48,8 @@ public final class AggregationDistinctQueryMetaData {
private final Map<Integer, Integer> aggregationDistinctColumnIndexAndSumColumnIndexes = new HashMap<>();
public AggregationDistinctQueryMetaData(final Collection<AggregationDistinctSelectItem> aggregationDistinctSelectItems, final Multimap<String, Integer> columnLabelAndIndexMap) {
aggregationDistinctColumnMetaDataList.addAll(getColumnMetaDataList(aggregationDistinctSelectItems, columnLabelAndIndexMap));
public AggregationDistinctQueryMetaData(final Collection<AggregationDistinctSelectItem> aggregationDistinctSelectItems, final QueryResultMetaData queryResultMetaData) {
aggregationDistinctColumnMetaDataList.addAll(getColumnMetaDataList(aggregationDistinctSelectItems, queryResultMetaData));
aggregationDistinctColumnIndexAndLabels.putAll(getAggregationDistinctColumnIndexAndLabels());
aggregationDistinctColumnIndexAndAggregationTypes.putAll(getAggregationDistinctColumnIndexAndAggregationTypes());
aggregationDistinctColumnIndexAndCountColumnIndexes.putAll(getAggregationDistinctColumnIndexAndCountColumnIndexes());
......@@ -59,22 +57,22 @@ public final class AggregationDistinctQueryMetaData {
}
private Collection<AggregationDistinctColumnMetaData> getColumnMetaDataList(final Collection<AggregationDistinctSelectItem> aggregationDistinctSelectItems,
final Multimap<String, Integer> columnLabelAndIndexMap) {
final QueryResultMetaData queryResultMetaData) {
Collection<AggregationDistinctColumnMetaData> result = new LinkedList<>();
for (AggregationDistinctSelectItem each : aggregationDistinctSelectItems) {
result.add(getAggregationDistinctColumnMetaData(each, new ArrayList<>(columnLabelAndIndexMap.get(each.getColumnLabel())).get(0), columnLabelAndIndexMap));
result.add(getAggregationDistinctColumnMetaData(each, queryResultMetaData.getColumnIndex(each.getColumnLabel()), queryResultMetaData));
}
return result;
}
private AggregationDistinctColumnMetaData getAggregationDistinctColumnMetaData(final AggregationDistinctSelectItem selectItem,
final int aggregationDistinctColumnIndex, final Multimap<String, Integer> columnLabelAndIndexMap) {
final int aggregationDistinctColumnIndex, final QueryResultMetaData queryResultMetaData) {
List<AggregationSelectItem> derivedSelectItems = selectItem.getDerivedAggregationItems();
if (derivedSelectItems.isEmpty()) {
return new AggregationDistinctColumnMetaData(aggregationDistinctColumnIndex, selectItem.getColumnLabel(), selectItem.getType());
}
int countDerivedIndex = columnLabelAndIndexMap.get(derivedSelectItems.get(0).getColumnLabel()).iterator().next();
int sumDerivedIndex = columnLabelAndIndexMap.get(derivedSelectItems.get(1).getColumnLabel()).iterator().next();
int countDerivedIndex = queryResultMetaData.getColumnIndex(derivedSelectItems.get(0).getColumnLabel());
int sumDerivedIndex = queryResultMetaData.getColumnIndex(derivedSelectItems.get(1).getColumnLabel());
return new AggregationDistinctColumnMetaData(aggregationDistinctColumnIndex, selectItem.getColumnLabel(), selectItem.getType(), countDerivedIndex, sumDerivedIndex);
}
......
......@@ -20,7 +20,6 @@ package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Function;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.execute.sql.execute.row.QueryRow;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationDistinctSelectItem;
......@@ -33,7 +32,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
......@@ -45,9 +43,9 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult {
private final AggregationDistinctQueryMetaData metaData;
private AggregationDistinctQueryResult(final Multimap<String, Integer> columnLabelAndIndexMap, final List<Boolean> columnCaseSensitive, final Iterator<QueryRow> resultData,
private AggregationDistinctQueryResult(final QueryResultMetaData queryResultMetaData, final List<Boolean> columnCaseSensitive, final Iterator<QueryRow> resultData,
final AggregationDistinctQueryMetaData distinctQueryMetaData) {
super(columnLabelAndIndexMap, columnCaseSensitive, resultData);
super(queryResultMetaData, columnCaseSensitive, resultData);
metaData = distinctQueryMetaData;
}
......@@ -60,7 +58,7 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult {
return input.getDistinctColumnLabel();
}
}));
metaData = new AggregationDistinctQueryMetaData(aggregationDistinctSelectItems, getColumnLabelAndIndexMap());
metaData = new AggregationDistinctQueryMetaData(aggregationDistinctSelectItems, getQueryResultMetaData());
}
/**
......@@ -76,7 +74,7 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult {
public DistinctQueryResult apply(final QueryRow input) {
Set<QueryRow> resultData = new LinkedHashSet<>();
resultData.add(input);
return new AggregationDistinctQueryResult(getColumnLabelAndIndexMap(), getColumnCaseSensitive(), resultData.iterator(), metaData);
return new AggregationDistinctQueryResult(getQueryResultMetaData(), getColumnCaseSensitive(), resultData.iterator(), metaData);
}
}));
}
......@@ -133,20 +131,14 @@ public final class AggregationDistinctQueryResult extends DistinctQueryResult {
return null == getCurrentRow();
}
@Override
public int getColumnCount() {
return getColumnLabelAndIndexMap().size();
}
@Override
public String getColumnLabel(final int columnIndex) throws SQLException {
if (metaData.isAggregationDistinctColumnIndex(columnIndex)) {
return metaData.getAggregationDistinctColumnLabel(columnIndex);
}
for (Entry<String, Integer> entry : getColumnLabelAndIndexMap().entries()) {
if (columnIndex == entry.getValue()) {
return entry.getKey();
}
String columnLabel = getQueryResultMetaData().getColumnLabel(columnIndex);
if (null != columnLabel) {
return columnLabel;
}
throw new SQLException("Column index out of range", "9999");
}
......
......@@ -18,10 +18,8 @@
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Function;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Iterators;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
......@@ -39,7 +37,6 @@ import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
......@@ -47,12 +44,14 @@ import java.util.Set;
*
* @author panjuan
* @author yangyi
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter(AccessLevel.PROTECTED)
public class DistinctQueryResult implements QueryResult {
private final Multimap<String, Integer> columnLabelAndIndexMap;
@Getter
private final QueryResultMetaData queryResultMetaData;
private final List<Boolean> columnCaseSensitive;
......@@ -62,20 +61,12 @@ public class DistinctQueryResult implements QueryResult {
@SneakyThrows
public DistinctQueryResult(final Collection<QueryResult> queryResults, final List<String> distinctColumnLabels) {
this.columnLabelAndIndexMap = getColumnLabelAndIndexMap(queryResults.iterator().next());
this.columnCaseSensitive = getColumnCaseSensitive(queryResults.iterator().next());
QueryResult firstQueryResult = queryResults.iterator().next();
this.queryResultMetaData = firstQueryResult.getQueryResultMetaData();
this.columnCaseSensitive = getColumnCaseSensitive(firstQueryResult);
resultData = getResultData(queryResults, distinctColumnLabels);
}
@SneakyThrows
private Multimap<String, Integer> getColumnLabelAndIndexMap(final QueryResult queryResult) {
Multimap<String, Integer> result = HashMultimap.create();
for (int columnIndex = 1; columnIndex <= queryResult.getColumnCount(); columnIndex++) {
result.put(queryResult.getColumnLabel(columnIndex), columnIndex);
}
return result;
}
@SneakyThrows
private List<Boolean> getColumnCaseSensitive(final QueryResult queryResult) {
List<Boolean> result = Lists.newArrayList(false);
......@@ -124,7 +115,7 @@ public class DistinctQueryResult implements QueryResult {
public DistinctQueryResult apply(final QueryRow row) {
Set<QueryRow> resultData = new LinkedHashSet<>();
resultData.add(row);
return new DistinctQueryResult(columnLabelAndIndexMap, columnCaseSensitive, resultData.iterator());
return new DistinctQueryResult(queryResultMetaData, columnCaseSensitive, resultData.iterator());
}
}));
}
......@@ -191,20 +182,19 @@ public class DistinctQueryResult implements QueryResult {
@Override
public int getColumnCount() {
return columnLabelAndIndexMap.size();
return queryResultMetaData.getColumnCount();
}
@Override
public String getColumnLabel(final int columnIndex) throws SQLException {
for (Entry<String, Integer> entry : columnLabelAndIndexMap.entries()) {
if (columnIndex == entry.getValue()) {
return entry.getKey();
}
String columnLabel = queryResultMetaData.getColumnLabel(columnIndex);
if (null != columnLabel) {
return columnLabel;
}
throw new SQLException("Column index out of range", "9999");
}
protected Integer getColumnIndex(final String columnLabel) {
return new ArrayList<>(columnLabelAndIndexMap.get(columnLabel)).get(0);
return queryResultMetaData.getColumnIndex(columnLabel);
}
}
......@@ -18,6 +18,7 @@
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.execute.sql.execute.row.QueryRow;
import org.apache.shardingsphere.core.rule.EncryptRule;
......@@ -48,25 +49,26 @@ public final class MemoryQueryResult implements QueryResult {
private final Iterator<QueryRow> resultData;
private QueryRow currentRow;
private final QueryResultMetaData metaData;
@Getter
private final QueryResultMetaData queryResultMetaData;
@SneakyThrows
public MemoryQueryResult(final ResultSet resultSet, final ShardingRule shardingRule) {
resultData = getResultData(resultSet);
metaData = new QueryResultMetaData(resultSet.getMetaData(), shardingRule);
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData(), shardingRule);
}
@SneakyThrows
public MemoryQueryResult(final ResultSet resultSet, final EncryptRule encryptRule) {
resultData = getResultData(resultSet);
metaData = new QueryResultMetaData(resultSet.getMetaData(), encryptRule);
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData(), encryptRule);
}
@SneakyThrows
public MemoryQueryResult(final ResultSet resultSet) {
resultData = getResultData(resultSet);
metaData = new QueryResultMetaData(resultSet.getMetaData());
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData());
}
@SneakyThrows
......@@ -99,7 +101,7 @@ public final class MemoryQueryResult implements QueryResult {
@Override
public Object getValue(final String columnLabel, final Class<?> type) {
return decrypt(columnLabel, currentRow.getColumnValue(metaData.getColumnIndex(columnLabel)));
return decrypt(columnLabel, currentRow.getColumnValue(queryResultMetaData.getColumnIndex(columnLabel)));
}
@Override
......@@ -109,7 +111,7 @@ public final class MemoryQueryResult implements QueryResult {
@Override
public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) {
return currentRow.getColumnValue(metaData.getColumnIndex(columnLabel));
return currentRow.getColumnValue(queryResultMetaData.getColumnIndex(columnLabel));
}
@Override
......@@ -119,7 +121,7 @@ public final class MemoryQueryResult implements QueryResult {
@Override
public InputStream getInputStream(final String columnLabel, final String type) {
return getInputStream(currentRow.getColumnValue(metaData.getColumnIndex(columnLabel)));
return getInputStream(currentRow.getColumnValue(queryResultMetaData.getColumnIndex(columnLabel)));
}
@SneakyThrows
......@@ -139,27 +141,27 @@ public final class MemoryQueryResult implements QueryResult {
@Override
public boolean isCaseSensitive(final int columnIndex) {
return metaData.isCaseSensitive(columnIndex);
return queryResultMetaData.isCaseSensitive(columnIndex);
}
@Override
public int getColumnCount() {
return metaData.getColumnCount();
return queryResultMetaData.getColumnCount();
}
@Override
public String getColumnLabel(final int columnIndex) {
return metaData.getColumnLabel(columnIndex);
return queryResultMetaData.getColumnLabel(columnIndex);
}
@SneakyThrows
private Object decrypt(final String columnLabel, final Object value) {
return decrypt(metaData.getColumnIndex(columnLabel), value);
return decrypt(queryResultMetaData.getColumnIndex(columnLabel), value);
}
@SneakyThrows
private Object decrypt(final int columnIndex, final Object value) {
Optional<ShardingEncryptor> shardingEncryptor = metaData.getShardingEncryptor(columnIndex);
Optional<ShardingEncryptor> shardingEncryptor = queryResultMetaData.getShardingEncryptor(columnIndex);
return shardingEncryptor.isPresent() ? shardingEncryptor.get().decrypt(getCiphertext(value)) : value;
}
......
......@@ -132,4 +132,11 @@ public interface QueryResult {
* @throws SQLException SQL Exception
*/
boolean isCaseSensitive(int columnIndex) throws SQLException;
/**
* Get QueryResultMetaData.
*
* @return QueryResultMetaData
*/
QueryResultMetaData getQueryResultMetaData();
}
......@@ -22,7 +22,6 @@ import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.core.strategy.encrypt.EncryptEngine;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import java.sql.ResultSetMetaData;
......@@ -38,40 +37,40 @@ import java.util.TreeMap;
*/
public final class QueryResultMetaData {
private final Map<String, Integer> columnLabelAndIndexes;
private final ResultSetMetaData resultSetMetaData;
private final ShardingRule shardingRule;
private final EncryptEngine encryptEngine;
private final EncryptRule encryptRule;
private final Map<String, Integer> columnLabelAndIndexes;
@SneakyThrows
public QueryResultMetaData(final ResultSetMetaData resultSetMetaData, final ShardingRule shardingRule) {
columnLabelAndIndexes = getColumnLabelAndIndexMap(resultSetMetaData);
this.resultSetMetaData = resultSetMetaData;
this.shardingRule = shardingRule;
this.encryptEngine = shardingRule.getEncryptRule().getEncryptEngine();
this.encryptRule = shardingRule.getEncryptRule();
columnLabelAndIndexes = getColumnLabelAndIndexMap();
}
@SneakyThrows
public QueryResultMetaData(final ResultSetMetaData resultSetMetaData, final EncryptRule encryptRule) {
columnLabelAndIndexes = getColumnLabelAndIndexMap(resultSetMetaData);
this.resultSetMetaData = resultSetMetaData;
this.shardingRule = null;
this.encryptEngine = encryptRule.getEncryptEngine();
this.encryptRule = encryptRule;
columnLabelAndIndexes = getColumnLabelAndIndexMap();
}
@SneakyThrows
public QueryResultMetaData(final ResultSetMetaData resultSetMetaData) {
columnLabelAndIndexes = getColumnLabelAndIndexMap(resultSetMetaData);
this.resultSetMetaData = resultSetMetaData;
this.shardingRule = null;
this.encryptEngine = new EncryptEngine();
this.encryptRule = new EncryptRule();
columnLabelAndIndexes = getColumnLabelAndIndexMap();
}
@SneakyThrows
private Map<String, Integer> getColumnLabelAndIndexMap(final ResultSetMetaData resultSetMetaData) {
private Map<String, Integer> getColumnLabelAndIndexMap() {
Map<String, Integer> result = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
for (int columnIndex = resultSetMetaData.getColumnCount(); columnIndex > 0; columnIndex--) {
result.put(resultSetMetaData.getColumnLabel(columnIndex), columnIndex);
......@@ -140,7 +139,8 @@ public final class QueryResultMetaData {
*/
@SneakyThrows
public Optional<ShardingEncryptor> getShardingEncryptor(final int columnIndex) {
return encryptEngine.getShardingEncryptor(getTableName(columnIndex), resultSetMetaData.getColumnName(columnIndex));
String logicTable = getTableName(columnIndex);
return encryptRule.getShardingEncryptor(logicTable, getLogicColumn(logicTable, columnIndex));
}
private String getTableName(final int columnIndex) throws SQLException {
......@@ -151,4 +151,10 @@ public final class QueryResultMetaData {
Optional<TableRule> tableRule = shardingRule.findTableRuleByActualTable(actualTableName);
return tableRule.isPresent() ? tableRule.get().getLogicTable() : actualTableName;
}
@SneakyThrows
private String getLogicColumn(final String tableName, final int columnIndex) {
String columnLabel = resultSetMetaData.getColumnName(columnIndex);
return encryptRule.isCipherColumn(tableName, columnLabel) ? encryptRule.getLogicColumn(tableName, columnLabel) : columnLabel;
}
}
......@@ -18,6 +18,7 @@
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
......@@ -39,27 +40,28 @@ import java.util.Calendar;
* @author yangyi
*/
public final class StreamQueryResult implements QueryResult {
private final QueryResultMetaData metaData;
@Getter
private final QueryResultMetaData queryResultMetaData;
private final ResultSet resultSet;
@SneakyThrows
public StreamQueryResult(final ResultSet resultSet, final ShardingRule shardingRule) {
this.resultSet = resultSet;
metaData = new QueryResultMetaData(resultSet.getMetaData(), shardingRule);
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData(), shardingRule);
}
@SneakyThrows
public StreamQueryResult(final ResultSet resultSet, final EncryptRule encryptRule) {
this.resultSet = resultSet;
metaData = new QueryResultMetaData(resultSet.getMetaData(), encryptRule);
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData(), encryptRule);
}
@SneakyThrows
public StreamQueryResult(final ResultSet resultSet) {
this.resultSet = resultSet;
metaData = new QueryResultMetaData(resultSet.getMetaData());
queryResultMetaData = new QueryResultMetaData(resultSet.getMetaData());
}
@Override
......@@ -74,7 +76,7 @@ public final class StreamQueryResult implements QueryResult {
@Override
public Object getValue(final String columnLabel, final Class<?> type) throws SQLException {
return decrypt(columnLabel, QueryResultUtil.getValue(resultSet, metaData.getColumnIndex(columnLabel)));
return decrypt(columnLabel, QueryResultUtil.getValue(resultSet, queryResultMetaData.getColumnIndex(columnLabel)));
}
@Override
......@@ -142,27 +144,27 @@ public final class StreamQueryResult implements QueryResult {
@Override
public boolean isCaseSensitive(final int columnIndex) {
return metaData.isCaseSensitive(columnIndex);
return queryResultMetaData.isCaseSensitive(columnIndex);
}
@Override
public int getColumnCount() {
return metaData.getColumnCount();
return queryResultMetaData.getColumnCount();
}
@Override
public String getColumnLabel(final int columnIndex) {
return metaData.getColumnLabel(columnIndex);
return queryResultMetaData.getColumnLabel(columnIndex);
}
@SneakyThrows
private Object decrypt(final String columnLabel, final Object value) {
return decrypt(metaData.getColumnIndex(columnLabel), value);
return decrypt(queryResultMetaData.getColumnIndex(columnLabel), value);
}
@SneakyThrows
private Object decrypt(final int columnIndex, final Object value) {
Optional<ShardingEncryptor> shardingEncryptor = metaData.getShardingEncryptor(columnIndex);
Optional<ShardingEncryptor> shardingEncryptor = queryResultMetaData.getShardingEncryptor(columnIndex);
return shardingEncryptor.isPresent() ? shardingEncryptor.get().decrypt(getCiphertext(value)) : value;
}
......
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Multimap;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationDistinctSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationSelectItem;
......@@ -32,16 +33,18 @@ import java.util.LinkedList;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class AggregationDistinctQueryMetaDataTest {
private AggregationDistinctQueryMetaData distinctQueryMetaData;
private AggregationDistinctQueryMetaData distinctQueryMetaData;
@Before
public void setUp() {
Collection<AggregationDistinctSelectItem> aggregationDistinctSelectItems = new LinkedList<>();
AggregationDistinctSelectItem distinctCountSelectItem = new AggregationDistinctSelectItem(AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
AggregationDistinctSelectItem distinctAvgSelectItem = new AggregationDistinctSelectItem(AggregationType.AVG, "(DISTINCT order_id)", "a", "order_id");
AggregationDistinctSelectItem distinctCountSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
AggregationDistinctSelectItem distinctAvgSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.AVG, "(DISTINCT order_id)", "a", "order_id");
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationSelectItem(AggregationType.COUNT, "(DISTINCT order_id)", "AVG_DERIVED_COUNT_0"));
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationSelectItem(AggregationType.SUM, "(DISTINCT order_id)", "AVG_DERIVED_SUM_0"));
aggregationDistinctSelectItems.add(distinctCountSelectItem);
......@@ -51,61 +54,76 @@ public class AggregationDistinctQueryMetaDataTest {
columnLabelAndIndexMap.put("a", 2);
columnLabelAndIndexMap.put("AVG_DERIVED_COUNT_0", 3);
columnLabelAndIndexMap.put("AVG_DERIVED_SUM_0", 4);
distinctQueryMetaData = new AggregationDistinctQueryMetaData(aggregationDistinctSelectItems, columnLabelAndIndexMap);
distinctQueryMetaData = new AggregationDistinctQueryMetaData(aggregationDistinctSelectItems, getQueryResultMetaData());
}
@SneakyThrows
private QueryResultMetaData getQueryResultMetaData() {
QueryResultMetaData queryResultMetaData = mock(QueryResultMetaData.class);
when(queryResultMetaData.getColumnCount()).thenReturn(4);
when(queryResultMetaData.getColumnLabel(1)).thenReturn("c");
when(queryResultMetaData.getColumnLabel(2)).thenReturn("a");
when(queryResultMetaData.getColumnLabel(3)).thenReturn("AVG_DERIVED_COUNT_0");
when(queryResultMetaData.getColumnLabel(4)).thenReturn("AVG_DERIVED_SUM_0");
when(queryResultMetaData.getColumnIndex("c")).thenReturn(1);
when(queryResultMetaData.getColumnIndex("a")).thenReturn(2);
when(queryResultMetaData.getColumnIndex("AVG_DERIVED_COUNT_0")).thenReturn(3);
when(queryResultMetaData.getColumnIndex("AVG_DERIVED_SUM_0")).thenReturn(4);
return queryResultMetaData;
}
@Test
public void assertIsAggregationDistinctColumnIndex() {
assertTrue(distinctQueryMetaData.isAggregationDistinctColumnIndex(1));
}
@Test
public void assertIsAggregationDistinctColumnLabel() {
assertTrue(distinctQueryMetaData.isAggregationDistinctColumnLabel("c"));
}
@Test
public void assertGetAggregationType() {
AggregationType actual = distinctQueryMetaData.getAggregationType(2);
assertThat(actual, is(AggregationType.AVG));
}
@Test
public void assertIsDerivedCountColumnIndex() {
assertTrue(distinctQueryMetaData.isDerivedCountColumnIndex(3));
}
@Test
public void assertIsDerivedSumColumnIndex() {
assertTrue(distinctQueryMetaData.isDerivedSumColumnIndex(4));
}
@Test
public void assertGetAggregationDistinctColumnIndexByColumnLabel() {
int actual = distinctQueryMetaData.getAggregationDistinctColumnIndex("a");
assertThat(actual, is(2));
}
@Test(expected = ShardingException.class)
public void assertGetAggregationDistinctColumnIndexByColumnLabelWithException() {
int actual = distinctQueryMetaData.getAggregationDistinctColumnIndex("f");
assertThat(actual, is(2));
}
@Test
public void assertGetAggregationDistinctColumnIndexBySumIndex() {
int actual = distinctQueryMetaData.getAggregationDistinctColumnIndex(4);
assertThat(actual, is(2));
}
@Test(expected = ShardingException.class)
public void assertGetAggregationDistinctColumnIndexBySumIndexWithException() {
int actual = distinctQueryMetaData.getAggregationDistinctColumnIndex(0);
assertThat(actual, is(2));
}
@Test
public void assertGetAggregationDistinctColumnLabel() {
public void assertGetAggregationDistinctColumnLabel() {
String actual = distinctQueryMetaData.getAggregationDistinctColumnLabel(1);
assertThat(actual, is("c"));
}
......
......@@ -36,6 +36,7 @@ import java.util.List;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
......@@ -65,18 +66,36 @@ public class AggregationDistinctQueryResultTest {
when(queryResult.getValue(3, Object.class)).thenReturn(10 * i);
when(queryResult.getValue(4, Object.class)).thenReturn(10 * i);
when(queryResult.getValue(5, Object.class)).thenReturn(10 * i);
doReturn(getQueryResultMetaData()).when(queryResult).getQueryResultMetaData();
result.add(queryResult);
result.add(queryResult);
}
return result;
}
@SneakyThrows
private QueryResultMetaData getQueryResultMetaData() {
QueryResultMetaData queryResultMetaData = mock(QueryResultMetaData.class);
when(queryResultMetaData.getColumnCount()).thenReturn(5);
when(queryResultMetaData.getColumnLabel(1)).thenReturn("order_id");
when(queryResultMetaData.getColumnLabel(2)).thenReturn("c");
when(queryResultMetaData.getColumnLabel(3)).thenReturn("a");
when(queryResultMetaData.getColumnLabel(4)).thenReturn("AVG_DERIVED_COUNT_0");
when(queryResultMetaData.getColumnLabel(5)).thenReturn("AVG_DERIVED_SUM_0");
when(queryResultMetaData.getColumnIndex("order_id")).thenReturn(1);
when(queryResultMetaData.getColumnIndex("c")).thenReturn(2);
when(queryResultMetaData.getColumnIndex("a")).thenReturn(3);
when(queryResultMetaData.getColumnIndex("AVG_DERIVED_COUNT_0")).thenReturn(4);
when(queryResultMetaData.getColumnIndex("AVG_DERIVED_SUM_0")).thenReturn(5);
return queryResultMetaData;
}
private List<AggregationDistinctSelectItem> getAggregationDistinctSelectItems() {
List<AggregationDistinctSelectItem> result = new LinkedList<>();
AggregationDistinctSelectItem distinctCountSelectItem = new AggregationDistinctSelectItem(AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
AggregationDistinctSelectItem distinctAvgSelectItem = new AggregationDistinctSelectItem(AggregationType.AVG, "(DISTINCT order_id)", "a", "order_id");
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationDistinctSelectItem(AggregationType.COUNT, "(DISTINCT order_id)", "AVG_DERIVED_COUNT_0", "order_id"));
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationDistinctSelectItem(AggregationType.SUM, "(DISTINCT order_id)", "AVG_DERIVED_SUM_0", "order_id"));
AggregationDistinctSelectItem distinctCountSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
AggregationDistinctSelectItem distinctAvgSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.AVG, "(DISTINCT order_id)", "a", "order_id");
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, "(DISTINCT order_id)", "AVG_DERIVED_COUNT_0", "order_id"));
distinctAvgSelectItem.getDerivedAggregationItems().add(new AggregationDistinctSelectItem(0, 0, AggregationType.SUM, "(DISTINCT order_id)", "AVG_DERIVED_SUM_0", "order_id"));
result.add(distinctCountSelectItem);
result.add(distinctAvgSelectItem);
return result;
......
......@@ -17,9 +17,7 @@
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.collect.HashMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import lombok.SneakyThrows;
import org.junit.Before;
import org.junit.Test;
......@@ -39,15 +37,19 @@ 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.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class DistinctQueryResultTest {
private DistinctQueryResult distinctQueryResult;
private QueryResultMetaData queryResultMetaData;
@Before
public void setUp() {
queryResultMetaData = getQueryResultMetaData();
Collection<QueryResult> queryResults = getQueryResults();
List<String> distinctColumnLabels = Collections.singletonList("order_id");
distinctQueryResult = new DistinctQueryResult(queryResults, distinctColumnLabels);
......@@ -63,11 +65,21 @@ public class DistinctQueryResultTest {
when(queryResult.getColumnLabel(1)).thenReturn("order_id");
when(queryResult.getValue(1, Object.class)).thenReturn(10 * i);
when(queryResult.isCaseSensitive(1)).thenReturn(true);
doReturn(queryResultMetaData).when(queryResult).getQueryResultMetaData();
result.add(queryResult);
result.add(queryResult);
}
return result;
}
@SneakyThrows
private QueryResultMetaData getQueryResultMetaData() {
QueryResultMetaData queryResultMetaData = mock(QueryResultMetaData.class);
when(queryResultMetaData.getColumnCount()).thenReturn(1);
when(queryResultMetaData.getColumnLabel(1)).thenReturn("order_id");
when(queryResultMetaData.getColumnIndex("order_id")).thenReturn(1);
return queryResultMetaData;
}
@Test
public void assertDivide() {
......@@ -164,10 +176,8 @@ public class DistinctQueryResultTest {
}
@Test
public void assertGetColumnLabelAndIndexMap() {
Multimap<String, Integer> expected = HashMultimap.create();
expected.put("order_id", 1);
assertThat(distinctQueryResult.getColumnLabelAndIndexMap(), is(expected));
public void assertGetQueryResultMetaData() {
assertThat(distinctQueryResult.getQueryResultMetaData(), is(queryResultMetaData));
}
@Test
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Optional;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Calendar;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MemoryQueryResultTest {
@SneakyThrows
private ResultSet getResultSet() {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1);
when(resultSet.wasNull()).thenReturn(false);
doReturn(getResultSetMetaData()).when(resultSet).getMetaData();
return resultSet;
}
@SneakyThrows
private ResultSetMetaData getResultSetMetaData() {
ResultSetMetaData metaData = mock(ResultSetMetaData.class);
when(metaData.getColumnCount()).thenReturn(1);
when(metaData.getColumnLabel(1)).thenReturn("order_id");
when(metaData.getColumnName(1)).thenReturn("order_id");
when(metaData.getColumnType(1)).thenReturn(Types.INTEGER);
when(metaData.getTableName(1)).thenReturn("order");
when(metaData.isCaseSensitive(1)).thenReturn(false);
return metaData;
}
private ShardingEncryptor shardingEncryptor = mock(ShardingEncryptor.class);
@Test
public void assertConstructorWithShardingRule() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet(), getShardingRule());
assertThat(queryResult.getQueryResultMetaData().getShardingEncryptor(1), is(Optional.fromNullable(shardingEncryptor)));
}
@Test
public void assertConstructorWithEncryptRule() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet(), getEncryptRule());
assertThat(queryResult.getQueryResultMetaData().getShardingEncryptor(1), is(Optional.fromNullable(shardingEncryptor)));
}
@Test(expected = SQLException.class)
@SneakyThrows
public void assertConstructorWithSqlException() {
ResultSet resultSet = getResultSet();
when(resultSet.next()).thenThrow(new SQLException());
new MemoryQueryResult(resultSet);
}
private ShardingRule getShardingRule() {
ShardingRule shardingRule = mock(ShardingRule.class);
doReturn(getEncryptRule()).when(shardingRule).getEncryptRule();
doReturn(Optional.fromNullable(getTableRule())).when(shardingRule).findTableRuleByActualTable("order");
return shardingRule;
}
private TableRule getTableRule() {
TableRule tableRule = mock(TableRule.class);
when(tableRule.getLogicTable()).thenReturn("order");
return tableRule;
}
private EncryptRule getEncryptRule() {
EncryptRule encryptRule = mock(EncryptRule.class);
when(encryptRule.getShardingEncryptor("order", "order_id")).thenReturn(Optional.fromNullable(shardingEncryptor));
when(encryptRule.isCipherColumn("order", "order_id")).thenReturn(false);
return encryptRule;
}
@Test
public void assertNext() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
assertTrue(queryResult.next());
assertFalse(queryResult.next());
}
@Test
public void assertGetValueWithColumnIndex() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getValue(1, Integer.class), Is.<Object>is(1));
}
@Test
public void assertGetValueWithColumnLabel() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getValue("order_id", Integer.class), Is.<Object>is(1));
}
@Test
public void assertGetValueWithShardingRule() {
when(shardingEncryptor.decrypt("1")).thenReturn("1");
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet(), getShardingRule());
queryResult.next();
assertThat(queryResult.getValue("order_id", Integer.class), Is.<Object>is("1"));
}
@Test(expected = Exception.class)
public void assertGetValueWithException() {
ResultSet resultSet = getResultSetWithException();
MemoryQueryResult queryResult = new MemoryQueryResult(resultSet);
queryResult.next();
queryResult.getValue("order_id", Integer.class);
}
@SneakyThrows
private ResultSet getResultSetWithException() {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1);
when(resultSet.wasNull()).thenReturn(false);
doReturn(getResultSetMetaDataWithException()).when(resultSet).getMetaData();
return resultSet;
}
@SneakyThrows
private ResultSetMetaData getResultSetMetaDataWithException() {
ResultSetMetaData metaData = mock(ResultSetMetaData.class);
when(metaData.getColumnCount()).thenReturn(1);
when(metaData.getColumnLabel(1)).thenReturn("order_id");
when(metaData.getColumnName(1)).thenThrow(new SQLException());
when(metaData.getColumnType(1)).thenReturn(Types.INTEGER);
when(metaData.getTableName(1)).thenReturn("order");
return metaData;
}
@Test
public void assertGetCalendarValueWithColumnIndex() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getCalendarValue(1, Integer.class, Calendar.getInstance()), Is.<Object>is(1));
}
@Test
public void assertGetCalendarValueWithColumnLabel() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getCalendarValue("order_id", Integer.class, Calendar.getInstance()), Is.<Object>is(1));
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnIndex() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
InputStream inputStream = queryResult.getInputStream(1, "Unicode");
assertThat(inputStream.read(), is(getInputStream(1).read()));
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnLabel() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
InputStream inputStream = queryResult.getInputStream("order_id", "Unicode");
assertThat(inputStream.read(), is(getInputStream(1).read()));
}
@SneakyThrows
private InputStream getInputStream(final Object value) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(value);
objectOutputStream.flush();
objectOutputStream.close();
return new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
}
@Test
public void assertWasNull() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
queryResult.next();
assertFalse(queryResult.wasNull());
queryResult.next();
assertTrue(queryResult.wasNull());
}
@Test
public void assertIsCaseSensitive() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
assertFalse(queryResult.isCaseSensitive(1));
}
@Test
public void assertGetColumnCount() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
assertThat(queryResult.getColumnCount(), is(1));
}
@Test
public void assertGetColumnLabel() {
MemoryQueryResult queryResult = new MemoryQueryResult(getResultSet());
assertThat(queryResult.getColumnLabel(1), is("order_id"));
}
}
......@@ -22,7 +22,6 @@ import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.core.strategy.encrypt.EncryptEngine;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import org.junit.Before;
import org.junit.Test;
......@@ -56,11 +55,9 @@ public class QueryResultMetaDataTest {
@SuppressWarnings("unchecked")
private ShardingRule getShardingRule() {
shardingEncryptor = mock(ShardingEncryptor.class);
EncryptEngine encryptEngine = mock(EncryptEngine.class);
when(encryptEngine.getShardingEncryptor(anyString(), anyString())).thenReturn(Optional.of(shardingEncryptor));
ShardingRule result = mock(ShardingRule.class);
EncryptRule encryptRule = mock(EncryptRule.class);
when(encryptRule.getEncryptEngine()).thenReturn(encryptEngine);
when(encryptRule.getShardingEncryptor(anyString(), anyString())).thenReturn(Optional.of(shardingEncryptor));
when(result.getEncryptRule()).thenReturn(encryptRule);
when(result.getLogicTableNames(anyString())).thenReturn(Collections.<String>emptyList());
when(result.findTableRuleByActualTable("table")).thenReturn(Optional.<TableRule>absent());
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.execute.sql.execute.result;
import com.google.common.base.Optional;
import lombok.SneakyThrows;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.rule.TableRule;
import org.apache.shardingsphere.spi.encrypt.ShardingEncryptor;
import org.hamcrest.core.Is;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;
import java.sql.Date;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.Calendar;
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.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class StreamQueryResultTest {
@SneakyThrows
private ResultSet getResultSet() {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1);
when(resultSet.wasNull()).thenReturn(false).thenReturn(true);
doReturn(getResultSetMetaData()).when(resultSet).getMetaData();
return resultSet;
}
@SneakyThrows
private ResultSetMetaData getResultSetMetaData() {
ResultSetMetaData metaData = mock(ResultSetMetaData.class);
when(metaData.getColumnCount()).thenReturn(1);
when(metaData.getColumnLabel(1)).thenReturn("order_id");
when(metaData.getColumnName(1)).thenReturn("order_id");
when(metaData.getColumnType(1)).thenReturn(Types.INTEGER);
when(metaData.getTableName(1)).thenReturn("order");
when(metaData.isCaseSensitive(1)).thenReturn(false);
return metaData;
}
private ShardingEncryptor shardingEncryptor = mock(ShardingEncryptor.class);
@Test
public void assertConstructorWithShardingRule() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet(), getShardingRule());
assertThat(queryResult.getQueryResultMetaData().getShardingEncryptor(1), is(Optional.fromNullable(shardingEncryptor)));
}
@Test
public void assertConstructorWithEncryptRule() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet(), getEncryptRule());
assertThat(queryResult.getQueryResultMetaData().getShardingEncryptor(1), is(Optional.fromNullable(shardingEncryptor)));
}
private ShardingRule getShardingRule() {
ShardingRule shardingRule = mock(ShardingRule.class);
doReturn(getEncryptRule()).when(shardingRule).getEncryptRule();
doReturn(Optional.fromNullable(getTableRule())).when(shardingRule).findTableRuleByActualTable("order");
return shardingRule;
}
private TableRule getTableRule() {
TableRule tableRule = mock(TableRule.class);
when(tableRule.getLogicTable()).thenReturn("order");
return tableRule;
}
private EncryptRule getEncryptRule() {
EncryptRule encryptRule = mock(EncryptRule.class);
when(encryptRule.getShardingEncryptor("order", "order_id")).thenReturn(Optional.fromNullable(shardingEncryptor));
when(encryptRule.isCipherColumn("order", "order_id")).thenReturn(false);
return encryptRule;
}
@Test
@SneakyThrows
public void assertNext() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
assertTrue(queryResult.next());
assertFalse(queryResult.next());
}
@Test
@SneakyThrows
public void assertGetValueWithColumnIndex() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getValue(1, Integer.class), Is.<Object>is(1));
}
@Test
@SneakyThrows
public void assertGetValueWithColumnLabel() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
assertThat(queryResult.getValue("order_id", Integer.class), Is.<Object>is(1));
}
@Test
@SneakyThrows
public void assertGetValueWithShardingRule() {
when(shardingEncryptor.decrypt("1")).thenReturn("1");
StreamQueryResult queryResult = new StreamQueryResult(getResultSet(), getShardingRule());
queryResult.next();
assertThat(queryResult.getValue("order_id", Integer.class), Is.<Object>is("1"));
}
@Test(expected = Exception.class)
@SneakyThrows
public void assertGetValueWithException() {
ResultSet resultSet = getResultSetWithException();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getValue("order_id", Integer.class);
}
@SneakyThrows
private ResultSet getResultSetWithException() {
ResultSet resultSet = mock(ResultSet.class);
when(resultSet.next()).thenReturn(true).thenReturn(false);
when(resultSet.getInt(1)).thenReturn(1);
when(resultSet.wasNull()).thenReturn(false);
doReturn(getResultSetMetaDataWithException()).when(resultSet).getMetaData();
return resultSet;
}
@SneakyThrows
private ResultSetMetaData getResultSetMetaDataWithException() {
ResultSetMetaData metaData = mock(ResultSetMetaData.class);
when(metaData.getColumnCount()).thenReturn(1);
when(metaData.getColumnLabel(1)).thenReturn("order_id");
when(metaData.getColumnName(1)).thenThrow(new SQLException());
when(metaData.getColumnType(1)).thenReturn(Types.INTEGER);
when(metaData.getTableName(1)).thenReturn("order");
return metaData;
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnIndexAndDate() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue(1, Date.class, calendar);
verify(resultSet).getDate(1, calendar);
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnIndexAndTime() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue(1, Time.class, calendar);
verify(resultSet).getTime(1, calendar);
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnIndexAndTimestamp() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue(1, Timestamp.class, calendar);
verify(resultSet).getTimestamp(1, calendar);
}
@Test(expected = SQLException.class)
@SneakyThrows
public void assertGetCalendarValueWithColumnIndexAndUnsupportedType() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
queryResult.getCalendarValue(1, Object.class, Calendar.getInstance());
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnLabelAndDate() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue("order_id", Date.class, calendar);
verify(resultSet).getDate("order_id", calendar);
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnLabelAndTime() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue("order_id", Time.class, calendar);
verify(resultSet).getTime("order_id", calendar);
}
@Test
@SneakyThrows
public void assertGetCalendarValueWithColumnLabelAndTimestamp() {
ResultSet resultSet = getResultSet();
Calendar calendar = Calendar.getInstance();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getCalendarValue("order_id", Timestamp.class, calendar);
verify(resultSet).getTimestamp("order_id", calendar);
}
@Test(expected = SQLException.class)
@SneakyThrows
public void assertGetCalendarValueWithColumnLabelAndUnsupportedType() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
queryResult.getCalendarValue("order_id", Object.class, Calendar.getInstance());
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnIndexAndAscii() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream(1, "Ascii");
verify(resultSet).getAsciiStream(1);
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnIndexAndUnicode() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream(1, "Unicode");
verify(resultSet).getUnicodeStream(1);
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnIndexAndBinary() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream(1, "Binary");
verify(resultSet).getBinaryStream(1);
}
@Test(expected = SQLException.class)
@SneakyThrows
public void assertGetInputStreamWithColumnIndexAndUnsupportedType() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
queryResult.getInputStream(1, "Unsupported Type");
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnLabelAndAscii() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream("order_id", "Ascii");
verify(resultSet).getAsciiStream("order_id");
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnLabelAndUnicode() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream("order_id", "Unicode");
verify(resultSet).getUnicodeStream("order_id");
}
@Test
@SneakyThrows
public void assertGetInputStreamWithColumnLabelAndBinary() {
ResultSet resultSet = getResultSet();
StreamQueryResult queryResult = new StreamQueryResult(resultSet);
queryResult.next();
queryResult.getInputStream("order_id", "Binary");
verify(resultSet).getBinaryStream("order_id");
}
@Test(expected = SQLException.class)
@SneakyThrows
public void assertGetInputStreamWithColumnLabelAndUnsupportedType() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
queryResult.getInputStream("order_id", "Unsupported Type");
}
@Test
@SneakyThrows
public void assertWasNull() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
queryResult.next();
assertFalse(queryResult.wasNull());
queryResult.next();
assertTrue(queryResult.wasNull());
}
@Test
public void assertIsCaseSensitive() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
assertFalse(queryResult.isCaseSensitive(1));
}
@Test
public void assertGetColumnCount() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
assertThat(queryResult.getColumnCount(), Is.is(1));
}
@Test
public void assertGetColumnLabel() {
StreamQueryResult queryResult = new StreamQueryResult(getResultSet());
assertThat(queryResult.getColumnLabel(1), Is.is("order_id"));
}
}
......@@ -36,6 +36,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.paginatio
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingInsertOptimizedStatement;
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.optimize.transparent.statement.TransparentOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dal.DALStatement;
import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
......@@ -76,7 +77,7 @@ public final class MergeEngineFactoryTest {
SQLRouteResult routeResult = new SQLRouteResult(
new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList())));
assertThat(MergeEngineFactory.newInstance(DatabaseTypes.getActualDatabaseType("MySQL"), null, routeResult, null, queryResults), instanceOf(DQLMergeEngine.class));
}
......
......@@ -37,6 +37,7 @@ import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSe
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import org.apache.shardingsphere.core.parse.core.constant.OrderDirection;
import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.IndexOrderByItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -85,7 +86,7 @@ public final class GroupByMemoryMergedResultTest {
AggregationSelectItem derivedAggregationSelectItem2 = new AggregationSelectItem(AggregationType.SUM, "(num)", "AVG_DERIVED_SUM_0");
aggregationSelectItem2.setIndex(5);
aggregationSelectItem2.getDerivedAggregationItems().add(derivedAggregationSelectItem2);
SelectItems selectItems = new SelectItems(Arrays.<SelectItem>asList(aggregationSelectItem1, aggregationSelectItem2), false, 0);
SelectItems selectItems = new SelectItems(0, 0, false, Arrays.<SelectItem>asList(aggregationSelectItem1, aggregationSelectItem2), Collections.<TableSegment>emptyList(), null);
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(
new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.singletonList(createOrderByItem(new IndexOrderByItemSegment(0, 0, 3, OrderDirection.ASC, OrderDirection.ASC))), 0),
......
......@@ -32,6 +32,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.paginatio
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.core.constant.OrderDirection;
import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.IndexOrderByItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.junit.Test;
......@@ -62,7 +63,7 @@ public final class GroupByRowComparatorTest {
new OrderBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4"));
......@@ -79,7 +80,7 @@ public final class GroupByRowComparatorTest {
new OrderBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4"));
......@@ -96,7 +97,7 @@ public final class GroupByRowComparatorTest {
new OrderBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
......@@ -110,7 +111,7 @@ public final class GroupByRowComparatorTest {
new GroupBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.ASC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4"));
......@@ -124,7 +125,7 @@ public final class GroupByRowComparatorTest {
new GroupBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.DESC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("3", "4"));
......@@ -138,7 +139,7 @@ public final class GroupByRowComparatorTest {
new GroupBy(Arrays.asList(
createOrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC)),
createOrderByItem(new IndexOrderByItemSegment(0, 0, 2, OrderDirection.DESC, OrderDirection.ASC))), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
GroupByRowComparator groupByRowComparator = new GroupByRowComparator(optimizedStatement, caseSensitives);
MemoryQueryResultRow o1 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
MemoryQueryResultRow o2 = new MemoryQueryResultRow(mockQueryResult("1", "2"));
......
......@@ -37,6 +37,7 @@ import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSe
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import org.apache.shardingsphere.core.parse.core.constant.OrderDirection;
import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.IndexOrderByItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -87,7 +88,7 @@ public final class GroupByStreamMergedResultTest {
AggregationSelectItem derivedAggregationSelectItem2 = new AggregationSelectItem(AggregationType.SUM, "(num)", "AVG_DERIVED_SUM_0");
aggregationSelectItem2.setIndex(6);
aggregationSelectItem2.getDerivedAggregationItems().add(derivedAggregationSelectItem2);
SelectItems selectItems = new SelectItems(Arrays.<SelectItem>asList(aggregationSelectItem1, aggregationSelectItem2), false, 0);
SelectItems selectItems = new SelectItems(0, 0, false, Arrays.<SelectItem>asList(aggregationSelectItem1, aggregationSelectItem2), Collections.<TableSegment>emptyList(), null);
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(
new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.singletonList(new OrderByItem(new IndexOrderByItemSegment(0, 0, 3, OrderDirection.ASC, OrderDirection.ASC))), 0),
......
......@@ -32,6 +32,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.O
import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.OrderByItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.pagination.Pagination;
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -64,7 +65,7 @@ public final class IteratorStreamMergedResultTest {
queryResults = Lists.<QueryResult>newArrayList(new TestQueryResult(resultSet), new TestQueryResult(mock(ResultSet.class)), new TestQueryResult(mock(ResultSet.class)));
routeResult = new SQLRouteResult(new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList())));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList())));
}
@Test
......
......@@ -35,6 +35,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.paginatio
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.core.constant.OrderDirection;
import org.apache.shardingsphere.core.parse.sql.segment.dml.order.item.IndexOrderByItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -68,7 +69,7 @@ public final class OrderByStreamMergedResultTest {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(
new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(), new GroupBy(Collections.<OrderByItem>emptyList(), 0),
new OrderBy(Collections.singletonList(new OrderByItem(new IndexOrderByItemSegment(0, 0, 1, OrderDirection.ASC, OrderDirection.ASC))), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
routeResult = new SQLRouteResult(optimizedStatement);
}
......
......@@ -34,6 +34,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.O
import org.apache.shardingsphere.core.optimize.sharding.segment.select.pagination.Pagination;
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.dml.pagination.limit.NumberLiteralLimitValueSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -76,7 +77,8 @@ public final class LimitDecoratorMergedResultTest {
public void assertNextForSkipAll() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(new NumberLiteralLimitValueSegment(0, 0, Integer.MAX_VALUE), null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralLimitValueSegment(0, 0, Integer.MAX_VALUE), null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -87,7 +89,8 @@ public final class LimitDecoratorMergedResultTest {
public void assertNextWithoutRowCount() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(new NumberLiteralLimitValueSegment(0, 0, 2), null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralLimitValueSegment(0, 0, 2), null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -100,7 +103,8 @@ public final class LimitDecoratorMergedResultTest {
@Test
public void assertNextWithRowCount() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralLimitValueSegment(0, 0, 2), new NumberLiteralLimitValueSegment(0, 0, 2), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("MySQL"), routeResult, queryResults);
......
......@@ -34,6 +34,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.orderby.O
import org.apache.shardingsphere.core.optimize.sharding.segment.select.pagination.Pagination;
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.dml.pagination.rownum.NumberLiteralRowNumberValueSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -75,8 +76,9 @@ public final class RowNumberDecoratorMergedResultTest {
@Test
public void assertNextForSkipAll() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, Integer.MAX_VALUE, true), null, Collections.emptyList()));
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, Integer.MAX_VALUE, true), null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("Oracle"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -87,7 +89,7 @@ public final class RowNumberDecoratorMergedResultTest {
public void assertNextWithoutOffsetWithoutRowCount() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null), new Pagination(null, null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("Oracle"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -100,7 +102,8 @@ public final class RowNumberDecoratorMergedResultTest {
@Test
public void assertNextForRowCountBoundOpenedFalse() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, true), new NumberLiteralRowNumberValueSegment(0, 0, 4, false), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("Oracle"), routeResult, queryResults);
......@@ -113,7 +116,8 @@ public final class RowNumberDecoratorMergedResultTest {
@Test
public void assertNextForRowCountBoundOpenedTrue() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, true), new NumberLiteralRowNumberValueSegment(0, 0, 4, true), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("Oracle"), routeResult, queryResults);
......
......@@ -35,6 +35,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.select.paginatio
import org.apache.shardingsphere.core.optimize.sharding.statement.dml.ShardingSelectOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.segment.dml.pagination.limit.NumberLiteralLimitValueSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.pagination.rownum.NumberLiteralRowNumberValueSegment;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.route.SQLRouteResult;
import org.junit.Before;
......@@ -76,7 +77,8 @@ public final class TopAndRowNumberDecoratorMergedResultTest {
@Test
public void assertNextForSkipAll() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, Integer.MAX_VALUE, true), null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("SQLServer"), routeResult, queryResults);
......@@ -88,7 +90,8 @@ public final class TopAndRowNumberDecoratorMergedResultTest {
public void assertNextWithoutOffsetWithRowCount() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(null, new NumberLiteralLimitValueSegment(0, 0, 5), Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(null, new NumberLiteralLimitValueSegment(0, 0, 5), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("SQLServer"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -102,7 +105,8 @@ public final class TopAndRowNumberDecoratorMergedResultTest {
public void assertNextWithOffsetWithoutRowCount() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(Collections.<SelectItem>emptyList(), false, 0), new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, true), null, Collections.emptyList()));
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, true), null, Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("SQLServer"), routeResult, queryResults);
MergedResult actual = mergeEngine.merge();
......@@ -115,7 +119,8 @@ public final class TopAndRowNumberDecoratorMergedResultTest {
@Test
public void assertNextWithOffsetBoundOpenedFalse() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, false), new NumberLiteralLimitValueSegment(0, 0, 4), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("SQLServer"), routeResult, queryResults);
......@@ -128,7 +133,8 @@ public final class TopAndRowNumberDecoratorMergedResultTest {
@Test
public void assertNextWithOffsetBoundOpenedTrue() throws SQLException {
OptimizedStatement optimizedStatement = new ShardingSelectOptimizedStatement(new SelectStatement(), Collections.<ShardingCondition>emptyList(), Collections.<EncryptCondition>emptyList(),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false), new SelectItems(Collections.<SelectItem>emptyList(), false, 0),
new GroupBy(Collections.<OrderByItem>emptyList(), 0), new OrderBy(Collections.<OrderByItem>emptyList(), false),
new SelectItems(0, 0, false, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), null),
new Pagination(new NumberLiteralRowNumberValueSegment(0, 0, 2, true), new NumberLiteralLimitValueSegment(0, 0, 4), Collections.emptyList()));
SQLRouteResult routeResult = new SQLRouteResult(optimizedStatement);
mergeEngine = new DQLMergeEngine(DatabaseTypes.getActualDatabaseType("SQLServer"), routeResult, queryResults);
......
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.merge.fixture;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResult;
import org.apache.shardingsphere.core.execute.sql.execute.result.QueryResultMetaData;
import java.io.InputStream;
import java.io.Reader;
......@@ -205,7 +206,17 @@ public final class TestQueryResult implements QueryResult {
public boolean isCaseSensitive(final int columnIndex) throws SQLException {
return resultSet.getMetaData().isCaseSensitive(columnIndex);
}
@Override
public QueryResultMetaData getQueryResultMetaData() {
try {
return new QueryResultMetaData(resultSet.getMetaData());
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
@Override
public int getColumnCount() throws SQLException {
return resultSet.getMetaData().getColumnCount();
......
......@@ -39,14 +39,11 @@ public final class Column {
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
if (obj instanceof Column) {
Column column = (Column) obj;
return Objects.equal(name.toUpperCase(), column.getName().toUpperCase()) && Objects.equal(tableName.toUpperCase(), column.getTableName().toUpperCase());
}
if (null == obj || getClass() != obj.getClass()) {
return false;
}
Column column = (Column) obj;
return Objects.equal(this.name.toUpperCase(), column.name.toUpperCase()) && Objects.equal(this.tableName.toUpperCase(), column.tableName.toUpperCase());
return false;
}
@Override
......
......@@ -27,6 +27,7 @@ import org.apache.shardingsphere.core.optimize.sharding.segment.insert.value.Ins
import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.rule.EncryptRule;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
......@@ -43,12 +44,16 @@ public final class EncryptInsertOptimizeEngine implements EncryptOptimizeEngine<
InsertValueEngine insertValueEngine = new InsertValueEngine();
EncryptInsertOptimizedStatement result = new EncryptInsertOptimizedStatement(
sqlStatement, new EncryptInsertColumns(encryptRule, shardingTableMetaData, sqlStatement), insertValueEngine.createInsertValues(sqlStatement));
int derivedColumnsCount = encryptRule.getEncryptEngine().getAssistedQueryColumnCount(sqlStatement.getTable().getTableName());
int derivedColumnsCount = encryptRule.getAssistedQueryAndPlainColumnCount(sqlStatement.getTable().getTableName());
int parametersCount = 0;
for (InsertValue each : result.getValues()) {
InsertOptimizeResultUnit unit = result.addUnit(each.getValues(derivedColumnsCount), each.getParameters(parameters, parametersCount, derivedColumnsCount), each.getParametersCount());
if (encryptRule.getEncryptEngine().isHasShardingQueryAssistedEncryptor(sqlStatement.getTable().getTableName())) {
fillAssistedQueryUnit(encryptRule, parameters, sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit);
Object[] currentParameters = each.getParameters(parameters, parametersCount, derivedColumnsCount);
InsertOptimizeResultUnit unit = result.addUnit(each.getValues(derivedColumnsCount), currentParameters, each.getParametersCount());
if (encryptRule.isHasQueryAssistedColumn(sqlStatement.getTable().getTableName())) {
fillAssistedQueryUnit(encryptRule, Arrays.asList(currentParameters), sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit);
}
if (encryptRule.isHasPlainColumn(sqlStatement.getTable().getTableName())) {
fillPlainUnit(encryptRule, Arrays.asList(currentParameters), sqlStatement.getTable().getTableName(), result.getInsertColumns().getRegularColumnNames(), unit);
}
parametersCount += each.getParametersCount();
}
......@@ -58,7 +63,16 @@ public final class EncryptInsertOptimizeEngine implements EncryptOptimizeEngine<
private void fillAssistedQueryUnit(final EncryptRule encryptRule, final List<Object> parameters,
final String tableName, final Collection<String> columnNames, final InsertOptimizeResultUnit unit) {
for (String each : columnNames) {
if (encryptRule.getEncryptEngine().getAssistedQueryColumn(tableName, each).isPresent()) {
if (encryptRule.getAssistedQueryColumn(tableName, each).isPresent()) {
unit.addInsertValue((Comparable<?>) unit.getColumnValue(each), parameters);
}
}
}
private void fillPlainUnit(final EncryptRule encryptRule, final List<Object> parameters,
final String tableName, final Collection<String> columnNames, final InsertOptimizeResultUnit unit) {
for (String each : columnNames) {
if (encryptRule.getPlainColumn(tableName, each).isPresent()) {
unit.addInsertValue((Comparable<?>) unit.getColumnValue(each), parameters);
}
}
......
......@@ -20,7 +20,7 @@ package org.apache.shardingsphere.core.optimize.encrypt.engine.dml;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.encrypt.engine.EncryptOptimizeEngine;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.engine.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.encrypt.statement.EncryptConditionOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.statement.dml.DMLStatement;
import org.apache.shardingsphere.core.rule.EncryptRule;
......
......@@ -18,6 +18,7 @@
package org.apache.shardingsphere.core.optimize.encrypt.segment;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.api.segment.InsertColumns;
import org.apache.shardingsphere.core.parse.sql.segment.dml.assignment.AssignmentSegment;
......@@ -33,31 +34,50 @@ import java.util.LinkedList;
* Insert columns for encrypt.
*
* @author zhangliang
* @author panjuan
*/
@ToString
public final class EncryptInsertColumns implements InsertColumns {
private final Collection<String> assistedQueryColumnNames;
private final Collection<String> assistedQueryAndPlainColumnNames;
@Getter
private final Collection<String> regularColumnNames;
public EncryptInsertColumns(final EncryptRule encryptRule, final ShardingTableMetaData shardingTableMetaData, final InsertStatement insertStatement) {
String tableName = insertStatement.getTable().getTableName();
assistedQueryColumnNames = encryptRule.getEncryptEngine().getAssistedQueryColumns(tableName);
regularColumnNames = insertStatement.useDefaultColumns() ? getRegularColumnNamesFromMetaData(shardingTableMetaData, tableName) : getColumnNamesFromSQLStatement(insertStatement);
assistedQueryAndPlainColumnNames = encryptRule.getAssistedQueryAndPlainColumns(insertStatement.getTable().getTableName());
regularColumnNames = insertStatement.useDefaultColumns()
? getRegularColumnNamesFromMetaData(encryptRule, shardingTableMetaData, insertStatement) : getColumnNamesFromSQLStatement(insertStatement);
}
private Collection<String> getRegularColumnNamesFromMetaData(final ShardingTableMetaData shardingTableMetaData, final String tableName) {
Collection<String> allColumnNames = shardingTableMetaData.getAllColumnNames(tableName);
Collection<String> result = new LinkedHashSet<>(allColumnNames.size() - assistedQueryColumnNames.size());
private Collection<String> getRegularColumnNamesFromMetaData(final EncryptRule encryptRule, final ShardingTableMetaData shardingTableMetaData, final InsertStatement insertStatement) {
Collection<String> allColumnNames = shardingTableMetaData.getAllColumnNames(insertStatement.getTable().getTableName());
Collection<String> result = new LinkedHashSet<>(allColumnNames.size() - assistedQueryAndPlainColumnNames.size());
String tableName = insertStatement.getTable().getTableName();
for (String each : allColumnNames) {
if (!assistedQueryColumnNames.contains(each)) {
if (isCipherColumn(encryptRule, tableName, each)) {
result.add(getLogicColumn(encryptRule, tableName, each));
continue;
}
if (!isAssistedQueryAndPlainColumns(each)) {
result.add(each);
}
}
return result;
}
private boolean isAssistedQueryAndPlainColumns(final String columnName) {
return assistedQueryAndPlainColumnNames.contains(columnName);
}
private boolean isCipherColumn(final EncryptRule encryptRule, final String tableName, final String columnName) {
return encryptRule.getCipherColumns(tableName).contains(columnName);
}
private String getLogicColumn(final EncryptRule encryptRule, final String tableName, final String columnName) {
return encryptRule.getLogicColumn(tableName, columnName);
}
private Collection<String> getColumnNamesFromSQLStatement(final InsertStatement insertStatement) {
Collection<String> result = new LinkedList<>();
for (ColumnSegment each : insertStatement.getColumns()) {
......@@ -73,9 +93,9 @@ public final class EncryptInsertColumns implements InsertColumns {
@Override
public Collection<String> getAllColumnNames() {
Collection<String> result = new LinkedHashSet<>(regularColumnNames.size() + assistedQueryColumnNames.size());
Collection<String> result = new LinkedHashSet<>(regularColumnNames.size() + assistedQueryAndPlainColumnNames.size());
result.addAll(regularColumnNames);
result.addAll(assistedQueryColumnNames);
result.addAll(assistedQueryAndPlainColumnNames);
return result;
}
}
......@@ -104,15 +104,4 @@ public final class EncryptCondition {
}
return result;
}
/**
* Judge is same index or not.
*
* @param startIndex start index
* @param stopIndex stop index
* @return is same index or not
*/
public boolean isSameIndex(final int startIndex, final int stopIndex) {
return this.startIndex == startIndex && this.stopIndex == stopIndex;
}
}
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.optimize.encrypt.segment.condition;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import java.util.List;
......@@ -29,6 +30,7 @@ import java.util.List;
*/
@RequiredArgsConstructor
@Getter
@ToString
public final class EncryptConditions {
private final List<EncryptCondition> conditions;
......
......@@ -15,13 +15,14 @@
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.encrypt.segment.condition;
package org.apache.shardingsphere.core.optimize.encrypt.segment.condition.engine;
import com.google.common.base.Optional;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptCondition;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.SimpleExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.AndPredicate;
......@@ -96,7 +97,7 @@ public final class WhereClauseEncryptConditionEngine {
private Optional<EncryptCondition> createEncryptCondition(final PredicateSegment predicateSegment, final Tables tables) {
Optional<String> tableName = tables.findTableName(predicateSegment.getColumn(), shardingTableMetaData);
if (!tableName.isPresent() || !encryptRule.getEncryptEngine().getShardingEncryptor(tableName.get(), predicateSegment.getColumn().getName()).isPresent()) {
if (!tableName.isPresent() || !encryptRule.getShardingEncryptor(tableName.get(), predicateSegment.getColumn().getName()).isPresent()) {
return Optional.absent();
}
return createEncryptCondition(predicateSegment, tableName.get());
......
......@@ -17,7 +17,9 @@
package org.apache.shardingsphere.core.optimize.encrypt.statement;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.api.statement.ConditionOptimizedStatement;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
......@@ -28,14 +30,15 @@ import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement;
*
* @author zhangliang
*/
@Getter
@ToString(exclude = "sqlStatement")
public final class EncryptConditionOptimizedStatement implements ConditionOptimizedStatement, EncryptOptimizedStatement {
@Getter(AccessLevel.NONE)
private final SQLStatement sqlStatement;
@Getter
private final Tables tables;
@Getter
private final EncryptConditions encryptConditions;
public EncryptConditionOptimizedStatement(final SQLStatement sqlStatement, final EncryptConditions encryptConditions) {
......
......@@ -17,7 +17,9 @@
package org.apache.shardingsphere.core.optimize.encrypt.statement;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.InsertValue;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.api.statement.InsertOptimizedStatement;
......@@ -35,20 +37,19 @@ import java.util.List;
*
* @author zhangliang
*/
@Getter
@ToString(exclude = "sqlStatement")
public final class EncryptInsertOptimizedStatement implements InsertOptimizedStatement, EncryptOptimizedStatement {
@Getter(AccessLevel.NONE)
private final SQLStatement sqlStatement;
@Getter
private final Tables tables;
@Getter
private final EncryptInsertColumns insertColumns;
@Getter
private final Collection<InsertValue> values;
@Getter
private final List<InsertOptimizeResultUnit> units = new LinkedList<>();
public EncryptInsertOptimizedStatement(final SQLStatement sqlStatement, final EncryptInsertColumns insertColumns, final Collection<InsertValue> values) {
......
......@@ -19,7 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.engnie.dml;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.engine.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.sharding.engnie.ShardingOptimizeEngine;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingConditions;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.engine.WhereClauseShardingConditionEngine;
......
......@@ -34,6 +34,7 @@ import org.apache.shardingsphere.core.parse.sql.segment.dml.column.OnDuplicateKe
import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.rule.ShardingRule;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
......@@ -66,13 +67,17 @@ public final class ShardingInsertOptimizeEngine implements ShardingOptimizeEngin
int derivedColumnsCount = getDerivedColumnsCount(shardingRule, tableName, isGeneratedValue);
int parametersCount = 0;
for (InsertValue each : result.getValues()) {
InsertOptimizeResultUnit unit = result.createUnit(each.getValues(derivedColumnsCount), each.getParameters(parameters, parametersCount, derivedColumnsCount), each.getParametersCount());
Object[] currentParameters = each.getParameters(parameters, parametersCount, derivedColumnsCount);
InsertOptimizeResultUnit unit = result.createUnit(each.getValues(derivedColumnsCount), currentParameters, each.getParametersCount());
result.addUnit(unit);
if (isGeneratedValue) {
unit.addInsertValue(generatedValues.next(), parameters);
unit.addInsertValue(generatedValues.next(), Arrays.asList(currentParameters));
}
if (shardingRule.getEncryptRule().getEncryptEngine().isHasShardingQueryAssistedEncryptor(tableName)) {
fillAssistedQueryUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, parameters);
if (shardingRule.getEncryptRule().isHasQueryAssistedColumn(tableName)) {
fillAssistedQueryUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, Arrays.asList(currentParameters));
}
if (shardingRule.getEncryptRule().isHasPlainColumn(tableName)) {
fillPlainUnit(shardingRule, tableName, insertColumns.getRegularColumnNames(), unit, Arrays.asList(currentParameters));
}
parametersCount += each.getParametersCount();
}
......@@ -96,14 +101,23 @@ public final class ShardingInsertOptimizeEngine implements ShardingOptimizeEngin
}
private int getDerivedColumnsCount(final ShardingRule shardingRule, final String tableName, final boolean isGeneratedValue) {
int assistedQueryColumnsCount = shardingRule.getEncryptRule().getEncryptEngine().getAssistedQueryColumnCount(tableName);
return isGeneratedValue ? assistedQueryColumnsCount + 1 : assistedQueryColumnsCount;
int assistedQueryAndPlainColumnsCount = shardingRule.getEncryptRule().getAssistedQueryAndPlainColumnCount(tableName);
return isGeneratedValue ? assistedQueryAndPlainColumnsCount + 1 : assistedQueryAndPlainColumnsCount;
}
private void fillAssistedQueryUnit(final ShardingRule shardingRule,
final String tableName, final Collection<String> columnNames, final InsertOptimizeResultUnit unit, final List<Object> parameters) {
for (String each : columnNames) {
if (shardingRule.getEncryptRule().getEncryptEngine().getAssistedQueryColumn(tableName, each).isPresent()) {
if (shardingRule.getEncryptRule().getAssistedQueryColumn(tableName, each).isPresent()) {
unit.addInsertValue((Comparable<?>) unit.getColumnValue(each), parameters);
}
}
}
private void fillPlainUnit(final ShardingRule shardingRule,
final String tableName, final Collection<String> columnNames, final InsertOptimizeResultUnit unit, final List<Object> parameters) {
for (String each : columnNames) {
if (shardingRule.getEncryptRule().getPlainColumn(tableName, each).isPresent()) {
unit.addInsertValue((Comparable<?>) unit.getColumnValue(each), parameters);
}
}
......
......@@ -19,7 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.engnie.dml;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptCondition;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.engine.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.sharding.engnie.ShardingOptimizeEngine;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingCondition;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.engine.WhereClauseShardingConditionEngine;
......
......@@ -19,7 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.engnie.dml;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.engine.WhereClauseEncryptConditionEngine;
import org.apache.shardingsphere.core.optimize.sharding.engnie.ShardingOptimizeEngine;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingConditions;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.engine.WhereClauseShardingConditionEngine;
......
......@@ -17,10 +17,13 @@
package org.apache.shardingsphere.core.optimize.sharding.segment.condition;
import lombok.ToString;
/**
* Always false sharding condition.
*
* @author maxiaoguang
*/
@ToString
public final class AlwaysFalseShardingCondition extends ShardingCondition {
}
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.segment.condition;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import java.util.List;
......@@ -30,6 +31,7 @@ import java.util.List;
*/
@RequiredArgsConstructor
@Getter
@ToString
public final class ShardingConditions {
private final List<ShardingCondition> conditions;
......
......@@ -20,6 +20,7 @@ package org.apache.shardingsphere.core.optimize.sharding.segment.insert;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.InsertValue;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.LiteralExpressionSegment;
......@@ -41,6 +42,7 @@ import java.util.List;
*/
@RequiredArgsConstructor
@Getter
@ToString
public final class GeneratedKey {
private final String columnName;
......
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.segment.insert;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.shardingsphere.core.exception.ShardingException;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.LiteralExpressionSegment;
......@@ -38,6 +39,7 @@ import java.util.List;
*/
@RequiredArgsConstructor
@Getter
@ToString(exclude = "dataNodes")
public final class InsertOptimizeResultUnit {
private final Collection<String> columnNames;
......@@ -50,33 +52,6 @@ public final class InsertOptimizeResultUnit {
private final List<DataNode> dataNodes = new LinkedList<>();
/**
* Add column value.
*
* @param expressionSegment expression segment
*/
public void addColumnValue(final ExpressionSegment expressionSegment) {
values[getCurrentIndex(values, 0)] = expressionSegment;
}
/**
* Add column parameter.
*
* @param parameter parameter
*/
public void addColumnParameter(final Object parameter) {
parameters[getCurrentIndex(parameters, startIndexOfAppendedParameters)] = parameter;
}
private int getCurrentIndex(final Object[] array, final int startIndex) {
for (int i = startIndex; i < array.length; i++) {
if (null == array[i]) {
return i;
}
}
throw new ShardingException("Index Out Of Bounds For InsertOptimizeResultUnit.");
}
/**
* Set column value.
*
......@@ -148,4 +123,21 @@ public final class InsertOptimizeResultUnit {
addColumnParameter(insertValue);
}
}
private void addColumnValue(final ExpressionSegment expressionSegment) {
values[getCurrentIndex(values, 0)] = expressionSegment;
}
private void addColumnParameter(final Object parameter) {
parameters[getCurrentIndex(parameters, startIndexOfAppendedParameters)] = parameter;
}
private int getCurrentIndex(final Object[] array, final int startIndex) {
for (int i = startIndex; i < array.length; i++) {
if (null == array[i]) {
return i;
}
}
throw new ShardingException("Index Out Of Bounds For InsertOptimizeResultUnit.");
}
}
......@@ -18,11 +18,13 @@
package org.apache.shardingsphere.core.optimize.sharding.segment.insert;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.optimize.api.segment.InsertColumns;
import org.apache.shardingsphere.core.parse.sql.segment.dml.assignment.AssignmentSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.InsertStatement;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import java.util.Collection;
......@@ -32,44 +34,61 @@ import java.util.LinkedHashSet;
* Insert columns for sharding.
*
* @author zhangliang
* @author panjuan
*/
@ToString
public final class ShardingInsertColumns implements InsertColumns {
private final InsertStatement insertStatement;
private final String generateKeyColumnName;
private final Collection<String> assistedQueryColumnNames;
private final Collection<String> assistedQueryAndPlainColumnNames;
@Getter
private final Collection<String> regularColumnNames;
public ShardingInsertColumns(final ShardingRule shardingRule, final ShardingTableMetaData shardingTableMetaData, final InsertStatement insertStatement) {
this.insertStatement = insertStatement;
generateKeyColumnName = shardingRule.findGenerateKeyColumnName(insertStatement.getTable().getTableName()).orNull();
assistedQueryColumnNames = shardingRule.getEncryptRule().getEncryptEngine().getAssistedQueryColumns(insertStatement.getTable().getTableName());
regularColumnNames = insertStatement.useDefaultColumns() ? getRegularColumnNamesFromMetaData(shardingTableMetaData) : getRegularColumnNamesFromSQLStatement();
assistedQueryAndPlainColumnNames = shardingRule.getEncryptRule().getAssistedQueryAndPlainColumns(insertStatement.getTable().getTableName());
regularColumnNames = insertStatement.useDefaultColumns()
? getRegularColumnNamesFromMetaData(shardingRule.getEncryptRule(), shardingTableMetaData, insertStatement) : getRegularColumnNamesFromSQLStatement(insertStatement);
}
private Collection<String> getRegularColumnNamesFromMetaData(final ShardingTableMetaData shardingTableMetaData) {
private Collection<String> getRegularColumnNamesFromMetaData(final EncryptRule encryptRule, final ShardingTableMetaData shardingTableMetaData, final InsertStatement insertStatement) {
Collection<String> allColumnNames = shardingTableMetaData.getAllColumnNames(insertStatement.getTable().getTableName());
Collection<String> result = new LinkedHashSet<>(allColumnNames.size() - assistedQueryColumnNames.size());
Collection<String> result = new LinkedHashSet<>(allColumnNames.size() - assistedQueryAndPlainColumnNames.size());
String tableName = insertStatement.getTable().getTableName();
for (String each : allColumnNames) {
if (!assistedQueryColumnNames.contains(each)) {
if (isCipherColumn(encryptRule, tableName, each)) {
result.add(getLogicColumn(encryptRule, tableName, each));
continue;
}
if (!isAssistedQueryAndPlainColumns(each)) {
result.add(each);
}
}
if (isGenerateKeyFromMetaData(allColumnNames)) {
if (isGenerateKeyFromMetaData(allColumnNames, insertStatement.getValueSize())) {
result.remove(generateKeyColumnName);
}
return result;
}
private boolean isGenerateKeyFromMetaData(final Collection<String> allColumnNames) {
return null != generateKeyColumnName && allColumnNames.size() - assistedQueryColumnNames.size() != insertStatement.getValueSize();
private boolean isAssistedQueryAndPlainColumns(final String columnName) {
return assistedQueryAndPlainColumnNames.contains(columnName);
}
private boolean isCipherColumn(final EncryptRule encryptRule, final String tableName, final String columnName) {
return encryptRule.getCipherColumns(tableName).contains(columnName);
}
private String getLogicColumn(final EncryptRule encryptRule, final String tableName, final String columnName) {
return encryptRule.getLogicColumn(tableName, columnName);
}
private boolean isGenerateKeyFromMetaData(final Collection<String> allColumnNames, final int columnValueSize) {
return null != generateKeyColumnName && allColumnNames.size() - assistedQueryAndPlainColumnNames.size() != columnValueSize;
}
private Collection<String> getRegularColumnNamesFromSQLStatement() {
private Collection<String> getRegularColumnNamesFromSQLStatement(final InsertStatement insertStatement) {
Collection<String> result = new LinkedHashSet<>(insertStatement.getColumns().size(), 1);
for (ColumnSegment each : insertStatement.getColumns()) {
result.add(each.getName());
......@@ -79,24 +98,24 @@ public final class ShardingInsertColumns implements InsertColumns {
result.add(each.getColumn().getName());
}
}
if (isGenerateKeyFromSQLStatement()) {
if (isGenerateKeyFromSQLStatement(insertStatement)) {
result.remove(generateKeyColumnName);
}
return result;
}
private boolean isGenerateKeyFromSQLStatement() {
return null != generateKeyColumnName && insertStatement.getColumns().size() != insertStatement.getValueSize();
private boolean isGenerateKeyFromSQLStatement(final InsertStatement insertStatement) {
return null != generateKeyColumnName && !insertStatement.getColumns().isEmpty() && insertStatement.getColumns().size() != insertStatement.getValueSize();
}
@Override
public Collection<String> getAllColumnNames() {
Collection<String> result = new LinkedHashSet<>(regularColumnNames.size() + assistedQueryColumnNames.size() + 1);
Collection<String> result = new LinkedHashSet<>(regularColumnNames.size() + assistedQueryAndPlainColumnNames.size() + 1);
result.addAll(regularColumnNames);
if (null != generateKeyColumnName && !regularColumnNames.contains(generateKeyColumnName)) {
result.add(generateKeyColumnName);
}
result.addAll(assistedQueryColumnNames);
result.addAll(assistedQueryAndPlainColumnNames);
return result;
}
}
......@@ -28,10 +28,17 @@ import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
@Getter
public final class AggregationDistinctSelectItem extends AggregationSelectItem {
private final int startIndex;
private final int stopIndex;
private final String distinctInnerExpression;
public AggregationDistinctSelectItem(final AggregationType type, final String innerExpression, final String alias, final String distinctInnerExpression) {
public AggregationDistinctSelectItem(final int startIndex, final int stopIndex,
final AggregationType type, final String innerExpression, final String alias, final String distinctInnerExpression) {
super(type, innerExpression, alias);
this.startIndex = startIndex;
this.stopIndex = stopIndex;
this.distinctInnerExpression = distinctInnerExpression;
}
......
......@@ -55,17 +55,18 @@ public class AggregationSelectItem implements SelectItem {
public final String getExpression() {
return SQLUtil.getExactlyValue(type.name() + innerExpression);
}
@Override
public final Optional<String> getAlias() {
return Optional.fromNullable(alias);
}
/**
* Get column label.
*
* @return column label
*/
@Override
public String getColumnLabel() {
return getAlias().or(getExpression());
}
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.sharding.segment.select.item;
import com.google.common.base.Optional;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Common select item.
*
* @author zhangliang
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public final class ColumnSelectItem implements SelectItem {
private final String owner;
private final String name;
private final String alias;
@Override
public String getExpression() {
return null == owner ? name : owner + "." + name;
}
@Override
public String getColumnLabel() {
return getAlias().or(name);
}
@Override
public Optional<String> getAlias() {
return Optional.fromNullable(alias);
}
}
......@@ -24,22 +24,28 @@ import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Common select item.
* Derived common select item.
*
* @author zhangliang
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public class CommonSelectItem implements SelectItem {
public final class DerivedSelectItem implements SelectItem {
private final String expression;
private final String alias;
@Override
public final Optional<String> getAlias() {
public Optional<String> getAlias() {
return Optional.fromNullable(alias);
}
@Override
public String getColumnLabel() {
return getAlias().or(getExpression());
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.sharding.segment.select.item;
import com.google.common.base.Optional;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
/**
* Expression select item.
*
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter
@EqualsAndHashCode
@ToString
public final class ExpressionSelectItem implements SelectItem {
private final String expression;
private final String alias;
@Override
public Optional<String> getAlias() {
return Optional.fromNullable(alias);
}
@Override
public String getColumnLabel() {
return getAlias().or(getExpression());
}
}
......@@ -39,4 +39,11 @@ public interface SelectItem {
* @return alias
*/
Optional<String> getAlias();
/**
* Get columnLabel.
*
* @return columnLabel
*/
String getColumnLabel();
}
......@@ -21,9 +21,13 @@ import com.google.common.base.Optional;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
......@@ -31,17 +35,25 @@ import java.util.List;
* Select items.
*
* @author zhangliang
* @author sunbufu
*/
@RequiredArgsConstructor
@Getter
@Setter
@ToString(exclude = "shardingTableMetaData")
public final class SelectItems {
private final Collection<SelectItem> items;
private final int startIndex;
private final int stopIndex;
private final boolean distinctRow;
private final int selectListStopIndex;
private final Collection<SelectItem> items;
private final Collection<TableSegment> tables;
private final ShardingTableMetaData shardingTableMetaData;
/**
* Judge is unqualified shorthand item or not.
......@@ -111,11 +123,33 @@ public final class SelectItems {
public List<String> getColumnLabels() {
List<String> result = new ArrayList<>(items.size());
for (SelectItem each : items) {
// TODO read * from metadata
if (!(each instanceof ShorthandSelectItem)) {
result.add(each.getAlias().or(each.getExpression()));
if (each instanceof ShorthandSelectItem) {
result.addAll(getShorthandColumnLabels((ShorthandSelectItem) each));
} else {
result.add(each.getColumnLabel());
}
}
return result;
}
private Collection<String> getShorthandColumnLabels(final ShorthandSelectItem shorthandSelectItem) {
return shorthandSelectItem.getOwner().isPresent() ? getQualifiedShorthandColumnLabels(shorthandSelectItem.getOwner().get()) : getUnqualifiedShorthandColumnLabels();
}
private Collection<String> getQualifiedShorthandColumnLabels(final String owner) {
for (TableSegment each : tables) {
if (owner.equalsIgnoreCase(each.getAlias().or(each.getTableName()))) {
return shardingTableMetaData.get(each.getTableName()).getColumns().keySet();
}
}
return Collections.emptyList();
}
private Collection<String> getUnqualifiedShorthandColumnLabels() {
Collection<String> result = new LinkedList<>();
for (TableSegment each : tables) {
result.addAll(shardingTableMetaData.get(each.getTableName()).getColumns().keySet());
}
return result;
}
}
......@@ -46,7 +46,12 @@ public final class ShorthandSelectItem implements SelectItem {
public Optional<String> getAlias() {
return Optional.absent();
}
@Override
public String getColumnLabel() {
return getAlias().or("*");
}
/**
* Get owner.
*
......
......@@ -20,8 +20,9 @@ package org.apache.shardingsphere.core.optimize.sharding.segment.select.item.eng
import com.google.common.base.Optional;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationDistinctSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.AggregationSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.CommonSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.ColumnSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.DerivedColumn;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.ExpressionSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.ShorthandSelectItem;
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
......@@ -76,18 +77,20 @@ public final class SelectItemEngine {
return new ShorthandSelectItem(owner.isPresent() ? owner.get().getTableName() : null);
}
private CommonSelectItem createSelectItem(final ColumnSelectItemSegment selectItemSegment) {
return new CommonSelectItem(selectItemSegment.getQualifiedName(), selectItemSegment.getAlias().orNull());
private ColumnSelectItem createSelectItem(final ColumnSelectItemSegment selectItemSegment) {
String owner = selectItemSegment.getOwner().isPresent() ? selectItemSegment.getOwner().get().getTableName() : null;
return new ColumnSelectItem(owner, selectItemSegment.getName(), selectItemSegment.getAlias().orNull());
}
private CommonSelectItem createSelectItem(final ExpressionSelectItemSegment selectItemSegment) {
return new CommonSelectItem(selectItemSegment.getText(), selectItemSegment.getAlias().orNull());
private ExpressionSelectItem createSelectItem(final ExpressionSelectItemSegment selectItemSegment) {
return new ExpressionSelectItem(selectItemSegment.getText(), selectItemSegment.getAlias().orNull());
}
private AggregationDistinctSelectItem createSelectItem(final String sql, final AggregationDistinctSelectItemSegment selectItemSegment) {
String innerExpression = sql.substring(selectItemSegment.getInnerExpressionStartIndex(), selectItemSegment.getStopIndex() + 1);
String alias = selectItemSegment.getAlias().or(DerivedColumn.AGGREGATION_DISTINCT_DERIVED.getDerivedColumnAlias(aggregationDistinctDerivedColumnCount++));
AggregationDistinctSelectItem result = new AggregationDistinctSelectItem(selectItemSegment.getType(), innerExpression, alias, selectItemSegment.getDistinctExpression());
AggregationDistinctSelectItem result = new AggregationDistinctSelectItem(
selectItemSegment.getStartIndex(), selectItemSegment.getStopIndex(), selectItemSegment.getType(), innerExpression, alias, selectItemSegment.getDistinctExpression());
if (AggregationType.AVG == result.getType()) {
appendAverageDistinctDerivedItem(result);
}
......@@ -108,9 +111,9 @@ public final class SelectItemEngine {
String innerExpression = averageDistinctSelectItem.getInnerExpression();
String distinctInnerExpression = averageDistinctSelectItem.getDistinctInnerExpression();
String countAlias = DerivedColumn.AVG_COUNT_ALIAS.getDerivedColumnAlias(aggregationAverageDerivedColumnCount);
AggregationDistinctSelectItem countDistinctSelectItem = new AggregationDistinctSelectItem(AggregationType.COUNT, innerExpression, countAlias, distinctInnerExpression);
AggregationDistinctSelectItem countDistinctSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, innerExpression, countAlias, distinctInnerExpression);
String sumAlias = DerivedColumn.AVG_SUM_ALIAS.getDerivedColumnAlias(aggregationAverageDerivedColumnCount);
AggregationDistinctSelectItem sumDistinctSelectItem = new AggregationDistinctSelectItem(AggregationType.SUM, innerExpression, sumAlias, distinctInnerExpression);
AggregationDistinctSelectItem sumDistinctSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.SUM, innerExpression, sumAlias, distinctInnerExpression);
averageDistinctSelectItem.getDerivedAggregationItems().add(countDistinctSelectItem);
averageDistinctSelectItem.getDerivedAggregationItems().add(sumDistinctSelectItem);
aggregationAverageDerivedColumnCount++;
......
......@@ -25,7 +25,7 @@ import org.apache.shardingsphere.core.optimize.api.segment.Table;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.groupby.GroupBy;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.DerivedColumn;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.DerivedCommonSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.DerivedSelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItem;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItems;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.ShorthandSelectItem;
......@@ -46,6 +46,7 @@ import java.util.LinkedList;
* Select items engine.
*
* @author zhangliang
* @author sunbufu
*/
@RequiredArgsConstructor
public final class SelectItemsEngine {
......@@ -56,7 +57,7 @@ public final class SelectItemsEngine {
/**
* Create select items.
*
*
* @param sql SQL
* @param selectStatement SQL statement
* @param groupBy group by
......@@ -66,7 +67,8 @@ public final class SelectItemsEngine {
public SelectItems createSelectItems(final String sql, final SelectStatement selectStatement, final GroupBy groupBy, final OrderBy orderBy) {
SelectItemsSegment selectItemsSegment = selectStatement.getSelectItems();
Collection<SelectItem> items = getSelectItemList(sql, selectItemsSegment);
SelectItems result = new SelectItems(items, selectItemsSegment.isDistinctRow(), selectItemsSegment.getStopIndex());
SelectItems result = new SelectItems(
selectItemsSegment.getStartIndex(), selectItemsSegment.getStopIndex(), selectItemsSegment.isDistinctRow(), items, selectStatement.getTables(), shardingTableMetaData);
Tables tables = new Tables(selectStatement);
result.getItems().addAll(getDerivedGroupByColumns(tables, items, groupBy));
result.getItems().addAll(getDerivedOrderByColumns(tables, items, orderBy));
......@@ -97,7 +99,7 @@ public final class SelectItemsEngine {
int derivedColumnOffset = 0;
for (OrderByItem each : orderItems) {
if (!containsItem(tables, selectItems, each.getSegment())) {
result.add(new DerivedCommonSelectItem(((TextOrderByItemSegment) each.getSegment()).getText(), derivedColumn.getDerivedColumnAlias(derivedColumnOffset++)));
result.add(new DerivedSelectItem(((TextOrderByItemSegment) each.getSegment()).getText(), derivedColumn.getDerivedColumnAlias(derivedColumnOffset++)));
}
}
return result;
......
......@@ -17,8 +17,10 @@
package org.apache.shardingsphere.core.optimize.sharding.statement.ddl;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.sharding.statement.ShardingOptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement;
......@@ -31,14 +33,15 @@ import java.util.Collection;
* @author zhangliang
*/
@RequiredArgsConstructor
@Getter
@ToString(exclude = "sqlStatement")
public final class ShardingDropIndexOptimizedStatement implements ShardingOptimizedStatement {
@Getter(AccessLevel.NONE)
private final SQLStatement sqlStatement;
@Getter
private final Tables tables;
@Getter
private final Collection<String> tableNames;
@Override
......
......@@ -17,7 +17,9 @@
package org.apache.shardingsphere.core.optimize.sharding.statement.dml;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.api.statement.ConditionOptimizedStatement;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
......@@ -30,17 +32,17 @@ import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement;
*
* @author zhangliang
*/
@Getter
@ToString(exclude = "sqlStatement")
public class ShardingConditionOptimizedStatement implements ShardingOptimizedStatement, ConditionOptimizedStatement {
@Getter(AccessLevel.NONE)
private final SQLStatement sqlStatement;
@Getter
private final Tables tables;
@Getter
private final ShardingConditions shardingConditions;
@Getter
private final EncryptConditions encryptConditions;
public ShardingConditionOptimizedStatement(final SQLStatement sqlStatement, final ShardingConditions shardingConditions, final EncryptConditions encryptConditions) {
......
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.optimize.sharding.statement.dml;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.InsertValue;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.api.statement.InsertOptimizedStatement;
......@@ -43,6 +44,7 @@ import java.util.List;
* @author zhangliang
*/
@Getter
@ToString(callSuper = true)
public final class ShardingInsertOptimizedStatement extends ShardingConditionOptimizedStatement implements InsertOptimizedStatement {
private final Tables tables;
......
......@@ -21,6 +21,7 @@ import com.google.common.base.Optional;
import com.google.common.base.Preconditions;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptCondition;
import org.apache.shardingsphere.core.optimize.encrypt.segment.condition.EncryptConditions;
......@@ -51,6 +52,7 @@ import java.util.Map;
*/
@Getter
@Setter
@ToString
public final class ShardingSelectOptimizedStatement extends ShardingConditionOptimizedStatement {
private final Tables tables;
......
......@@ -18,6 +18,7 @@
package org.apache.shardingsphere.core.optimize.transparent.statement;
import lombok.Getter;
import lombok.ToString;
import org.apache.shardingsphere.core.optimize.api.segment.Tables;
import org.apache.shardingsphere.core.optimize.api.statement.OptimizedStatement;
import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement;
......@@ -27,6 +28,7 @@ import org.apache.shardingsphere.core.parse.sql.statement.SQLStatement;
*
* @author zhangliang
*/
@ToString(exclude = "sqlStatement")
public final class TransparentOptimizedStatement implements OptimizedStatement {
private final SQLStatement sqlStatement;
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.api.segment;
import org.junit.Test;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class ColumnTest {
@Test
public void assertEqualsForDifferentObjectType() {
assertFalse(new Column("col", "tbl").equals(new Object()));
}
@Test
public void assertEquals() {
assertTrue(new Column("col", "tbl").equals(new Column("COL", "TBL")));
}
@Test
public void assertNotEqualsWhenColumnNameIsDifferent() {
assertFalse(new Column("col", "tbl").equals(new Column("col1", "tbl")));
}
@Test
public void assertNotEqualsWhenTableNameIsDifferent() {
assertFalse(new Column("col", "tbl").equals(new Column("col", "tbl1")));
}
}
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.api.segment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.LiteralExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.ParameterMarkerExpressionSegment;
import org.junit.Test;
import java.util.Arrays;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
public final class InsertValueTest {
@Test
public void assertGetParametersCount() {
InsertValue actual = new InsertValue(Arrays.<ExpressionSegment>asList(new LiteralExpressionSegment(0, 0, 1), new ParameterMarkerExpressionSegment(0, 0, 1)));
assertThat(actual.getParametersCount(), is(1));
}
}
......@@ -19,13 +19,17 @@ package org.apache.shardingsphere.core.optimize.sharding.engnie.dml;
import com.google.common.base.Optional;
import com.google.common.collect.Range;
import org.apache.shardingsphere.core.metadata.table.ColumnMetaData;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.metadata.table.TableMetaData;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingCondition;
import org.apache.shardingsphere.core.optimize.sharding.segment.condition.ShardingConditions;
import org.apache.shardingsphere.core.optimize.sharding.segment.select.item.SelectItems;
import org.apache.shardingsphere.core.parse.sql.segment.dml.column.ColumnSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.ExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.expr.simple.LiteralExpressionSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.item.SelectItemsSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.item.ShorthandSelectItemSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.AndPredicate;
import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.PredicateSegment;
import org.apache.shardingsphere.core.parse.sql.segment.dml.predicate.WhereSegment;
......@@ -36,7 +40,6 @@ import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.apache.shardingsphere.core.parse.sql.statement.dml.SelectStatement;
import org.apache.shardingsphere.core.rule.EncryptRule;
import org.apache.shardingsphere.core.rule.ShardingRule;
import org.apache.shardingsphere.core.strategy.encrypt.EncryptEngine;
import org.apache.shardingsphere.core.strategy.route.value.ListRouteValue;
import org.apache.shardingsphere.core.strategy.route.value.RangeRouteValue;
import org.apache.shardingsphere.core.strategy.route.value.RouteValue;
......@@ -75,9 +78,7 @@ public final class ShardingSelectOptimizeEngineTest {
public void setUp() {
when(shardingRule.isShardingColumn("column", "tbl")).thenReturn(true);
EncryptRule encryptRule = mock(EncryptRule.class);
EncryptEngine encryptEngine = mock(EncryptEngine.class);
when(encryptEngine.getShardingEncryptor("tbl", "column")).thenReturn(Optional.<ShardingEncryptor>absent());
when(encryptRule.getEncryptEngine()).thenReturn(encryptEngine);
when(encryptRule.getShardingEncryptor("tbl", "column")).thenReturn(Optional.<ShardingEncryptor>absent());
when(shardingRule.getEncryptRule()).thenReturn(encryptRule);
selectStatement = new SelectStatement();
selectStatement.getAllSQLSegments().add(new TableSegment(0, 0, "tbl"));
......@@ -206,4 +207,31 @@ public final class ShardingSelectOptimizeEngineTest {
result.setOwner(new TableSegment(0, 0, "tbl"));
return result;
}
@Test
public void assertOptimizeWithShorthandItems() {
when(shardingTableMetaData.get("tbl")).thenReturn(createTableMetaData());
selectStatement.setSelectItems(createSelectItemsSegment());
selectStatement.getTables().add(new TableSegment(0, 0, "tbl"));
SelectItems selectItems = new ShardingSelectOptimizeEngine().optimize(shardingRule, shardingTableMetaData, "", Collections.emptyList(), selectStatement).getSelectItems();
assertThat(selectItems.getColumnLabels().size(), is(2));
assertThat(selectItems.getColumnLabels().get(0), is("id"));
assertThat(selectItems.getColumnLabels().get(1), is("user_id"));
}
private SelectItemsSegment createSelectItemsSegment() {
TableSegment owner = mock(TableSegment.class);
when(owner.getTableName()).thenReturn("tbl");
ShorthandSelectItemSegment shorthandSelectItemSegment = new ShorthandSelectItemSegment(0, 0, "tbl.*");
shorthandSelectItemSegment.setOwner(owner);
SelectItemsSegment result = new SelectItemsSegment(0, 0, false);
result.getSelectItems().add(shorthandSelectItemSegment);
return result;
}
private TableMetaData createTableMetaData() {
ColumnMetaData idColumnMetaData = new ColumnMetaData("id", "int", true);
ColumnMetaData nameColumnMetaData = new ColumnMetaData("user_id", "int", false);
return new TableMetaData(Arrays.asList(idColumnMetaData, nameColumnMetaData), Arrays.asList("id", "user_id"));
}
}
......@@ -25,7 +25,7 @@ import static org.junit.Assert.assertThat;
public final class AggregationDistinctSelectItemTest {
private final AggregationDistinctSelectItem aggregationDistinctSelectItem = new AggregationDistinctSelectItem(AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
private final AggregationDistinctSelectItem aggregationDistinctSelectItem = new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, "(DISTINCT order_id)", "c", "order_id");
@Test
public void assertGetDistinctColumnLabel() {
......
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.shardingsphere.core.optimize.sharding.segment.select.item;
import org.apache.shardingsphere.core.metadata.table.ColumnMetaData;
import org.apache.shardingsphere.core.metadata.table.ShardingTableMetaData;
import org.apache.shardingsphere.core.metadata.table.TableMetaData;
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import org.apache.shardingsphere.core.parse.sql.segment.generic.TableSegment;
import org.junit.Test;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
public final class SelectItemsTest {
@Test
public void assertUnqualifiedShorthandItemWithEmptyItems() {
SelectItems selectItems = new SelectItems(0, 0, true, Collections.<SelectItem>emptySet(), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertFalse(selectItems.isUnqualifiedShorthandItem());
}
@Test
public void assertUnqualifiedShorthandItemWithWrongSelectItem() {
SelectItems selectItems = new SelectItems(0, 0, true, Collections.singleton((SelectItem) getColumnSelectItem()), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertFalse(selectItems.isUnqualifiedShorthandItem());
}
@Test
public void assertUnqualifiedShorthandItemWithWrongShortSelectItem() {
SelectItems selectItems = new SelectItems(0, 0, true, Collections.singleton((SelectItem) getShorthandSelectItem()), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertFalse(selectItems.isUnqualifiedShorthandItem());
}
@Test
public void assertUnqualifiedShorthandItem() {
SelectItem selectItem = new ShorthandSelectItem(null);
SelectItems selectItems = new SelectItems(0, 0, true, Collections.singleton(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertTrue(selectItems.isUnqualifiedShorthandItem());
}
@Test
public void assertFindAliasWithOutAlias() {
SelectItems selectItems = new SelectItems(0, 0, true, Collections.<SelectItem>emptyList(), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertFalse(selectItems.findAlias("").isPresent());
}
@Test
public void assertFindAlias() {
SelectItem selectItem = getColumnSelectItemWithAlias();
SelectItems selectItems = new SelectItems(0, 0, true, Collections.singleton(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData());
assertTrue(selectItems.findAlias(selectItem.getExpression()).isPresent());
}
@Test
public void assertGetAggregationSelectItems() {
SelectItem aggregationSelectItem = getAggregationSelectItem();
List<AggregationSelectItem> items = new SelectItems(0, 0, true,
Arrays.asList(aggregationSelectItem, getColumnSelectItem()), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getAggregationSelectItems();
assertTrue(items.contains(aggregationSelectItem));
assertEquals(items.size(), 1);
}
@Test
public void assertGetAggregationDistinctSelectItems() {
SelectItem aggregationDistinctSelectItem = getAggregationDistinctSelectItem();
List<AggregationDistinctSelectItem> items = new SelectItems(0, 0, true,
Arrays.asList(aggregationDistinctSelectItem, getColumnSelectItem()), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getAggregationDistinctSelectItems();
assertTrue(items.contains(aggregationDistinctSelectItem));
assertEquals(items.size(), 1);
}
@Test
public void assertGetColumnLabelWithShorthandSelectItem() {
SelectItem selectItem = getShorthandSelectItem();
List<String> columnLabels = new SelectItems(
0, 0, true, Collections.singletonList(selectItem), Collections.singletonList(new TableSegment(0, 0, "table")), createShardingTableMetaData()).getColumnLabels();
assertEquals(columnLabels, Arrays.asList("id", "name"));
}
@Test
public void assertGetColumnLabelWithShorthandSelectItem2() {
SelectItem selectItem = getShorthandSelectItemWithOutOwner();
List<String> columnLabels = new SelectItems(
0, 0, true, Collections.singletonList(selectItem), Collections.singletonList(new TableSegment(0, 0, "table")), createShardingTableMetaData()).getColumnLabels();
assertEquals(columnLabels, Arrays.asList("id", "name"));
}
@Test
public void assertGetColumnLabelsWithCommonSelectItem() {
SelectItem selectItem = getColumnSelectItem();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getColumnLabel()));
}
@Test
public void assertGetColumnLabelsWithCommonSelectItemAlias() {
SelectItem selectItem = getColumnSelectItemWithAlias();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getAlias().or("")));
}
@Test
public void assertGetColumnLabelsWithExpressionSelectItem() {
SelectItem selectItem = getExpressionSelectItem();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getColumnLabel()));
}
@Test
public void assertGetColumnLabelsWithExpressionSelectItemAlias() {
SelectItem selectItem = getExpressionSelectItemWithAlias();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getAlias().or("")));
}
@Test
public void assertGetColumnLabelsWithDerivedSelectItem() {
SelectItem selectItem = getDerivedSelectItem();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getColumnLabel()));
}
@Test
public void assertGetColumnLabelsWithDerivedSelectItemAlias() {
SelectItem selectItem = getDerivedSelectItemWithAlias();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getAlias().or("")));
}
@Test
public void assertGetColumnLabelsWithAggregationSelectItem() {
SelectItem selectItem = getAggregationSelectItem();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getColumnLabel()));
}
@Test
public void assertGetColumnLabelsWithAggregationDistinctSelectItem() {
SelectItem selectItem = getAggregationDistinctSelectItem();
List<String> columnLabels = new SelectItems(0, 0, true, Collections.singletonList(selectItem), Collections.<TableSegment>emptyList(), createShardingTableMetaData()).getColumnLabels();
assertTrue(columnLabels.contains(selectItem.getColumnLabel()));
}
private ShardingTableMetaData createShardingTableMetaData() {
Map<String, TableMetaData> tables = new HashMap<>(1, 1);
tables.put("table", new TableMetaData(Arrays.asList(new ColumnMetaData("id", "number", true), new ColumnMetaData("name", "varchar", false)), Collections.<String>emptyList()));
return new ShardingTableMetaData(tables);
}
private ShorthandSelectItem getShorthandSelectItem() {
return new ShorthandSelectItem("table");
}
private ShorthandSelectItem getShorthandSelectItemWithOutOwner() {
return new ShorthandSelectItem(null);
}
private ColumnSelectItem getColumnSelectItem() {
return new ColumnSelectItem("table", "name", null);
}
private ColumnSelectItem getColumnSelectItemWithAlias() {
return new ColumnSelectItem("table", "name", "n");
}
private ExpressionSelectItem getExpressionSelectItem() {
return new ExpressionSelectItem("table.name", null);
}
private ExpressionSelectItem getExpressionSelectItemWithAlias() {
return new ExpressionSelectItem("table.name", "n");
}
private DerivedSelectItem getDerivedSelectItem() {
return new DerivedSelectItem("table.name", null);
}
private DerivedSelectItem getDerivedSelectItemWithAlias() {
return new DerivedSelectItem("table.name", "n");
}
private AggregationSelectItem getAggregationSelectItem() {
return new AggregationSelectItem(AggregationType.COUNT, "(column)", "c");
}
private AggregationDistinctSelectItem getAggregationDistinctSelectItem() {
return new AggregationDistinctSelectItem(0, 0, AggregationType.COUNT, "(DISTINCT column)", "c", "column");
}
}
......@@ -17,6 +17,7 @@
package org.apache.shardingsphere.core.parse.core.constant;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
/**
......@@ -25,13 +26,14 @@ import lombok.RequiredArgsConstructor;
* @author zhangliang
*/
@RequiredArgsConstructor
@Getter
public enum Paren {
PARENTHESES("(", ")"), BRACKET("[", "]"), BRACES("{", "}");
PARENTHESES('(', ')'), BRACKET('[', ']'), BRACES('{', '}');
private final String leftParen;
private final char leftParen;
private final String rightParen;
private final char rightParen;
/**
* Judge passed token is left paren or not.
......@@ -39,9 +41,9 @@ public enum Paren {
* @param token token
* @return is left paren or not
*/
public static boolean isLeftParen(final String token) {
public static boolean isLeftParen(final char token) {
for (Paren each : Paren.values()) {
if (each.leftParen.equals(token)) {
if (each.leftParen == token) {
return true;
}
}
......@@ -55,9 +57,9 @@ public enum Paren {
* @param rightToken right token
* @return match or not
*/
public static boolean match(final String leftToken, final String rightToken) {
public static boolean match(final char leftToken, final char rightToken) {
for (Paren each : Paren.values()) {
if (each.leftParen.equals(leftToken) && each.rightParen.equals(rightToken)) {
if (each.leftParen == leftToken && each.rightParen == rightToken) {
return true;
}
}
......
......@@ -79,7 +79,7 @@ public final class PredicateExtractor implements OptionalSQLSegmentExtractor {
}
private Optional<OrPredicateSegment> extractRecursiveWithParen(final ParserRuleContext exprNode, final Map<ParserRuleContext, Integer> parameterMarkerIndexes) {
if (Paren.isLeftParen(exprNode.getChild(0).getText())) {
if (1 == exprNode.getChild(0).getText().length() && Paren.isLeftParen(exprNode.getChild(0).getText().charAt(0))) {
return extractRecursiveWithLogicalOperation((ParserRuleContext) exprNode.getChild(1), parameterMarkerIndexes);
}
Optional<PredicateSegment> predicate = extractPredicate(exprNode, parameterMarkerIndexes);
......
......@@ -19,6 +19,7 @@ package org.apache.shardingsphere.core.parse.sql.segment.dml.item;
import lombok.Getter;
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import org.apache.shardingsphere.core.parse.util.SQLUtil;
/**
* Aggregation distinct select item segment.
......@@ -33,6 +34,6 @@ public final class AggregationDistinctSelectItemSegment extends AggregationSelec
public AggregationDistinctSelectItemSegment(final int startIndex, final int stopIndex,
final String text, final AggregationType type, final int innerExpressionStartIndex, final String distinctExpression) {
super(startIndex, stopIndex, text, type, innerExpressionStartIndex);
this.distinctExpression = distinctExpression;
this.distinctExpression = SQLUtil.getExpressionWithoutOutsideParentheses(distinctExpression);
}
}
......@@ -19,7 +19,6 @@ package org.apache.shardingsphere.core.parse.sql.segment.dml.item;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.parse.core.constant.AggregationType;
import org.apache.shardingsphere.core.parse.sql.segment.generic.AliasAvailable;
import org.apache.shardingsphere.core.parse.util.SQLUtil;
......@@ -29,7 +28,6 @@ import org.apache.shardingsphere.core.parse.util.SQLUtil;
*
* @author zhangliang
*/
@RequiredArgsConstructor
@Getter
public class AggregationSelectItemSegment implements SelectItemSegment, AliasAvailable {
......@@ -45,6 +43,14 @@ public class AggregationSelectItemSegment implements SelectItemSegment, AliasAva
private String alias;
public AggregationSelectItemSegment(final int startIndex, final int stopIndex, final String text, final AggregationType type, final int innerExpressionStartIndex) {
this.startIndex = startIndex;
this.stopIndex = stopIndex;
this.text = SQLUtil.getExpressionWithoutOutsideParentheses(text);
this.type = type;
this.innerExpressionStartIndex = innerExpressionStartIndex;
}
@Override
public final Optional<String> getAlias() {
return Optional.fromNullable(alias);
......
......@@ -37,7 +37,7 @@ public final class ColumnSelectItemSegment extends ColumnSegment implements Sele
public ColumnSelectItemSegment(final String text, final ColumnSegment columnSegment) {
super(columnSegment.getStartIndex(), columnSegment.getStopIndex(), columnSegment.getName());
this.text = text;
this.text = SQLUtil.getExpressionWithoutOutsideParentheses(text);
if (columnSegment.getOwner().isPresent()) {
setOwner(columnSegment.getOwner().get());
}
......
......@@ -19,7 +19,6 @@ package org.apache.shardingsphere.core.parse.sql.segment.dml.item;
import com.google.common.base.Optional;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import org.apache.shardingsphere.core.parse.sql.segment.generic.AliasAvailable;
import org.apache.shardingsphere.core.parse.util.SQLUtil;
......@@ -28,7 +27,6 @@ import org.apache.shardingsphere.core.parse.util.SQLUtil;
*
* @author zhangliang
*/
@RequiredArgsConstructor
@Getter
public final class ExpressionSelectItemSegment implements SelectItemSegment, AliasAvailable {
......@@ -40,6 +38,12 @@ public final class ExpressionSelectItemSegment implements SelectItemSegment, Ali
private String alias;
public ExpressionSelectItemSegment(final int startIndex, final int stopIndex, final String text) {
this.startIndex = startIndex;
this.stopIndex = stopIndex;
this.text = SQLUtil.getExpressionWithoutOutsideParentheses(text);
}
@Override
public Optional<String> getAlias() {
return Optional.fromNullable(alias);
......
......@@ -18,8 +18,10 @@
package org.apache.shardingsphere.core.parse.util;
import com.google.common.base.CharMatcher;
import com.google.common.base.Strings;
import lombok.AccessLevel;
import lombok.AllArgsConstructor;
import org.apache.shardingsphere.core.parse.core.constant.Paren;
import java.math.BigDecimal;
import java.math.BigInteger;
......@@ -80,6 +82,25 @@ public final class SQLUtil {
* @return exactly SQL expression
*/
public static String getExactlyExpression(final String value) {
return null == value ? null : CharMatcher.anyOf(" ").removeFrom(value);
return Strings.isNullOrEmpty(value) ? value : CharMatcher.anyOf(" ").removeFrom(value);
}
/**
* Get exactly SQL expression without outside parentheses.
*
* @param value SQL expression
* @return exactly SQL expression
*/
public static String getExpressionWithoutOutsideParentheses(final String value) {
int parenthesesOffset = getParenthesesOffset(value);
return 0 == parenthesesOffset ? value : value.substring(parenthesesOffset, value.length() - parenthesesOffset);
}
private static int getParenthesesOffset(final String value) {
int result = 0;
while (Paren.PARENTHESES.getLeftParen() == value.charAt(result)) {
result++;
}
return result;
}
}
......@@ -26,43 +26,43 @@ public final class ParenTest {
@Test
public void assertIsLeftParenForParentheses() {
assertTrue(Paren.isLeftParen("("));
assertTrue(Paren.isLeftParen('('));
}
@Test
public void assertIsLeftParenForBracket() {
assertTrue(Paren.isLeftParen("["));
assertTrue(Paren.isLeftParen('['));
}
@Test
public void assertIsLeftParenForBraces() {
assertTrue(Paren.isLeftParen("{"));
assertTrue(Paren.isLeftParen('{'));
}
@Test
public void assertIsNotLeftParen() {
assertFalse(Paren.isLeftParen(")"));
assertFalse(Paren.isLeftParen("]"));
assertFalse(Paren.isLeftParen("}"));
assertFalse(Paren.isLeftParen(')'));
assertFalse(Paren.isLeftParen(']'));
assertFalse(Paren.isLeftParen('}'));
}
@Test
public void assertMatchForParentheses() {
assertTrue(Paren.match("(", ")"));
assertTrue(Paren.match('(', ')'));
}
@Test
public void assertMatchForBracket() {
assertTrue(Paren.match("[", "]"));
assertTrue(Paren.match('[', ']'));
}
@Test
public void assertMatchForBraces() {
assertTrue(Paren.match("{", "}"));
assertTrue(Paren.match('{', '}'));
}
@Test
public void assertNotMatch() {
assertFalse(Paren.match("{", "]"));
assertFalse(Paren.match('{', ']'));
}
}
......@@ -23,7 +23,6 @@ import java.math.BigDecimal;
import java.math.BigInteger;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThat;
......@@ -66,18 +65,28 @@ public final class SQLUtilTest {
assertThat(SQLUtil.getExactlyValue("'xxx'"), is("xxx"));
}
@Test
public void assertGetExactlyValueUsingNull() {
assertNull(SQLUtil.getExactlyValue(null));
}
@Test
public void assertGetExactlyExpressionUsingAndReturningNull() {
assertNull(SQLUtil.getExactlyExpression(null));
}
@Test
public void testGetExactlyExpressionUsingAndReturningEmptyString() {
assertEquals("", SQLUtil.getExactlyExpression(""));
public void assertGetExactlyExpressionUsingAndReturningEmptyString() {
assertThat(SQLUtil.getExactlyExpression(""), is(""));
}
@Test
public void assertGetExactlyValueUsingNull() {
assertNull(SQLUtil.getExactlyValue(null));
public void assertGetExactlyExpression() {
assertThat(SQLUtil.getExactlyExpression("((a + b*c))"), is("((a+b*c))"));
}
@Test
public void assertGetExpressionWithoutOutsideParentheses() {
assertThat(SQLUtil.getExpressionWithoutOutsideParentheses("((a + b*c))"), is("a + b*c"));
}
}
......@@ -98,7 +98,13 @@ unreservedWord_
| BOOLEAN | MAX | MIN | SUM | COUNT | AVG | BIT_AND
| BIT_OR | BIT_XOR | GROUP_CONCAT | JSON_ARRAYAGG | JSON_OBJECTAGG | STD | STDDEV
| STDDEV_POP | STDDEV_SAMP | VAR_POP | VAR_SAMP | VARIANCE | EXTENDED | STATUS
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF
| FIELDS | INDEXES | USER | ROLE | OJ | AUTOCOMMIT | OFF | ROTATE | INSTANCE | MASTER | BINLOG |ERROR
| SCHEDULE | COMPLETION | DO | DEFINER | START | EVERY | HOST | SOCKET | OWNER | PORT | RETURNS | CONTAINS
| SECURITY | INVOKER | UNDEFINED | MERGE | TEMPTABLE | CASCADED | LOCAL | SERVER | WRAPPER | OPTIONS | DATAFILE
| FILE_BLOCK_SIZE | EXTENT_SIZE | INITIAL_SIZE | AUTOEXTEND_SIZE | MAX_SIZE | NODEGROUP
| WAIT | LOGFILE | UNDOFILE | UNDO_BUFFER_SIZE | REDO_BUFFER_SIZE | DEFINITION | ORGANIZATION
| DESCRIPTION | REFERENCE | FOLLOWS | PRECEDES | NAME |CLOSE | OPEN | NEXT | HANDLER | PREV
| IMPORT | CONCURRENT | XML
;
schemaName
......@@ -113,6 +119,38 @@ columnName
: (owner DOT_)? name
;
userName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_)
| identifier_
| STRING_
;
eventName
: (STRING_ | IDENTIFIER_) AT_ (STRING_ IDENTIFIER_)
| identifier_
| STRING_
;
serverName
: identifier_
| STRING_
;
wrapperName
: identifier_
| STRING_
;
functionName
: identifier_
| (owner DOT_)? identifier_
;
viewName
: identifier_
| (owner DOT_)? identifier_
;
owner
: identifier_
;
......@@ -137,6 +175,10 @@ characterSetName_
: IDENTIFIER_
;
collationName_
: IDENTIFIER_
;
expr
: expr logicalOperator expr
| expr XOR expr
......
......@@ -100,6 +100,68 @@ select
: withClause_? unionClause_
;
callStatement
: CALL identifier_ (LP_ (identifier_ | expr)? RP_)?
;
doStatement
: DO expr (COMMA_ expr)?
;
handlerStatement
: handlerOpenStatement | handlerReadIndexStatement | handlerReadStatement | handlerCloseStatement
;
handlerOpenStatement
: HANDLER tableName OPEN (AS? identifier_)?
;
handlerReadIndexStatement
: HANDLER tableName READ identifier_ ( comparisonOperator LP_ identifier_ RP_ | (FIRST | NEXT | PREV | LAST) )
(WHERE expr)? (LIMIT numberLiterals)?
;
handlerReadStatement
: HANDLER tableName READ (FIRST | NEXT)
(WHERE expr)? (LIMIT numberLiterals)?
;
handlerCloseStatement
: HANDLER tableName CLOSE
;
importStatement
: IMPORT TABLE FROM STRING_ (COMMA_ STRING_)?
;
loadDataStatement
: LOAD DATA
(LOW_PRIORITY | CONCURRENT)? LOCAL?
INFILE STRING_
(REPLACE | IGNORE)?
INTO TABLE tableName
(PARTITION LP_ identifier_ (COMMA_ identifier_)* RP_ )?
(CHARACTER SET identifier_)?
( (FIELDS | COLUMNS) selectFieldsInto_+ )?
( LINES selectLinesInto_+ )?
( IGNORE numberLiterals (LINES | ROWS) )?
( LP_ identifier_ (COMMA_ identifier_)* RP_ )?
(setAssignmentsClause)?
;
loadXmlStatement
: LOAD XML
(LOW_PRIORITY | CONCURRENT)? LOCAL?
INFILE STRING_
(REPLACE | IGNORE)?
INTO TABLE tableName
(CHARACTER SET identifier_)?
(ROWS IDENTIFIED BY LT_ STRING_ GT_)?
( IGNORE numberLiterals (LINES | ROWS) )?
( LP_ identifier_ (COMMA_ identifier_)* RP_ )?
(setAssignmentsClause)?
;
withClause_
: WITH RECURSIVE? cteClause_ (COMMA_ cteClause_)*
;
......@@ -221,3 +283,11 @@ windowItem_
subquery
: LP_ unionClause_ RP_ AS? alias?
;
selectLinesInto_
: STARTING BY STRING_ | TERMINATED BY STRING_
;
selectFieldsInto_
: TERMINATED BY STRING_ | OPTIONALLY? ENCLOSED BY STRING_ | ESCAPED BY STRING_
;
......@@ -22,6 +22,7 @@ import Alphabet, Symbol;
IDENTIFIER_
: [A-Za-z_$0-9]*?[A-Za-z_$]+?[A-Za-z_$0-9]*
| BQ_ ~'`'+ BQ_
| (DQ_ ( '\\'. | '""' | ~('"'| '\\') )* DQ_)
;
STRING_
......
......@@ -94,7 +94,8 @@ unreservedWord_
| MEASURE | FOLDER | BUILD | PROCESS | OPERATOR | OUTLINE | PLUGGABLE
| CONTAINER | SEGMENT | RESTRICTED | COST | SYNONYM | BACKUP | UNLIMITED
| BECOME | CHANGE | NOTIFICATION | ACCESS | PRIVILEGE | PURGE | RESUMABLE
| SYSGUID | SYSBACKUP | SYSDBA | SYSDG | SYSKM | SYSOPER | DBA_RECYCLEBIN
| SYSGUID | SYSBACKUP | SYSDBA | SYSDG | SYSKM | SYSOPER | DBA_RECYCLEBIN |SCHEMA
| DO | DEFINER | CURRENT_USER | CASCADED | CLOSE | OPEN | NEXT | NAME
;
schemaName
......
......@@ -155,10 +155,6 @@ TRANSLATE
: T R A N S L A T E
;
SQL
: S Q L
;
MERGE
: M E R G E
;
......@@ -279,10 +275,6 @@ LEVELS
: L E V E L S
;
LOCAL
: L O C A L
;
MAXVALUE
: M A X V A L U E
;
......@@ -335,10 +327,6 @@ ONLY
: O N L Y
;
PRESERVE
: P R E S E R V E
;
PRIOR
: P R I O R
;
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册