clearTable.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. package task
  2. import (
  3. "errors"
  4. "fmt"
  5. "server/model/common"
  6. "time"
  7. "gorm.io/gorm"
  8. )
  9. //@author: [songzhibin97](https://github.com/songzhibin97)
  10. //@function: ClearTable
  11. //@description: 清理数据库表数据
  12. //@param: db(数据库对象) *gorm.DB, tableName(表名) string, compareField(比较字段) string, interval(间隔) string
  13. //@return: error
  14. func ClearTable(db *gorm.DB) error {
  15. var ClearTableDetail []common.ClearDB
  16. ClearTableDetail = append(ClearTableDetail, common.ClearDB{
  17. TableName: "sys_operation_records",
  18. CompareField: "created_at",
  19. Interval: "2160h",
  20. })
  21. ClearTableDetail = append(ClearTableDetail, common.ClearDB{
  22. TableName: "jwt_blacklists",
  23. CompareField: "created_at",
  24. Interval: "168h",
  25. })
  26. if db == nil {
  27. return errors.New("db Cannot be empty")
  28. }
  29. for _, detail := range ClearTableDetail {
  30. duration, err := time.ParseDuration(detail.Interval)
  31. if err != nil {
  32. return err
  33. }
  34. if duration < 0 {
  35. return errors.New("parse duration < 0")
  36. }
  37. err = db.Debug().Exec(fmt.Sprintf("DELETE FROM %s WHERE %s < ?", detail.TableName, detail.CompareField), time.Now().Add(-duration)).Error
  38. if err != nil {
  39. return err
  40. }
  41. }
  42. return nil
  43. }