1 | /* |
2 | * Copyright 2004-2014 H2 Group. Multiple-Licensed under the MPL 2.0, |
3 | * and the EPL 1.0 (http://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.engine.Database; |
14 | import org.h2.engine.Right; |
15 | import org.h2.engine.Session; |
16 | import org.h2.index.Index; |
17 | import org.h2.message.DbException; |
18 | import org.h2.schema.Schema; |
19 | import org.h2.table.Table; |
20 | |
21 | /** |
22 | * This class represents the statement |
23 | * DROP INDEX |
24 | */ |
25 | public class DropIndex extends SchemaCommand { |
26 | |
27 | private String indexName; |
28 | private boolean ifExists; |
29 | |
30 | public DropIndex(Session session, Schema schema) { |
31 | super(session, schema); |
32 | } |
33 | |
34 | public void setIfExists(boolean b) { |
35 | ifExists = b; |
36 | } |
37 | |
38 | public void setIndexName(String indexName) { |
39 | this.indexName = indexName; |
40 | } |
41 | |
42 | @Override |
43 | public int update() { |
44 | session.commit(true); |
45 | Database db = session.getDatabase(); |
46 | Index index = getSchema().findIndex(session, indexName); |
47 | if (index == null) { |
48 | if (!ifExists) { |
49 | throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName); |
50 | } |
51 | } else { |
52 | Table table = index.getTable(); |
53 | session.getUser().checkRight(index.getTable(), Right.ALL); |
54 | Constraint pkConstraint = null; |
55 | ArrayList<Constraint> constraints = table.getConstraints(); |
56 | for (int i = 0; constraints != null && i < constraints.size(); i++) { |
57 | Constraint cons = constraints.get(i); |
58 | if (cons.usesIndex(index)) { |
59 | // can drop primary key index (for compatibility) |
60 | if (Constraint.PRIMARY_KEY.equals(cons.getConstraintType())) { |
61 | pkConstraint = cons; |
62 | } else { |
63 | throw DbException.get( |
64 | ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, |
65 | indexName, cons.getName()); |
66 | } |
67 | } |
68 | } |
69 | index.getTable().setModified(); |
70 | if (pkConstraint != null) { |
71 | db.removeSchemaObject(session, pkConstraint); |
72 | } else { |
73 | db.removeSchemaObject(session, index); |
74 | } |
75 | } |
76 | return 0; |
77 | } |
78 | |
79 | @Override |
80 | public int getType() { |
81 | return CommandInterface.DROP_INDEX; |
82 | } |
83 | |
84 | } |