sys_initdb_sqlite.go 2.4 KB

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