Debian Codegraph @

src/main/org/h2/command/ddl/DropView.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 import org.h2.api.ErrorCode;
10 import org.h2.command.CommandInterface;
11 import org.h2.constraint.ConstraintActionType;
12 import org.h2.engine.Database;
13 import org.h2.engine.DbObject;
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 import org.h2.table.TableType;
19 import org.h2.table.TableView;
20
21 /**
22 * This class represents the statement
23 * DROP VIEW
24 */
25 public class DropView extends SchemaCommand {
26
27 private String viewName;
28 private boolean ifExists;
29 private ConstraintActionType dropAction;
30
31 public DropView(SessionLocal session, Schema schema) {
32 super(session, schema);
33 dropAction = getDatabase().getSettings().dropRestrict ?
34 ConstraintActionType.RESTRICT :
35 ConstraintActionType.CASCADE;
36 }
37
38 public void setIfExists(boolean b) {
39 ifExists = b;
40 }
41
42 public void setDropAction(ConstraintActionType dropAction) {
43 this.dropAction = dropAction;
44 }
45
46 public void setViewName(String viewName) {
47 this.viewName = viewName;
48 }
49
50 @Override
51 public long update() {
52 Table view = getSchema().findTableOrView(session, viewName);
53 if (view == null) {
54 if (!ifExists) {
55 throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
56 }
57 } else {
58 if (TableType.VIEW != view.getTableType()) {
59 throw DbException.get(ErrorCode.VIEW_NOT_FOUND_1, viewName);
60 }
61 session.getUser().checkSchemaOwner(view.getSchema());
62
63 if (dropAction == ConstraintActionType.RESTRICT) {
64 for (DbObject child : view.getChildren()) {
65 if (child instanceof TableView) {
66 throw DbException.get(ErrorCode.CANNOT_DROP_2, viewName, child.getName());
67 }
68 }
69 }
70
71 // TODO: Where is the ConstraintReferential.CASCADE style drop processing ? It's
72 // supported from imported keys - but not for dependent db objects
73
74 TableView tableView = (TableView) view;
75 ArrayList<Table> copyOfDependencies = new ArrayList<>(tableView.getTables());
76
77 view.lock(session, Table.EXCLUSIVE_LOCK);
78 Database database = getDatabase();
79 database.removeSchemaObject(session, view);
80
81 // remove dependent table expressions
82 for (Table childTable: copyOfDependencies) {
83 if (TableType.VIEW == childTable.getTableType()) {
84 TableView childTableView = (TableView) childTable;
85 if (childTableView.isTableExpression() && childTableView.getName() != null) {
86 database.removeSchemaObject(session, childTableView);
87 }
88 }
89 }
90 // make sure its all unlocked
91 database.unlockMeta(session);
92 }
93 return 0;
94 }
95
96 @Override
97 public int getType() {
98 return CommandInterface.DROP_VIEW;
99 }
100
101 }