Skip to content

armgit / wger

Public Imported from GitHub
0

Self hosted FLOSS fitness/workout, nutrition and weight tracker

Wrap custom delete-and-replace exercise logic in a transaction

Roland Geiderb0ce2a544d8a
diff --git a/wger/exercises/models/base.py b/wger/exercises/models/base.py
index eeb15f8c2..39dbc6abc 100644
--- a/wger/exercises/models/base.py
+++ b/wger/exercises/models/base.py
@@ -28,8 +28,8 @@ from django.db import (
OperationalError,
ProgrammingError,
models,
+ transaction,
)
-from django.db.models import Q
from django.urls import reverse
from django.utils.translation import get_language
@@ -150,8 +150,8 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
errors.append(
Warning(
'exercises without translations',
- hint=f'There are {no_translations} exercises without translations, this will '
- 'cause problems! You can output or delete them with "python manage.py '
+ hint=f'There are {no_translations} exercises without translations, this '
+ 'will cause problems! You can output or delete them with "python manage.py '
'exercises-health-check --help"',
id='wger.W002',
)
@@ -282,35 +282,40 @@ class Exercise(AbstractLicenseModel, AbstractHistoryMixin, models.Model):
except Exercise.DoesNotExist:
replace_by = None
- DeletionLog.objects.update_or_create(
- uuid=self.uuid,
- defaults={
- 'model_type': DeletionLog.MODEL_EXERCISE,
- 'comment': f'Exercise base of {self.get_translation(ENGLISH_SHORT_NAME)}',
- 'replaced_by': replace_by,
- },
- )
-
- # Replace references in workout logs and routines before deleting,
- # so that user data is not lost on this instance
- if replacement:
- SlotEntry.objects.filter(exercise=self).update(exercise=replacement)
- WorkoutLog.objects.filter(exercise=self).update(exercise=replacement)
-
- if transfer_media:
- ExerciseImage.objects.filter(exercise=self).update(exercise=replacement)
- ExerciseVideo.objects.filter(exercise=self).update(exercise=replacement)
-
- if transfer_translations:
- existing_languages = Translation.objects.filter(
- exercise=replacement,
- ).values_list('language_id', flat=True)
- Translation.objects.filter(exercise=self).exclude(
- language_id__in=list(existing_languages),
- ).update(exercise=replacement)
-
- reset_exercise_api_cache(str(self.uuid))
- if replacement:
- reset_exercise_api_cache(str(replacement.uuid))
-
- return super().delete(using, keep_parents)
+ # Wrap everything in a single transaction so the deletion-log entry,
+ # the reference repointing and the delete itself are all-or-nothing.
+ # Otherwise a failing delete would leave the exercise behind with its
+ # references already moved to the replacement.
+ with transaction.atomic():
+ DeletionLog.objects.update_or_create(
+ uuid=self.uuid,
+ defaults={
+ 'model_type': DeletionLog.MODEL_EXERCISE,
+ 'comment': f'Exercise base of {self.get_translation(ENGLISH_SHORT_NAME)}',
+ 'replaced_by': replace_by,
+ },
+ )
+
+ # Replace references in workout logs and routines before deleting,
+ # so that user data is not lost on this instance
+ if replacement:
+ SlotEntry.objects.filter(exercise=self).update(exercise=replacement)
+ WorkoutLog.objects.filter(exercise=self).update(exercise=replacement)
+
+ if transfer_media:
+ ExerciseImage.objects.filter(exercise=self).update(exercise=replacement)
+ ExerciseVideo.objects.filter(exercise=self).update(exercise=replacement)
+
+ if transfer_translations:
+ existing_languages = Translation.objects.filter(
+ exercise=replacement,
+ ).values_list('language_id', flat=True)
+ Translation.objects.filter(exercise=self).exclude(
+ language_id__in=list(existing_languages),
+ ).update(exercise=replacement)
+
+ reset_exercise_api_cache(str(self.uuid))
+ if replacement:
+ reset_exercise_api_cache(str(replacement.uuid))
+
+ return super().delete(using, keep_parents)
diff --git a/wger/exercises/tests/test_deletion_log.py b/wger/exercises/tests/test_deletion_log.py
index 78cb23a04..95bcbba2f 100644
--- a/wger/exercises/tests/test_deletion_log.py
+++ b/wger/exercises/tests/test_deletion_log.py
@@ -13,6 +13,7 @@
# You should have received a copy of the GNU Affero General Public License
# Standard Library
+from unittest.mock import patch
from uuid import UUID
# wger
@@ -115,6 +116,28 @@ class DeletionLogTestCase(WgerTestCase):
# The slot entry should now point to the replacement
self.assertEqual(SlotEntry.objects.filter(exercise=replacement).count(), 2)
+ def test_exercise_replace_by_delete_is_atomic_on_failure(self):
+ """
+ Test that a failure during the delete rolls back the deletion log and
+ the reference repointing instead of leaving them half-applied
+ """
+ exercise_to_delete = Exercise.objects.get(pk=1)
+ replacement = Exercise.objects.get(pk=2)
+
+ # Make the delete fail after the deletion log and the repointing
+ with patch(
+ 'wger.exercises.models.base.reset_exercise_api_cache',
+ side_effect=RuntimeError('boom'),
+ ):
+ with self.assertRaises(RuntimeError):
+ exercise_to_delete.delete(replace_by=str(replacement.uuid))
+
+ # Nothing was committed: no deletion log, and the slot entry still
+ # points to the original exercise
+ self.assertFalse(DeletionLog.objects.filter(uuid=exercise_to_delete.uuid).exists())
+ self.assertEqual(SlotEntry.objects.filter(exercise=exercise_to_delete).count(), 1)
+ self.assertEqual(SlotEntry.objects.filter(exercise=replacement).count(), 1)
+
def test_exercise_replace_by_transfers_media(self):
"""
Test that images and videos of the deleted exercise are reassigned to