liquibase

How do I get result from SQL query in custom liquibase precondition?


I am trying to create a custom precondition as defined in https://docs.liquibase.com/concepts/changelogs/preconditions.html and https://javadocs.liquibase.com/liquibase-core/liquibase/precondition/CustomPrecondition.html

The interface has a void check(Database database) method but I'm not sure how I'm supposed to actually run any checks.

For example, if I wanted to run a sql query select max(len(user_name)) from users against the database and get an Integer result from this, how would I write this within my check method? I can't see anything about this in the docs


Solution

  • check method has Database object as an argument, which has getConnection() method which gets you the connection to the database.

    From here you can make the needed DB query, return a result set and verify it.

    E.g.:

    @Override
    public void check(Database database) throws CustomPreconditionFailedException,
            CustomPreconditionErrorException {
        try (Connection connection = ((JdbcConnection) database.getConnection()).getWrappedConnection();
             Statement statement = connection.createStatement();
             ResultSet resultSet = statement.executeQuery("select max(len(user_name)) from users")) {
            if (resultSet.next()) {
                int count = resultSet.getInt(1);
                // implement your check here
            } else {
                throw new CustomPreconditionFailedException("something went wrong");
            }
        } catch (Exception e) {
            throw new CustomPreconditionErrorException(e.getMessage());
        }
    }