migrate

package module
v0.0.0-...-e7c7069 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: GPL-3.0 Imports: 16 Imported by: 3

README

Migrate 数据库迁移工具

一、说明

本包为日常工作中用到的数据库迁移管理工具提炼而来,本包仅提供基础的迁移管理实现,具体的嵌入到命令行中请自主实现或嵌入即可。

二、使用示例

注意:使用go-sql-driver/mysql驱动时,DSN格式中请携带参数?parseTime=true

// 实例化迁移工具
migration := migrate.New(migrate.Config{
    Dir:       "migrations", // 迁移文件的存储目录,相对于main包或binary可执行文件
    Fs:        migrations.File // 迁移文件的存储目录embed嵌入的FS只读文件系统变量
    TableName: "migrations", // 迁移工具本身所依赖的Db数据表表名
    DB:        db,           // *sql.DB 对象实例
})

// 创建迁移文件
migration.Create('不带后缀的文件名称')

// 查看迁移状态
migration.Status()

// 执行迁移
migration.ExecUp()

// 回滚迁移
migration.ExecDown("给空字符串则回滚最后1条,给定迁移文件名称则仅回滚指定名称的迁移")

请注意:go1.16之后go原生支持embed嵌入迁移文件,一个二进制文件可内嵌包含所有迁移文件, migrate.Config.Dir目录下自主使用embed生成一个fs.FS的嵌入变量,传参给migrate.Config.Fs即可。

嵌入迁移文件至二进制可执行程序的嵌入写法参考,或参考:migrate example

package migrations

import "embed"

//go:embed *.sql
var Sql embed.FS

migrate实例对象提供的方法可以嵌入到cli命令行入口,通过不同的参数执行不同的迁移命令

三、迁移文件写法

迁移文件本身就是一个SQL文件,基础结构如下,其中-- +migrate Up-- +migrate Down是不可缺少的标识符。

migration.Create('不带后缀的文件名称')被调用时将自动在migrate.Config.Dir目录生成如下结构的sql文件。

-- +migrate Up下方写迁移被ExecUp时也就是创建时执行的sql语句

-- +migrate Down下方写迁移被ExecDown时也就是回滚时执行的sql语句

多行或者复杂的sql语句,可使用-- +migrate StatementBegin-- +migrate StatementEnd作为标识符进行包裹,这个包裹符并不是必须的。

注意上述标识符本身是一个标准的SQL语句中的注释段,注意其中的空格、+、大小写都是刻意如此设定的。

空迁移文件样例:

-- +migrate Up


-- +migrate Down

无包裹符迁移文件写法样例:

-- +migrate Up
CREATE TABLE migrate_1 (id int);
CREATE TABLE migrate_2 (id int);

-- +migrate Down
DROP TABLE migrate_1;
DROP TABLE migrate_2;
DROP TABLE test_table;

有包裹符迁移文件写法样例:

-- +migrate Up
-- +migrate StatementBegin
CREATE TABLE `test_table` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='test_table';
-- +migrate StatementEnd

-- +migrate Down
DROP TABLE migrate_1;
DROP TABLE migrate_2;
DROP TABLE test_table;

Documentation

Index

Constants

View Source
const (
	MigrationUp   uint8 = 1
	MigrationDown uint8 = 2
)

迁移操作

Variables

View Source
var (
	// LineSeparator can be used to split migrations by an exact line match. This line
	// will be removed from the output. If left blank, it is not considered. It is defaulted
	// to blank so you will have to set it manually.
	// Use case: in MSSQL, it is convenient to separate commands by GO statements like in
	// SQL Query Analyzer.
	LineSeparator = ""
)

Functions

func CheckFileExist

func CheckFileExist(filename string) (exists bool)

CheckFileExist 判断文件是否存在

func Output

func Output(slice interface{}, grid Grid)

Output formats slice of structs data and writes to standard output.(Using box drawing characters)

func StringLength

func StringLength(r []rune) int

StringLength string display length

func WriteFile

func WriteFile(filename, content string) (n int, err error)

WriteFile 写入文件

Types

type Config

type Config struct {
	Dir       string    // migrate迁移文件的路径,相对路径<相对main入口|编译后二进制文件>
	Fs        *embed.FS // `Dir`参数指向的路径里的embed机制形成的fs.FS变量,以实现build编译嵌入embed迁移文件
	TableName string    // 记录migrate迁移历史的数据库表名
	DB        *sql.DB   // 数据库驱动句柄,用于操纵数据库
}

Config 配置

type Grid

type Grid string

Grid Grid

const GridASCII Grid = "ascii"

GridASCII ascii格式表格

const GridBoxDrawing Grid = "box-drawing"

GridBoxDrawing box-drawing格式表格

type Migrate

type Migrate struct {
	// contains filtered or unexported fields
}

Migrate Migrate对象

func New

func New(conf Config) *Migrate

New 实例化migrate迁移对象

func (Migrate) Create

func (m Migrate) Create(filename string) (err error)

Create 创建迁移文件--仅开发阶段可用

func (Migrate) ExecDown

func (m Migrate) ExecDown(filename string) (err error)

ExecDown 回滚已执行的迁移文件,每次回滚一个

func (Migrate) ExecUp

func (m Migrate) ExecUp() (err error)

ExecUp 执行迁移文件

func (Migrate) FindMigrations

func (m Migrate) FindMigrations() ([]*Migration, error)

FindMigrations 从本地文件系统|fs.FS读取全部迁移文件

func (Migrate) GetExecutedMigrations

func (m Migrate) GetExecutedMigrations() (migrations []MigrationModel, err error)

GetExecutedMigrations 从Db获取已执行的迁移记录

func (Migrate) InitMigrationTable

func (m Migrate) InitMigrationTable() (err error)

InitMigrationTable 初始化数据迁移表

func (Migrate) Status

func (m Migrate) Status() (err error)

Status 查看迁移文件列表状态

type Migration

type Migration struct {
	Id   string
	Up   []string
	Down []string

	DisableTransactionUp   bool
	DisableTransactionDown bool
}

Migration 解析后的迁移文件数据结构

func (Migration) Less

func (m Migration) Less(other *Migration) bool

Less less

func (Migration) NumberPrefixMatches

func (m Migration) NumberPrefixMatches() []string

NumberPrefixMatches 匹配数字版本号

func (Migration) VersionInt

func (m Migration) VersionInt() int64

VersionInt VersionInt

type MigrationModel

type MigrationModel struct {
	ID        uint64    `json:"id"`
	Migration string    `json:"migration"`
	CreatedAt time.Time `json:"created_at"`
}

MigrationModel MigrationModel

type MigrationOutput

type MigrationOutput struct {
	Migration string
	Status    string
}

MigrationOutput 列表输出

type ParsedMigration

type ParsedMigration struct {
	UpStatements   []string
	DownStatements []string

	DisableTransactionUp   bool
	DisableTransactionDown bool
}

func ParseMigration

func ParseMigration(r io.ReadSeeker) (*ParsedMigration, error)

ParseMigration Split the given sql script into individual statements.

The base case is to simply split on semicolons, as these naturally terminate a statement.

However, more complex cases like pl/pgsql can have semicolons within a statement. For these cases, we provide the explicit annotations 'StatementBegin' and 'StatementEnd' to allow the script to tell us to ignore semicolons.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL