07-gorm实现数据库升级

2022/7/2 2:20:09

本文主要是介绍07-gorm实现数据库升级,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

Gorm 实现对数据库的版本升级

1. 实现原理

package main

import (
	"log"

	"github.com/go-gormigrate/gormigrate/v2"
	"gorm.io/driver/sqlite"
	"gorm.io/gorm"
)

func main() {
	db, err := gorm.Open(sqlite.Open("sqlite.db"), &gorm.Config{})
	if err != nil {
		log.Fatal(err)
	}

	m := gormigrate.New(db, gormigrate.DefaultOptions, []*gormigrate.Migration{
		// create persons table
		{
			ID: "201608301400",
			Migrate: func(tx *gorm.DB) error {
				// it's a good pratice to copy the struct inside the function,
				// so side effects are prevented if the original struct changes during the time
				type Person struct {
					gorm.Model
					Name string
				}
				return tx.AutoMigrate(&Person{})
			},
			Rollback: func(tx *gorm.DB) error {
				return tx.Migrator().DropTable("people")
			},
		},
		// add age column to persons
		{
			ID: "201608301415",
			Migrate: func(tx *gorm.DB) error {
				// when table already exists, it just adds fields as columns
				type Person struct {
					Age int
				}
				return tx.AutoMigrate(&Person{})
			},
			Rollback: func(tx *gorm.DB) error {
				return tx.Migrator().DropColumn("people", "age")
			},
		},
		// add pets table
		{
			ID: "201608301430",
			Migrate: func(tx *gorm.DB) error {
				type Pet struct {
					gorm.Model
					Name     string
					PersonID int
				}
				return tx.AutoMigrate(&Pet{})
			},
			Rollback: func(tx *gorm.DB) error {
				return tx.Migrator().DropTable("pets")
			},
		},
	})

	//// migrage
	if err = m.Migrate(); err != nil {
		log.Fatalf("Could not migrate: %v", err)
	}

	// migrate to version (add column)
	if err = m.MigrateTo("201608301415"); err != nil {
		log.Fatalf("Could not migrate to version: %v", err)
	}

	// rollback to version
	if err = m.RollbackTo("201608301415"); err != nil {
		log.Fatalf("Could not rollback: %v", err)
	}

	log.Printf("Migration did run successfully")
}

2. 代码封装

代码结构

https://github.com/JmilkFan/gormigrate-demo/

参考链接

gorm migration

gorm_migration_demo



这篇关于07-gorm实现数据库升级的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程