Debian Codegraph @

src/main/org/h2/command/ddl/AlterTableDropConstraint.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 org.h2.api.ErrorCode;
9 import org.h2.command.CommandInterface;
10 import org.h2.constraint.Constraint;
11 import org.h2.constraint.Constraint.Type;
12 import org.h2.constraint.ConstraintActionType;
13 import org.h2.engine.Right;
14 import org.h2.engine.SessionLocal;
15 import org.h2.message.DbException;
16 import org.h2.schema.Schema;
17 import org.h2.table.Table;
18
19 /**
20 * This class represents the statement
21 * ALTER TABLE DROP CONSTRAINT
22 */
23 public class AlterTableDropConstraint extends AlterTable {
24
25 private String constraintName;
26 private final boolean ifExists;
27 private ConstraintActionType dropAction;
28
29 public AlterTableDropConstraint(SessionLocal session, Schema schema, boolean ifExists) {
30 super(session, schema);
31 this.ifExists = ifExists;
32 dropAction = getDatabase().getSettings().dropRestrict ?
33 ConstraintActionType.RESTRICT : ConstraintActionType.CASCADE;
34 }
35
36 public void setConstraintName(String string) {
37 constraintName = string;
38 }
39
40 public void setDropAction(ConstraintActionType dropAction) {
41 this.dropAction = dropAction;
42 }
43
44 @Override
45 public long update(Table table) {
46 Constraint constraint = getSchema().findConstraint(session, constraintName);
47 Type constraintType;
48 if (constraint == null || (constraintType = constraint.getConstraintType()) == Type.DOMAIN
49 || constraint.getTable() != table) {
50 if (!ifExists) {
51 throw DbException.get(ErrorCode.CONSTRAINT_NOT_FOUND_1, constraintName);
52 }
53 } else {
54 Table refTable = constraint.getRefTable();
55 if (refTable != table) {
56 session.getUser().checkTableRight(refTable, Right.SCHEMA_OWNER);
57 }
58 if (constraintType == Type.PRIMARY_KEY || constraintType == Type.UNIQUE) {
59 for (Constraint c : constraint.getTable().getConstraints()) {
60 if (c.getReferencedConstraint() == constraint) {
61 if (dropAction == ConstraintActionType.RESTRICT) {
62 throw DbException.get(ErrorCode.CONSTRAINT_IS_USED_BY_CONSTRAINT_2,
63 constraint.getTraceSQL(), c.getTraceSQL());
64 }
65 Table t = c.getTable();
66 if (t != table && t != refTable) {
67 session.getUser().checkTableRight(t, Right.SCHEMA_OWNER);
68 }
69 }
70 }
71 }
72 getDatabase().removeSchemaObject(session, constraint);
73 }
74 return 0;
75 }
76
77 @Override
78 public int getType() {
79 return CommandInterface.ALTER_TABLE_DROP_CONSTRAINT;
80 }
81
82 }