| 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.engine.Database; |
| 14 |
import org.h2.engine.Right; |
| 15 |
import org.h2.engine.SessionLocal; |
| 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(SessionLocal 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 long update() { |
| 44 |
Database db = getDatabase(); |
| 45 |
Index index = getSchema().findIndex(session, indexName); |
| 46 |
if (index == null) { |
| 47 |
if (!ifExists) { |
| 48 |
throw DbException.get(ErrorCode.INDEX_NOT_FOUND_1, indexName); |
| 49 |
} |
| 50 |
} else { |
| 51 |
Table table = index.getTable(); |
| 52 |
session.getUser().checkTableRight(index.getTable(), Right.SCHEMA_OWNER); |
| 53 |
Constraint pkConstraint = null; |
| 54 |
ArrayList<Constraint> constraints = table.getConstraints(); |
| 55 |
for (int i = 0; constraints != null && i < constraints.size(); i++) { |
| 56 |
Constraint cons = constraints.get(i); |
| 57 |
if (cons.usesIndex(index)) { |
| 58 |
// can drop primary key index (for compatibility) |
| 59 |
if (Constraint.Type.PRIMARY_KEY == cons.getConstraintType()) { |
| 60 |
for (Constraint c : constraints) { |
| 61 |
if (c.getReferencedConstraint() == cons) { |
| 62 |
throw DbException.get(ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, indexName, |
| 63 |
cons.getName()); |
| 64 |
} |
| 65 |
} |
| 66 |
pkConstraint = cons; |
| 67 |
} else { |
| 68 |
throw DbException.get(ErrorCode.INDEX_BELONGS_TO_CONSTRAINT_2, indexName, cons.getName()); |
| 69 |
} |
| 70 |
} |
| 71 |
} |
| 72 |
index.getTable().setModified(); |
| 73 |
if (pkConstraint != null) { |
| 74 |
db.removeSchemaObject(session, pkConstraint); |
| 75 |
} else { |
| 76 |
db.removeSchemaObject(session, index); |
| 77 |
} |
| 78 |
} |
| 79 |
return 0; |
| 80 |
} |
| 81 |
|
| 82 |
@Override |
| 83 |
public int getType() { |
| 84 |
return CommandInterface.DROP_INDEX; |
| 85 |
} |
| 86 |
|
| 87 |
} |