database.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /**
  2. ******************************************************************************
  3. * @file database.go
  4. * @author MakerYang
  5. ******************************************************************************
  6. */
  7. package Database
  8. import (
  9. "Game/framework/config"
  10. "fmt"
  11. "github.com/gookit/color"
  12. "github.com/jinzhu/gorm"
  13. _ "github.com/jinzhu/gorm/dialects/mysql"
  14. "log"
  15. "time"
  16. )
  17. var Get *gorm.DB
  18. type DefaultField struct {
  19. CreateAt int `gorm:"Column:create_at" json:"create_at"`
  20. UpdateAt int `gorm:"Column:update_at" json:"update_at"`
  21. DeleteAt int `gorm:"Column:delete_at" json:"delete_at"`
  22. }
  23. func Init() {
  24. var err error
  25. Get, err = gorm.Open(Config.Get.Database.Type, fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4&parseTime=True&loc=Local", Config.Get.Database.User, Config.Get.Database.Password, Config.Get.Database.Host, Config.Get.Database.Name))
  26. if err != nil {
  27. log.Println("[database]", color.Red.Text(err.Error()))
  28. }
  29. if Config.Get.Service.Mode == "release" {
  30. Get.LogMode(false)
  31. } else {
  32. Get.LogMode(true)
  33. }
  34. gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
  35. return defaultTableName
  36. }
  37. Get.SingularTable(true)
  38. Get.Callback().Create().Replace("gorm:update_time_stamp", func(scope *gorm.Scope) {
  39. if !scope.HasError() {
  40. nowTime := time.Now().Unix()
  41. if createTimeField, ok := scope.FieldByName("CreateAt"); ok {
  42. if createTimeField.IsBlank {
  43. err := createTimeField.Set(nowTime)
  44. if err != nil {
  45. }
  46. }
  47. }
  48. if modifyTimeField, ok := scope.FieldByName("UpdateAt"); ok {
  49. if modifyTimeField.IsBlank {
  50. err := modifyTimeField.Set(nowTime)
  51. if err != nil {
  52. }
  53. }
  54. }
  55. }
  56. })
  57. Get.DB().SetMaxIdleConns(1000)
  58. Get.DB().SetMaxOpenConns(10000)
  59. Get.DB().SetConnMaxLifetime(time.Second * 45)
  60. }