rw_store.go 956 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package kptstore
  2. import (
  3. "kpt-tmr-group/config"
  4. "kpt-tmr-group/pkg/logger/logrus"
  5. "kpt-tmr-group/pkg/xerr"
  6. "time"
  7. "gorm.io/driver/mysql"
  8. "gorm.io/gorm"
  9. "gorm.io/gorm/logger"
  10. "kpt-tmr-group/pkg/di"
  11. )
  12. var Module = di.Options(
  13. di.Provide(MustNewStore),
  14. )
  15. type DB struct {
  16. *gorm.DB
  17. }
  18. func NewStore(engine *gorm.DB) *DB {
  19. return &DB{engine}
  20. }
  21. type goRmLog struct {
  22. }
  23. func (g goRmLog) Printf(s string, i ...interface{}) {
  24. logrus.Infof(s, i...)
  25. }
  26. func MustNewStore(cfg *config.AppConfig) *DB {
  27. newLogger := logger.New(
  28. goRmLog{},
  29. logger.Config{
  30. SlowThreshold: 5 * time.Second,
  31. LogLevel: logger.Info,
  32. },
  33. )
  34. db, err := gorm.Open(mysql.New(mysql.Config{
  35. DriverName: cfg.StoreSetting.DriverName,
  36. DSN: cfg.StoreSetting.KptEventDSNRW}),
  37. &gorm.Config{Logger: newLogger},
  38. )
  39. if err != nil {
  40. panic(xerr.WithStack(err))
  41. }
  42. if cfg.StoreSetting.ShowSQL {
  43. db.Logger.LogMode(logger.Info)
  44. }
  45. return NewStore(db)
  46. }