Flyway for DB

本文详细介绍了如何使用Flyway和H2数据库进行数据库迁移的过程,包括下载安装所需组件、配置文件设置、创建迁移脚本等关键步骤。通过实践示例,读者可以轻松掌握数据库迁移的基本操作。

Flyway for DB

1. Command Tool
1.1 Command Tool with H2 DB demo
Find and download the flyway-commandline-2.3.zip, unzip and put it in the working directory.
>cd /opt/flyway
>cd jars
>wget http://repo1.maven.org/maven2/com/h2database/h2/1.3.170/h2-1.3.170.jar

Just download the driver and place them in the jars directory

Just use H2 for demo, set up the configuration file like this
>vi conf/flyway.properties
flyway.url=jdbc:h2:file:./foobardb
flyway.user=SA

Put the first SQL migration under sql
>vi sql/V1__Create_person_table.sql
create table PERSON (        ID int not null,        NAME varchar(100) not null );

The first letter should be V, can not be v.

>./flyway migrate
/opt/local/bin/tput Flyway (Command-line Tool) v.2.3 Current version of schema "PUBLIC": << Empty Schema >> Migrating schema "PUBLIC" to version 1 Successfully applied 1 migration to schema "PUBLIC" (execution time 00:00.104s).

Adding a second migration
sparkworker1:flyway carl$ cat sql/V2__Add_people.sql insert into PERSON (ID, NAME) values (1, 'Axel'); insert into PERSON (ID, NAME) values (2, 'Mr. Foo'); insert into PERSON (ID, NAME) values (3, 'Ms. Bar');

1.2 Let us play with MySql
Download the jar from the official website
>wget http://cdn.mysql.com/Downloads/Connector-J/mysql-connector-java-5.1.29.tar.gz
Find and place the jar mysql-connector-java-5.1.29-bin.jar  under the jars directory.

Edit the configuration file
>vi conf/flyway.properties
flyway.url=jdbc:mysql://localhost:3306/test
flyway.user=root
flyway.password=

>flyway migrate

There are a lot of other command parameters I can use. For example, clean, migrate, validate, info, repair

2. Flyway DB for SBT
First of all, if I want to use flyway plugin, I need to update my sbt version to 1.13.0 to support the latest version.
Check this file 
>cat project/build.properties sbt.version=0.13.0

And update the version of my other plugins to support the sbt 0.13
>cat project/plugins.sbt addSbtPlugin("com.googlecode.flyway" % "flyway-sbt" % "2.3") resolvers += "Flyway" at "http://flywaydb.org/repo" addSbtPlugin("io.spray" % "sbt-revolver" % "0.7.1") addSbtPlugin("com.eed3si9n" % "sbt-assembly" % "0.10.2") addSbtPlugin("com.typesafe.sbt" % "sbt-scalariform" % "1.3.0") addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "2.2.0") resolvers += "Sonatype snapshots" at "http://oss.sonatype.org/content/repositories/snapshots/" addSbtPlugin("com.github.mpeltonen" % "sbt-idea" % "1.5.0-SNAPSHOT")

Check the build.sbt to make sure the flyway configuration
import com.googlecode.flyway.sbt.FlywayPlugin._
//flyway start
seq(flywaySettings: _*)

flywayUrl := "jdbc:h2:~/demo_test;DB_CLOSE_DELAY=-1"

flywayUser := "sa"

flywayPassword := "password"

//flyway end

And place the migration files in the directory like these>

src/main/resources/db/migration/V1__Create_person_table.sql
src/main/resources/db/migration/V2__Add_people.sql

create table PERSON (
    ID int not null,
    NAME varchar(100) not null
);

insert into PERSON (ID, NAME) values (1, 'Axel');
insert into PERSON (ID, NAME) values (2, 'Mr. Foo');
insert into PERSON (ID, NAME) values (3, 'Ms. Bar');

Run the command to migrate the DB
>sbt flywayMigrate

There are also other commands flywayClean, flywayInit, flywayMigrate, flywayValidate, flywayInfo, flywayRepair

References:
http://flywaydb.org/getstarted/firststeps/commandline.html

http://flywaydb.org/getstarted/firststeps/sbt.html

http://flywaydb.org/documentation/sbt/


<think>我们正在讨论的是如何在Solon框架中集成Flyway进行数据库迁移。根据之前的引用内容,用户可能遇到了Flyway的校验和错误(Migration checksum mismatch)的问题,并且希望了解如何在Solon中正确使用Flyway。 步骤: 1. 添加Flyway依赖 2. 配置Flyway(数据源、迁移脚本位置等) 3. 执行迁移(通常在应用启动时) 4. 处理常见问题(如校验和错误) 注意:Solon是一个轻量级Java开发框架,因此我们可以使用FlywayJava API或者通过Solon的插件机制来集成。 根据引用[^1][^2][^3][^4],我们知道Flyway在校验和错误时通常是因为已经执行过的迁移脚本被修改,导致Flyway检测到脚本的checksum与元数据表中记录的不一致。解决方式有两种: a. 修复元数据表中的checksum(通过flyway:repair命令或手动更新) b. 重新创建数据库(开发环境) c. 使用-outOfOrder参数(但需谨慎) 但是,我们的重点是如何在Solon中集成Flyway。 下面将详细介绍集成步骤:</think>### Solon 框架中集成 Flyway 实现数据库迁移 #### 一、核心步骤 1. **添加依赖** 在 `pom.xml` 中添加 Flyway 和 Solon JDBC 依赖: ```xml <dependency> <groupId>org.flywaydb</groupId> <artifactId>flyway-core</artifactId> <version>9.22.0</version> </dependency> <dependency> <groupId>org.noear</groupId> <artifactId>solon-jdbc</artifactId> </dependency> ``` 2. **配置数据源** 在 `app.yml` 中配置数据库连接: ```yaml jdbc: default: url: jdbc:mysql://localhost:3306/db_demo username: root password: 123456 driverClassName: com.mysql.cj.jdbc.Driver ``` 3. **创建迁移脚本** 在 `resources/db/migration` 目录下创建 SQL 脚本(命名规则:`V{版本}__{描述}.sql`): ```sql -- V1.0__create_user_table.sql CREATE TABLE user ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(100) NOT NULL ); ``` 4. **初始化 Flyway** 在 Solon 启动类中集成 Flyway: ```java @Configuration public class App { public static void main(String[] args) { Solon.start(App.class, args, app -> { // 获取数据源 DataSource dataSource = app.cfg().getBean(DataSource.class); // 配置 Flyway Flyway flyway = Flyway.configure() .dataSource(dataSource) .locations("db/migration") .load(); // 执行迁移 flyway.migrate(); }); } } ``` #### 二、常见问题解决 1. **校验和错误(Checksum Mismatch)** 当已执行的 SQL 脚本被修改时,Flyway 会报错: `Validate failed: Migration checksum mismatch for migration version` **解决方案**: - **修复元数据**(开发环境): ```java flyway.repair(); // 重置元数据校验和 ``` - **手动更新**(生产环境): ```sql UPDATE flyway_schema_history SET checksum = -1934991199 -- 新校验和(通过flyway.info()获取) WHERE version = '1.0'; ``` 2. **乱序执行迁移** 允许非连续版本迁移(慎用于生产环境): ```java Flyway.configure() .outOfOrder(true) // 启用乱序执行 .load() .migrate(); ``` #### 三、最佳实践 1. **版本管理** - 使用语义化版本:`V1.0.1__add_email_column.sql` - 禁止修改已部署的脚本(需新增版本修复) 2. **多环境配置** 在 `app.yml` 中区分环境: ```yaml # 开发环境 jdbc.default.url: "jdbc:h2:mem:test" # 生产环境(通过 -Dprofile=prod 激活) jdbc.prod: url: "jdbc:mysql://prod-db:3306/app" ``` 3. **与 Solon 热更新结合** 通过 `@RefreshScope` 实现配置动态更新: ```java @Bean @RefreshScope public DataSource dataSource(@Value("${jdbc.default}") HikariDataSource ds) { return ds; } ``` > **迁移原理**:Flyway 通过 `flyway_schema_history` 表记录迁移状态,每次启动时对比文件校验和决定是否执行新脚本[^1][^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值