当前位置:网站首页>Flyway's quick start tutorial
Flyway's quick start tutorial
2022-07-29 00:26:00 【web18484626332】
Catalog
3、 ... and 、flyway How it works
1、 First initialize a SpringBoot project , Introduce dependencies
2、 stay application.yml Add the relevant configuration
3、 According to the script storage path filled in the configuration file , Create folder
5、 Start project , adopt flyway Execute the defined script
5、 ... and 、maven Use of plug-ins
2、 Plug in command description
6、 ... and 、flyway Knowledge supplement
7、 ... and 、flyway Configuration list
One 、 Brief introduction
Flyway Is an open source database version management tool . It can be easily used on the command line , Or in Java Introduction in application , Used to manage our database version .
In a project or product , It's hard to sort out the business at the beginning , Design the database table , Therefore, the data table will continue to iterate in the iteration cycle . stay Java Used in applications Flyway, It can be used to iterate database table structure quickly and effectively , And ensure that when deployed to the test environment or production environment , The data tables are consistent .
flyway Official documents [ Here is the picture 001]https://flywaydb.org/documentation/
Two 、 Why use flyway
In projects developed by many people , We are all used to using SVN perhaps Git To version control the code , The main purpose is to solve the problems of code conflict and version fallback in multi person development .
Actually , Database changes also require version control , In daily development , We often encounter the following problems :
- His writing SQL Forget to perform in all environments .
- Someone else wrote SQL We're not sure if it's all done in all environments .
- Someone has modified what has been executed SQL, Expect to execute again .
- New environment is needed for data migration .
- Every time you send a version, you need to control it manually DB edition , Then release the app version .
- Other scenes .
With flyway, These problems can be well solved .
3、 ... and 、flyway How it works
flyway The workflow is as follows :
- Project start , After the application completes the establishment of the database connection pool ,Flyway Automatic operation .
- First use ,flyway Will create a flyway_schema_history surface , Used to record sql Execution records .
- Flyway Will scan the project under the specified path ( The default is classpath:db/migration) All of the sql Script , And flyway_schema_history Table script records . If the database records the scripts that have been executed , And the... In the project sql The script is inconsistent ,Flyway Error will be reported and project execution will be stopped .
- If the verification passes , According to sql Record the maximum version number , Ignore all scripts with a version number no greater than that version . Then according to the version number from small to large , Execute the rest of the scripts one by one .
Four 、 How to use flyway
notes : The following is the source code corresponding to the content of this article , You can download and test by yourself , You only need to modify the corresponding database account password configuration . If it helps you , Please give me a compliment or star, Your encouragement , It's my motivation to update .
flyway Use sample code [ Here is the picture 002]https://github.com/wangming2674/flyway-use-demo
1、 First initialize a SpringBoot project , Introduce dependencies
The version I use is 2.3.5.RELEASE, introduce mysql、mybatis、flyway Such dependence ,pom.xml The contents of the document are as follows :
<properties>
<java.version>1.8</java.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<mysql.version>8.0.25</mysql.version>
<mybatis-starter.version>2.2.1</mybatis-starter.version>
<flyway.version>6.1.0</flyway.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
<version>${mysql.version}</version>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>${mybatis-starter.version}</version>
</dependency>
<dependency>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-core</artifactId>
<version>${flyway.version}</version>
</dependency>
</dependencies>
2、 stay application.yml Add the relevant configuration
spring:
# Database connection configuration
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/flyway-demo?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
username: root
password: root
flyway:
# Is it enabled? flyway
enabled: true
# Coding format , Default UTF-8
encoding: UTF-8
# transfer sql Script file storage path , Default db/migration
locations: classpath:db/migration
# transfer sql Prefix of script file name , Default V
sql-migration-prefix: V
# transfer sql Separator for script file name , Default 2 Underscores __
sql-migration-separator: __
# transfer sql The suffix of the script file name
sql-migration-suffixes: .sql
# Check when migrating , Default true
validate-on-migrate: true
# When the migration finds that the database is not empty and there are tables without metadata , Automate baseline migration , newly build schema_version surface
baseline-on-migrate: true
3、 According to the script storage path filled in the configuration file , Create folder
According to the script storage path in the above configuration file , We need to be in resource Create folder under directory db/migration .
4、 Add the to run sql Script .sql The naming of scripts must be standardized , Otherwise run flyway Will report a mistake
There are two main naming rules :
- That only needs to be executed once SQL Name it in uppercase "V" start ,V+ Version number ( The number of version number is marked with ”.“ or ”_“ Separate )+ Double underline ( Used to separate version numbers and descriptions )+ File description + Suffix name . for example :V20201100__create_user.sql、V2.1.5__create_user_ddl.sql、V4.1_2__add_user_dml.sql.
- Repeatable SQL, In capital letters “R” start , Then split it with two underscores , Followed by the name of the file , Finally .sql ending .( It is not recommended to use ) such as :R__truncate_user_dml.sql.
among ,V At the beginning SQL Execution priority is higher than R At the beginning SQL High priority .
After creation , The catalogue should be as follows :
among 2.1.6、2.1.7 and every The folder of will not affect flyway Yes SQL Identification and operation of , You can name and classify yourself .

5、 Start project , adopt flyway Execute the defined script
Relevant log printing can be seen on the console , And check the created tables and related record changes in the database .


6、 Note
If we modify V2__add_user.sql The content in , If you do it again , You're going to report a mistake , The message is as follows :
[ERROR] Migration checksum mismatchformigration version 2
If we modify R__add_unknown_user.sql, If you do it again , The script will be executed again , also flyway The record of this execution will also be added to the history table of .
5、 ... and 、maven Use of plug-ins
1、 Configuration plug-ins
In the above steps , Every time I want migration Need to run the whole springboot project , And can only execute migrate A command , Actually flyway There are still many other commands .maven The plug-in gives us the ability to execute without starting the project flyway Opportunities for various orders .
stay pom.xml Introduction in flyway Plug in for , At the same time, configure the corresponding database connection .
<build>
<plugins>
<plugin>
<groupId>org.flywaydb</groupId>
<artifactId>flyway-maven-plugin</artifactId>
<version>5.2.4</version>
<configuration>
<url>jdbc:mysql://localhost:3306/flyway-demo?characterEncoding=utf-8&useSSL=false&serverTimezone=Asia/Shanghai
</url>
<user>root</user>
<password>root</password>
<driver>com.mysql.cj.jdbc.Driver</driver>
</configuration>
</plugin>
</plugins>
</build>

2、 Plug in command description
here , We double-click to execute flyway:migrate Effect and start the whole project implementation migrate The effect is the same .
The functions of other commands are as follows :
baseline
Yes, the database already exists Schema Structured database is a solution . Realize new creation in non empty database MetaData surface , And put Migrations Apply to the database ; It can also be added in the database with existing table structure Metadata surface .
clean
Clear the corresponding database Schema All the objects in , Including table structure , View , Stored procedure, etc ,clean Operation in dev and test The stage is very easy to use , But it must be disabled in the production environment .
info
Used to print all Migrations Details and status information for , through MetaData and Migrations Accomplished , You can quickly locate the current database version .
repair
repair Operation can repair metaData surface , The operation is in metadata Useful when errors occur .
undo
Cancel the operation , The Community Edition doesn't support .
validate
Verify that apply Of Migrations Is there any change , On by default , The principle is comparison MetaData Tables and local Migrations Of checkNum value , If the values are the same, the verification passes , Otherwise failure .
6、 ... and 、flyway Knowledge supplement
- flyway perform migrate Must be done on a blank database , Otherwise, the report will be wrong .
- For databases that already have data , Must first baseline, Then you can migrate.
- clean The operation is to delete all the contents of the database , Include baseline Previous content .
- Try not to modify what has been executed SQL, even R Beginning with something that can be executed repeatedly SQL, They can be detrimental to data migration .
- When data migration is needed , Replace a new blank database , Under execution migrate command , All database changes can be migrated in one step .
7、 ... and 、flyway Configuration list
flyway.baseline-description A description of the baseline version when performing the migration .
flyway.baseline-on-migrate Find the target when migrating schema Non empty , And with tables without metadata , Whether to perform benchmark migration automatically , Default false.
flyway.baseline-version Start the benchmark migration against the existing schema The version of is labeled , The default value is 1.
flyway.check-location Check if the location of the migration script exists , Default false.
flyway.clean-on-validation-error Whether to call automatically when checking error is found clean, Default false.
flyway.enabled Open or not flywary, Default true.
flyway.encoding Set the encoding for migration , Default UTF-8.
flyway.ignore-failed-future-migration Whether to ignore error migration when reading metadata table , Default false.
flyway.init-sqls When the connection is initialized SQL.
flyway.locations The location of the migration script , Default db/migration.
flyway.out-of-order Whether to allow unordered migration , Default false.
flyway.password The password of the target database .
flyway.placeholder-prefix Set each placeholder The prefix of , Default ${.
flyway.placeholder-replacementplaceholders Whether to be replaced , Default true.
flyway.placeholder-suffix Set each placeholder The suffix , Default }.
flyway.placeholders.[placeholder name] Set up placeholder Of value
flyway.schemas Set the need for flywary Migrated schema, Case sensitive , The default is to connect the default schema.
flyway.sql-migration-prefix Prefix of migration file , The default is V.
flyway.sql-migration-separator The file name separator for the migration script , Default __
flyway.sql-migration-suffix The suffix of the migration script , The default is .sql
flyway.tableflyway Metadata table name used , The default is schema_version
flyway.target Target version used for migration , The default is latest version
flyway.url Used when migrating JDBC URL, If not specified , The configured master data source will be used
flyway.user The user name of the migration database
flyway.validate-on-migrate Check when migrating , The default is true
边栏推荐
- Multimodal model sketch (1)
- Google browser, no installation required
- The difference between {} and ${}
- PTA (daily question) 7-72 calculate the cumulative sum
- Dynamic programming problem (6)
- 【开发教程11】疯壳·开源蓝牙心率防水运动手环-整机功能代码讲解
- MySQL安装配置教程(超级详细、保姆级)
- Api 接口优化有哪些技巧?
- 乱打日志的男孩运气怎么样我不知道,加班肯定很多!
- Principle of meter skipping
猜你喜欢

Immutable x officially opens IMX token pledge detailed IMX pledge introduction optimistic about the development prospect of IMX

面试被问到了String相关的几道题,你能答上来吗?

Event extraction and documentation (2008-2017)

feign调用不通问题,JSON parse error Illegal character ((CTRL-CHAR, code 31)) only regular white space (r

时间序列统计分析

Idea connection database

Api 接口优化有哪些技巧?

Oracle实例无法启动的问题如何解决

Simple use and understanding of laravel message queue

分布式限流 redission RRateLimiter 的使用及原理
随机推荐
Summary: the difference between pod and container
What does the expression > > 0 in JS mean
2022网络安全学习路线 非常详细 推荐学习
Software designer - intermediate, exam summary
Oracle super full SQL, details crazy
Principle of meter skipping
聊聊异步编程的 7 种实现方式
动态规划问题(八)
【微服务~Nacos】Nacos服务提供者和服务消费者
MySQL事务(transaction) (有这篇就足够了..)
MySQL installation and configuration tutorial (super detailed, nanny level)
Introduction and solution of common security vulnerabilities in Web System SQL injection
Web系统常见安全漏洞介绍及解决方案-CSRF攻击
Control fillet stroke materialshapedrawable
Why is it so difficult for the SEC to refuse the application for transferring gray-scale GBTC to spot ETF? What is the attraction of ETF transfer?
Develop effective Tao spell
动态规划问题(七)
The difference between {} and ${}
"Method not allowed", 405 problem analysis and solution
Everything you have learned will come in handy at some point in your life (turn)