Debian Codegraph @

src/main/org/h2/command/dml/Insert.java

raw
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.HashMap;
9 import java.util.HashSet;
10 import java.util.Map.Entry;
11
12 import org.h2.api.ErrorCode;
13 import org.h2.api.Trigger;
14 import org.h2.command.Command;
15 import org.h2.command.CommandInterface;
16 import org.h2.command.query.Query;
17 import org.h2.engine.DbObject;
18 import org.h2.engine.Right;
19 import org.h2.engine.SessionLocal;
20 import org.h2.expression.Expression;
21 import org.h2.expression.ExpressionColumn;
22 import org.h2.expression.ExpressionVisitor;
23 import org.h2.expression.Parameter;
24 import org.h2.expression.ValueExpression;
25 import org.h2.expression.condition.Comparison;
26 import org.h2.expression.condition.ConditionAndOr;
27 import org.h2.index.Index;
28 import org.h2.message.DbException;
29 import org.h2.mvstore.db.MVPrimaryIndex;
30 import org.h2.result.ResultInterface;
31 import org.h2.result.ResultTarget;
32 import org.h2.result.Row;
33 import org.h2.table.Column;
34 import org.h2.table.DataChangeDeltaTable;
35 import org.h2.table.DataChangeDeltaTable.ResultOption;
36 import org.h2.table.Table;
37 import org.h2.util.HasSQL;
38 import org.h2.value.Value;
39
40 /**
41 * This class represents the statement
42 * INSERT
43 */
44 public final class Insert extends CommandWithValues implements ResultTarget {
45
46 private Table table;
47 private Column[] columns;
48 private Query query;
49 private long rowNumber;
50 private boolean insertFromSelect;
51
52 private Boolean overridingSystem;
53
54 /**
55 * For MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ....
56 */
57 private HashMap<Column, Expression> duplicateKeyAssignmentMap;
58
59 private Value[] onDuplicateKeyRow;
60
61 /**
62 * For MySQL-style INSERT IGNORE and PostgreSQL-style ON CONFLICT DO
63 * NOTHING.
64 */
65 private boolean ignore;
66
67 private ResultTarget deltaChangeCollector;
68
69 private ResultOption deltaChangeCollectionMode;
70
71 public Insert(SessionLocal session) {
72 super(session);
73 }
74
75 @Override
76 public void setCommand(Command command) {
77 super.setCommand(command);
78 if (query != null) {
79 query.setCommand(command);
80 }
81 }
82
83 @Override
84 public Table getTable() {
85 return table;
86 }
87
88 public void setTable(Table table) {
89 this.table = table;
90 }
91
92 public void setColumns(Column[] columns) {
93 this.columns = columns;
94 }
95
96 /**
97 * Sets MySQL-style INSERT IGNORE mode or PostgreSQL-style ON CONFLICT
98 * DO NOTHING.
99 *
100 * @param ignore ignore duplicates
101 */
102 public void setIgnore(boolean ignore) {
103 this.ignore = ignore;
104 }
105
106 public void setQuery(Query query) {
107 this.query = query;
108 }
109
110 public void setOverridingSystem(Boolean overridingSystem) {
111 this.overridingSystem = overridingSystem;
112 }
113
114 /**
115 * Keep a collection of the columns to pass to update if a duplicate key
116 * happens, for MySQL-style INSERT ... ON DUPLICATE KEY UPDATE ....
117 *
118 * @param column the column
119 * @param expression the expression
120 */
121 public void addAssignmentForDuplicate(Column column, Expression expression) {
122 if (duplicateKeyAssignmentMap == null) {
123 duplicateKeyAssignmentMap = new HashMap<>();
124 }
125 if (duplicateKeyAssignmentMap.putIfAbsent(column, expression) != null) {
126 throw DbException.get(ErrorCode.DUPLICATE_COLUMN_NAME_1, column.getName());
127 }
128 }
129
130 @Override
131 public long update(ResultTarget deltaChangeCollector, ResultOption deltaChangeCollectionMode) {
132 this.deltaChangeCollector = deltaChangeCollector;
133 this.deltaChangeCollectionMode = deltaChangeCollectionMode;
134 try {
135 return insertRows();
136 } finally {
137 this.deltaChangeCollector = null;
138 this.deltaChangeCollectionMode = null;
139 }
140 }
141
142 private long insertRows() {
143 session.getUser().checkTableRight(table, Right.INSERT);
144 setCurrentRowNumber(0);
145 table.fire(session, Trigger.INSERT, true);
146 rowNumber = 0;
147 int listSize = valuesExpressionList.size();
148 if (listSize > 0) {
149 int columnLen = columns.length;
150 for (int x = 0; x < listSize; x++) {
151 Row newRow = table.getTemplateRow();
152 Expression[] expr = valuesExpressionList.get(x);
153 setCurrentRowNumber(x + 1);
154 for (int i = 0; i < columnLen; i++) {
155 Column c = columns[i];
156 int index = c.getColumnId();
157 Expression e = expr[i];
158 if (e != ValueExpression.DEFAULT) {
159 try {
160 newRow.setValue(index, e.getValue(session));
161 } catch (DbException ex) {
162 throw setRow(ex, x, getSimpleSQL(expr));
163 }
164 }
165 }
166 rowNumber++;
167 table.convertInsertRow(session, newRow, overridingSystem);
168 if (deltaChangeCollectionMode == ResultOption.NEW) {
169 deltaChangeCollector.addRow(newRow.getValueList().clone());
170 }
171 if (!table.fireBeforeRow(session, null, newRow)) {
172 table.lock(session, Table.WRITE_LOCK);
173 try {
174 table.addRow(session, newRow);
175 } catch (DbException de) {
176 if (handleOnDuplicate(de, null)) {
177 // MySQL returns 2 for updated row
178 // TODO: detect no-op change
179 rowNumber++;
180 } else {
181 // INSERT IGNORE case
182 rowNumber--;
183 }
184 continue;
185 }
186 DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector,
187 deltaChangeCollectionMode, newRow);
188 table.fireAfterRow(session, null, newRow, false);
189 } else {
190 DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector,
191 deltaChangeCollectionMode, newRow);
192 }
193 }
194 } else {
195 table.lock(session, Table.WRITE_LOCK);
196 if (insertFromSelect) {
197 query.query(0, this);
198 } else {
199 ResultInterface rows = query.query(0);
200 while (rows.next()) {
201 Value[] r = rows.currentRow();
202 try {
203 addRow(r);
204 } catch (DbException de) {
205 if (handleOnDuplicate(de, r)) {
206 // MySQL returns 2 for updated row
207 // TODO: detect no-op change
208 rowNumber++;
209 } else {
210 // INSERT IGNORE case
211 rowNumber--;
212 }
213 }
214 }
215 rows.close();
216 }
217 }
218 table.fire(session, Trigger.INSERT, false);
219 return rowNumber;
220 }
221
222 @Override
223 public void addRow(Value... values) {
224 Row newRow = table.getTemplateRow();
225 setCurrentRowNumber(++rowNumber);
226 for (int j = 0, len = columns.length; j < len; j++) {
227 newRow.setValue(columns[j].getColumnId(), values[j]);
228 }
229 table.convertInsertRow(session, newRow, overridingSystem);
230 if (deltaChangeCollectionMode == ResultOption.NEW) {
231 deltaChangeCollector.addRow(newRow.getValueList().clone());
232 }
233 if (!table.fireBeforeRow(session, null, newRow)) {
234 table.addRow(session, newRow);
235 DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector,
236 deltaChangeCollectionMode, newRow);
237 table.fireAfterRow(session, null, newRow, false);
238 } else {
239 DataChangeDeltaTable.collectInsertedFinalRow(session, table, deltaChangeCollector,
240 deltaChangeCollectionMode, newRow);
241 }
242 }
243
244 @Override
245 public long getRowCount() {
246 // This method is not used in this class
247 return rowNumber;
248 }
249
250 @Override
251 public void limitsWereApplied() {
252 // Nothing to do
253 }
254
255 @Override
256 public String getPlanSQL(int sqlFlags) {
257 StringBuilder builder = new StringBuilder("INSERT INTO ");
258 table.getSQL(builder, sqlFlags).append('(');
259 Column.writeColumns(builder, columns, sqlFlags);
260 builder.append(")\n");
261 if (insertFromSelect) {
262 builder.append("DIRECT ");
263 }
264 if (!valuesExpressionList.isEmpty()) {
265 builder.append("VALUES ");
266 int row = 0;
267 if (valuesExpressionList.size() > 1) {
268 builder.append('\n');
269 }
270 for (Expression[] expr : valuesExpressionList) {
271 if (row++ > 0) {
272 builder.append(",\n");
273 }
274 Expression.writeExpressions(builder.append('('), expr, sqlFlags).append(')');
275 }
276 } else {
277 builder.append(query.getPlanSQL(sqlFlags));
278 }
279 return builder.toString();
280 }
281
282 @Override
283 void doPrepare() {
284 if (columns == null) {
285 if (!valuesExpressionList.isEmpty() && valuesExpressionList.get(0).length == 0) {
286 // special case where table is used as a sequence
287 columns = new Column[0];
288 } else {
289 columns = table.getColumns();
290 }
291 }
292 if (!valuesExpressionList.isEmpty()) {
293 for (Expression[] expr : valuesExpressionList) {
294 if (expr.length != columns.length) {
295 throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
296 }
297 for (int i = 0, len = expr.length; i < len; i++) {
298 Expression e = expr[i];
299 if (e != null) {
300 e = e.optimize(session);
301 if (e instanceof Parameter) {
302 Parameter p = (Parameter) e;
303 p.setColumn(columns[i]);
304 }
305 expr[i] = e;
306 }
307 }
308 }
309 } else {
310 query.prepare();
311 if (query.getColumnCount() != columns.length) {
312 throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
313 }
314 }
315 }
316
317 @Override
318 public int getType() {
319 return CommandInterface.INSERT;
320 }
321
322 @Override
323 public String getStatementName() {
324 return "INSERT";
325 }
326
327 public void setInsertFromSelect(boolean value) {
328 this.insertFromSelect = value;
329 }
330
331 @Override
332 public boolean isCacheable() {
333 return duplicateKeyAssignmentMap == null;
334 }
335
336 /**
337 * @param de duplicate key exception
338 * @param currentRow current row values (optional)
339 * @return {@code true} if row was updated, {@code false} if row was ignored
340 */
341 private boolean handleOnDuplicate(DbException de, Value[] currentRow) {
342 if (de.getErrorCode() != ErrorCode.DUPLICATE_KEY_1) {
343 throw de;
344 }
345 if (duplicateKeyAssignmentMap == null) {
346 if (ignore) {
347 return false;
348 }
349 throw de;
350 }
351
352 int columnCount = columns.length;
353 Expression[] row = (currentRow == null) ? valuesExpressionList.get((int) getCurrentRowNumber() - 1)
354 : new Expression[columnCount];
355 onDuplicateKeyRow = new Value[table.getColumns().length];
356 for (int i = 0; i < columnCount; i++) {
357 Value value;
358 if (currentRow != null) {
359 value = currentRow[i];
360 row[i] = ValueExpression.get(value);
361 } else {
362 value = row[i].getValue(session);
363 }
364 onDuplicateKeyRow[columns[i].getColumnId()] = value;
365 }
366
367 StringBuilder builder = new StringBuilder("UPDATE ");
368 table.getSQL(builder, HasSQL.DEFAULT_SQL_FLAGS).append(" SET ");
369 boolean f = false;
370 for (Entry<Column, Expression> entry : duplicateKeyAssignmentMap.entrySet()) {
371 if (f) {
372 builder.append(", ");
373 }
374 f = true;
375 entry.getKey().getSQL(builder, HasSQL.DEFAULT_SQL_FLAGS).append('=');
376 entry.getValue().getUnenclosedSQL(builder, HasSQL.DEFAULT_SQL_FLAGS);
377 }
378 builder.append(" WHERE ");
379 Index foundIndex = (Index) de.getSource();
380 if (foundIndex == null) {
381 throw DbException.getUnsupportedException(
382 "Unable to apply ON DUPLICATE KEY UPDATE, no index found!");
383 }
384 prepareUpdateCondition(foundIndex, row).getUnenclosedSQL(builder, HasSQL.DEFAULT_SQL_FLAGS);
385 String sql = builder.toString();
386 Update command = (Update) session.prepare(sql);
387 command.setOnDuplicateKeyInsert(this);
388 for (Parameter param : command.getParameters()) {
389 Parameter insertParam = parameters.get(param.getIndex());
390 param.setValue(insertParam.getValue(session));
391 }
392 boolean result = command.update() > 0;
393 onDuplicateKeyRow = null;
394 return result;
395 }
396
397 private Expression prepareUpdateCondition(Index foundIndex, Expression[] row) {
398 // MVPrimaryIndex is playing fast and loose with it's implementation of
399 // the Index interface.
400 // It returns all of the columns in the table when we call
401 // getIndexColumns() or getColumns().
402 // Don't have time right now to fix that, so just special-case it.
403 // PageDataIndex has the same problem.
404 final Column[] indexedColumns;
405 if (foundIndex instanceof MVPrimaryIndex) {
406 MVPrimaryIndex foundMV = (MVPrimaryIndex) foundIndex;
407 indexedColumns = new Column[] { foundMV.getIndexColumns()[foundMV
408 .getMainIndexColumn()].column };
409 } else {
410 indexedColumns = foundIndex.getColumns();
411 }
412
413 Expression condition = null;
414 for (Column column : indexedColumns) {
415 ExpressionColumn expr = new ExpressionColumn(getDatabase(),
416 table.getSchema().getName(), table.getName(), column.getName());
417 for (int i = 0; i < columns.length; i++) {
418 if (expr.getColumnName(session, i).equals(columns[i].getName())) {
419 if (condition == null) {
420 condition = new Comparison(Comparison.EQUAL, expr, row[i], false);
421 } else {
422 condition = new ConditionAndOr(ConditionAndOr.AND, condition,
423 new Comparison(Comparison.EQUAL, expr, row[i], false));
424 }
425 break;
426 }
427 }
428 }
429 return condition;
430 }
431
432 /**
433 * Get the value to use for the specified column in case of a duplicate key.
434 *
435 * @param columnIndex the column index
436 * @return the value
437 */
438 public Value getOnDuplicateKeyValue(int columnIndex) {
439 return onDuplicateKeyRow[columnIndex];
440 }
441
442 @Override
443 public void collectDependencies(HashSet<DbObject> dependencies) {
444 ExpressionVisitor visitor = ExpressionVisitor.getDependenciesVisitor(dependencies);
445 if (!valuesExpressionList.isEmpty()) {
446 for (Expression[] expr : valuesExpressionList) {
447 for (Expression e : expr) {
448 e.isEverything(visitor);
449 }
450 }
451 } else {
452 query.isEverything(visitor);
453 }
454 }
455
456 }