database.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /**
  2. #*****************************************************************************
  3. # @file database.go
  4. # @author MakerYang(https://www.makeryang.com)
  5. # @statement 免费课程配套开源项目,任何形式收费均为盗版
  6. #*****************************************************************************
  7. */
  8. package Database
  9. import (
  10. "Game/framework/config"
  11. "fmt"
  12. "github.com/gookit/color"
  13. "github.com/jinzhu/gorm"
  14. _ "github.com/jinzhu/gorm/dialects/mysql"
  15. "log"
  16. "time"
  17. )
  18. // Get 定义数据库模块的调用指针
  19. var Get *gorm.DB
  20. // DefaultField 声明数据库默认字段
  21. type DefaultField struct {
  22. CreateAt int `gorm:"Column:create_at" json:"create_at"`
  23. UpdateAt int `gorm:"Column:update_at" json:"update_at"`
  24. DeleteAt int `gorm:"Column:delete_at" json:"delete_at"`
  25. }
  26. // Init 初始化数据库连接
  27. func Init() {
  28. var err error
  29. 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))
  30. if err != nil {
  31. log.Println("[database]", color.Red.Text(err.Error()))
  32. }
  33. if Config.Get.Service.Mode == "release" {
  34. Get.LogMode(false)
  35. } else {
  36. Get.LogMode(true)
  37. }
  38. gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
  39. return defaultTableName
  40. }
  41. Get.SingularTable(true)
  42. Get.Callback().Create().Replace("gorm:update_time_stamp", func(scope *gorm.Scope) {
  43. if !scope.HasError() {
  44. nowTime := time.Now().Unix()
  45. if createTimeField, ok := scope.FieldByName("CreateAt"); ok {
  46. if createTimeField.IsBlank {
  47. err := createTimeField.Set(nowTime)
  48. if err != nil {
  49. }
  50. }
  51. }
  52. if modifyTimeField, ok := scope.FieldByName("UpdateAt"); ok {
  53. if modifyTimeField.IsBlank {
  54. err := modifyTimeField.Set(nowTime)
  55. if err != nil {
  56. }
  57. }
  58. }
  59. }
  60. })
  61. Get.DB().SetMaxIdleConns(1000)
  62. Get.DB().SetMaxOpenConns(10000)
  63. Get.DB().SetConnMaxLifetime(time.Second * 45)
  64. }