ReplaceCustomChange: assume auto commit off during Liquibase-Changeset

This commit is contained in:
Michael Hoennig 2019-05-06 18:20:10 +02:00
parent 1284c2acaa
commit 295e45e8b8
2 changed files with 20 additions and 2 deletions

View File

@ -1,6 +1,8 @@
// Licensed under Apache-2.0
package org.hostsharing.hsadminng.liquibase;
import static com.google.common.base.Verify.verify;
import liquibase.change.custom.CustomTaskChange;
import liquibase.database.Database;
import liquibase.database.jvm.JdbcConnection;
@ -28,7 +30,7 @@ public class ReplaceCustomChange implements CustomTaskChange {
final JdbcConnection conn = (JdbcConnection) database.getConnection();
final boolean isH2 = "H2".equals(database.getDatabaseProductName());
try {
conn.setAutoCommit(false);
verify(!conn.getAutoCommit(), "assuming auto commit to be off in Liquibase changeset");
final Statement statement = conn.createStatement();
for (String columnName : columnNames.split(",")) {
final String sql = "UPDATE " + tableName + " SET " + columnName + "= replace(" + columnName + ", '" + searchFor
@ -36,7 +38,6 @@ public class ReplaceCustomChange implements CustomTaskChange {
(isH2 ? "STRINGDECODE('" + replaceWith + "')" : "E'" + replaceWith + "'") + ")";
statement.executeUpdate(sql);
}
conn.commit();
} catch (DatabaseException | SQLException e) {
throw new CustomChangeException("cannot perform search&replace", e);
}

View File

@ -13,6 +13,8 @@ import liquibase.exception.CustomChangeException;
import liquibase.exception.DatabaseException;
import liquibase.exception.SetupException;
import com.google.common.base.VerifyException;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
@ -43,6 +45,7 @@ public class ReplaceCustomChangeUnitTest {
@Before
public void initMocks() throws DatabaseException {
given(database.getConnection()).willReturn(connection);
given(connection.getAutoCommit()).willReturn(false);
given(connection.createStatement()).willReturn(statement);
}
@ -86,6 +89,20 @@ public class ReplaceCustomChangeUnitTest {
assertThat(actual).isEqualTo("in table some_table / columns address,remark: replaced all '|' to '\\n'");
}
@Test
public void throwsValidationErrorIfAutoCommitIsOff() throws Exception {
// given
given(database.getDatabaseProductName()).willReturn(POSTGRES_DATABASE_PRODUCT_NAME);
final ReplaceCustomChange replaceCustomChange = givenReplaceCustomChange("some_table", "address,remark", "|", "\\n");
given(connection.getAutoCommit()).willReturn(true);
// when
final Throwable actual = catchThrowable(() -> replaceCustomChange.execute(database));
// then
assertThat(actual).isInstanceOf(VerifyException.class);
}
@Test
public void onDatabaseExceptionThrowsCustomChangeException() throws Exception {
// given