Files
go_blog/models/init.go

57 lines
1.1 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"
"go_blog/conf"
"go_blog/pkg/util"
"time"
2024-01-23 18:29:13 +08:00
"gorm.io/gorm"
2024-01-10 16:05:15 +08:00
)
var DB *gorm.DB
func SetUp(isOrmDebug bool) {
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,
conf.DataBase.DB,
conf.DataBase.Charset)
db, err := gorm.Open(conf.DataBase.Type, conUri)
if err != nil {
panic(err)
}
DB = db
DB.LogMode(isOrmDebug)
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return conf.DataBase.Prefix + defaultTableName
}
DB.AutoMigrate(&Account{})
2024-01-23 18:29:13 +08:00
DB.AutoMigrate(&Content{})
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
func (m *BaseModel) BeforeCreate(scope *gorm.Scope) error {
if m.ID == 0 {
m.ID = util.GenSonyFlakeId()
}
return nil
}