Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support batch insert(支持批量插入) #776

Merged
merged 2 commits into from
Apr 30, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
import io.shardingjdbc.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingjdbc.core.parsing.parser.sql.dql.select.SelectStatement;
import io.shardingjdbc.core.routing.router.sharding.GeneratedKey;
import io.shardingjdbc.core.rule.ShardingRule;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

Expand All @@ -33,21 +34,23 @@
* Optimize engine factory.
*
* @author zhangliang
* @author maxiaoguang
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class OptimizeEngineFactory {

/**
* Create optimize engine instance.
*
* @param shardingRule sharding rule
* @param sqlStatement SQL statement
* @param parameters parameters
* @param generatedKey generated key
* @return optimize engine instance
*/
public static OptimizeEngine newInstance(final SQLStatement sqlStatement, final List<Object> parameters, final GeneratedKey generatedKey) {
public static OptimizeEngine newInstance(final ShardingRule shardingRule, final SQLStatement sqlStatement, final List<Object> parameters, final GeneratedKey generatedKey) {
if (sqlStatement instanceof InsertStatement) {
return new InsertOptimizeEngine(sqlStatement.getConditions().getOrCondition(), parameters, generatedKey);
return new InsertOptimizeEngine(shardingRule, (InsertStatement) sqlStatement, parameters, generatedKey);
}
if (sqlStatement instanceof SelectStatement || sqlStatement instanceof DMLStatement) {
return new QueryOptimizeEngine(sqlStatement.getConditions().getOrCondition(), parameters);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,46 +17,76 @@

package io.shardingjdbc.core.optimizer.insert;

import com.google.common.base.Optional;
import io.shardingjdbc.core.api.algorithm.sharding.ListShardingValue;
import io.shardingjdbc.core.optimizer.OptimizeEngine;
import io.shardingjdbc.core.optimizer.condition.ShardingCondition;
import io.shardingjdbc.core.optimizer.condition.ShardingConditions;
import io.shardingjdbc.core.parsing.parser.context.condition.AndCondition;
import io.shardingjdbc.core.parsing.parser.context.condition.Column;
import io.shardingjdbc.core.parsing.parser.context.condition.Condition;
import io.shardingjdbc.core.parsing.parser.context.condition.GeneratedKeyCondition;
import io.shardingjdbc.core.parsing.parser.context.condition.OrCondition;
import io.shardingjdbc.core.parsing.parser.context.insertvalue.InsertValue;
import io.shardingjdbc.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingjdbc.core.routing.router.sharding.GeneratedKey;
import io.shardingjdbc.core.rule.ShardingRule;
import lombok.RequiredArgsConstructor;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

/**
* Insert optimize engine.
*
* @author zhangliang
* @author maxiaoguang
*/
@RequiredArgsConstructor
public final class InsertOptimizeEngine implements OptimizeEngine {

private final OrCondition orCondition;
private final ShardingRule shardingRule;

private final InsertStatement insertStatement;

private final List<Object> parameters;

private final GeneratedKey generatedKey;

@Override
public ShardingConditions optimize() {
ShardingCondition result = new ShardingCondition();
for (AndCondition each : orCondition.getAndConditions()) {
result.getShardingValues().addAll(getShardingCondition(each));
}
if (null != generatedKey) {
result.getShardingValues().add(getShardingCondition(generatedKey));
List<AndCondition> andConditions = insertStatement.getConditions().getOrCondition().getAndConditions();
List<InsertValue> insertValues = insertStatement.getInsertValues().getInsertValues();
List<ShardingCondition> result = new ArrayList<>(andConditions.size());
int count = 0;
for (AndCondition each : andConditions) {
InsertValue insertValue = insertValues.get(count);
List<Object> currentParameters = new ArrayList<>(insertValue.getParametersCount() + 1);
currentParameters.addAll(parameters.subList(count * insertValue.getParametersCount(), (count + 1) * insertValue.getParametersCount()));

String logicTableName = insertStatement.getTables().getSingleTableName();
Optional<Column> generateKeyColumn = shardingRule.getGenerateKeyColumn(logicTableName);
String expression;
if (-1 != insertStatement.getGenerateKeyColumnIndex() || !generateKeyColumn.isPresent()) {
expression = insertValue.getExpression();
} else {
if (0 == parameters.size()) {
expression = insertValue.getExpression().substring(0, insertValue.getExpression().length() - 1) + ", " + generatedKey.getGeneratedKeys().get(count).toString() + ")";
} else {
expression = insertValue.getExpression().substring(0, insertValue.getExpression().length() - 1) + ", ?)";
currentParameters.add(generatedKey.getGeneratedKeys().get(count));
}
}
InsertShardingCondition insertShardingCondition = new InsertShardingCondition(expression, currentParameters);
insertShardingCondition.getShardingValues().addAll(getShardingCondition(each));
if (-1 == insertStatement.getGenerateKeyColumnIndex() && generateKeyColumn.isPresent()) {
insertShardingCondition.getShardingValues().add(getShardingCondition(generateKeyColumn.get(), generatedKey.getGeneratedKeys().get(count)));
}
result.add(insertShardingCondition);
count++;
}
return new ShardingConditions(result.getShardingValues().isEmpty() ? Collections.<ShardingCondition>emptyList() : Collections.singletonList(result));
return new ShardingConditions(result);
}

private Collection<ListShardingValue> getShardingCondition(final AndCondition andCondition) {
Expand All @@ -67,8 +97,8 @@ private Collection<ListShardingValue> getShardingCondition(final AndCondition an
return result;
}

private ListShardingValue getShardingCondition(final GeneratedKey generatedKey) {
return new ListShardingValue<>(generatedKey.getColumn().getTableName(), generatedKey.getColumn().getName(),
new GeneratedKeyCondition(generatedKey.getColumn(), generatedKey.getIndex(), generatedKey.getValue()).getConditionValues(parameters));
private ListShardingValue getShardingCondition(final Column column, final Number value) {
return new ListShardingValue<>(column.getTableName(), column.getName(),
new GeneratedKeyCondition(column, -1, value).getConditionValues(parameters));
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/

package io.shardingjdbc.core.optimizer.insert;

import io.shardingjdbc.core.optimizer.condition.ShardingCondition;
import io.shardingjdbc.core.rule.DataNode;
import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.ToString;

import java.util.LinkedList;
import java.util.List;

/**
* Sharding condition.
*
* @author maxiaoguang
*/
@RequiredArgsConstructor
@Getter
@ToString
public class InsertShardingCondition extends ShardingCondition {

private final String insertValueExpression;

private final List<Object> parameters;

private final List<DataNode> dataNodes = new LinkedList<>();
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,18 @@
import io.shardingjdbc.core.parsing.lexer.token.Keyword;
import io.shardingjdbc.core.parsing.lexer.token.Symbol;
import io.shardingjdbc.core.parsing.parser.clause.expression.BasicExpressionParser;
import io.shardingjdbc.core.parsing.parser.context.condition.AndCondition;
import io.shardingjdbc.core.parsing.parser.context.condition.Column;
import io.shardingjdbc.core.parsing.parser.context.condition.Condition;
import io.shardingjdbc.core.parsing.parser.context.condition.Conditions;
import io.shardingjdbc.core.parsing.parser.context.condition.GeneratedKeyCondition;
import io.shardingjdbc.core.parsing.parser.context.insertvalue.InsertValue;
import io.shardingjdbc.core.parsing.parser.dialect.ExpressionParserFactory;
import io.shardingjdbc.core.parsing.parser.expression.SQLExpression;
import io.shardingjdbc.core.parsing.parser.expression.SQLNumberExpression;
import io.shardingjdbc.core.parsing.parser.expression.SQLPlaceholderExpression;
import io.shardingjdbc.core.parsing.parser.sql.dml.insert.InsertStatement;
import io.shardingjdbc.core.parsing.parser.token.InsertValuesToken;
import io.shardingjdbc.core.parsing.parser.token.ItemsToken;
import io.shardingjdbc.core.parsing.parser.token.MultipleInsertValuesToken;
import io.shardingjdbc.core.rule.ShardingRule;

import java.util.Arrays;
Expand Down Expand Up @@ -74,42 +75,59 @@ public void parse(final InsertStatement insertStatement, final ShardingMetaData
valueKeywords.add(DefaultKeyword.VALUES);
valueKeywords.addAll(Arrays.asList(getSynonymousKeywordsForValues()));
if (lexerEngine.skipIfEqual(valueKeywords.toArray(new Keyword[valueKeywords.size()]))) {
insertStatement.setAfterValuesPosition(lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length());
parseValues(insertStatement);
if (lexerEngine.equalAny(Symbol.COMMA)) {
parseMultipleValues(insertStatement);
}
}
}

protected Keyword[] getSynonymousKeywordsForValues() {
return new Keyword[0];
}

/**
* Parse insert values.
*
* @param insertStatement insert statement
*/
private void parseValues(final InsertStatement insertStatement) {
lexerEngine.accept(Symbol.LEFT_PAREN);
int count = 0;
List<SQLExpression> sqlExpressions = new LinkedList<>();
int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length();
int endPosition;
insertStatement.getSqlTokens().add(new InsertValuesToken(beginPosition, insertStatement.getTables().getSingleTableName()));
do {
sqlExpressions.add(basicExpressionParser.parse(insertStatement));
skipsDoubleColon();
count++;
} while (lexerEngine.skipIfEqual(Symbol.COMMA));
removeGenerateKeyColumn(insertStatement, count);
count = 0;
for (Column each : insertStatement.getColumns()) {
SQLExpression sqlExpression = sqlExpressions.get(count);
insertStatement.getConditions().add(new Condition(each, sqlExpression), shardingRule);
if (insertStatement.getGenerateKeyColumnIndex() == count) {
insertStatement.setGeneratedKeyCondition(createGeneratedKeyCondition(each, sqlExpression));
beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length();
lexerEngine.accept(Symbol.LEFT_PAREN);
List<SQLExpression> sqlExpressions = new LinkedList<>();
int columnsCount = 0;
do {
sqlExpressions.add(basicExpressionParser.parse(insertStatement));
skipsDoubleColon();
columnsCount++;
} while (lexerEngine.skipIfEqual(Symbol.COMMA));
removeGenerateKeyColumn(insertStatement, columnsCount);
columnsCount = 0;
int parametersCount = 0;
AndCondition andCondition = new AndCondition();
for (Column each : insertStatement.getColumns()) {
SQLExpression sqlExpression = sqlExpressions.get(columnsCount);
if (shardingRule.isShardingColumn(each)) {
andCondition.getConditions().add(new Condition(each, sqlExpression));
}
if (insertStatement.getGenerateKeyColumnIndex() == columnsCount) {
insertStatement.getGeneratedKeyConditions().add(createGeneratedKeyCondition(each, sqlExpression));
}
columnsCount++;
if (sqlExpression instanceof SQLPlaceholderExpression) {
parametersCount++;
}
}
count++;
}
lexerEngine.accept(Symbol.RIGHT_PAREN);
lexerEngine.accept(Symbol.RIGHT_PAREN);
endPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length();
insertStatement.getInsertValues().getInsertValues().add(new InsertValue(lexerEngine.getInput().substring(beginPosition, endPosition), parametersCount));
insertStatement.getConditions().getOrCondition().getAndConditions().add(andCondition);
} while (lexerEngine.skipIfEqual(Symbol.COMMA));
insertStatement.setInsertValuesListLastPosition(endPosition);
}

private void removeGenerateKeyColumn(final InsertStatement insertStatement, final int valueCount) {
insertStatement.setValuesListLastPosition(lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length());
Optional<Column> generateKeyColumn = shardingRule.getGenerateKeyColumn(insertStatement.getTables().getSingleTableName());
if (generateKeyColumn.isPresent() && valueCount < insertStatement.getColumns().size()) {
List<ItemsToken> itemsTokens = insertStatement.getItemsTokens();
Expand All @@ -133,22 +151,6 @@ private GeneratedKeyCondition createGeneratedKeyCondition(final Column column, f
return result;
}

private void parseMultipleValues(final InsertStatement insertStatement) {
insertStatement.getMultipleConditions().add(new Conditions(insertStatement.getConditions()));
MultipleInsertValuesToken valuesToken = new MultipleInsertValuesToken(insertStatement.getAfterValuesPosition());
valuesToken.getValues().add(
lexerEngine.getInput().substring(insertStatement.getAfterValuesPosition(), lexerEngine.getCurrentToken().getEndPosition() - Symbol.COMMA.getLiterals().length()));
while (lexerEngine.skipIfEqual(Symbol.COMMA)) {
int beginPosition = lexerEngine.getCurrentToken().getEndPosition() - lexerEngine.getCurrentToken().getLiterals().length();
parseValues(insertStatement);
insertStatement.getMultipleConditions().add(new Conditions(insertStatement.getConditions()));
int endPosition = lexerEngine.equalAny(Symbol.COMMA)
? lexerEngine.getCurrentToken().getEndPosition() - Symbol.COMMA.getLiterals().length() : lexerEngine.getCurrentToken().getEndPosition();
valuesToken.getValues().add(lexerEngine.getInput().substring(beginPosition, endPosition));
}
insertStatement.getSqlTokens().add(valuesToken);
}

private void skipsDoubleColon() {
if (lexerEngine.skipIfEqual(Symbol.DOUBLE_COLON)) {
lexerEngine.nextToken();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/

package io.shardingjdbc.core.parsing.parser.context.insertvalue;

import lombok.Getter;
import lombok.RequiredArgsConstructor;
import lombok.Setter;
import lombok.ToString;

/**
* Insert value.
*
* @author maxiaoguang
*/
@RequiredArgsConstructor
@Getter
@Setter
@ToString
public final class InsertValue {

private final String expression;

private final int parametersCount;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/*
* Copyright 1999-2015 dangdang.com.
* <p>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* </p>
*/

package io.shardingjdbc.core.parsing.parser.context.insertvalue;

import lombok.Getter;
import lombok.ToString;

import java.util.LinkedList;
import java.util.List;

/**
* Insert values.
*
* @author maxiaoguang
*/
@Getter
@ToString
public final class InsertValues {

private final List<InsertValue> insertValues = new LinkedList<>();
}
Loading