使用 Gorm 进行数据库迁移管理
时间:2024-03-09
浏览:226
作者:佚名
“纵有疾风来,人生不言弃”,这句话送给正在学习Golang的朋友们,也希望在阅读本文《使用 Gorm 进行数据库迁移管理》后,能够真的帮助到大家。我也会在后续的文章中,陆续更新Golang相关的技术文章,有好的建议欢迎大家在评论留言,非常感谢!
问题内容
我决定使用 gorm 作为我的 ORM。我想使用 golang-migrate/migrate 进行迁移,因为看起来 GORM 没有版本化的迁移文件。我宁愿使用 CLI 进行迁移,而不是使用自动迁移。
我阅读了gorm文档,但没有看到gorm如何将模型转换为SQL表。有没有关于为 gorm 生成的 SQL 表的示例或文档? (尤其是类型或关联如何映射到 SQL)
解决方案
几年前我第一次开始使用 gorm 时,我一直在寻找与您正在寻找的类似的东西。我最终使用了一个名为 goose (https://github.com/pressly/goose) 的包来创建迁移文件并从 cli 运行迁移。它实际上效果非常好。基本上,在 up 和 down 函数上,您可以使用 gorm 的内置迁移函数 (https://gorm.io/docs/migration.html)。
这是一个利用 gorm 的 goose 迁移文件的示例。
package main
import (
"database/sql"
"encoding/json"
"my-api/internal/pkg/db"
"time"
"my-api/internal/pkg/private/models"
"github.com/pressly/goose"
)
func init() {
goose.AddMigration(Up00007, Down00007)
}
type Event struct {
models.DefaultModel
VenueID uint `gorm:"not null"`
Tags json.RawMessage `gorm:"not null;type:json" sql:"type:json"`
Name string `gorm:"not null"`
Details string `gorm:"not null"`
Picture string `gorm:"not null"`
StartDate time.Time
EndDate time.Time
}
func Up00007(tx *sql.Tx) error {
// This code is executed when the migration is applied.
return db.Get().CreateTable(&Event{}).Error
}
func Down00007(tx *sql.Tx) error {
// This code is executed when the migration is rolled back.
return db.Get().DropTable(&Event{}).Error
}
仅供参考 db.get() 获取 gorm 数据库。
以上就是本文的全部内容了,是否有顺利帮助你解决问题?若是能给你带来学习上的帮助,请大家多多支持golang学习网!更多关于Golang的相关知识,也可关注golang学习网公众号。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
12.01
热门专题
