1 package liquibase.precondition.core;
2
3 import liquibase.changelog.ChangeSet;
4 import liquibase.changelog.DatabaseChangeLog;
5 import liquibase.database.Database;
6 import liquibase.exception.DatabaseException;
7 import liquibase.exception.PreconditionErrorException;
8 import liquibase.exception.PreconditionFailedException;
9 import liquibase.exception.ValidationErrors;
10 import liquibase.exception.Warnings;
11 import liquibase.precondition.Precondition;
12 import liquibase.snapshot.DatabaseSnapshot;
13 import liquibase.snapshot.DatabaseSnapshotGeneratorFactory;
14 import liquibase.util.StringUtils;
15
16 public class PrimaryKeyExistsPrecondition implements Precondition {
17 private String schemaName;
18 private String primaryKeyName;
19 private String tableName;
20
21 public String getSchemaName() {
22 return schemaName;
23 }
24
25 public void setSchemaName(String schemaName) {
26 this.schemaName = StringUtils.trimToNull(schemaName);
27 }
28
29 public String getPrimaryKeyName() {
30 return primaryKeyName;
31 }
32
33 public void setPrimaryKeyName(String primaryKeyName) {
34 this.primaryKeyName = primaryKeyName;
35 }
36
37 public String getTableName() {
38 return tableName;
39 }
40
41 public void setTableName(String tableName) {
42 this.tableName = tableName;
43 }
44
45 @Override
46 public Warnings warn(Database database) {
47 return new Warnings();
48 }
49
50 @Override
51 public ValidationErrors validate(Database database) {
52 return new ValidationErrors();
53 }
54
55 @Override
56 public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet)
57 throws PreconditionFailedException, PreconditionErrorException {
58 DatabaseSnapshot snapshot;
59 try {
60 snapshot = DatabaseSnapshotGeneratorFactory.getInstance().createSnapshot(database, getSchemaName(), null);
61 } catch (DatabaseException e) {
62 throw new PreconditionErrorException(e, changeLog, this);
63 }
64 if (tableName != null) {
65 if (snapshot.getPrimaryKeyForTable(getTableName()) == null) {
66 throw new PreconditionFailedException("Primary Key does not exist on "
67 + database.escapeStringForDatabase(getTableName()), changeLog, this);
68 }
69 } else if (primaryKeyName != null) {
70 if (snapshot.getPrimaryKey(getPrimaryKeyName()) == null) {
71 throw new PreconditionFailedException("Primary Key "
72 + database.escapeStringForDatabase(getPrimaryKeyName()) + " does not exist", changeLog, this);
73 }
74 } else {
75 throw new RuntimeException("primaryKeyExists precondition requires a tableName or primaryKeyName");
76 }
77 }
78
79 @Override
80 public String getName() {
81 return "primaryKeyExists";
82 }
83 }