sys_initdb_sqlite.go 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. package system
  2. import (
  3. "context"
  4. "errors"
  5. "github.com/glebarez/sqlite"
  6. "github.com/gofrs/uuid/v5"
  7. "github.com/gookit/color"
  8. "gorm.io/gorm"
  9. "path/filepath"
  10. "server/config"
  11. "server/global"
  12. "server/model/system/request"
  13. "server/utils"
  14. )
  15. type SqliteInitHandler struct{}
  16. func NewSqliteInitHandler() *SqliteInitHandler {
  17. return &SqliteInitHandler{}
  18. }
  19. // WriteConfig mysql回写配置
  20. func (h SqliteInitHandler) WriteConfig(ctx context.Context) error {
  21. c, ok := ctx.Value("config").(config.Sqlite)
  22. if !ok {
  23. return errors.New("mysql config invalid")
  24. }
  25. global.GVA_CONFIG.System.DbType = "sqlite"
  26. global.GVA_CONFIG.Sqlite = c
  27. global.GVA_CONFIG.JWT.SigningKey = uuid.Must(uuid.NewV4()).String()
  28. cs := utils.StructToMap(global.GVA_CONFIG)
  29. for k, v := range cs {
  30. global.GVA_VP.Set(k, v)
  31. }
  32. return global.GVA_VP.WriteConfig()
  33. }
  34. // EnsureDB 创建数据库并初始化 sqlite
  35. func (h SqliteInitHandler) EnsureDB(ctx context.Context, conf *request.InitDB) (next context.Context, err error) {
  36. if s, ok := ctx.Value("dbtype").(string); !ok || s != "sqlite" {
  37. return ctx, ErrDBTypeMismatch
  38. }
  39. c := conf.ToSqliteConfig()
  40. next = context.WithValue(ctx, "config", c)
  41. if c.Dbname == "" {
  42. return ctx, nil
  43. } // 如果没有数据库名, 则跳出初始化数据
  44. dsn := conf.SqliteEmptyDsn()
  45. var db *gorm.DB
  46. if db, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{
  47. DisableForeignKeyConstraintWhenMigrating: true,
  48. }); err != nil {
  49. return ctx, err
  50. }
  51. global.GVA_CONFIG.AutoCode.Root, _ = filepath.Abs("..")
  52. next = context.WithValue(next, "db", db)
  53. return next, err
  54. }
  55. func (h SqliteInitHandler) InitTables(ctx context.Context, inits initSlice) error {
  56. return createTables(ctx, inits)
  57. }
  58. func (h SqliteInitHandler) InitData(ctx context.Context, inits initSlice) error {
  59. next, cancel := context.WithCancel(ctx)
  60. defer func(c func()) { c() }(cancel)
  61. for _, init := range inits {
  62. if init.DataInserted(next) {
  63. color.Info.Printf(InitDataExist, Sqlite, init.InitializerName())
  64. continue
  65. }
  66. if n, err := init.InitializeData(next); err != nil {
  67. color.Info.Printf(InitDataFailed, Sqlite, init.InitializerName(), err)
  68. return err
  69. } else {
  70. next = n
  71. color.Info.Printf(InitDataSuccess, Sqlite, init.InitializerName())
  72. }
  73. }
  74. color.Info.Printf(InitSuccess, Sqlite)
  75. return nil
  76. }