dictionary.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. package system
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. sysModel "server/model/system"
  7. "server/service/system"
  8. )
  9. const initOrderDict = initOrderCasbin + 1
  10. type initDict struct{}
  11. // auto run
  12. func init() {
  13. system.RegisterInit(initOrderDict, &initDict{})
  14. }
  15. func (i *initDict) MigrateTable(ctx context.Context) (context.Context, error) {
  16. db, ok := ctx.Value("db").(*gorm.DB)
  17. if !ok {
  18. return ctx, system.ErrMissingDBContext
  19. }
  20. return ctx, db.AutoMigrate(&sysModel.SysDictionary{})
  21. }
  22. func (i *initDict) TableCreated(ctx context.Context) bool {
  23. db, ok := ctx.Value("db").(*gorm.DB)
  24. if !ok {
  25. return false
  26. }
  27. return db.Migrator().HasTable(&sysModel.SysDictionary{})
  28. }
  29. func (i initDict) InitializerName() string {
  30. return sysModel.SysDictionary{}.TableName()
  31. }
  32. func (i *initDict) InitializeData(ctx context.Context) (next context.Context, err error) {
  33. db, ok := ctx.Value("db").(*gorm.DB)
  34. if !ok {
  35. return ctx, system.ErrMissingDBContext
  36. }
  37. True := true
  38. entities := []sysModel.SysDictionary{
  39. {Name: "性别", Type: "gender", Status: &True, Desc: "性别字典"},
  40. {Name: "数据库int类型", Type: "int", Status: &True, Desc: "int类型对应的数据库类型"},
  41. {Name: "数据库时间日期类型", Type: "time.Time", Status: &True, Desc: "数据库时间日期类型"},
  42. {Name: "数据库浮点型", Type: "float64", Status: &True, Desc: "数据库浮点型"},
  43. {Name: "数据库字符串", Type: "string", Status: &True, Desc: "数据库字符串"},
  44. {Name: "数据库bool类型", Type: "bool", Status: &True, Desc: "数据库bool类型"},
  45. }
  46. if err = db.Create(&entities).Error; err != nil {
  47. return ctx, errors.Wrap(err, sysModel.SysDictionary{}.TableName()+"表数据初始化失败!")
  48. }
  49. next = context.WithValue(ctx, i.InitializerName(), entities)
  50. return next, nil
  51. }
  52. func (i *initDict) DataInserted(ctx context.Context) bool {
  53. db, ok := ctx.Value("db").(*gorm.DB)
  54. if !ok {
  55. return false
  56. }
  57. if errors.Is(db.Where("type = ?", "bool").First(&sysModel.SysDictionary{}).Error, gorm.ErrRecordNotFound) { // 判断是否存在数据
  58. return false
  59. }
  60. return true
  61. }