db.go 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. package global
  2. import (
  3. "Ic_ouath/configs"
  4. "Ic_ouath/models"
  5. "fmt"
  6. "gorm.io/driver/mysql"
  7. "gorm.io/gorm"
  8. "gorm.io/gorm/logger"
  9. "log"
  10. "runtime"
  11. )
  12. var (
  13. DBLink *gorm.DB
  14. )
  15. func SetupDBLink() error {
  16. var err error
  17. dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?%s",
  18. configs.Config.GetString("database.userName"),
  19. configs.Config.GetString("database.password"),
  20. configs.Config.GetString("database.host"),
  21. configs.Config.GetString("database.db"),
  22. configs.Config.GetString("database.otherParams"),
  23. )
  24. //判断当前系统是windows还是linux
  25. //runtime获取的是当前Go语言框架的参数,不是实际运行的操作系统的参数
  26. sysType := runtime.GOOS
  27. if sysType == "windows" {
  28. DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
  29. DisableForeignKeyConstraintWhenMigrating: true,
  30. Logger: logger.Default.LogMode(logger.Info),
  31. })
  32. log.Print("当前系统为windows")
  33. } else if sysType == "linux" {
  34. DBLink, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
  35. }
  36. if err != nil {
  37. return err
  38. }
  39. //DBLink.SingularTable(true)
  40. //DBLink.DB().SetMaxIdleConns(DatabaseSetting.MaxIdleConn)
  41. //DBLink.DB().SetMaxOpenConns(DatabaseSetting.MaxOpenConn)
  42. DBLink.Set("gorm:table_options", "ENGINE=InnoDB").AutoMigrate(&models.User{})
  43. return nil
  44. }