Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(statistics): use subquery instead of join to avoid cartesian product #558

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
fix(statistics): use subquery instead of join to avoid cartesian product
The way we filter in the statistics view, any added filter (that affects
reports) adds a "dimension" to the cartesian product, exploding the total
number of hours reported.

Instead of using JOIN, we do EXISTS(SUBQUERY) now, which should avoid this
issue. Might be a tiny bit slower, but let's try to make it correct first, then fast.
  • Loading branch information
winged committed Dec 23, 2024
commit 0fcff27bdd48736c675cfada34f87d93caad3e98
9 changes: 7 additions & 2 deletions backend/timed/reports/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
from zipfile import ZipFile

from django.conf import settings
from django.db.models import F, Q, QuerySet, Sum
from django.db.models import Exists, F, OuterRef, Q, QuerySet, Sum
from django.db.models.functions import ExtractMonth, ExtractYear
from django.http import HttpResponse
from django.utils.http import content_disposition_header
Expand Down Expand Up @@ -117,9 +117,14 @@ def filter(self, /, **kwargs):
return new_qs

def filter_base(self, *args, **kwargs):
filtered = (
self.model.objects.filter(*args, **kwargs)
.values("pk")
.filter(pk=OuterRef("pk"))
)
return StatisticQueryset(
model=self.model,
base_qs=self._base.filter(*args, **kwargs),
base_qs=self._base.filter(Exists(filtered)),
catch_prefixes=self._catch_prefixes,
agg_filters=self._agg_filters,
)
Expand Down
Loading