Flyway 检查数据库是否存在并在 java 中建立基线

Flyway check if database exists and was baselined in java

我正在尝试在我的网络应用程序中使用 Flyway。我已阅读文档,但找不到以下问题的答案:

是否可以在运行宁migrate之前检查数据库是否baselined

Web 应用程序已使用大型数据库。所以我需要 运行 baseline 。我希望应用程序在启动时 运行 baseline and/or migrate。如果数据库不存在,则应创建该数据库;如果存在,则应为 baselined,但之前不是 baselined

我已经在迁移包中添加了 3 个 SQL 个文件:

V4_0_0__schema.sql
V4_0_1__index.sql
V4_0_2__initial_inserts.sql

我想这样做:

DataSource dataSource = new MysqlDataSource();
String[] locations = {"path/to/location"};

Flyway flyway = new Flyway();
flyway.setCleanDisabled(true);
flyway.setLocations(locations);
flyway.setDataSource(dataSource);

if (databaseExists()) { // how to determine that the db already exists?
    if (databaseWasBaselined() == false) { // How to check this?
        flyway.setBaselineVersion(MigrationVersion.LATEST); // will this set the version to 4_0_2?
        flyway.baseline();
    }
}
flyway.migrate();

我需要一点帮助才能以正确的方式进行。我希望有人能指出我正确的方向。

使用 baselineOnMigrate 选项,如 Flyway site 中所述:

Whether to automatically call baseline when migrate is executed against a non-empty schema with no metadata table. This schema will then be baselined with the baselineVersion before executing the migrations. Only migrations above baselineVersion will then be applied.

This is useful for initial Flyway production deployments on projects with an existing DB.

Be careful when enabling this as it removes the safety net that ensures Flyway does not migrate the wrong database in case of a configuration mistake!