01: package liquibase.preconditions;
02:
03: import liquibase.DatabaseChangeLog;
04: import liquibase.database.Database;
05: import liquibase.exception.PreconditionFailedException;
06:
07: import java.sql.ResultSet;
08: import java.sql.SQLException;
09: import java.sql.Statement;
10:
11: public class SqlPrecondition implements Precondition {
12:
13: private String expectedResult;
14: private String sql;
15:
16: public String getExpectedResult() {
17: return expectedResult;
18: }
19:
20: public void setExpectedResult(String expectedResult) {
21: this .expectedResult = expectedResult;
22: }
23:
24: public String getSql() {
25: return sql;
26: }
27:
28: public void setSql(String sql) {
29: this .sql = sql;
30: }
31:
32: public void check(Database database, DatabaseChangeLog changeLog)
33: throws PreconditionFailedException {
34: Statement statement = null;
35: ResultSet resultSet = null;
36: try {
37: statement = database.getConnection().createStatement();
38: resultSet = statement.executeQuery(getSql());
39: if (!resultSet.next()) {
40: throw new PreconditionFailedException(
41: "No rows returned from SQL Precondition",
42: changeLog, this );
43: }
44: String returnString = resultSet.getString(1);
45: if (resultSet.next()) {
46: throw new PreconditionFailedException(
47: "Too Many rows returned from SQL Precondition",
48: changeLog, this );
49: }
50:
51: if (!expectedResult.equals(returnString)) {
52: throw new PreconditionFailedException(
53: "SQL Precondition failed. Expected '"
54: + expectedResult + "' got '"
55: + returnString + "'", changeLog, this );
56: }
57:
58: } catch (SQLException e) {
59: throw new PreconditionFailedException(
60: "Error executing SQL precondition: "
61: + e.getMessage(), changeLog, this );
62: } finally {
63: try {
64: if (resultSet != null) {
65: resultSet.close();
66: }
67: } catch (SQLException e) {
68: ;
69: }
70: try {
71: if (statement != null) {
72: statement.close();
73: }
74: } catch (SQLException e) {
75: ;
76: }
77: }
78: }
79:
80: public String getTagName() {
81: return "sqlCheck";
82: }
83: }
|