关于Java:如何使用Flyway回滚迁移?

How to roll back migrations using Flyway?

MyBatis迁移将每个SQL文件分为两部分:

  • 一种用于向前迁移一个版本
  • 一个用于迁移回一个版本
  • 如何使用Flyway回滚版本?


    尽管Flyway支持回滚(仅作为商业功能),但不鼓励使用它:

    https://flywaydb.org/documentation/command/undo

    While the idea of undo migrations is nice, unfortunately it sometimes breaks down in practice. As soon as you have destructive changes (drop, delete, truncate, …), you start getting into trouble. And even if you don’t, you end up creating home-made alternatives for restoring backups, which need to be properly tested as well.

    Undo migrations assume the whole migration succeeded and should now be undone. This does not help with failed versioned migrations on databases without DDL transactions. Why? A migration can fail at any point. If you have 10 statements, it is possible for the 1st, the 5th, the 7th or the 10th to fail. There is simply no way to know in advance. In contrast, undo migrations are written to undo an entire versioned migration and will not help under such conditions.

    An alternative approach which we find preferable is to maintain backwards compatibility between the DB and all versions of the code currently deployed in production. This way a failed migration is not a disaster. The old version of the application is still compatible with the DB, so you can simply roll back the application code, investigate, and take corrective measures.

    This should be complemented with a proper, well tested, backup and restore strategy. It is independent of the database structure, and once it is tested and proven to work, no migration script can break it. For optimal performance, and if your infrastructure supports this, we recommend using the snapshot technology of your underlying storage solution. Especially for larger data volumes, this can be several orders of magnitude faster than traditional backups and restores.


    从Flyway 5.0开始支持。可悲的是,这只是商业用途。

    https://flywaydb.org/documentation/command/undo


    我假设您需要一个回滚策略,例如一个合作伙伴在生产阶段失败,并且他的部署对于您的发布至关重要。

    您可以像这样命名您的flyway SQL脚本:
    V .000_ <描述> .sql

    现在你可以离开
    V .998_rollback.sql用于回滚
    并使V .999_reenroll.sql重新注册。

    在CI / CD环境中,在部署作业之后,您还需要再执行2个作业(手动触发)。一种用于回滚,运行回滚过程,包括飞行路线迁移。其他重新注册。
    您只需要关心飞行通道中的目标配置即可。
    对于您的部署工作,您的目标应为 .997
    对于您的回滚作业 .998

    开始新发行版时,请确保您不会运行旧发行版的回滚/重新注册脚本。

    如前所述,在经过充分测试之前,建议您使用备份和还原策略。

    (不好意思的英语)


    我发现执行此操作的最佳方法是清除数据库,然后向前迁移到要还原到的特定版本。

    正如FAQ所建议的那样,回滚脚本在理论上是不错的,但是某些迁移只是无法回滚。 (例如,如果删除了表,则恢复表DDL很容易,但是恢复其中包含的数据可能很困难。)