Files
Message-Push-Nest/models/models.go
T

132 lines
4.0 KiB
Go
Raw Normal View History

2023-12-30 17:40:20 +08:00
package models
import (
"fmt"
"github.com/google/uuid"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
"log"
"message-nest/pkg/setting"
"message-nest/pkg/util"
"time"
)
var db *gorm.DB
2023-12-31 21:31:56 +08:00
type IDModel struct {
2024-01-07 21:30:59 +08:00
ID int `gorm:"type:int(11) AUTO_INCREMENT comment 'id';primary_key" json:"id"`
2023-12-31 21:31:56 +08:00
2024-01-07 21:30:59 +08:00
CreatedBy string `json:"created_by" gorm:"type:varchar(100) comment '创建人';default:'';"`
ModifiedBy string `json:"modified_by" gorm:"type:varchar(100) comment '修改人';default:'';"`
CreatedOn util.Time `json:"created_on" gorm:"type:timestamp comment '创建时间';default:current_timestamp;"`
ModifiedOn util.Time `json:"modified_on" gorm:"type:timestamp comment '更新时间';default:current_timestamp on update current_timestamp;"`
2023-12-31 21:31:56 +08:00
}
2023-12-30 17:40:20 +08:00
type UUIDModel struct {
2024-01-07 21:30:59 +08:00
ID uuid.UUID `gorm:"type:varchar(36) comment 'id';primary_key" json:"id"`
2023-12-30 17:40:20 +08:00
2024-01-07 21:30:59 +08:00
CreatedBy string `json:"created_by" gorm:"type:varchar(100) comment '创建人';default:'';"`
ModifiedBy string `json:"modified_by" gorm:"type:varchar(100) comment '修改人';default:'';"`
CreatedOn util.Time `json:"created_on" gorm:"type:timestamp comment '创建时间';default:current_timestamp;"`
ModifiedOn util.Time `json:"modified_on" gorm:"type:timestamp comment '更新时间';default:current_timestamp on update current_timestamp;"`
2023-12-30 17:40:20 +08:00
}
// Setup initializes the database instance
2024-01-07 21:30:59 +08:00
func Setup() *gorm.DB {
2023-12-30 17:40:20 +08:00
var err error
2024-01-02 22:19:12 +08:00
connStr := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
2023-12-30 17:40:20 +08:00
setting.DatabaseSetting.User,
setting.DatabaseSetting.Password,
setting.DatabaseSetting.Host,
2024-01-02 22:19:12 +08:00
setting.DatabaseSetting.Port,
setting.DatabaseSetting.Name)
db, err = gorm.Open(setting.DatabaseSetting.Type, connStr)
2023-12-30 17:40:20 +08:00
if err != nil {
log.Fatalf("models.Setup err: %v", err)
}
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return setting.DatabaseSetting.TablePrefix + defaultTableName
}
2024-01-07 00:25:35 +08:00
if setting.DatabaseSetting.SqlDebug == "enable" {
db.LogMode(true)
}
2023-12-30 17:40:20 +08:00
db.SingularTable(true)
db.Callback().Create().Replace("gorm:update_time_stamp", updateTimeStampForCreateCallback)
db.Callback().Update().Replace("gorm:update_time_stamp", updateTimeStampForUpdateCallback)
db.Callback().Delete().Replace("gorm:delete", deleteCallback)
db.DB().SetMaxIdleConns(10)
db.DB().SetMaxOpenConns(100)
2024-01-07 21:30:59 +08:00
return db
2023-12-30 17:40:20 +08:00
}
// CloseDB closes database connection (unnecessary)
func CloseDB() {
defer db.Close()
}
// updateTimeStampForCreateCallback will set `CreatedOn`, `ModifiedOn` when creating
func updateTimeStampForCreateCallback(scope *gorm.Scope) {
if !scope.HasError() {
nowTime := time.Now()
if createTimeField, ok := scope.FieldByName("CreatedOn"); ok {
if createTimeField.IsBlank {
createTimeField.Set(nowTime)
}
}
if modifyTimeField, ok := scope.FieldByName("ModifiedOn"); ok {
if modifyTimeField.IsBlank {
modifyTimeField.Set(nowTime)
}
}
}
}
// updateTimeStampForUpdateCallback will set `ModifiedOn` when updating
func updateTimeStampForUpdateCallback(scope *gorm.Scope) {
if _, ok := scope.Get("gorm:update_column"); !ok {
scope.SetColumn("ModifiedOn", time.Now())
}
}
// deleteCallback will set `DeletedOn` where deleting
func deleteCallback(scope *gorm.Scope) {
if !scope.HasError() {
var extraOption string
if str, ok := scope.Get("gorm:delete_option"); ok {
extraOption = fmt.Sprint(str)
}
deletedOnField, hasDeletedOnField := scope.FieldByName("DeletedOn")
if !scope.Search.Unscoped && hasDeletedOnField {
scope.Raw(fmt.Sprintf(
"UPDATE %v SET %v=%v%v%v",
scope.QuotedTableName(),
scope.Quote(deletedOnField.DBName),
scope.AddToVars(time.Now().Unix()),
addExtraSpaceIfExist(scope.CombinedConditionSql()),
addExtraSpaceIfExist(extraOption),
)).Exec()
} else {
scope.Raw(fmt.Sprintf(
"DELETE FROM %v%v%v",
scope.QuotedTableName(),
addExtraSpaceIfExist(scope.CombinedConditionSql()),
addExtraSpaceIfExist(extraOption),
)).Exec()
}
}
}
// addExtraSpaceIfExist adds a separator
func addExtraSpaceIfExist(str string) string {
if str != "" {
return " " + str
}
return ""
}