From ee4e41329ada6580704e15bcff295b240c86373f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Tue, 28 May 2024 16:34:09 +0200 Subject: [PATCH] Manager: properly set task.JobUUID and task.WorkerUUID when using GORM Add a GORM hook that sets `task.JobUUID` and `.WorkerUUID`. These were only set by the sqlc code; this change ensures that they are now always set, so that the caller doesn't have to worry about which function is already ported to sqlc and which one is still GORM. --- internal/manager/persistence/jobs.go | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/internal/manager/persistence/jobs.go b/internal/manager/persistence/jobs.go index fc88d8fe..17333bdb 100644 --- a/internal/manager/persistence/jobs.go +++ b/internal/manager/persistence/jobs.go @@ -65,14 +65,14 @@ type Task struct { Type string `gorm:"type:varchar(32);default:''"` JobID uint `gorm:"default:0"` Job *Job `gorm:"foreignkey:JobID;references:ID;constraint:OnDelete:CASCADE"` - JobUUID string `gorm:"-"` // Fetched by SQLC, not GORM. + JobUUID string `gorm:"-"` // Fetched by SQLC, handled by GORM in Task.AfterFind() Priority int `gorm:"type:smallint;default:50"` Status api.TaskStatus `gorm:"type:varchar(16);default:''"` // Which worker is/was working on this. WorkerID *uint Worker *Worker `gorm:"foreignkey:WorkerID;references:ID;constraint:OnDelete:SET NULL"` - WorkerUUID string `gorm:"-"` // Fetched by SQLC, not GORM. + WorkerUUID string `gorm:"-"` // Fetched by SQLC, handled by GORM in Task.AfterFind() LastTouchedAt time.Time `gorm:"index"` // Should contain UTC timestamps. // Dependencies are tasks that need to be completed before this one can run. @@ -82,6 +82,17 @@ type Task struct { Activity string `gorm:"type:varchar(255);default:''"` } +// AfterFind updates the task JobUUID and WorkerUUID fields from its job/worker, if known. +func (t *Task) AfterFind(tx *gorm.DB) error { + if t.JobUUID == "" && t.Job != nil { + t.JobUUID = t.Job.UUID + } + if t.WorkerUUID == "" && t.Worker != nil { + t.WorkerUUID = t.Worker.UUID + } + return nil +} + type Commands []Command type Command struct {