01: /*
02: * Copyright 2004-2008 H2 Group. Licensed under the H2 License, Version 1.0
03: * (http://h2database.com/html/license.html).
04: * Initial Developer: H2 Group
05: */
06: package org.h2.command.ddl;
07:
08: import java.sql.SQLException;
09:
10: import org.h2.constant.ErrorCode;
11: import org.h2.engine.Database;
12: import org.h2.engine.Right;
13: import org.h2.engine.Session;
14: import org.h2.message.Message;
15: import org.h2.schema.Schema;
16: import org.h2.table.Table;
17:
18: /**
19: * This class represents the statement
20: * DROP TABLE
21: */
22: public class DropTable extends SchemaCommand {
23:
24: private boolean ifExists;
25: private String tableName;
26: private Table table;
27: private DropTable next;
28:
29: public DropTable(Session session, Schema schema) {
30: super (session, schema);
31: }
32:
33: /**
34: * Chain another drop table statement to this statement.
35: *
36: * @param next the statement to add
37: */
38: public void addNextDropTable(DropTable next) {
39: if (this .next == null) {
40: this .next = next;
41: } else {
42: this .next.addNextDropTable(next);
43: }
44: }
45:
46: public void setIfExists(boolean b) {
47: ifExists = b;
48: if (next != null) {
49: next.setIfExists(b);
50: }
51: }
52:
53: public void setTableName(String tableName) {
54: this .tableName = tableName;
55: }
56:
57: private void prepareDrop() throws SQLException {
58: table = getSchema().findTableOrView(session, tableName);
59: // TODO drop table: drops views as well (is this ok?)
60: if (table == null) {
61: if (!ifExists) {
62: throw Message.getSQLException(
63: ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1, tableName);
64: }
65: } else {
66: session.getUser().checkRight(table, Right.ALL);
67: if (!table.canDrop()) {
68: throw Message.getSQLException(
69: ErrorCode.CANNOT_DROP_TABLE_1, tableName);
70: }
71: table.lock(session, true, true);
72: }
73: if (next != null) {
74: next.prepareDrop();
75: }
76: }
77:
78: private void executeDrop() throws SQLException {
79: // need to get the table again, because it may be dropped already
80: // meanwhile (dependent object, or same object)
81: table = getSchema().findTableOrView(session, tableName);
82: if (table != null) {
83: table.setModified();
84: Database db = session.getDatabase();
85: db.removeSchemaObject(session, table);
86: }
87: if (next != null) {
88: next.executeDrop();
89: }
90: }
91:
92: public int update() throws SQLException {
93: session.commit(true);
94: prepareDrop();
95: executeDrop();
96: return 0;
97: }
98:
99: }
|