package workers import ( "fmt" "gorm.io/gorm" db "git.zervo.org/scheduletogether/backend/internal/database" ) func workerSchedules_PurgeAbandonedData() { reporter := NewReporter("Schedules", "PurgeAbandonedData") // Start a transaction tx := db.Db.Begin() // Get all schedule entries reporter.Status("1/2: Get all schedule entries") var schedules []db.Schedule err := tx.Model(&db.Schedule{}).Find(&schedules).Error if err != nil { tx.Rollback() reporter.Fail("Failed to retrieve schedule entries from the database: " + err.Error()) return } reporter.Status(fmt.Sprintf("Found %d schedule entries", len(schedules))) // Loop over schedule entries reporter.Status("2/2: Purge abandoned schedule entries") var purged int for _, schedule := range schedules { // Get source user var sourceUser db.User err = tx.Where("uuid = ?", schedule.Uuid).First(&sourceUser).Error // If error, check if error is user not found if err != nil { if err == gorm.ErrRecordNotFound { // If error is "not found", delete schedule data entry reporter.Status("Deleting abandoned schedule data for source user " + sourceUser.Username + " (" + schedule.Uuid + ")") purged += 1 err := tx.Model(&db.Schedule{}).Delete(&schedule).Error if err != nil { tx.Rollback() reporter.Fail("Failed to delete schedule data from the database: " + err.Error()) return } continue } } reporter.Status(fmt.Sprintf("Purged %d abandoned schedule entries", purged)) } // Commit the transaction if everything is successful err = tx.Commit().Error if err != nil { tx.Rollback() reporter.Fail("Failed to commit transaction: " + err.Error()) return } // Finish job reporter.Finish() }