Files
go_blog/models/init.go

64 lines
1.3 KiB
Go
Raw Normal View History

2024-01-10 16:05:15 +08:00
/*
@Time : 2020/6/28 21:46
@Author : xuyiqing
@File : init.py
*/
package models
import (
"fmt"
2025-04-15 16:47:00 +08:00
"go_blog/config"
2024-01-10 16:05:15 +08:00
"go_blog/pkg/util"
"time"
2024-07-04 19:15:44 +08:00
"gorm.io/driver/mysql"
2024-01-23 18:29:13 +08:00
"gorm.io/gorm"
2024-07-04 19:15:44 +08:00
"gorm.io/gorm/schema"
2024-01-10 16:05:15 +08:00
)
var DB *gorm.DB
2025-04-15 16:47:00 +08:00
func InitDatabase(conf *config.Config) {
2024-01-10 16:05:15 +08:00
conUri := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=%s&parseTime=True&loc=Local",
conf.DataBase.User,
conf.DataBase.Password,
conf.DataBase.Host,
conf.DataBase.Port,
2024-07-04 19:15:44 +08:00
conf.DataBase.DBName,
2024-01-10 16:05:15 +08:00
conf.DataBase.Charset)
2025-04-15 16:47:00 +08:00
// 2. 初始化数据库
2024-07-04 19:15:44 +08:00
db, err := gorm.Open(mysql.Open(conUri), &gorm.Config{
NamingStrategy: schema.NamingStrategy{
TablePrefix: conf.DataBase.Prefix,
},
})
2024-01-10 16:05:15 +08:00
if err != nil {
2025-04-15 16:47:00 +08:00
panic("数据库连接失败: " + err.Error())
2024-01-10 16:05:15 +08:00
}
2025-04-15 16:47:00 +08:00
DB = db
// 3. 自动迁移数据模型
2024-01-10 16:05:15 +08:00
DB.AutoMigrate(&Account{})
2024-01-23 18:29:13 +08:00
DB.AutoMigrate(&Content{})
2025-04-15 16:47:00 +08:00
// if err := db.AutoMigrate(&models.Article{}, &models.User{}); err != nil {
// panic("数据库迁移失败: " + err.Error())
// }
2024-01-10 16:05:15 +08:00
}
type BaseModel struct {
ID uint64 `gorm:"primary_key'" json:"id"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `sql:"index" json:"-"`
}
// 生成全局唯一ID
2024-07-04 19:15:44 +08:00
func (m *BaseModel) BeforeCreate(scope *gorm.DB) error {
2024-01-10 16:05:15 +08:00
if m.ID == 0 {
m.ID = util.GenSonyFlakeId()
}
return nil
}