sys_initdb_mysql.go 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. package system
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "path/filepath"
  7. "github.com/gookit/color"
  8. "server/config"
  9. "server/utils"
  10. "github.com/gofrs/uuid/v5"
  11. "gorm.io/driver/mysql"
  12. "gorm.io/gorm"
  13. "server/global"
  14. "server/model/system/request"
  15. )
  16. type MysqlInitHandler struct{}
  17. func NewMysqlInitHandler() *MysqlInitHandler {
  18. return &MysqlInitHandler{}
  19. }
  20. // WriteConfig mysql回写配置
  21. func (h MysqlInitHandler) WriteConfig(ctx context.Context) error {
  22. c, ok := ctx.Value("config").(config.Mysql)
  23. if !ok {
  24. return errors.New("mysql config invalid")
  25. }
  26. global.GVA_CONFIG.System.DbType = "mysql"
  27. global.GVA_CONFIG.Mysql = c
  28. global.GVA_CONFIG.JWT.SigningKey = uuid.Must(uuid.NewV4()).String()
  29. cs := utils.StructToMap(global.GVA_CONFIG)
  30. for k, v := range cs {
  31. global.GVA_VP.Set(k, v)
  32. }
  33. return global.GVA_VP.WriteConfig()
  34. }
  35. // EnsureDB 创建数据库并初始化 mysql
  36. func (h MysqlInitHandler) EnsureDB(ctx context.Context, conf *request.InitDB) (next context.Context, err error) {
  37. if s, ok := ctx.Value("dbtype").(string); !ok || s != "mysql" {
  38. return ctx, ErrDBTypeMismatch
  39. }
  40. c := conf.ToMysqlConfig()
  41. next = context.WithValue(ctx, "config", c)
  42. if c.Dbname == "" {
  43. return ctx, nil
  44. } // 如果没有数据库名, 则跳出初始化数据
  45. dsn := conf.MysqlEmptyDsn()
  46. createSql := fmt.Sprintf("CREATE DATABASE IF NOT EXISTS `%s` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_general_ci;", c.Dbname)
  47. if err = createDatabase(dsn, "mysql", createSql); err != nil {
  48. return nil, err
  49. } // 创建数据库
  50. var db *gorm.DB
  51. if db, err = gorm.Open(mysql.New(mysql.Config{
  52. DSN: c.Dsn(), // DSN data source name
  53. DefaultStringSize: 191, // string 类型字段的默认长度
  54. SkipInitializeWithVersion: true, // 根据版本自动配置
  55. }), &gorm.Config{DisableForeignKeyConstraintWhenMigrating: true}); err != nil {
  56. return ctx, err
  57. }
  58. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  59. next = context.WithValue(next, "db", db)
  60. return next, err
  61. }
  62. func (h MysqlInitHandler) InitTables(ctx context.Context, inits initSlice) error {
  63. return createTables(ctx, inits)
  64. }
  65. func (h MysqlInitHandler) InitData(ctx context.Context, inits initSlice) error {
  66. next, cancel := context.WithCancel(ctx)
  67. defer func(c func()) { c() }(cancel)
  68. for _, init := range inits {
  69. if init.DataInserted(next) {
  70. color.Info.Printf(InitDataExist, Mysql, init.InitializerName())
  71. continue
  72. }
  73. if n, err := init.InitializeData(next); err != nil {
  74. color.Info.Printf(InitDataFailed, Mysql, init.InitializerName(), err)
  75. return err
  76. } else {
  77. next = n
  78. color.Info.Printf(InitDataSuccess, Mysql, init.InitializerName())
  79. }
  80. }
  81. color.Info.Printf(InitSuccess, Mysql)
  82. return nil
  83. }