以下简单从技术和应用的角度简单描述一下初步的使用!
Why(我们为什么要使用它?)
官方解释如下:
当你的项目绑定不同的DB版本 ,不同的code分支切换不同的数据库版本的时候可能会遇到一下几个问题。
What state is the database in on this machine?(当前机器里面的数据库是什么状态?)
Has this script already been applied or not?(当前脚本已经在数据库运行了吗?)
Has the quick fix in production been applied in test afterwards?(生产中的快速修复是否已经在测试中应用了?)
How do you set up a new database instance?(你如何设置一个新的数据库实例?)
What(我们使用它做什么?)
很明显主要是做数据库版本管理,那么版本管理管理在哪里呢?,在默认的表里面(flyway_schema_history)如下
不同的版本对应不同的脚本script ,一个很真实的场景是某次线上回滚失败主要由于sql_script回滚不完全,那么如果使用flyway_db 我们只需要确定的写明当前的脚本以及对应的版本就可以了类似如下图:
回滚重未如此简单!(官示)
之外我们怎么去写这个脚本呢,格式很简单管网解释如下:
Each versioned migration must be assigned a unique version. Any version is valid as long as it conforms to the usual dotted notation. For most cases a simple increasing integer should be all you need. However Flyway is quite flexible and all these versions are valid versioned migration versions:
1
001
5.2
1.2.3.4.5.6.7.8.9
205.68
20130115113556
2013.1.15.11.35.56
2013.01.15.11.35.56
Versioned migrations are applied in the order of their versions. Versions are sorted numerically as you would normally expect.
换句话说版本号V只要是个可以比较大小的数就可以了,但是通常情况下一般用整数
以上解释同时也说明了启动原理,默认排序脚本依次启动,这里就涉及到一个启动失败的问题如何处理?
When the migration succeeds it is marked as success in Flyway’s schema history table.
When the migration fails and the database supports DDL transactions, the migration is rolled back and nothing is recorded in the schema history table.
When the migration fails and the database doesn’t supports DDL transactions, the migration is marked as failed in the schema history table, indicating manual database cleanup may be required.
大概意思是如果迁移失败分情况,如果对应数据库不支持DDL事务,迁移标记为失败在表中记录,状态标记为失败,如果支持事务则执行回滚,表中不添加任何记录,控制台可以捕获到信息。
How(我们如何去做?)
步骤很简单如下:
1
首先需要导入flyway_db的核心包,具体版本
2
导入数据库驱动(也可以使用Druid,阿里巴巴的驱动底层也是调的java.sql.connection操作的数据库包括数据库回滚操作,所以druid内涵这个包)可以从这个码TransactionIntercepter类开始看源码
3
创建初始化脚本以及其他需求脚本等如下
4
启动脚本查看结果如下:
1-1
1-2
1-3
补充:
图1-1,1-2,1-3 的migration structure 为 如下:
PS: At the time ,new branch need some newly function~
比如我又不要原来的test_field字段了,需要加入新的字段,则需要加入如下脚本:
Now we gonna to start here , the results as follows :
It’s pretty clearly to see the right results ,We have succeeded to convert test_field into test_field_another
可以看到我的命名特点
We can see what’s happened inner flyway_db_history_scheme table ?
V2.2 is behind with V2 on version ,Its’ has been valitated the concept of home web site.
Who(谁去做?)
按先阶段公司情况,建议运维操作和维护环境内部结构,开发编写sql_script由各自项目code owner审核。
注意一个点,常见的flyway_db异常一般的解决方案是删除对应异常栈指定的版本迁移对应记录重启,也是官网推荐。