Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[server] Wrap inside db transaction

Neeraj Gupta05f5c7f439bb
diff --git a/server/pkg/repo/storagebonus/bf_addon.go b/server/pkg/repo/storagebonus/bf_addon.go
index 00326b4777..2c5a759c28 100644
--- a/server/pkg/repo/storagebonus/bf_addon.go
+++ b/server/pkg/repo/storagebonus/bf_addon.go
@@ -24,20 +24,34 @@ func (r *Repository) RemoveAddOnBonus(ctx context.Context, bonusType storagebonu
if err := _validate(bonusType); err != nil {
return 0, err
}
+
bonusID := fmt.Sprintf("%s-%d", bonusType, userID)
- res, err := r.DB.ExecContext(ctx, "DELETE FROM storage_bonus WHERE bonus_id = $1", bonusID)
+
+ tx, err := r.DB.BeginTx(ctx, nil)
if err != nil {
- return 0, err
+ return 0, fmt.Errorf("failed to begin transaction: %w", err)
+ }
+ defer tx.Rollback() // Will be no-op if transaction is committed
+ res, err := tx.ExecContext(ctx, "DELETE FROM storage_bonus WHERE bonus_id = $1", bonusID)
+ if err != nil {
+ return 0, fmt.Errorf("failed to execute delete query: %w", err)
}
- // verify if the bonus was removed
rowsAffected, err := res.RowsAffected()
if err != nil {
- return 0, err
+ return 0, fmt.Errorf("failed to get affected rows: %w", err)
}
- if rowsAffected == int64(0) {
+ switch {
+ case rowsAffected == 0:
return 0, ente.NewBadRequestWithMessage(fmt.Sprintf("bonus not found for user %d with bonusID %s", userID, bonusID))
+ case rowsAffected > 1:
+ return 0, fmt.Errorf("more than one (%d) bonus found for user %d with bonusID %s", rowsAffected, userID, bonusID)
+ }
+
+ if err := tx.Commit(); err != nil {
+ return 0, fmt.Errorf("failed to commit transaction: %w", err)
}
- return rowsAffected, nil
+
+ return 1, nil // We know exactly one row was affected at this point
}
func (r *Repository) UpdateAddOnBonus(ctx context.Context, bonusType storagebonus.BonusType, userID int64, validTill int64, storage int64) error {