You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

29 lines
762 B

3 years ago
  1. package utils
  2. import (
  3. "errors"
  4. "fmt"
  5. "time"
  6. "gorm.io/gorm"
  7. )
  8. //@author: [songzhibin97](https://github.com/songzhibin97)
  9. //@function: ClearTable
  10. //@description: 清理数据库表数据
  11. //@param: db(数据库对象) *gorm.DB, tableName(表名) string, compareField(比较字段) string, interval(间隔) string
  12. //@return: error
  13. func ClearTable(db *gorm.DB, tableName string, compareField string, interval string) error {
  14. if db == nil {
  15. return errors.New("db Cannot be empty")
  16. }
  17. duration, err := time.ParseDuration(interval)
  18. if err != nil {
  19. return err
  20. }
  21. if duration < 0 {
  22. return errors.New("parse duration < 0")
  23. }
  24. return db.Debug().Exec(fmt.Sprintf("DELETE FROM %s WHERE %s < ?", tableName, compareField), time.Now().Add(-duration)).Error
  25. }