数据库
首页 > 数据库> > 07-gorm实现数据库升级

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

标签:return,07,err,数据库,func,tx,gorm,log
来源: https://www.cnblogs.com/tomtellyou/p/16435632.html