Debian Codegraph @

src/main/org/h2/command/ddl/AlterTableAddConstraint.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.ddl;
7
8 import java.util.ArrayList;
9
10 import org.h2.api.ErrorCode;
11 import org.h2.command.CommandInterface;
12 import org.h2.constraint.Constraint;
13 import org.h2.constraint.ConstraintActionType;
14 import org.h2.constraint.ConstraintCheck;
15 import org.h2.constraint.ConstraintReferential;
16 import org.h2.constraint.ConstraintUnique;
17 import org.h2.engine.Constants;
18 import org.h2.engine.Database;
19 import org.h2.engine.Right;
20 import org.h2.engine.SessionLocal;
21 import org.h2.engine.NullsDistinct;
22 import org.h2.expression.Expression;
23 import org.h2.index.Index;
24 import org.h2.index.IndexType;
25 import org.h2.message.DbException;
26 import org.h2.schema.Schema;
27 import org.h2.table.Column;
28 import org.h2.table.IndexColumn;
29 import org.h2.table.Table;
30 import org.h2.table.TableFilter;
31 import org.h2.util.HasSQL;
32 import org.h2.value.DataType;
33
34 /**
35 * This class represents the statement
36 * ALTER TABLE ADD CONSTRAINT
37 */
38 public class AlterTableAddConstraint extends AlterTable {
39
40 private final int type;
41 private String constraintName;
42 private NullsDistinct nullsDistinct;
43 private IndexColumn[] indexColumns;
44 private ConstraintActionType deleteAction = ConstraintActionType.RESTRICT;
45 private ConstraintActionType updateAction = ConstraintActionType.RESTRICT;
46 private Schema refSchema;
47 private String refTableName;
48 private IndexColumn[] refIndexColumns;
49 private Expression checkExpression;
50 private Index index, refIndex;
51 private String comment;
52 private boolean checkExisting;
53 private boolean primaryKeyHash;
54 private final boolean ifNotExists;
55 private final ArrayList<Index> createdIndexes = new ArrayList<>();
56 private ConstraintUnique createdUniqueConstraint;
57
58 public AlterTableAddConstraint(SessionLocal session, Schema schema, int type, boolean ifNotExists) {
59 super(session, schema);
60 this.ifNotExists = ifNotExists;
61 this.type = type;
62 }
63
64 private String generateConstraintName(Table table) {
65 if (constraintName == null) {
66 constraintName = getSchema().getUniqueConstraintName(session, table);
67 }
68 return constraintName;
69 }
70
71 @Override
72 public long update(Table table) {
73 try {
74 return tryUpdate(table);
75 } catch (DbException e) {
76 try {
77 if (createdUniqueConstraint != null) {
78 Index index = createdUniqueConstraint.getIndex();
79 getDatabase().removeSchemaObject(session, createdUniqueConstraint);
80 createdIndexes.remove(index);
81 }
82 for (Index index : createdIndexes) {
83 getDatabase().removeSchemaObject(session, index);
84 }
85 } catch (Throwable ex) {
86 e.addSuppressed(ex);
87 }
88 throw e;
89 } finally {
90 getSchema().freeUniqueName(constraintName);
91 }
92 }
93
94 /**
95 * Try to execute the statement.
96 *
97 * @return the update count
98 */
99 private int tryUpdate(Table table) {
100 if (constraintName != null && getSchema().findConstraint(session, constraintName) != null) {
101 if (ifNotExists) {
102 return 0;
103 }
104 /**
105 * 1.4.200 and older databases don't always have a unique constraint
106 * for each referential constraint, so these constraints are created
107 * and they may use the same generated name as some other not yet
108 * initialized constraint that may lead to a name conflict.
109 */
110 if (!session.isQuirksMode()) {
111 throw DbException.get(ErrorCode.CONSTRAINT_ALREADY_EXISTS_1, constraintName);
112 }
113 constraintName = null;
114 }
115 Database db = getDatabase();
116 db.lockMeta(session);
117 table.lock(session, Table.EXCLUSIVE_LOCK);
118 Constraint constraint;
119 switch (type) {
120 case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_PRIMARY_KEY: {
121 IndexColumn.mapColumns(indexColumns, table);
122 index = table.findPrimaryKey();
123 ArrayList<Constraint> constraints = table.getConstraints();
124 for (int i = 0; constraints != null && i < constraints.size(); i++) {
125 Constraint c = constraints.get(i);
126 if (Constraint.Type.PRIMARY_KEY == c.getConstraintType()) {
127 throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
128 }
129 }
130 if (index != null) {
131 // if there is an index, it must match with the one declared
132 // we don't test ascending / descending
133 IndexColumn[] pkCols = index.getIndexColumns();
134 if (pkCols.length != indexColumns.length) {
135 throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
136 }
137 for (int i = 0; i < pkCols.length; i++) {
138 if (pkCols[i].column != indexColumns[i].column) {
139 throw DbException.get(ErrorCode.SECOND_PRIMARY_KEY);
140 }
141 }
142 } else {
143 IndexType indexType = IndexType.createPrimaryKey(
144 table.isPersistIndexes(), primaryKeyHash);
145 String indexName = table.getSchema().getUniqueIndexName(
146 session, table, Constants.PREFIX_PRIMARY_KEY);
147 int indexId = getDatabase().allocateObjectId();
148 try {
149 index = table.addIndex(session, indexName, indexId, indexColumns, indexColumns.length, indexType,
150 true, null);
151 } finally {
152 getSchema().freeUniqueName(indexName);
153 }
154 }
155 index.getIndexType().setBelongsToConstraint(true);
156 int id = getObjectId();
157 String name = generateConstraintName(table);
158 ConstraintUnique pk = new ConstraintUnique(getSchema(), id, name, table, true, null);
159 pk.setColumns(indexColumns);
160 pk.setIndex(index, true);
161 constraint = pk;
162 break;
163 }
164 case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_UNIQUE:
165 if (indexColumns == null) {
166 Column[] columns = table.getColumns();
167 int columnCount = columns.length;
168 ArrayList<IndexColumn> list = new ArrayList<>(columnCount);
169 for (int i = 0; i < columnCount; i++) {
170 Column c = columns[i];
171 if (c.getVisible()) {
172 IndexColumn indexColumn = new IndexColumn(c.getName());
173 indexColumn.column = c;
174 list.add(indexColumn);
175 }
176 }
177 if (list.isEmpty()) {
178 throw DbException.get(ErrorCode.SYNTAX_ERROR_1, "UNIQUE(VALUE) on table without columns");
179 }
180 indexColumns = list.toArray(new IndexColumn[0]);
181 } else {
182 IndexColumn.mapColumns(indexColumns, table);
183 }
184 constraint = createUniqueConstraint(table, index, indexColumns, false);
185 break;
186 case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_CHECK: {
187 int id = getObjectId();
188 String name = generateConstraintName(table);
189 ConstraintCheck check = new ConstraintCheck(getSchema(), id, name, table);
190 TableFilter filter = new TableFilter(session, table, null, false, null, 0, null);
191 checkExpression.mapColumns(filter, 0, Expression.MAP_INITIAL);
192 checkExpression = checkExpression.optimize(session);
193 check.setExpression(checkExpression);
194 check.setTableFilter(filter);
195 constraint = check;
196 if (checkExisting) {
197 check.checkExistingData(session);
198 }
199 break;
200 }
201 case CommandInterface.ALTER_TABLE_ADD_CONSTRAINT_REFERENTIAL: {
202 Table refTable = refSchema.resolveTableOrView(session, refTableName);
203 if (refTable == null) {
204 throw DbException.get(ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, refTableName);
205 }
206 if (refTable != table) {
207 session.getUser().checkTableRight(refTable, Right.SCHEMA_OWNER);
208 }
209 if (!refTable.canReference()) {
210 StringBuilder builder = new StringBuilder("Reference ");
211 refTable.getSQL(builder, HasSQL.TRACE_SQL_FLAGS);
212 throw DbException.getUnsupportedException(builder.toString());
213 }
214 boolean isOwner = false;
215 IndexColumn.mapColumns(indexColumns, table);
216 if (refIndexColumns == null) {
217 refIndexColumns = refTable.getPrimaryKey().getIndexColumns();
218 } else {
219 IndexColumn.mapColumns(refIndexColumns, refTable);
220 }
221 int columnCount = indexColumns.length;
222 if (refIndexColumns.length != columnCount) {
223 throw DbException.get(ErrorCode.COLUMN_COUNT_DOES_NOT_MATCH);
224 }
225 for (IndexColumn indexColumn : indexColumns) {
226 Column column = indexColumn.column;
227 if (column.isGeneratedAlways()) {
228 switch (deleteAction) {
229 case SET_DEFAULT:
230 case SET_NULL:
231 throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_UPDATABLE_BY_CONSTRAINT_2,
232 column.getSQLWithTable(new StringBuilder(), HasSQL.TRACE_SQL_FLAGS).toString(),
233 "ON DELETE " + deleteAction.getSqlName());
234 default:
235 // All other actions are allowed
236 }
237 switch (updateAction) {
238 case CASCADE:
239 case SET_DEFAULT:
240 case SET_NULL:
241 throw DbException.get(ErrorCode.GENERATED_COLUMN_CANNOT_BE_UPDATABLE_BY_CONSTRAINT_2,
242 column.getSQLWithTable(new StringBuilder(), HasSQL.TRACE_SQL_FLAGS).toString(),
243 "ON UPDATE " + updateAction.getSqlName());
244 default:
245 // All other actions are allowed
246 }
247 }
248 }
249 for (int i = 0; i < columnCount; i++) {
250 Column column1 = indexColumns[i].column, column2 = refIndexColumns[i].column;
251 if (!DataType.areStableComparable(column1.getType(), column2.getType())) {
252 throw DbException.get(ErrorCode.UNCOMPARABLE_REFERENCED_COLUMN_2, column1.getCreateSQL(),
253 column2.getCreateSQL());
254 }
255 }
256 ConstraintUnique unique = getUniqueConstraint(refTable, refIndexColumns);
257 if (unique == null && !session.isQuirksMode()
258 && !session.getMode().createUniqueConstraintForReferencedColumns) {
259 throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, IndexColumn.writeColumns(
260 new StringBuilder("PRIMARY KEY | UNIQUE ("), refIndexColumns, HasSQL.TRACE_SQL_FLAGS)
261 .append(')').toString());
262 }
263 if (index != null && canUseIndex(index, table, indexColumns, null)) {
264 isOwner = true;
265 index.getIndexType().setBelongsToConstraint(true);
266 } else {
267 index = getIndex(table, indexColumns, null);
268 if (index == null) {
269 index = createIndex(table, indexColumns, null);
270 isOwner = true;
271 }
272 }
273 int id = getObjectId();
274 String name = generateConstraintName(table);
275 ConstraintReferential refConstraint = new ConstraintReferential(getSchema(),
276 id, name, table);
277 refConstraint.setColumns(indexColumns);
278 refConstraint.setIndex(index, isOwner);
279 refConstraint.setRefTable(refTable);
280 refConstraint.setRefColumns(refIndexColumns);
281 if (unique == null) {
282 unique = createUniqueConstraint(refTable, refIndex, refIndexColumns, true);
283 addConstraintToTable(db, refTable, unique);
284 createdUniqueConstraint = unique;
285 }
286 refConstraint.setRefConstraint(unique);
287 if (checkExisting) {
288 refConstraint.checkExistingData(session);
289 }
290 refTable.addConstraint(refConstraint);
291 refConstraint.setDeleteAction(deleteAction);
292 refConstraint.setUpdateAction(updateAction);
293 constraint = refConstraint;
294 break;
295 }
296 default:
297 throw DbException.getInternalError("type=" + type);
298 }
299 // parent relationship is already set with addConstraint
300 constraint.setComment(comment);
301 addConstraintToTable(db, table, constraint);
302 return 0;
303 }
304
305 private ConstraintUnique createUniqueConstraint(Table table, Index index, IndexColumn[] indexColumns,
306 boolean forForeignKey) {
307 boolean isOwner = false;
308 NullsDistinct needNullsDistinct = nullsDistinct != null ? nullsDistinct : NullsDistinct.DISTINCT;
309 if (index != null && canUseIndex(index, table, indexColumns, needNullsDistinct)) {
310 isOwner = true;
311 index.getIndexType().setBelongsToConstraint(true);
312 } else {
313 index = getIndex(table, indexColumns, needNullsDistinct);
314 if (index == null) {
315 index = createIndex(table, indexColumns,
316 nullsDistinct != null ? nullsDistinct : session.getMode().nullsDistinct);
317 isOwner = true;
318 }
319 }
320 int id;
321 String name;
322 Schema tableSchema = table.getSchema();
323 if (forForeignKey) {
324 id = getDatabase().allocateObjectId();
325 try {
326 tableSchema.reserveUniqueName(constraintName);
327 name = tableSchema.getUniqueConstraintName(session, table);
328 } finally {
329 tableSchema.freeUniqueName(constraintName);
330 }
331 } else {
332 id = getObjectId();
333 name = generateConstraintName(table);
334 }
335 if (indexColumns.length == 1 && needNullsDistinct == NullsDistinct.ALL_DISTINCT) {
336 needNullsDistinct = NullsDistinct.DISTINCT;
337 }
338 ConstraintUnique unique = new ConstraintUnique(tableSchema, id, name, table, false, needNullsDistinct);
339 unique.setColumns(indexColumns);
340 unique.setIndex(index, isOwner);
341 return unique;
342 }
343
344 private void addConstraintToTable(Database db, Table table, Constraint constraint) {
345 if (table.isTemporary() && !table.isGlobalTemporary()) {
346 session.addLocalTempTableConstraint(constraint);
347 } else {
348 db.addSchemaObject(session, constraint);
349 }
350 table.addConstraint(constraint);
351 }
352
353 private Index createIndex(Table t, IndexColumn[] cols, NullsDistinct nullsDistinct) {
354 int indexId = getDatabase().allocateObjectId();
355 IndexType indexType;
356 if (nullsDistinct != null) {
357 // for unique constraints
358 indexType = IndexType.createUnique(t.isPersistIndexes(), false, cols.length, nullsDistinct);
359 } else {
360 // constraints
361 indexType = IndexType.createNonUnique(t.isPersistIndexes());
362 }
363 indexType.setBelongsToConstraint(true);
364 String prefix = constraintName == null ? "CONSTRAINT" : constraintName;
365 String indexName = t.getSchema().getUniqueIndexName(session, t,
366 prefix + "_INDEX_");
367 try {
368 Index index = t.addIndex(session, indexName, indexId, cols, nullsDistinct != null ? cols.length : 0,
369 indexType, true, null);
370 createdIndexes.add(index);
371 return index;
372 } finally {
373 getSchema().freeUniqueName(indexName);
374 }
375 }
376
377 public void setDeleteAction(ConstraintActionType action) {
378 this.deleteAction = action;
379 }
380
381 public void setUpdateAction(ConstraintActionType action) {
382 this.updateAction = action;
383 }
384
385 private static ConstraintUnique getUniqueConstraint(Table t, IndexColumn[] cols) {
386 ArrayList<Constraint> constraints = t.getConstraints();
387 if (constraints != null) {
388 for (Constraint constraint : constraints) {
389 if (constraint.getTable() == t) {
390 Constraint.Type constraintType = constraint.getConstraintType();
391 if (constraintType == Constraint.Type.PRIMARY_KEY || constraintType == Constraint.Type.UNIQUE) {
392 if (canUseIndex(constraint.getIndex(), t, cols, NullsDistinct.DISTINCT)) {
393 return (ConstraintUnique) constraint;
394 }
395 }
396 }
397 }
398 }
399 return null;
400 }
401
402 private static Index getIndex(Table t, IndexColumn[] cols, NullsDistinct nullsDistinct) {
403 ArrayList<Index> indexes = t.getIndexes();
404 Index index = null;
405 if (indexes != null) {
406 for (Index idx : indexes) {
407 if (canUseIndex(idx, t, cols, nullsDistinct)) {
408 if (index == null || idx.getIndexColumns().length < index.getIndexColumns().length) {
409 index = idx;
410 }
411 }
412 }
413 }
414 return index;
415 }
416
417 private static boolean canUseIndex(Index index, Table table, IndexColumn[] cols, NullsDistinct nullsDistinct) {
418 if (index.getTable() != table) {
419 return false;
420 }
421 int allowedColumns;
422 if (nullsDistinct != null) {
423 allowedColumns = index.getUniqueColumnCount();
424 if (allowedColumns != cols.length) {
425 return false;
426 }
427 if (index.getIndexType().getEffectiveNullsDistinct().compareTo(nullsDistinct) < 0) {
428 return false;
429 }
430 } else {
431 if (index.getCreateSQL() == null || (allowedColumns = index.getColumns().length) != cols.length) {
432 return false;
433 }
434 }
435 for (IndexColumn col : cols) {
436 // all columns of the list must be part of the index
437 int i = index.getColumnIndex(col.column);
438 if (i < 0 || i >= allowedColumns) {
439 return false;
440 }
441 }
442 return true;
443 }
444
445 public void setConstraintName(String constraintName) {
446 this.constraintName = constraintName;
447 }
448
449 public String getConstraintName() {
450 return constraintName;
451 }
452
453 @Override
454 public int getType() {
455 return type;
456 }
457
458 public void setNullsDistinct(NullsDistinct nullsDistinct) {
459 this.nullsDistinct = nullsDistinct;
460 }
461
462 public void setCheckExpression(Expression expression) {
463 this.checkExpression = expression;
464 }
465
466 public void setIndexColumns(IndexColumn[] indexColumns) {
467 this.indexColumns = indexColumns;
468 }
469
470 public IndexColumn[] getIndexColumns() {
471 return indexColumns;
472 }
473
474 /**
475 * Set the referenced table.
476 *
477 * @param refSchema the schema
478 * @param ref the table name
479 */
480 public void setRefTableName(Schema refSchema, String ref) {
481 this.refSchema = refSchema;
482 this.refTableName = ref;
483 }
484
485 public void setRefIndexColumns(IndexColumn[] indexColumns) {
486 this.refIndexColumns = indexColumns;
487 }
488
489 public void setIndex(Index index) {
490 this.index = index;
491 }
492
493 public void setRefIndex(Index refIndex) {
494 this.refIndex = refIndex;
495 }
496
497 public void setComment(String comment) {
498 this.comment = comment;
499 }
500
501 public void setCheckExisting(boolean b) {
502 this.checkExisting = b;
503 }
504
505 public void setPrimaryKeyHash(boolean b) {
506 this.primaryKeyHash = b;
507 }
508
509 }