Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 36 additions & 2 deletions dojo/notes/helper.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import logging
from contextlib import contextmanager
from contextvars import ContextVar

from django.db.models import Prefetch, Q

Expand Down Expand Up @@ -56,8 +58,40 @@ def visible_notes(notes, user):


def delete_related_notes(obj):
"""
Delete ``obj``'s notes and their edit history in a fixed number of queries, however many notes there are.

A note's history rows belong to that note alone (``Notes.copy`` copies them), so they go with it. The per-note
``pre_delete`` receiver (dojo.notes.signals) deletes them one note at a time, about four queries per note, which
made deleting a finding with a hundred notes cost some 500 queries. Here every history row is read once, the notes
are deleted with that receiver standing down, and the history rows are deleted in one batch.
"""
if not hasattr(obj, "notes"):
logger.warning(f"Attempted to delete notes from object type {type(obj)} without 'notes' attribute.")
return
logger.debug(f"Deleting {obj.notes.count()} notes for {type(obj).__name__} {obj.id}")
obj.notes.all().delete()
note_ids = list(obj.notes.values_list("id", flat=True))
logger.debug("Deleting %d notes for %s %s", len(note_ids), type(obj).__name__, obj.id)
if not note_ids:
return
history_ids = list(Notes.history.through.objects.filter(notes__in=note_ids).values_list("notehistory_id", flat=True))
with note_history_deleted_by_caller():
Notes.objects.filter(id__in=note_ids).delete()
if history_ids:
NoteHistory.objects.filter(id__in=history_ids).delete()


_note_history_deleted_by_caller = ContextVar("note_history_deleted_by_caller", default=False)


@contextmanager
def note_history_deleted_by_caller():
"""Notes deleted inside this block leave their history to the caller, which deletes it in one batch."""
token = _note_history_deleted_by_caller.set(True)
try:
yield
finally:
_note_history_deleted_by_caller.reset(token)


def is_note_history_deleted_by_caller() -> bool:
return _note_history_deleted_by_caller.get()
4 changes: 4 additions & 0 deletions dojo/notes/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from django.dispatch import receiver

from dojo.models import Notes
from dojo.notes.helper import is_note_history_deleted_by_caller

logger = logging.getLogger(__name__)

Expand All @@ -15,4 +16,7 @@ def delete_note_history(note):

@receiver(pre_delete, sender=Notes)
def note_pre_delete(sender, instance, **kwargs):
# delete_related_notes deletes a whole batch's history itself, in one query.
if is_note_history_deleted_by_caller():
return
delete_note_history(instance)
98 changes: 98 additions & 0 deletions unittests/test_notes_delete_in_bulk.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
from django.db import connection
from django.test import TestCase
from django.test.utils import CaptureQueriesContext
from django.utils.timezone import now

from dojo.models import (
Dojo_User,
Engagement,
Finding,
NoteHistory,
Notes,
Product,
Product_Type,
Test,
Test_Type,
)
from dojo.notes.helper import delete_related_notes


class TestDeleteRelatedNotesInBulk(TestCase):

"""
Regression: deleting an object's notes deleted each note's edit history from the per-note pre_delete receiver
(dojo.notes.signals), about four queries per note, so deleting a finding with a hundred notes ran some 500 queries.
delete_related_notes now deletes every note and every history row in a fixed number of queries. The receiver still
cleans up a note deleted on its own.
"""

@classmethod
def setUpTestData(cls):
cls.user = Dojo_User.objects.create(username="notes_bulk_user")
product = Product.objects.create(
name="Notes Bulk Product",
prod_type=Product_Type.objects.create(name="Notes Bulk Product Type"),
description="notes bulk",
)
engagement = Engagement.objects.create(
name="Notes Bulk Engagement", product=product, target_start=now(), target_end=now(),
)
cls.test = Test.objects.create(
title="Notes Bulk Test",
engagement=engagement,
test_type=Test_Type.objects.create(name="Notes Bulk Test Type"),
target_start=now(),
target_end=now(),
)

def _finding_with_notes(self, count):
finding = Finding.objects.create(
title=f"Notes Bulk {count}", test=self.test, reporter=self.user, severity="High",
)
for n in range(count):
note = Notes.objects.create(entry=f"note {n}", author=self.user)
note.history.add(
NoteHistory.objects.create(data=f"first {n}", current_editor=self.user),
NoteHistory.objects.create(data=f"second {n}", current_editor=self.user),
)
finding.notes.add(note)
note_ids = list(finding.notes.values_list("id", flat=True))
history_ids = list(Notes.history.through.objects.filter(notes__in=note_ids).values_list("notehistory_id", flat=True))
return finding, note_ids, history_ids

def _delete(self, count):
finding, note_ids, history_ids = self._finding_with_notes(count)
with CaptureQueriesContext(connection) as ctx:
delete_related_notes(finding)
left = (
Notes.objects.filter(id__in=note_ids).count(),
NoteHistory.objects.filter(id__in=history_ids).count(),
)
self.assertEqual(left, (0, 0), f"{count} notes: notes and history rows left after the delete: {left}")
return len(ctx.captured_queries)

def test_query_count_does_not_grow_with_notes(self):
few, many = self._delete(1), self._delete(10)
self.assertEqual(few, many, f"delete_related_notes: {few} queries for 1 note, {many} for 10")

def test_no_notes_is_one_query(self):
finding, _, _ = self._finding_with_notes(0)
with CaptureQueriesContext(connection) as ctx:
delete_related_notes(finding)
self.assertEqual(len(ctx.captured_queries), 1, [q["sql"] for q in ctx.captured_queries])

def test_other_notes_and_their_history_are_kept(self):
_, kept_note_ids, kept_history_ids = self._finding_with_notes(2)
self._delete(3)
self.assertEqual(
(
Notes.objects.filter(id__in=kept_note_ids).count(),
NoteHistory.objects.filter(id__in=kept_history_ids).count(),
),
(2, 4),
)

def test_a_note_deleted_on_its_own_still_takes_its_history(self):
_, note_ids, history_ids = self._finding_with_notes(1)
Notes.objects.get(id=note_ids[0]).delete()
self.assertEqual(NoteHistory.objects.filter(id__in=history_ids).count(), 0)
Loading