Debian Codegraph @

src/main/org/h2/constraint/ConstraintReferential.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.constraint;
7
8 import java.util.ArrayList;
9 import java.util.HashSet;
10 import org.h2.api.ErrorCode;
11 import org.h2.command.Prepared;
12 import org.h2.engine.SessionLocal;
13 import org.h2.expression.Expression;
14 import org.h2.expression.Parameter;
15 import org.h2.index.Cursor;
16 import org.h2.index.Index;
17 import org.h2.message.DbException;
18 import org.h2.result.ResultInterface;
19 import org.h2.result.Row;
20 import org.h2.result.SearchRow;
21 import org.h2.schema.Schema;
22 import org.h2.table.Column;
23 import org.h2.table.IndexColumn;
24 import org.h2.table.Table;
25 import org.h2.util.StringUtils;
26 import org.h2.value.Value;
27 import org.h2.value.ValueNull;
28
29 /**
30 * A referential constraint.
31 */
32 public class ConstraintReferential extends Constraint {
33
34 private IndexColumn[] columns;
35 private IndexColumn[] refColumns;
36 private ConstraintActionType deleteAction = ConstraintActionType.RESTRICT;
37 private ConstraintActionType updateAction = ConstraintActionType.RESTRICT;
38 private Table refTable;
39 private Index index;
40 private ConstraintUnique refConstraint;
41 private boolean indexOwner;
42 private String deleteSQL, updateSQL;
43 private boolean skipOwnTable;
44
45 public ConstraintReferential(Schema schema, int id, String name, Table table) {
46 super(schema, id, name, table);
47 }
48
49 @Override
50 public Type getConstraintType() {
51 return Constraint.Type.REFERENTIAL;
52 }
53
54 /**
55 * Create the SQL statement of this object so a copy of the table can be
56 * made.
57 *
58 * @param forTable the table to create the object for
59 * @param quotedName the name of this object (quoted if necessary)
60 * @return the SQL statement
61 */
62 @Override
63 public String getCreateSQLForCopy(Table forTable, String quotedName) {
64 return getCreateSQLForCopy(forTable, refTable, quotedName, true);
65 }
66
67 /**
68 * Create the SQL statement of this object so a copy of the table can be
69 * made.
70 *
71 * @param forTable the table to create the object for
72 * @param forRefTable the referenced table
73 * @param quotedName the name of this object (quoted if necessary)
74 * @param internalIndex add the index name to the statement
75 * @return the SQL statement
76 */
77 public String getCreateSQLForCopy(Table forTable, Table forRefTable,
78 String quotedName, boolean internalIndex) {
79 StringBuilder builder = new StringBuilder("ALTER TABLE ");
80 forTable.getSQL(builder, DEFAULT_SQL_FLAGS).append(" ADD CONSTRAINT ");
81 if (forTable.isHidden()) {
82 builder.append("IF NOT EXISTS ");
83 }
84 builder.append(quotedName);
85 if (comment != null) {
86 builder.append(" COMMENT ");
87 StringUtils.quoteStringSQL(builder, comment);
88 }
89 IndexColumn[] cols = columns;
90 IndexColumn[] refCols = refColumns;
91 builder.append(" FOREIGN KEY(");
92 IndexColumn.writeColumns(builder, cols, DEFAULT_SQL_FLAGS);
93 builder.append(')');
94 if (internalIndex && indexOwner && forTable == this.table) {
95 builder.append(" INDEX ");
96 index.getSQL(builder, DEFAULT_SQL_FLAGS);
97 }
98 builder.append(" REFERENCES ");
99 if (this.table == this.refTable) {
100 // self-referencing constraints: need to use new table
101 forTable.getSQL(builder, DEFAULT_SQL_FLAGS);
102 } else {
103 forRefTable.getSQL(builder, DEFAULT_SQL_FLAGS);
104 }
105 builder.append('(');
106 IndexColumn.writeColumns(builder, refCols, DEFAULT_SQL_FLAGS);
107 builder.append(')');
108 if (deleteAction != ConstraintActionType.RESTRICT) {
109 builder.append(" ON DELETE ").append(deleteAction.getSqlName());
110 }
111 if (updateAction != ConstraintActionType.RESTRICT) {
112 builder.append(" ON UPDATE ").append(updateAction.getSqlName());
113 }
114 return builder.append(" NOCHECK").toString();
115 }
116
117
118 /**
119 * Get a short description of the constraint. This includes the constraint
120 * name (if set), and the constraint expression.
121 *
122 * @param searchIndex the index, or null
123 * @param check the row, or null
124 * @return the description
125 */
126 private String getShortDescription(Index searchIndex, SearchRow check) {
127 StringBuilder builder = new StringBuilder(getName()).append(": ");
128 table.getSQL(builder, TRACE_SQL_FLAGS).append(" FOREIGN KEY(");
129 IndexColumn.writeColumns(builder, columns, TRACE_SQL_FLAGS);
130 builder.append(") REFERENCES ");
131 refTable.getSQL(builder, TRACE_SQL_FLAGS).append('(');
132 IndexColumn.writeColumns(builder, refColumns, TRACE_SQL_FLAGS);
133 builder.append(')');
134 if (searchIndex != null && check != null) {
135 builder.append(" (");
136 Column[] cols = searchIndex.getColumns();
137 int len = Math.min(columns.length, cols.length);
138 for (int i = 0; i < len; i++) {
139 int idx = cols[i].getColumnId();
140 Value c = check.getValue(idx);
141 if (i > 0) {
142 builder.append(", ");
143 }
144 builder.append(c == null ? "" : c.toString());
145 }
146 builder.append(')');
147 }
148 return builder.toString();
149 }
150
151 @Override
152 public String getCreateSQLWithoutIndexes() {
153 return getCreateSQLForCopy(table, refTable, getSQL(DEFAULT_SQL_FLAGS), false);
154 }
155
156 @Override
157 public String getCreateSQL() {
158 return getCreateSQLForCopy(table, getSQL(DEFAULT_SQL_FLAGS));
159 }
160
161 public void setColumns(IndexColumn[] cols) {
162 columns = cols;
163 }
164
165 public IndexColumn[] getColumns() {
166 return columns;
167 }
168
169 @Override
170 public HashSet<Column> getReferencedColumns(Table table) {
171 HashSet<Column> result = new HashSet<>();
172 if (table == this.table) {
173 for (IndexColumn c : columns) {
174 result.add(c.column);
175 }
176 } else if (table == this.refTable) {
177 for (IndexColumn c : refColumns) {
178 result.add(c.column);
179 }
180 }
181 return result;
182 }
183
184 public void setRefColumns(IndexColumn[] refCols) {
185 refColumns = refCols;
186 }
187
188 public IndexColumn[] getRefColumns() {
189 return refColumns;
190 }
191
192 public void setRefTable(Table refTable) {
193 this.refTable = refTable;
194 if (refTable.isTemporary()) {
195 setTemporary(true);
196 }
197 }
198
199 /**
200 * Set the index to use for this constraint.
201 *
202 * @param index the index
203 * @param isOwner true if the index is generated by the system and belongs
204 * to this constraint
205 */
206 public void setIndex(Index index, boolean isOwner) {
207 this.index = index;
208 this.indexOwner = isOwner;
209 }
210
211 /**
212 * Set the unique constraint of the referenced table to use for this
213 * constraint.
214 *
215 * @param refConstraint
216 * the unique constraint
217 */
218 public void setRefConstraint(ConstraintUnique refConstraint) {
219 this.refConstraint = refConstraint;
220 }
221
222 @Override
223 public void removeChildrenAndResources(SessionLocal session) {
224 table.removeConstraint(this);
225 refTable.removeConstraint(this);
226 if (indexOwner) {
227 table.removeIndexOrTransferOwnership(session, index);
228 }
229 database.removeMeta(session, getId());
230 refTable = null;
231 index = null;
232 refConstraint = null;
233 columns = null;
234 refColumns = null;
235 deleteSQL = null;
236 updateSQL = null;
237 table = null;
238 invalidate();
239 }
240
241 @Override
242 public void checkRow(SessionLocal session, Table t, Row oldRow, Row newRow) {
243 if (!database.getReferentialIntegrity()) {
244 return;
245 }
246 if (!table.getCheckForeignKeyConstraints() ||
247 !refTable.getCheckForeignKeyConstraints()) {
248 return;
249 }
250 if (t == table) {
251 if (!skipOwnTable) {
252 checkRowOwnTable(session, oldRow, newRow);
253 }
254 }
255 if (t == refTable) {
256 checkRowRefTable(session, oldRow, newRow);
257 }
258 }
259
260 private void checkRowOwnTable(SessionLocal session, Row oldRow, Row newRow) {
261 if (newRow == null) {
262 return;
263 }
264 boolean constraintColumnsEqual = oldRow != null;
265 for (IndexColumn col : columns) {
266 int idx = col.column.getColumnId();
267 Value v = newRow.getValue(idx);
268 if (v == ValueNull.INSTANCE) {
269 // return early if one of the columns is NULL
270 return;
271 }
272 if (constraintColumnsEqual) {
273 if (!session.areEqual(v, oldRow.getValue(idx))) {
274 constraintColumnsEqual = false;
275 }
276 }
277 }
278 if (constraintColumnsEqual) {
279 // return early if the key columns didn't change
280 return;
281 }
282 if (refTable == table) {
283 // special case self referencing constraints:
284 // check the inserted row first
285 boolean self = true;
286 for (int i = 0, len = columns.length; i < len; i++) {
287 int idx = columns[i].column.getColumnId();
288 Value v = newRow.getValue(idx);
289 Column refCol = refColumns[i].column;
290 int refIdx = refCol.getColumnId();
291 Value r = newRow.getValue(refIdx);
292 if (!session.areEqual(r, v)) {
293 self = false;
294 break;
295 }
296 }
297 if (self) {
298 return;
299 }
300 }
301 Row check = refTable.getTemplateRow();
302 for (int i = 0, len = columns.length; i < len; i++) {
303 int idx = columns[i].column.getColumnId();
304 Value v = newRow.getValue(idx);
305 Column refCol = refColumns[i].column;
306 int refIdx = refCol.getColumnId();
307 check.setValue(refIdx, refCol.convert(session, v));
308 }
309 Index refIndex = refConstraint.getIndex();
310 if (!existsRow(session, refIndex, check, null)) {
311 throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1,
312 getShortDescription(refIndex, check));
313 }
314 }
315
316 private boolean existsRow(SessionLocal session, Index searchIndex,
317 SearchRow check, Row excluding) {
318 Table searchTable = searchIndex.getTable();
319 searchTable.lock(session, Table.READ_LOCK);
320 Cursor cursor = searchIndex.find(session, check, check);
321 while (cursor.next()) {
322 SearchRow found;
323 found = cursor.getSearchRow();
324 if (excluding != null && found.getKey() == excluding.getKey()) {
325 continue;
326 }
327 Column[] cols = searchIndex.getColumns();
328 boolean allEqual = true;
329 int len = Math.min(columns.length, cols.length);
330 for (int i = 0; i < len; i++) {
331 int idx = cols[i].getColumnId();
332 Value c = check.getValue(idx);
333 Value f = found.getValue(idx);
334 if (searchTable.compareValues(session, c, f) != 0) {
335 allEqual = false;
336 break;
337 }
338 }
339 if (allEqual) {
340 return true;
341 }
342 }
343 return false;
344 }
345
346 private boolean isEqual(Row oldRow, Row newRow) {
347 return refConstraint.getIndex().compareRows(oldRow, newRow) == 0;
348 }
349
350 private void checkRow(SessionLocal session, Row oldRow) {
351 SearchRow check = table.getRowFactory().createRow();
352 for (int i = 0, len = columns.length; i < len; i++) {
353 Column refCol = refColumns[i].column;
354 int refIdx = refCol.getColumnId();
355 Column col = columns[i].column;
356 Value v = col.convert(session, oldRow.getValue(refIdx));
357 if (v == ValueNull.INSTANCE) {
358 return;
359 }
360 check.setValue(col.getColumnId(), v);
361 }
362 // exclude the row only for self-referencing constraints
363 Row excluding = (refTable == table) ? oldRow : null;
364 if (existsRow(session, index, check, excluding)) {
365 throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_CHILD_EXISTS_1,
366 getShortDescription(index, check));
367 }
368 }
369
370 private void checkRowRefTable(SessionLocal session, Row oldRow, Row newRow) {
371 if (oldRow == null) {
372 // this is an insert
373 return;
374 }
375 if (newRow != null && isEqual(oldRow, newRow)) {
376 // on an update, if both old and new are the same, don't do anything
377 return;
378 }
379 if (newRow == null) {
380 // this is a delete
381 if (deleteAction == ConstraintActionType.RESTRICT) {
382 checkRow(session, oldRow);
383 } else {
384 int i = deleteAction == ConstraintActionType.CASCADE ? 0 : columns.length;
385 Prepared deleteCommand = getDelete(session);
386 setWhere(deleteCommand, i, oldRow);
387 updateWithSkipCheck(deleteCommand);
388 }
389 } else {
390 // this is an update
391 if (updateAction == ConstraintActionType.RESTRICT) {
392 checkRow(session, oldRow);
393 } else {
394 Prepared updateCommand = getUpdate(session);
395 if (updateAction == ConstraintActionType.CASCADE) {
396 ArrayList<Parameter> params = updateCommand.getParameters();
397 for (int i = 0, len = columns.length; i < len; i++) {
398 Parameter param = params.get(i);
399 Column refCol = refColumns[i].column;
400 param.setValue(newRow.getValue(refCol.getColumnId()));
401 }
402 }
403 setWhere(updateCommand, columns.length, oldRow);
404 updateWithSkipCheck(updateCommand);
405 }
406 }
407 }
408
409 private void updateWithSkipCheck(Prepared prep) {
410 // TODO constraints: maybe delay the update or support delayed checks
411 // (until commit)
412 try {
413 // TODO multithreaded kernel: this works only if nobody else updates
414 // this or the ref table at the same time
415 skipOwnTable = true;
416 prep.update();
417 } finally {
418 skipOwnTable = false;
419 }
420 }
421
422 private void setWhere(Prepared command, int pos, Row row) {
423 for (int i = 0, len = refColumns.length; i < len; i++) {
424 int idx = refColumns[i].column.getColumnId();
425 Value v = row.getValue(idx);
426 ArrayList<Parameter> params = command.getParameters();
427 Parameter param = params.get(pos + i);
428 param.setValue(v);
429 }
430 }
431
432 public ConstraintActionType getDeleteAction() {
433 return deleteAction;
434 }
435
436 /**
437 * Set the action to apply (restrict, cascade,...) on a delete.
438 *
439 * @param action the action
440 */
441 public void setDeleteAction(ConstraintActionType action) {
442 if (action == deleteAction && deleteSQL == null) {
443 return;
444 }
445 if (deleteAction != ConstraintActionType.RESTRICT) {
446 throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, "ON DELETE");
447 }
448 this.deleteAction = action;
449 buildDeleteSQL();
450 }
451
452 /**
453 * Update the constraint SQL when a referenced column is renamed.
454 */
455 public void updateOnTableColumnRename() {
456 if (deleteAction != null) {
457 deleteSQL = null;
458 buildDeleteSQL();
459 }
460 if (updateAction != null) {
461 updateSQL = null;
462 buildUpdateSQL();
463 }
464 }
465
466 private void buildDeleteSQL() {
467 if (deleteAction == ConstraintActionType.RESTRICT) {
468 return;
469 }
470 StringBuilder builder = new StringBuilder();
471 if (deleteAction == ConstraintActionType.CASCADE) {
472 builder.append("DELETE FROM ");
473 table.getSQL(builder, DEFAULT_SQL_FLAGS);
474 } else {
475 appendUpdate(builder);
476 }
477 appendWhere(builder);
478 deleteSQL = builder.toString();
479 }
480
481 private Prepared getUpdate(SessionLocal session) {
482 return prepare(session, updateSQL, updateAction);
483 }
484
485 private Prepared getDelete(SessionLocal session) {
486 return prepare(session, deleteSQL, deleteAction);
487 }
488
489 public ConstraintActionType getUpdateAction() {
490 return updateAction;
491 }
492
493 /**
494 * Set the action to apply (restrict, cascade,...) on an update.
495 *
496 * @param action the action
497 */
498 public void setUpdateAction(ConstraintActionType action) {
499 if (action == updateAction && updateSQL == null) {
500 return;
501 }
502 if (updateAction != ConstraintActionType.RESTRICT) {
503 throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, "ON UPDATE");
504 }
505 this.updateAction = action;
506 buildUpdateSQL();
507 }
508
509 private void buildUpdateSQL() {
510 if (updateAction == ConstraintActionType.RESTRICT) {
511 return;
512 }
513 StringBuilder builder = new StringBuilder();
514 appendUpdate(builder);
515 appendWhere(builder);
516 updateSQL = builder.toString();
517 }
518
519 @Override
520 public void rebuild() {
521 buildUpdateSQL();
522 buildDeleteSQL();
523 }
524
525 private Prepared prepare(SessionLocal session, String sql, ConstraintActionType action) {
526 Prepared command = session.prepare(sql);
527 if (action != ConstraintActionType.CASCADE) {
528 ArrayList<Parameter> params = command.getParameters();
529 for (int i = 0, len = columns.length; i < len; i++) {
530 Column column = columns[i].column;
531 Parameter param = params.get(i);
532 Value value;
533 if (action == ConstraintActionType.SET_NULL) {
534 value = ValueNull.INSTANCE;
535 } else {
536 Expression expr = column.getEffectiveDefaultExpression();
537 if (expr == null) {
538 throw DbException.get(ErrorCode.NO_DEFAULT_SET_1, column.getName());
539 }
540 value = expr.getValue(session);
541 }
542 param.setValue(value);
543 }
544 }
545 return command;
546 }
547
548 private void appendUpdate(StringBuilder builder) {
549 builder.append("UPDATE ");
550 table.getSQL(builder, DEFAULT_SQL_FLAGS).append(" SET ");
551 IndexColumn.writeColumns(builder, columns, ", ", "=?", IndexColumn.SQL_NO_ORDER);
552 }
553
554 private void appendWhere(StringBuilder builder) {
555 builder.append(" WHERE ");
556 IndexColumn.writeColumns(builder, columns, " AND ", "=?", IndexColumn.SQL_NO_ORDER);
557 }
558
559 @Override
560 public Table getRefTable() {
561 return refTable;
562 }
563
564 @Override
565 public boolean usesIndex(Index idx) {
566 return idx == index;
567 }
568
569 @Override
570 public void setIndexOwner(Index index) {
571 if (this.index == index) {
572 indexOwner = true;
573 } else {
574 throw DbException.getInternalError(index + " " + toString());
575 }
576 }
577
578 @Override
579 public boolean isBefore() {
580 return false;
581 }
582
583 @Override
584 public void checkExistingData(SessionLocal session) {
585 if (session.getDatabase().isStarting()) {
586 // don't check at startup
587 return;
588 }
589 StringBuilder builder = new StringBuilder("SELECT 1 FROM (SELECT ");
590 IndexColumn.writeColumns(builder, columns, IndexColumn.SQL_NO_ORDER);
591 builder.append(" FROM ");
592 table.getSQL(builder, DEFAULT_SQL_FLAGS).append(" WHERE ");
593 IndexColumn.writeColumns(builder, columns, " AND ", " IS NOT NULL ", IndexColumn.SQL_NO_ORDER);
594 builder.append(" ORDER BY ");
595 IndexColumn.writeColumns(builder, columns, DEFAULT_SQL_FLAGS);
596 builder.append(") C WHERE NOT EXISTS(SELECT 1 FROM ");
597 refTable.getSQL(builder, DEFAULT_SQL_FLAGS).append(" P WHERE ");
598 for (int i = 0, l = columns.length; i < l; i++) {
599 if (i > 0) {
600 builder.append(" AND ");
601 }
602 builder.append("C.");
603 columns[i].column.getSQL(builder, DEFAULT_SQL_FLAGS).append('=').append("P.");
604 refColumns[i].column.getSQL(builder, DEFAULT_SQL_FLAGS);
605 }
606 builder.append(')');
607
608 session.startStatementWithinTransaction(null);
609 try {
610 ResultInterface r = session.prepare(builder.toString()).query(1);
611 if (r.next()) {
612 throw DbException.get(ErrorCode.REFERENTIAL_INTEGRITY_VIOLATED_PARENT_MISSING_1,
613 getShortDescription(null, null));
614 }
615 } finally {
616 session.endStatement();
617 }
618 }
619
620 @Override
621 public Index getIndex() {
622 return index;
623 }
624
625 @Override
626 public ConstraintUnique getReferencedConstraint() {
627 return refConstraint;
628 }
629
630 }