From e35911d106e159a1dfb33cf1dcb56d9dac2693bc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sybren=20A=2E=20St=C3=BCvel?= Date: Mon, 13 Jun 2022 15:44:23 +0200 Subject: [PATCH] Manager: add ability to delete jobs This is needed for a future unit test, and exposed the fact that SQLite didn't enforce foreign key constraints (and thus also didn't handle on-delete-cascade attributes). This has been fixed in the previous commit. --- internal/manager/persistence/jobs.go | 12 ++++++++++ internal/manager/persistence/jobs_test.go | 28 +++++++++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/internal/manager/persistence/jobs.go b/internal/manager/persistence/jobs.go index 81f5223a..f02b2fe1 100644 --- a/internal/manager/persistence/jobs.go +++ b/internal/manager/persistence/jobs.go @@ -183,6 +183,18 @@ func (db *DB) FetchJob(ctx context.Context, jobUUID string) (*Job, error) { return &dbJob, nil } +// DeleteJob deletes a job from the database. +// The deletion cascades to its tasks and other job-related tables. +func (db *DB) DeleteJob(ctx context.Context, jobUUID string) error { + tx := db.gormDB.WithContext(ctx). + Where("uuid = ?", jobUUID). + Delete(&Job{}) + if tx.Error != nil { + return jobError(tx.Error, "deleting job") + } + return nil +} + func (db *DB) FetchJobsInStatus(ctx context.Context, jobStatuses ...api.JobStatus) ([]*Job, error) { var jobs []*Job diff --git a/internal/manager/persistence/jobs_test.go b/internal/manager/persistence/jobs_test.go index 47210c4d..d8465dc5 100644 --- a/internal/manager/persistence/jobs_test.go +++ b/internal/manager/persistence/jobs_test.go @@ -53,6 +53,34 @@ func TestStoreAuthoredJob(t *testing.T) { assert.Equal(t, api.TaskStatusQueued, tasks[2].Status) } +func TestDeleteJob(t *testing.T) { + ctx, cancel, db := persistenceTestFixtures(t, 1*time.Second) + defer cancel() + + authJob := createTestAuthoredJobWithTasks() + persistAuthoredJob(t, ctx, db, authJob) + + // Delete the job. + err := db.DeleteJob(ctx, authJob.JobID) + assert.NoError(t, err) + + // Test it cannot be found via the API. + _, err = db.FetchJob(ctx, authJob.JobID) + assert.ErrorIs(t, err, ErrJobNotFound, "deleted jobs should not be found") + + // Test that the job is really gone. + var numJobs int64 + tx := db.gormDB.Model(&Job{}).Count(&numJobs) + assert.NoError(t, tx.Error) + assert.Equal(t, int64(0), numJobs, "the job should have been deleted") + + // Test that the tasks are gone too. + var numTasks int64 + tx = db.gormDB.Model(&Task{}).Count(&numTasks) + assert.NoError(t, tx.Error) + assert.Equal(t, int64(0), numTasks, "tasks should have been deleted along with their job") +} + func TestJobHasTasksInStatus(t *testing.T) { ctx, close, db, job, _ := jobTasksTestFixtures(t) defer close()