【问题标题】:How to do partial migration in Flyway for testing?如何在 Flyway 中进行部分迁移以进行测试?
【发布时间】:2020-08-31 12:24:55
【问题描述】:

我正在尝试编写一个测试来验证我的新迁移脚本(位于 src/main/resources/db/migration)是否在我的 Postgres DB 中的现有数据上正确执行。

我有 5 个迁移脚本,其中第 2 个创建包含一些列的初始 Users 表,第 5 个添加到现有的 Users 表中,并为该新列添加一个新列和默认值。

首先,我想只迁移到脚本,使Users表的初始版本,然后我会正常填充它,最后通过运行第5个脚本完成迁移,然后检查是否第 5 个脚本实际上是否更新了现有数据。但是,我不明白如何只迁移到某个版本,然后再迁移到其余版本...

这是我目前所拥有的:

实际测试

@RunWith(SpringRunner.class)
@SpringBootTest
class MigrationTest extends ComponentTest {

  private static final String USER_ID = "1337";

  @Autowired
  private InitialUserRepository initialUserRepository;
  @Autowired
  private UserRepository userRepository;

  @Autowired
  private Flyway flyway;

  @Transactional
  @Test
  public void test() {

    flyway.baseline(); // default 1
    flyway.migrate(); // this will migrate to the final script/version where it will add the new column
    // replace the above line, flyway.migrate(), with a partial migration to version 2 ONLY, something like flyway.migrate(2)

    var initialUserMappingEntity = new InitialUserMappingEntity(USER_ID, "some other data");
    initialUserRepository.saveAndFlush(initialUserMappingEntity);

    var user = initialUserRepository.findById(USER_ID);
    assertTrue(user.isPresent());

    // complete the full migration here, something like flyway.migrate(5)

    var updatedUser = userRepository.findById(USER_ID);
    assertTrue(updatedUser.isPresent());
    assertNotNull(updatedUser.get().getNewColumn());
  }
}

EmptyMigrationStrategyConfig

@Configuration
public class EmptyMigrationStrategyConfig {

  @Bean
  public FlywayMigrationStrategy flywayMigrationStrategy() {
    return flyway -> {
      // do nothing
    };
  }
}

application-test.yaml

spring:
  flyway:
    locations: classpath:/db/migration

【问题讨论】:

    标签: java flyway


    【解决方案1】:

    您正在寻找flyway.target 选项(API 中的.target())。见https://flywaydb.org/documentation/commandline/migrate#target

    此配置参数设置要迁移到的版本。因此,如果您有 3 个迁移 V1__, v2__, v3__ 使用 flyway.target=2 仅迁移 V1__v2__

    【讨论】:

      【解决方案2】:

      最后我换了

      var initialUserMappingEntity = new InitialUserMappingEntity(USER_ID, "some other data");
      initialUserRepository.saveAndFlush(initialUserMappingEntity);
      

      插入脚本位于:/db/testdata/V2.1__insert_user_data.sql 然后只做了一次迁移,直到结束。

      因此,您基本上需要在您要在 /db/migration 中测试的最终脚本之前添加一个插入脚本,然后修改您的 spring.flyway.locations 以具有这两个基本路径

      【讨论】:

        猜你喜欢
        • 2023-03-13
        • 2015-08-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-08-11
        • 2021-02-02
        • 2015-12-28
        • 2018-11-26
        相关资源
        最近更新 更多