package liquibase.precondition.core;

import liquibase.changelog.DatabaseChangeLog;
import liquibase.changelog.ChangeSet;
import liquibase.database.Database;
import liquibase.database.DatabaseConnection;
import liquibase.exception.*;
import liquibase.executor.ExecutorService;
import liquibase.precondition.Precondition;
import liquibase.statement.core.RawSqlStatement;

public class SqlPrecondition implements Precondition {

    private String expectedResult;
    private String sql;


    public String getExpectedResult() {
        return expectedResult;
    }

    public void setExpectedResult(String expectedResult) {
        this.expectedResult = expectedResult;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

    public Warnings warn(Database database) {
        return new Warnings();
    }

    public ValidationErrors validate(Database database) {
        return new ValidationErrors();
    }

    public void check(Database database, DatabaseChangeLog changeLog, ChangeSet changeSet) throws PreconditionFailedException, PreconditionErrorException {
        DatabaseConnection connection = database.getConnection();
        try {
            String result = (String) ExecutorService.getInstance().getExecutor(database).queryForObject(new RawSqlStatement(getSql().replaceFirst(";$","")), String.class);
            if (result == null) {
                throw new PreconditionFailedException("No rows returned from SQL Precondition", changeLog, this);
            }

            if (!expectedResult.equals(result)) {
                throw new PreconditionFailedException("SQL Precondition failed.  Expected '"+expectedResult+"' got '"+result+"'", changeLog, this);
            }

        } catch (DatabaseException e) {
            throw new PreconditionErrorException(e, changeLog, this);
        }
    }

    public String getName() {
        return "sqlCheck";
    }
}

@@ -820,32 +820,47 @@
  sql;%0D%0A    %7D%0D%0A%0D%0A
+    @Override%0D%0A
     public Warni
@@ -923,32 +923,47 @@
 gs();%0D%0A    %7D%0D%0A%0D%0A
+    @Override%0D%0A
     public Valid
@@ -1046,32 +1046,47 @@
 rs();%0D%0A    %7D%0D%0A%0D%0A
+    @Override%0D%0A
     public void 
@@ -1640,32 +1640,90 @@
            %7D%0D%0A%0D%0A
+            String expectedResult = getExpectedResult();%0D%0A
             if (
@@ -1850,16 +1850,17 @@
 cted '%22+
+ 
 expected
@@ -1865,16 +1865,17 @@
 edResult
+ 
 +%22' got 
@@ -2049,32 +2049,47 @@
     %7D%0D%0A    %7D%0D%0A%0D%0A
+    @Override%0D%0A
     public Strin

check method should use getExpectedResult() method for better overriding