一锅必、下載flyway
官網(wǎng)地址:https://flywaydb.org/
以下演示的所有示例都是
Community Flyway
版本,版本區(qū)別詳見https://flywaydb.org/download/
二践叠、簡述
Flyway是一個(gè)開源數(shù)據(jù)庫遷移工具,引用官言就是:
Flyway is an open-source database migration tool
而且它基于 7 個(gè)基本命令登钥,分別如下:
-
Migrate
(遷移):將schema更新到最新的版本并且如果不存在flyway_schema_history
表就會(huì)創(chuàng)建一個(gè)。
它是flyway工作流程的核心。它將掃描文件系統(tǒng)或您的類路徑以獲取可用的遷移。它將它們與已應(yīng)用于數(shù)據(jù)庫的遷移進(jìn)行比較豺撑,如果發(fā)現(xiàn)任何差異,它將遷移數(shù)據(jù)庫以縮小差距黔牵。 -
clean(刪除)
:刪除已配置的schema中所有對(duì)象聪轿,當(dāng)然,不要對(duì)生產(chǎn)DB操作猾浦,畢竟有點(diǎn)類似刪庫跑路陆错。。金赦。 -
info(信息)
:打印所有的Migration的信息音瓷,包含狀態(tài),通過info可以知道哪些Migration已經(jīng)應(yīng)用了素邪,哪些處于pending
狀態(tài) -
Validate(驗(yàn)證)
:驗(yàn)證將要更新的migrations是否與已更新的migration有沖突外莲,有點(diǎn)類似于代碼合并時(shí)git會(huì)檢查是否有沖突 -
Undo(撤銷)
:撤消最近應(yīng)用的版本遷移⊥秒可指定撤銷的最終版本偷线。
-BaseLine
(基準(zhǔn)線):相對(duì)于Migrate
來說,它不再是從最初開始遷移沽甥,而是先將某數(shù)據(jù)庫作為基準(zhǔn)線声邦,然后遷移相對(duì)此數(shù)據(jù)庫還未更新的migrations -
repaire
(修復(fù)):修復(fù)flyway_schema_history
表
三、命令行工具嘗試
在第一步中下載了flyway后摆舟,我們需要先修改一下配置文件flyway.conf
亥曹,修改部分如下:
flyway.url=jdbc:h2:file:./foobardb
上面設(shè)置的是連接一個(gè)內(nèi)存數(shù)據(jù)庫h2
,當(dāng)然也可以設(shè)置成mysql恨诱,但是有點(diǎn)限制:
從上圖可以看出媳瞪,
5.7+
版本的mysql是受flyway所有版本(Community
,Pro
照宝,Enterprise
)支持的,5.6-
版本的mysql只受Flyway Enterprise
版本支持,不過這個(gè)版本是可以試用的蛇受。
我們可以直接用命令行工具嘗試一下一些命令:
migrate
flyway migrate
結(jié)果如下:
Database user:
Database password:
Flyway Community Edition 6.0.7 by Redgate
Database: jdbc:h2:file:./foobardb (H2 1.4)
Successfully validated 1 migration (execution time 00:00.068s)
Creating Schema History table "PUBLIC"."flyway_schema_history" ...
Current version of schema "PUBLIC": << Empty Schema >>
Migrating schema "PUBLIC" to version 1 - Create person table
Successfully applied 1 migration to schema "PUBLIC" (execution time 00:00.124s)
上面的密碼和用戶都留空是因?yàn)閯偛旁谛薷呐渲梦募臅r(shí)候,我并沒有修改用戶和密碼項(xiàng)厕鹃,也就意味著連接時(shí)用戶和密碼都是空,同時(shí)也說明只有url
是必填的兢仰。
info
flyway info
結(jié)果如下:
Database user:
Database password:
Flyway Community Edition 6.0.7 by Redgate
Database: jdbc:h2:file:./foobardb (H2 1.4)
Schema version: 1
+-----------+---------+---------------------+------+---------------------+---------+
| Category | Version | Description | Type | Installed On | State |
+-----------+---------+---------------------+------+---------------------+---------+
| Versioned | 1 | Create person table | SQL | 2019-10-24 14:44:38 | Success |
+-----------+---------+---------------------+------+---------------------+---------+
validate
flyway validate
結(jié)果如下:
F:\flyway\flyway-6.0.7>flyway validate
Database user:
Database password:
Flyway Community Edition 6.0.7 by Redgate
Database: jdbc:h2:file:./foobardb (H2 1.4)
Successfully validated 1 migration (execution time 00:00.118s)
其他的就不一一列舉了,大家可以參考https://flywaydb.org/documentation/command/migrate來操作一下
四剂碴、Java集成
4.1 限制
4.2 依賴
- maven
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>6.0.7</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.199</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
- gradle
compile "org.flywaydb:flyway-core:6.0.7"
compile "com.h2database:h2:1.4.999"
compile "org.springframework.boot:spring-boot-starter"
4.3 項(xiàng)目結(jié)構(gòu)
4.4 示例代碼-FlywayApplication
類
@SpringBootApplication
public class FlywayApplication {
private static Logger log = LoggerFactory.getLogger(FlywayApplication.class);
public static void main(String[] args) {
SpringApplication.run(FlywayApplication.class, args);
Flyway flyway = Flyway.configure().dataSource("jdbc:h2:file:./foobardb","xzl","123456").load();
log.info("數(shù)據(jù)開始遷移======");
flyway.migrate();
log.info("數(shù)據(jù)結(jié)束遷移------");
}
}
4.5 sql
在創(chuàng)建項(xiàng)目的時(shí)候把将,如果一開始就選擇了flyway
組件,那么創(chuàng)建完的項(xiàng)目就會(huì)在resources
目錄下自帶db/migration
文件夾忆矛,flyway在進(jìn)行migrate等操作時(shí)察蹲,默認(rèn)掃描此包下的sql文件,所以在此包下我們可以創(chuàng)建一個(gè)sql文件,但這個(gè)sql文件名不能亂取递览,規(guī)則如下:
文件名由以下部分組成:
-
前綴:
V
用于版本化遷移叼屠,U
撤消遷移,R
可重復(fù)遷移 - 版本:下劃線(在運(yùn)行時(shí)自動(dòng)替換為點(diǎn))可根據(jù)需要分隔任意多個(gè)部分(不適用于可重復(fù)的遷移)
-
分隔符:(__兩個(gè)英文下劃線)
說明:下劃線(在運(yùn)行時(shí)自動(dòng)由空格代替)將單詞分開
如果需要對(duì)類名進(jìn)行更多控制绞铃,則可以通過JavaMigration
直接實(shí)現(xiàn)接口來覆蓋默認(rèn)約定 镜雨。 -
JavaMigratiion
原代碼如下:
public interface JavaMigration {
MigrationVersion getVersion();
String getDescription();
Integer getChecksum();
boolean isUndo();
boolean canExecuteInTransaction();
void migrate(Context var1) throws Exception;
}
默認(rèn)取名規(guī)則是由BaseJavaMigration
這個(gè)抽象類決定的,源代碼如下:
public abstract class BaseJavaMigration implements JavaMigration {
private final MigrationVersion version;
private final String description;
public BaseJavaMigration() {
//獲取sql文件的名稱
String shortName = this.getClass().getSimpleName();
//判斷是否是可重復(fù)遷移
boolean repeatable = shortName.startsWith("R");
//判斷是否是版本化遷移或者可重復(fù)遷移
if (!shortName.startsWith("V") && !repeatable) {
//不滿足條件儿捧,掏出異常
throw new FlywayException("Invalid Java-based migration class name: " + this.getClass().getName() + " => ensure it starts with V or R, or implement org.flywaydb.core.api.migration.JavaMigration directly for non-default naming");
} else {
//獲取前綴--V/R
String prefix = shortName.substring(0, 1);
//獲取Pair對(duì)象荚坞,封裝了version和description
Pair info = MigrationInfoHelper.extractVersionAndDescription(shortName, prefix, "__", new String[]{""}, repeatable);
this.version = (MigrationVersion)info.getLeft();
this.description = (String)info.getRight();
}
}
public MigrationVersion getVersion() {
return this.version;
}
public String getDescription() {
return this.description;
}
public Integer getChecksum() {
return null;
}
public boolean isUndo() {
return false;
}
public boolean canExecuteInTransaction() {
return true;
}
}
通過以上代碼可以發(fā)現(xiàn),明明規(guī)則沒有對(duì)可撤銷遷移操作(U
開頭)文件進(jìn)行判斷菲盾,這是因?yàn)?code>Undo操作至少需要Flyway Pro
版本才能支持颓影,如果您有看過這張表格就會(huì)明白了,我給大家截兩個(gè)小圖看看:
em...把這兩張圖拼一拼就可以了
啟動(dòng)程序懒鉴,結(jié)果如下:
2019-10-24 16:49:56.007 INFO 6432 --- [ main] xzl.xiongzelin.flyway.FlywayApplication : 數(shù)據(jù)開始遷移======
2019-10-24 16:49:56.015 INFO 6432 --- [ main] o.f.c.internal.license.VersionPrinter : Flyway Community Edition 6.0.7 by Redgate
2019-10-24 16:49:56.369 INFO 6432 --- [ main] o.f.c.internal.database.DatabaseFactory : Database: jdbc:h2:file:./foobardb (H2 1.4)
2019-10-24 16:49:56.662 INFO 6432 --- [ main] o.f.core.internal.command.DbValidate : Successfully validated 1 migration (execution time 00:00.082s)
2019-10-24 16:49:56.709 INFO 6432 --- [ main] o.f.core.internal.command.DbMigrate : Current version of schema "PUBLIC": 1.0.0
2019-10-24 16:49:56.713 INFO 6432 --- [ main] o.f.core.internal.command.DbMigrate : Schema "PUBLIC" is up to date. No migration necessary.
2019-10-24 16:49:57.445 INFO 6432 --- [ main] xzl.xiongzelin.flyway.FlywayApplication : 數(shù)據(jù)結(jié)束遷移------
剛才的代碼中只有遷移操作诡挂,不過其他操作也是類似的,大家可以看看Flyway
這個(gè)類的方法临谱,這里就不說明了璃俗。
五、maven啟動(dòng)
5.1 限制
Flyway Community
版本和Flyway Pro
支持Maven 3.x悉默,同時(shí)還要求java
版本在 8+,Flyway Enterprise
支持java 7
5.2 插件
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>6.0.7</version>
</plugin>
5.3 屬性配置
從上面的講解可以知道城豁,屬性url
必須配置,user
和password
可以空著抄课。
配置屬性的幾種方式:
- 在flyway插件下配置
configuration
屬性唱星,如下:
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>6.0.7</version>
<!--配置屬性-->
<configuration>
<user>xzl</user>
<password>123456</password>
<url>jdbc:h2:file:./foobardb</url>
</configuration>
</plugin>
這是最簡單的配置方式,不過它有一個(gè)缺點(diǎn),就是不能配置空值跟磨,否則報(bào)錯(cuò)间聊。
- maven properties,如下:
<properties>
<flyway.url>jdbc:h2:file:./foobardb</flyway.url>
<flyway.user>xzl</flyway.user>
<flyway.password>123456</flyway.password>
<java.version>1.8</java.version>
</properties>
- maven 的setting.xml文件
<settings>
<servers>
<server>
<!-- By default Flyway will look for the server with the id 'flyway-db' -->
<!-- This can be customized by configuring the 'serverId' property -->
<id>flyway-db</id>
<url>jdbc:h2:file:./foobardb</url>
<username>myUser</username>
<password>mySecretPwd</password>
</server>
</servers>
</settings>
- 系統(tǒng)環(huán)境變量
FLYWAY_URL:jdbc:h2:file:./foobardb
FLYWAY_USER:xzl
FLYWAY_PASSWORD:123456
- jvm系統(tǒng)屬性
mvn -Dflyway.url=jdbc:h2:file:./foobardb -Dflyway.user=xzl -Dflyway.password=123456
- 自定義配置文件
文件格式如下,flyway默認(rèn)使用utf-8
加載配置文件:
# These are some example settings
flyway.url=jdbc:mydb://mydatabaseurl
flyway.schemas=schema1,schema2
flyway.placeholders.keyABC=valueXYZ
命令:
mvn -Dflyway.configFiles=path/to/myAlternativeConfig.conf flyway:migrate
- flyway.conf配置文件
Flyway將搜索并自動(dòng)加載<user-home>/flyway.conf配置文件(如果存在)。
加載優(yōu)先順序:
- jvm系統(tǒng)屬性
- 系統(tǒng)環(huán)境變量
- 自定義配置文件
- maven properties
- 配置
configuration
屬性 - maven 的setting.xml文件
- flyway.conf配置文件
- Flyway Maven插件默認(rèn)
這就意味著:flyway.url
如果既存在于jvm
系統(tǒng)屬性又存在于configuration
標(biāo)簽中抵拘,那么JVM系統(tǒng)屬性將具有優(yōu)先權(quán)并被使用甸饱。