file_upload_download.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. package example
  2. import (
  3. "context"
  4. "github.com/pkg/errors"
  5. "gorm.io/gorm"
  6. "server/model/example"
  7. "server/service/system"
  8. )
  9. const initOrderExaFile = system.InitOrderInternal + 1
  10. type initExaFileMysql struct{}
  11. // auto run
  12. func init() {
  13. system.RegisterInit(initOrderExaFile, &initExaFileMysql{})
  14. }
  15. func (i *initExaFileMysql) 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(&example.ExaFileUploadAndDownload{})
  21. }
  22. func (i *initExaFileMysql) 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(&example.ExaFileUploadAndDownload{})
  28. }
  29. func (i initExaFileMysql) InitializerName() string {
  30. return example.ExaFileUploadAndDownload{}.TableName()
  31. }
  32. func (i *initExaFileMysql) InitializeData(ctx context.Context) (context.Context, error) {
  33. db, ok := ctx.Value("db").(*gorm.DB)
  34. if !ok {
  35. return ctx, system.ErrMissingDBContext
  36. }
  37. entities := []example.ExaFileUploadAndDownload{
  38. {Name: "10.png", Url: "https://qmplusimg.henrongyi.top/gvalogo.png", Tag: "png", Key: "158787308910.png"},
  39. {Name: "logo.png", Url: "https://qmplusimg.henrongyi.top/1576554439myAvatar.png", Tag: "png", Key: "1587973709logo.png"},
  40. }
  41. if err := db.Create(&entities).Error; err != nil {
  42. return ctx, errors.Wrap(err, example.ExaFileUploadAndDownload{}.TableName()+"表数据初始化失败!")
  43. }
  44. return ctx, nil
  45. }
  46. func (i *initExaFileMysql) DataInserted(ctx context.Context) bool {
  47. db, ok := ctx.Value("db").(*gorm.DB)
  48. if !ok {
  49. return false
  50. }
  51. lookup := example.ExaFileUploadAndDownload{Name: "logo.png", Key: "1587973709logo.png"}
  52. if errors.Is(db.First(&lookup, &lookup).Error, gorm.ErrRecordNotFound) {
  53. return false
  54. }
  55. return true
  56. }