2
0
Эх сурвалжийг харах

Fixes #23721: Use an EXISTS subquery for the device interfaces filter

Filtering devices on interfaces__isnull self-joined the device table, and PostgreSQL can choose a very slow plan for that when most devices have no interfaces. Query the interface table with a correlated EXISTS instead. Results are unchanged.
Jason Novinger 1 долоо хоног өмнө
parent
commit
ee3ec000a0

+ 5 - 2
netbox/dcim/filtersets.py

@@ -1,7 +1,7 @@
 import django_filters
 import netaddr
 from django.contrib.contenttypes.models import ContentType
-from django.db.models import Func, IntegerField, Q
+from django.db.models import Exists, Func, IntegerField, OuterRef, Q
 from django.utils.translation import gettext as _
 from drf_spectacular.types import OpenApiTypes
 from drf_spectacular.utils import extend_schema_field
@@ -1682,7 +1682,10 @@ class DeviceFilterSet(
         return queryset.exclude(poweroutlets__isnull=value)
 
     def _interfaces(self, queryset, name, value):
-        return queryset.exclude(interfaces__isnull=value)
+        # Query Interface directly. Excluding on interfaces__isnull self-joins Device, which
+        # PostgreSQL can plan very poorly when most devices have no interfaces (#23721).
+        has_interfaces = Exists(Interface.objects.filter(device=OuterRef('pk')))
+        return queryset.filter(has_interfaces if value else ~has_interfaces)
 
     def _pass_through_ports(self, queryset, name, value):
         return queryset.exclude(

+ 23 - 1
netbox/dcim/tests/test_filtersets.py

@@ -3,7 +3,8 @@ from decimal import Decimal
 from django.conf import settings
 from django.contrib.contenttypes.models import ContentType
 from django.db import DEFAULT_DB_ALIAS, connection
-from django.test import TestCase
+from django.db.models import Exists
+from django.test import TestCase, tag
 
 from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
 from dcim.choices import *
@@ -3466,6 +3467,27 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         params = {'interfaces': 'false'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 1)
 
+    @tag('performance', 'regression')
+    def test_interfaces_query_uses_interface_subquery(self):
+        """
+        Regression test for #23721: the interfaces filter must query the Interface table directly
+        rather than self-joining Device, which PostgreSQL can plan very poorly on large inventories.
+        """
+        def find_exists(node):
+            # An EXISTS condition compiles to an exact lookup with the Exists (or its negation) as lhs
+            lhs = getattr(node, 'lhs', None)
+            lhs = getattr(lhs, 'expression', lhs)
+            if isinstance(lhs, Exists):
+                return [lhs]
+            return [found for child in getattr(node, 'children', []) for found in find_exists(child)]
+
+        for value in ('true', 'false'):
+            with self.subTest(interfaces=value):
+                qs = self.filterset({'interfaces': value}, self.queryset).qs
+                subqueries = find_exists(qs.query.where)
+                self.assertEqual(len(subqueries), 1)
+                self.assertIs(subqueries[0].query.model, Interface)
+
     def test_pass_through_ports(self):
         params = {'pass_through_ports': 'true'}
         self.assertEqual(self.filterset(params, self.queryset).qs.count(), 2)