打赏

gorm实现sqlite数据库升级

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

posted @ 2022-07-01 18:24  苍山落暮  阅读(791)  评论(0编辑  收藏  举报