| 1 | |
package liquibase.precondition.core; |
| 2 | |
|
| 3 | |
import liquibase.changelog.ChangeSet; |
| 4 | |
import liquibase.changelog.DatabaseChangeLog; |
| 5 | |
import liquibase.database.Database; |
| 6 | |
import liquibase.database.DatabaseConnection; |
| 7 | |
import liquibase.exception.DatabaseException; |
| 8 | |
import liquibase.exception.PreconditionErrorException; |
| 9 | |
import liquibase.exception.PreconditionFailedException; |
| 10 | |
import liquibase.exception.ValidationErrors; |
| 11 | |
import liquibase.exception.Warnings; |
| 12 | |
import liquibase.executor.ExecutorService; |
| 13 | |
import liquibase.precondition.Precondition; |
| 14 | |
import liquibase.statement.core.RawSqlStatement; |
| 15 | |
|
| 16 | 8 | public class SqlPrecondition implements Precondition { |
| 17 | |
|
| 18 | |
private String expectedResult; |
| 19 | |
private String sql; |
| 20 | |
|
| 21 | |
public String getExpectedResult() { |
| 22 | 0 | return expectedResult; |
| 23 | |
} |
| 24 | |
|
| 25 | |
public void setExpectedResult(String expectedResult) { |
| 26 | 0 | this.expectedResult = expectedResult; |
| 27 | 0 | } |
| 28 | |
|
| 29 | |
public String getSql() { |
| 30 | 0 | return sql; |
| 31 | |
} |
| 32 | |
|
| 33 | |
public void setSql(String sql) { |
| 34 | 0 | this.sql = sql; |
| 35 | 0 | } |
| 36 | |
|
| 37 | |
@Override |
| 38 | |
public Warnings warn(Database database) { |
| 39 | 0 | return new Warnings(); |
| 40 | |
} |
| 41 | |
|
| 42 | |
@Override |
| 43 | |
public ValidationErrors validate(Database database) { |
| 44 | 0 | return new ValidationErrors(); |
| 45 | |
} |
| 46 | |
|
| 47 | |
@Override |
| 48 | |
public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) |
| 49 | |
throws PreconditionFailedException, PreconditionErrorException { |
| 50 | 0 | DatabaseConnection connection = database.getConnection(); |
| 51 | |
try { |
| 52 | 0 | String result = (String) ExecutorService.getInstance().getExecutor(database) |
| 53 | |
.queryForObject(new RawSqlStatement(getSql().replaceFirst(";$", "")), String.class); |
| 54 | 0 | if (result == null) { |
| 55 | 0 | throw new PreconditionFailedException("No rows returned from SQL Precondition", changeLog, this); |
| 56 | |
} |
| 57 | |
|
| 58 | 0 | if (!expectedResult.equals(result)) { |
| 59 | 0 | throw new PreconditionFailedException("SQL Precondition failed. Expected '" + expectedResult |
| 60 | |
+ "' got '" + result + "'", changeLog, this); |
| 61 | |
} |
| 62 | |
|
| 63 | 0 | } catch (DatabaseException e) { |
| 64 | 0 | throw new PreconditionErrorException(e, changeLog, this); |
| 65 | 0 | } |
| 66 | 0 | } |
| 67 | |
|
| 68 | |
@Override |
| 69 | |
public String getName() { |
| 70 | 8 | return "sqlCheck"; |
| 71 | |
} |
| 72 | |
} |