forked from apache/incubator-seata
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MySQLInsertOnDuplicateUpdateExecutor.java
413 lines (384 loc) · 17.4 KB
/
MySQLInsertOnDuplicateUpdateExecutor.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
/*
* Copyright 1999-2019 Seata.io Group.
*
* 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.
*/
package io.seata.rm.datasource.exec.mysql;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
import java.util.Collections;
import java.util.Set;
import java.util.StringJoiner;
import java.util.stream.Collectors;
import com.google.common.base.Joiner;
import io.seata.common.exception.NotSupportYetException;
import io.seata.common.exception.ShouldNeverHappenException;
import io.seata.common.loader.LoadLevel;
import io.seata.common.loader.Scope;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.IOUtil;
import io.seata.common.util.LowerCaseLinkHashMap;
import io.seata.common.util.StringUtils;
import io.seata.rm.datasource.ConnectionProxy;
import io.seata.rm.datasource.PreparedStatementProxy;
import io.seata.rm.datasource.StatementProxy;
import io.seata.rm.datasource.exec.StatementCallback;
import io.seata.rm.datasource.sql.struct.ColumnMeta;
import io.seata.rm.datasource.sql.struct.Field;
import io.seata.rm.datasource.sql.struct.Row;
import io.seata.rm.datasource.sql.struct.TableMeta;
import io.seata.rm.datasource.sql.struct.TableRecords;
import io.seata.rm.datasource.sql.struct.IndexMeta;
import io.seata.rm.datasource.undo.SQLUndoLog;
import io.seata.sqlparser.SQLInsertRecognizer;
import io.seata.sqlparser.SQLRecognizer;
import io.seata.sqlparser.SQLType;
import io.seata.sqlparser.struct.Defaultable;
import io.seata.sqlparser.struct.Null;
import io.seata.sqlparser.util.JdbcConstants;
/**
* @author yangyicong
*/
@LoadLevel(name = JdbcConstants.MYSQL, scope = Scope.PROTOTYPE)
public class MySQLInsertOnDuplicateUpdateExecutor extends MySQLInsertExecutor implements Defaultable {
private static final String COLUMN_SEPARATOR = "|";
/**
* is updated or not
*/
private boolean isUpdateFlag = false;
public String getSelectSQL() {
return selectSQL;
}
/**
* before image sql and after image sql,condition is unique index
*/
private String selectSQL;
public ArrayList<List<Object>> getParamAppenderList() {
return paramAppenderList;
}
/**
* the params of selectSQL, value is the unique index
*/
private ArrayList<List<Object>> paramAppenderList;
/**
* the primary keys in before image sql. if the primary key is auto increment,the set is empty
*/
private Set<String> primaryKeysInBeforeImageSql = new HashSet<>(4);
public MySQLInsertOnDuplicateUpdateExecutor(StatementProxy statementProxy, StatementCallback statementCallback, SQLRecognizer sqlRecognizer) {
super(statementProxy, statementCallback, sqlRecognizer);
}
/**
* Execute auto commit false t.
*
* @param args the args
* @return the t
* @throws Exception the exception
*/
@Override
protected Object executeAutoCommitFalse(Object[] args) throws Exception {
if (!JdbcConstants.MYSQL.equalsIgnoreCase(getDbType()) && getTableMeta().getPrimaryKeyOnlyName().size() > 1) {
throw new NotSupportYetException("multi pk only support mysql!");
}
TableRecords beforeImage = beforeImage();
if (CollectionUtils.isNotEmpty(beforeImage.getRows())) {
isUpdateFlag = true;
} else {
beforeImage = TableRecords.empty(getTableMeta());
}
Object result = statementCallback.execute(statementProxy.getTargetStatement(), args);
int updateCount = statementProxy.getUpdateCount();
if (updateCount > 0) {
TableRecords afterImage = afterImage(beforeImage);
prepareUndoLogAll(beforeImage, afterImage);
}
return result;
}
/**
* prepare undo log.
*
* @param beforeImage the before image
* @param afterImage the after image
*/
protected void prepareUndoLogAll(TableRecords beforeImage, TableRecords afterImage) {
if (beforeImage.getRows().isEmpty() && afterImage.getRows().isEmpty()) {
return;
}
ConnectionProxy connectionProxy = statementProxy.getConnectionProxy();
String lockKeys = buildLockKey(afterImage);
connectionProxy.appendLockKey(lockKeys);
buildUndoItemAll(connectionProxy, beforeImage, afterImage);
}
/**
* build a SQLUndoLog
*
* @param beforeImage the before image
* @param afterImage the after image
*/
protected void buildUndoItemAll(ConnectionProxy connectionProxy, TableRecords beforeImage, TableRecords afterImage) {
if (!isUpdateFlag) {
SQLUndoLog sqlUndoLog = buildUndoItem(SQLType.INSERT, TableRecords.empty(getTableMeta()), afterImage);
connectionProxy.appendUndoLog(sqlUndoLog);
return;
}
List<Row> beforeImageRows = beforeImage.getRows();
List<String> beforePrimaryValues = new ArrayList<>();
for (Row r : beforeImageRows) {
String primaryValue = "";
for (Field f: r.primaryKeys()) {
primaryValue = primaryValue + f.getValue() + COLUMN_SEPARATOR;
}
beforePrimaryValues.add(primaryValue);
}
List<Row> insertRows = new ArrayList<>();
List<Row> updateRows = new ArrayList<>();
List<Row> afterImageRows = afterImage.getRows();
for (Row r : afterImageRows) {
String primaryValue = "";
for (Field f: r.primaryKeys()) {
primaryValue = primaryValue + f.getValue() + COLUMN_SEPARATOR;
}
if (beforePrimaryValues.contains(primaryValue)) {
updateRows.add(r);
} else {
insertRows.add(r);
}
}
if (CollectionUtils.isNotEmpty(updateRows)) {
TableRecords partAfterImage = new TableRecords(afterImage.getTableMeta());
partAfterImage.setTableName(afterImage.getTableName());
partAfterImage.setRows(updateRows);
if (beforeImage.getRows().size() != partAfterImage.getRows().size()) {
throw new ShouldNeverHappenException("Before image size is not equaled to after image size, probably because you updated the primary keys.");
}
connectionProxy.appendUndoLog(buildUndoItem(SQLType.UPDATE, beforeImage, partAfterImage));
}
if (CollectionUtils.isNotEmpty(insertRows)) {
TableRecords partAfterImage = new TableRecords(afterImage.getTableMeta());
partAfterImage.setTableName(afterImage.getTableName());
partAfterImage.setRows(insertRows);
connectionProxy.appendUndoLog(buildUndoItem(SQLType.INSERT, TableRecords.empty(getTableMeta()), partAfterImage));
}
}
/**
* build a SQLUndoLog
*
* @param sqlType
* @param beforeImage
* @param afterImage
* @return sqlUndoLog the sql undo log
*/
protected SQLUndoLog buildUndoItem(SQLType sqlType, TableRecords beforeImage, TableRecords afterImage) {
String tableName = sqlRecognizer.getTableName();
SQLUndoLog sqlUndoLog = new SQLUndoLog();
sqlUndoLog.setSqlType(sqlType);
sqlUndoLog.setTableName(tableName);
sqlUndoLog.setBeforeImage(beforeImage);
sqlUndoLog.setAfterImage(afterImage);
return sqlUndoLog;
}
@Override
protected TableRecords afterImage(TableRecords beforeImage) throws SQLException {
TableMeta tableMeta = getTableMeta();
List<Row> rows = beforeImage.getRows();
Map<String, ArrayList<Object>> primaryValueMap = new HashMap<>();
rows.forEach(m -> {
List<Field> fields = m.primaryKeys();
fields.forEach(f -> {
ArrayList<Object> values = primaryValueMap.computeIfAbsent(f.getName(), v -> new ArrayList<>());
values.add(f.getValue());
});
});
// The origin select sql contains the unique keys sql
StringBuilder afterImageSql = new StringBuilder(selectSQL);
List<Object> primaryValues = new ArrayList<>();
// Appends the pk when the origin select sql not contains
for (int i = 0; i < rows.size(); i++) {
List<String> wherePrimaryList = new ArrayList<>();
primaryValueMap.forEach((k, v) -> {
if (!primaryKeysInBeforeImageSql.contains(k)) {
wherePrimaryList.add(k + " = ? ");
primaryValues.add(v);
}
});
afterImageSql.append(" OR (").append(Joiner.on(" and ").join(wherePrimaryList)).append(") ");
}
return buildTableRecords2(tableMeta, afterImageSql.toString(), paramAppenderList, primaryValues);
}
@Override
public TableRecords beforeImage() throws SQLException {
TableMeta tableMeta = getTableMeta();
// After image sql the same of before image
if (StringUtils.isBlank(selectSQL)) {
paramAppenderList = new ArrayList<>();
selectSQL = buildImageSQL(tableMeta);
}
return buildTableRecords2(tableMeta, selectSQL, paramAppenderList, Collections.emptyList());
}
/**
* build TableRecords
*
* @param tableMeta the meta info of table
* @param selectSQL the sql to select images
* @param paramAppenderList the param list
* @param primaryKeys the primary keys
* @return the table records
* @throws SQLException then execute fail
*/
public TableRecords buildTableRecords2(TableMeta tableMeta, String selectSQL, ArrayList<List<Object>> paramAppenderList, List<Object> primaryKeys) throws SQLException {
ResultSet rs = null;
try (PreparedStatement ps = statementProxy.getConnection()
.prepareStatement(primaryKeys.isEmpty() ? selectSQL + " FOR UPDATE" : selectSQL)) {
int ts = CollectionUtils.isEmpty(paramAppenderList) ? 0 : paramAppenderList.size();
int ds = ts == 0 ? 0 : paramAppenderList.get(0).size();
for (int i = 0; i < ts; i++) {
List<Object> paramAppender = paramAppenderList.get(i);
for (int j = 0; j < ds; j++) {
ps.setObject(i * ds + j + 1, "NULL".equals(paramAppender.get(j).toString()) ? null : paramAppender.get(j));
}
}
for (int i = 0; i < primaryKeys.size(); i++) {
ps.setObject(ts * ds + i + 1, primaryKeys.get(i));
}
rs = ps.executeQuery();
return TableRecords.buildRecords(tableMeta, rs);
} finally {
IOUtil.close(rs);
}
}
/**
* build image sql
*
* @param tableMeta the meta info of table
* @return image sql
*/
public String buildImageSQL(TableMeta tableMeta) {
if (CollectionUtils.isEmpty(paramAppenderList)) {
paramAppenderList = new ArrayList<>();
}
SQLInsertRecognizer recognizer = (SQLInsertRecognizer) sqlRecognizer;
int insertNum = recognizer.getInsertParamsValue().size();
Map<String, ArrayList<Object>> imageParameterMap = buildImageParameters(recognizer);
String prefix = "SELECT * ";
StringBuilder suffix = new StringBuilder(" FROM ").append(getFromTableInSQL());
boolean[] isContainWhere = {false};
for (int i = 0; i < insertNum; i++) {
int finalI = i;
List<Object> paramAppenderTempList = new ArrayList<>();
tableMeta.getAllIndexes().forEach((k, v) -> {
if (!v.isNonUnique() && isIndexValueNotNull(v,imageParameterMap,finalI)) {
boolean columnIsNull = true;
List<String> uniqueList = new ArrayList<>();
for (ColumnMeta m : v.getValues()) {
String columnName = m.getColumnName();
List<Object> imageParameters = imageParameterMap.get(columnName);
if (imageParameters == null && m.getColumnDef() != null) {
uniqueList.add(columnName + " = DEFAULT(" + columnName + ") ");
if ("PRIMARY".equalsIgnoreCase(k)) {
primaryKeysInBeforeImageSql.add(columnName);
}
columnIsNull = false;
continue;
}
if ("PRIMARY".equalsIgnoreCase(k)) {
primaryKeysInBeforeImageSql.add(columnName);
}
columnIsNull = false;
uniqueList.add(columnName + " = ? ");
paramAppenderTempList.add(imageParameters.get(finalI));
}
if (!columnIsNull) {
if (isContainWhere[0]) {
suffix.append(" OR (").append(Joiner.on(" and ").join(uniqueList)).append(") ");
} else {
suffix.append(" WHERE (").append(Joiner.on(" and ").join(uniqueList)).append(") ");
isContainWhere[0] = true;
}
}
}
});
paramAppenderList.add(paramAppenderTempList);
}
StringJoiner selectSQLJoin = new StringJoiner(", ", prefix, suffix.toString());
return selectSQLJoin.toString();
}
/**
* build sql params
*
* @param recognizer the sql recognizer
* @return map, key is column, value is paramperter
*/
@SuppressWarnings("lgtm[java/dereferenced-value-may-be-null]")
public Map<String, ArrayList<Object>> buildImageParameters(SQLInsertRecognizer recognizer) {
List<String> duplicateKeyUpdateColumns = recognizer.getDuplicateKeyUpdate();
if (CollectionUtils.isNotEmpty(duplicateKeyUpdateColumns)) {
List<String> duplicateKeyUpdateLowerCaseColumns =
duplicateKeyUpdateColumns.parallelStream().map(String::toLowerCase).collect(Collectors.toList());
getTableMeta().getAllIndexes().forEach((k, v) -> {
if ("PRIMARY".equalsIgnoreCase(k)) {
for (ColumnMeta m : v.getValues()) {
if (duplicateKeyUpdateLowerCaseColumns.contains(m.getColumnName().toLowerCase())) {
throw new ShouldNeverHappenException("update pk value is not supported!");
}
}
}
});
}
Map<String, ArrayList<Object>> imageParameterMap = new LowerCaseLinkHashMap<>();
Map<Integer, ArrayList<Object>> parameters = ((PreparedStatementProxy) statementProxy).getParameters();
// VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
List<String> insertParamsList = recognizer.getInsertParamsValue();
List<String> sqlRecognizerColumns = recognizer.getInsertColumns();
List<String> insertColumns = CollectionUtils.isEmpty(sqlRecognizerColumns) ? new ArrayList<>(getTableMeta().getAllColumns().keySet()) : sqlRecognizerColumns;
int paramsindex = 1;
for (String insertParams : insertParamsList) {
String[] insertParamsArray = insertParams.split(",");
for (int i = 0; i < insertColumns.size(); i++) {
String m = insertColumns.get(i);
String params = insertParamsArray[i];
ArrayList<Object> imageListTemp = imageParameterMap.computeIfAbsent(m, k -> new ArrayList<>());
if ("?".equals(params.trim())) {
ArrayList<Object> objects = parameters.get(paramsindex);
imageListTemp.addAll(objects);
paramsindex++;
} else {
// params is character string constant
if ((params.trim().startsWith("'") && params.trim().endsWith("'")) || params.trim().startsWith("\"") && params.trim().endsWith("\"")) {
params = params.trim();
params = params.substring(1, params.length() - 1);
}
imageListTemp.add(params);
}
imageParameterMap.put(m, imageListTemp);
}
}
return imageParameterMap;
}
private boolean isIndexValueNotNull(IndexMeta indexMeta, Map<String, ArrayList<Object>> imageParameterMap,int rowIndex) {
for (ColumnMeta columnMeta : indexMeta.getValues()) {
String columnName = columnMeta.getColumnName();
List<Object> imageParameters = imageParameterMap.get(columnName);
if (imageParameters == null && columnMeta.getColumnDef() == null) {
return false;
} else if (imageParameters != null && (imageParameters.get(rowIndex) == null || imageParameters.get(rowIndex) instanceof Null)) {
return false;
}
}
return true;
}
}