| 1 |
/* |
| 2 |
* Copyright 2004-2023 H2 Group. Multiple-Licensed under the MPL 2.0, |
| 3 |
* and the EPL 1.0 (https://h2database.com/html/license.html). |
| 4 |
* Initial Developer: H2 Group |
| 5 |
*/ |
| 6 |
package org.h2.command.dml; |
| 7 |
|
| 8 |
import java.util.ArrayList; |
| 9 |
import java.util.HashSet; |
| 10 |
import org.h2.api.ErrorCode; |
| 11 |
import org.h2.api.Trigger; |
| 12 |
import org.h2.command.Command; |
| 13 |
import org.h2.command.CommandInterface; |
| 14 |
import org.h2.command.query.Query; |
| 15 |
import org.h2.engine.DbObject; |
| 16 |
import org.h2.engine.Right; |
| 17 |
import org.h2.engine.SessionLocal; |
| 18 |
import org.h2.expression.Expression; |
| 19 |
import org.h2.expression.Parameter; |
| 20 |
import org.h2.expression.ValueExpression; |
| 21 |
import org.h2.index.Index; |
| 22 |
import org.h2.message.DbException; |
| 23 |
import org.h2.mvstore.db.MVPrimaryIndex; |
| 24 |
import org.h2.result.ResultInterface; |
| 25 |
import org.h2.result.ResultTarget; |
| 26 |
import org.h2.result.Row; |
| 27 |
import org.h2.table.Column; |
| 28 |
import org.h2.table.DataChangeDeltaTable; |
| 29 |
import org.h2.table.DataChangeDeltaTable.ResultOption; |
| 30 |
import org.h2.table.Table; |
| 31 |
import org.h2.util.HasSQL; |
| 32 |
import org.h2.value.Value; |
| 33 |
import org.h2.value.ValueNull; |
| 34 |
|
| 35 |
/** |
| 36 |
* This class represents the statement |
| 37 |
* MERGE |
| 38 |
* or the MySQL compatibility statement |
| 39 |
* REPLACE |
| 40 |
*/ |
| 41 |
public final class Merge extends CommandWithValues { |
| 42 |
|
| 43 |
private boolean isReplace; |
| 44 |
|
| 45 |
private Table table; |
| 46 |
private Column[] columns; |
| 47 |
private Column[] keys; |
| 48 |
private Query query; |
| 49 |
private Update update; |
| 50 |
|
| 51 |
public Merge(SessionLocal session, boolean isReplace) { |
| 52 |
super(session); |
| 53 |
this.isReplace = isReplace; |
| 54 |
} |
| 55 |
|
| 56 |
@Override |
| 57 |
public void setCommand(Command command) { |
| 58 |
super.setCommand(command); |
| 59 |
if (query != null) { |
| 60 |
query.setCommand(command); |
| 61 |
} |
| 62 |
} |
| 63 |
|
| 64 |
@Override |
| 65 |
public Table getTable() { |
| 66 |
return table; |
| 67 |
} |
| 68 |
|
| 69 |
public void setTable(Table table) { |
| 70 |
this.table = table; |
| 71 |
} |
| 72 |
|
| 73 |
public void setColumns(Column[] columns) { |
| 74 |
this.columns = columns; |
| 75 |
} |
| 76 |
|
| 77 |
public void setKeys(Column[] keys) { |
| 78 |
this.keys = keys; |
| 79 |
} |
| 80 |
|
| 81 |
public void setQuery(Query query) { |
| 82 |
this.query = query; |
| 83 |
} |
| 84 |
|
| 85 |
@Override |
| 86 |
public long update(ResultTarget deltaChangeCollector, ResultOption deltaChangeCollectionMode) { |
| 87 |
long count = 0; |
| 88 |
session.getUser().checkTableRight(table, Right.INSERT); |
| 89 |
session.getUser().checkTableRight(table, Right.UPDATE); |
| 90 |
setCurrentRowNumber(0); |
| 91 |
if (!valuesExpressionList.isEmpty()) { |
| 92 |
// process values in list |
| 93 |
for (int x = 0, size = valuesExpressionList.size(); x < size; x++) { |
| 94 |
setCurrentRowNumber(x + 1); |
| 95 |
Expression[] expr = valuesExpressionList.get(x); |
| 96 |
Row newRow = table.getTemplateRow(); |
| 97 |
for (int i = 0, len = columns.length; i < len; i++) { |
| 98 |
Column c = columns[i]; |
| 99 |
int index = c.getColumnId(); |
| 100 |
Expression e = expr[i]; |
| 101 |
if (e != ValueExpression.DEFAULT) { |
| 102 |
try { |
| 103 |
newRow.setValue(index, e.getValue(session)); |
| 104 |
} catch (DbException ex) { |
| 105 |
throw setRow(ex, count, getSimpleSQL(expr)); |
| 106 |
} |
| 107 |
} |
| 108 |
} |
| 109 |
count += merge(newRow, expr, deltaChangeCollector, deltaChangeCollectionMode); |
| 110 |
} |
| 111 |
} else { |
| 112 |
// process select data for list |
| 113 |
query.setNeverLazy(true); |
| 114 |
ResultInterface rows = query.query(0); |
| 115 |
table.fire(session, Trigger.UPDATE | Trigger.INSERT, true); |
| 116 |
table.lock(session, Table.WRITE_LOCK); |
| 117 |
while (rows.next()) { |
| 118 |
Value[] r = rows.currentRow(); |
| 119 |
Row newRow = table.getTemplateRow(); |
| 120 |
setCurrentRowNumber(count); |
| 121 |
for (int j = 0; j < columns.length; j++) { |
| 122 |
newRow.setValue(columns[j].getColumnId(), r[j]); |
| 123 |
} |
| 124 |
count += merge(newRow, null, deltaChangeCollector, deltaChangeCollectionMode); |
| 125 |
} |
| 126 |
rows.close(); |
| 127 |
table.fire(session, Trigger.UPDATE | Trigger.INSERT, false); |
| 128 |
} |
| 129 |
return count; |
| 130 |
} |
| 131 |
|
| 132 |
/** |
| 133 |
* Updates an existing row or inserts a new one. |
| 134 |
* |
| 135 |
* @param row row to replace |
| 136 |
* @param expressions source expressions, or null |
| 137 |
* @param deltaChangeCollector target result |
| 138 |
* @param deltaChangeCollectionMode collection mode |
| 139 |
* @return 1 if row was inserted, 1 if row was updated by a MERGE statement, |
| 140 |
* and 2 if row was updated by a REPLACE statement |
| 141 |
*/ |
| 142 |
private int merge(Row row, Expression[] expressions, ResultTarget deltaChangeCollector, |
| 143 |
ResultOption deltaChangeCollectionMode) { |
| 144 |
long count; |
| 145 |
if (update == null) { |
| 146 |
// if there is no valid primary key, |
| 147 |
// the REPLACE statement degenerates to an INSERT |
| 148 |
count = 0; |
| 149 |
} else { |
| 150 |
ArrayList<Parameter> k = update.getParameters(); |
| 151 |
int j = 0; |
| 152 |
for (int i = 0, l = columns.length; i < l; i++) { |
| 153 |
Column col = columns[i]; |
| 154 |
if (col.isGeneratedAlways()) { |
| 155 |
if (expressions == null || expressions[i] != ValueExpression.DEFAULT) { |
| 156 |
throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_ASSIGNED_1, |
| 157 |
col.getSQLWithTable(new StringBuilder(), HasSQL.TRACE_SQL_FLAGS).toString()); |
| 158 |
} |
| 159 |
} else { |
| 160 |
Value v = row.getValue(col.getColumnId()); |
| 161 |
if (v == null) { |
| 162 |
Expression defaultExpression = col.getEffectiveDefaultExpression(); |
| 163 |
v = defaultExpression != null ? defaultExpression.getValue(session) : ValueNull.INSTANCE; |
| 164 |
} |
| 165 |
k.get(j++).setValue(v); |
| 166 |
} |
| 167 |
} |
| 168 |
for (Column col : keys) { |
| 169 |
Value v = row.getValue(col.getColumnId()); |
| 170 |
if (v == null) { |
| 171 |
throw DbException.get(ErrorCode.COLUMN_CONTAINS_NULL_VALUES_1, col.getTraceSQL()); |
| 172 |
} |
| 173 |
k.get(j++).setValue(v); |
| 174 |
} |
| 175 |
count = update.update(deltaChangeCollector, deltaChangeCollectionMode); |
| 176 |
} |
| 177 |
// if update fails try an insert |
| 178 |
if (count == 0) { |
| 179 |
try { |
| 180 |
table.convertInsertRow(session, row, null); |
| 181 |
if (deltaChangeCollectionMode == ResultOption.NEW) { |
| 182 |
deltaChangeCollector.addRow(row.getValueList().clone()); |
| 183 |
} |
| 184 |
if (!table.fireBeforeRow(session, null, row)) { |
| 185 |
table.lock(session, Table.WRITE_LOCK); |
| 186 |
table.addRow(session, row); |
| 187 |
DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector, |
| 188 |
deltaChangeCollectionMode, row); |
| 189 |
table.fireAfterRow(session, null, row, false); |
| 190 |
} else { |
| 191 |
DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector, |
| 192 |
deltaChangeCollectionMode, row); |
| 193 |
} |
| 194 |
return 1; |
| 195 |
} catch (DbException e) { |
| 196 |
if (e.getErrorCode() == ErrorCode.DUPLICATE_KEY_1) { |
| 197 |
// possibly a concurrent merge or insert |
| 198 |
Index index = (Index) e.getSource(); |
| 199 |
if (index != null) { |
| 200 |
// verify the index columns match the key |
| 201 |
Column[] indexColumns; |
| 202 |
if (index instanceof MVPrimaryIndex) { |
| 203 |
MVPrimaryIndex foundMV = (MVPrimaryIndex) index; |
| 204 |
indexColumns = new Column[] { |
| 205 |
foundMV.getIndexColumns()[foundMV.getMainIndexColumn()].column }; |
| 206 |
} else { |
| 207 |
indexColumns = index.getColumns(); |
| 208 |
} |
| 209 |
boolean indexMatchesKeys; |
| 210 |
if (indexColumns.length <= keys.length) { |
| 211 |
indexMatchesKeys = true; |
| 212 |
for (int i = 0; i < indexColumns.length; i++) { |
| 213 |
if (indexColumns[i] != keys[i]) { |
| 214 |
indexMatchesKeys = false; |
| 215 |
break; |
| 216 |
} |
| 217 |
} |
| 218 |
} else { |
| 219 |
indexMatchesKeys = false; |
| 220 |
} |
| 221 |
if (indexMatchesKeys) { |
| 222 |
throw DbException.get(ErrorCode.CONCURRENT_UPDATE_1, table.getName()); |
| 223 |
} |
| 224 |
} |
| 225 |
} |
| 226 |
throw e; |
| 227 |
} |
| 228 |
} else if (count == 1) { |
| 229 |
return isReplace ? 2 : 1; |
| 230 |
} |
| 231 |
throw DbException.get(ErrorCode.DUPLICATE_KEY_1, table.getTraceSQL()); |
| 232 |
} |
| 233 |
|
| 234 |
@Override |
| 235 |
public String getPlanSQL(int sqlFlags) { |
| 236 |
StringBuilder builder = new StringBuilder(isReplace ? "REPLACE INTO " : "MERGE INTO "); |
| 237 |
table.getSQL(builder, sqlFlags).append('('); |
| 238 |
Column.writeColumns(builder, columns, sqlFlags); |
| 239 |
builder.append(')'); |
| 240 |
if (!isReplace && keys != null) { |
| 241 |
builder.append(" KEY("); |
| 242 |
Column.writeColumns(builder, keys, sqlFlags); |
| 243 |
builder.append(')'); |
| 244 |
} |
| 245 |
builder.append('\n'); |
| 246 |
if (!valuesExpressionList.isEmpty()) { |
| 247 |
builder.append("VALUES "); |
| 248 |
int row = 0; |
| 249 |
for (Expression[] expr : valuesExpressionList) { |
| 250 |
if (row++ > 0) { |
| 251 |
builder.append(", "); |
| 252 |
} |
| 253 |
Expression.writeExpressions(builder.append('('), expr, sqlFlags).append(')'); |
| 254 |
} |
| 255 |
} else { |
| 256 |
builder.append(query.getPlanSQL(sqlFlags)); |
| 257 |
} |
| 258 |
return builder.toString(); |
| 259 |
} |
| 260 |
|
| 261 |
@Override |
| 262 |
void doPrepare() { |
| 263 |
if (columns == null) { |
| 264 |
if (!valuesExpressionList.isEmpty() && valuesExpressionList.get(0).length == 0) { |
| 265 |
// special case where table is used as a sequence |
| 266 |
columns = new Column[0]; |
| 267 |
} else { |
| 268 |
columns = table.getColumns(); |
| 269 |
} |
| 270 |
} |
| 271 |
if (!valuesExpressionList.isEmpty()) { |
| 272 |
for (Expression[] expr : valuesExpressionList) { |
| 273 |
if (expr.length != columns.length) { |
| 274 |
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH); |
| 275 |
} |
| 276 |
for (int i = 0; i < expr.length; i++) { |
| 277 |
Expression e = expr[i]; |
| 278 |
if (e != null) { |
| 279 |
expr[i] = e.optimize(session); |
| 280 |
} |
| 281 |
} |
| 282 |
} |
| 283 |
} else { |
| 284 |
query.prepare(); |
| 285 |
if (query.getColumnCount() != columns.length) { |
| 286 |
throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH); |
| 287 |
} |
| 288 |
} |
| 289 |
if (keys == null) { |
| 290 |
Index idx = table.getPrimaryKey(); |
| 291 |
if (idx == null) { |
| 292 |
throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, "PRIMARY KEY"); |
| 293 |
} |
| 294 |
keys = idx.getColumns(); |
| 295 |
} |
| 296 |
if (isReplace) { |
| 297 |
// if there is no valid primary key, |
| 298 |
// the REPLACE statement degenerates to an INSERT |
| 299 |
for (Column key : keys) { |
| 300 |
boolean found = false; |
| 301 |
for (Column column : columns) { |
| 302 |
if (column.getColumnId() == key.getColumnId()) { |
| 303 |
found = true; |
| 304 |
break; |
| 305 |
} |
| 306 |
} |
| 307 |
if (!found) { |
| 308 |
return; |
| 309 |
} |
| 310 |
} |
| 311 |
} |
| 312 |
StringBuilder builder = table.getSQL(new StringBuilder("UPDATE "), HasSQL.DEFAULT_SQL_FLAGS).append(" SET "); |
| 313 |
boolean hasColumn = false; |
| 314 |
for (int i = 0, l = columns.length; i < l; i++) { |
| 315 |
Column column = columns[i]; |
| 316 |
if (!column.isGeneratedAlways()) { |
| 317 |
if (hasColumn) { |
| 318 |
builder.append(", "); |
| 319 |
} |
| 320 |
hasColumn = true; |
| 321 |
column.getSQL(builder, HasSQL.DEFAULT_SQL_FLAGS).append("=?"); |
| 322 |
} |
| 323 |
} |
| 324 |
if (!hasColumn) { |
| 325 |
throw DbException.getSyntaxError(sqlStatement, sqlStatement.length(), |
| 326 |
"Valid MERGE INTO statement with at least one updatable column"); |
| 327 |
} |
| 328 |
Column.writeColumns(builder.append(" WHERE "), keys, " AND ", "=?", HasSQL.DEFAULT_SQL_FLAGS); |
| 329 |
update = (Update) session.prepare(builder.toString()); |
| 330 |
} |
| 331 |
|
| 332 |
@Override |
| 333 |
public int getType() { |
| 334 |
return isReplace ? CommandInterface.REPLACE : CommandInterface.MERGE; |
| 335 |
} |
| 336 |
|
| 337 |
@Override |
| 338 |
public String getStatementName() { |
| 339 |
return isReplace ? "REPLACE" : "MERGE"; |
| 340 |
} |
| 341 |
|
| 342 |
@Override |
| 343 |
public void collectDependencies(HashSet<DbObject> dependencies) { |
| 344 |
if (query != null) { |
| 345 |
query.collectDependencies(dependencies); |
| 346 |
} |
| 347 |
} |
| 348 |
|
| 349 |
} |