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.
This commit is contained in:
Sybren A. Stüvel 2022-06-13 15:44:23 +02:00
parent e5d0e987e1
commit e35911d106
2 changed files with 40 additions and 0 deletions

View File

@ -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

View File

@ -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()