/internal/app/model/gormx/gorm.go

https://github.com/LyricTian/gin-admin · Go · 79 lines · 63 code · 12 blank · 4 comment · 9 complexity · 84b378be95783bc6813c5330021159b7 MD5 · raw file

  1. package gormx
  2. import (
  3. "strings"
  4. "time"
  5. "github.com/LyricTian/gin-admin/v7/internal/app/config"
  6. "github.com/LyricTian/gin-admin/v7/internal/app/model/gormx/entity"
  7. "github.com/LyricTian/gin-admin/v7/pkg/logger"
  8. "github.com/jinzhu/gorm"
  9. // gorm存储注入
  10. _ "github.com/jinzhu/gorm/dialects/mysql"
  11. _ "github.com/jinzhu/gorm/dialects/postgres"
  12. _ "github.com/jinzhu/gorm/dialects/sqlite"
  13. )
  14. // Config 配置参数
  15. type Config struct {
  16. Debug bool
  17. DBType string
  18. DSN string
  19. MaxLifetime int
  20. MaxOpenConns int
  21. MaxIdleConns int
  22. TablePrefix string
  23. }
  24. // NewDB 创建DB实例
  25. func NewDB(c *Config) (*gorm.DB, func(), error) {
  26. gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
  27. return c.TablePrefix + defaultTableName
  28. }
  29. db, err := gorm.Open(c.DBType, c.DSN)
  30. if err != nil {
  31. return nil, nil, err
  32. }
  33. if c.Debug {
  34. db = db.Debug()
  35. }
  36. cleanFunc := func() {
  37. err := db.Close()
  38. if err != nil {
  39. logger.Errorf("Gorm db close error: %s", err.Error())
  40. }
  41. }
  42. err = db.DB().Ping()
  43. if err != nil {
  44. return nil, cleanFunc, err
  45. }
  46. db.SingularTable(true)
  47. db.DB().SetMaxIdleConns(c.MaxIdleConns)
  48. db.DB().SetMaxOpenConns(c.MaxOpenConns)
  49. db.DB().SetConnMaxLifetime(time.Duration(c.MaxLifetime) * time.Second)
  50. return db, cleanFunc, nil
  51. }
  52. // AutoMigrate 自动映射数据表
  53. func AutoMigrate(db *gorm.DB) error {
  54. if dbType := config.C.Gorm.DBType; strings.ToLower(dbType) == "mysql" {
  55. db = db.Set("gorm:table_options", "ENGINE=InnoDB")
  56. }
  57. return db.AutoMigrate(
  58. new(entity.Demo),
  59. new(entity.MenuAction),
  60. new(entity.MenuActionResource),
  61. new(entity.Menu),
  62. new(entity.RoleMenu),
  63. new(entity.Role),
  64. new(entity.UserRole),
  65. new(entity.User),
  66. ).Error
  67. }