From 9f32ae5d2e93e0b1197e240f08224f6718c04cda Mon Sep 17 00:00:00 2001 From: David Dworken Date: Sun, 15 Oct 2023 10:29:47 -0700 Subject: [PATCH] Refactor deletion request creation to happen in a transaction to avoid 1-n DB queries --- backend/server/internal/database/db.go | 28 +++++++++++++------------- 1 file changed, 14 insertions(+), 14 deletions(-) diff --git a/backend/server/internal/database/db.go b/backend/server/internal/database/db.go index 55f68fc..56b071e 100644 --- a/backend/server/internal/database/db.go +++ b/backend/server/internal/database/db.go @@ -243,22 +243,22 @@ func (db *DB) DeletionRequestCreate(ctx context.Context, request *shared.Deletio fmt.Printf("db.DeletionRequestCreate: Found %d devices\n", len(devices)) - // TODO: maybe this should be a transaction? - for _, device := range devices { - request.DestinationDeviceId = device.DeviceId - tx := db.WithContext(ctx).Create(&request) - if tx.Error != nil { - return fmt.Errorf("tx.Error: %w", tx.Error) + return db.Transaction(func(tx *gorm.DB) error { + for _, device := range devices { + request.DestinationDeviceId = device.DeviceId + tx := db.WithContext(ctx).Create(&request) + if tx.Error != nil { + return fmt.Errorf("create: tx.Error: %w", tx.Error) + } } - } - numDeleted, err := db.DeleteMessagesFromBackend(ctx, userID, request.Messages.Ids) - if err != nil { - return fmt.Errorf("db.DeleteMessagesFromBackend: %w", err) - } - fmt.Printf("addDeletionRequestHandler: Deleted %d rows in the backend\n", numDeleted) - - return nil + numDeleted, err := db.DeleteMessagesFromBackend(ctx, userID, request.Messages.Ids) + if err != nil { + return fmt.Errorf("db.DeleteMessagesFromBackend: %w", err) + } + fmt.Printf("addDeletionRequestHandler: Deleted %d rows in the backend\n", numDeleted) + return nil + }) } func (db *DB) FeedbackCreate(ctx context.Context, feedback *shared.Feedback) error {