Sfoglia il codice sorgente

Fixes #23721: Check the interfaces filter's compiled SQL

Assert on the SQL the filter compiles to: dcim_device appears once at any nesting depth, with EXISTS for true and NOT EXISTS for false. This replaces walking Django's where tree, which relied on ORM internals. Also explain why the false branch uses ~Exists rather than a pk__in subquery.
Jason Novinger 10 ore fa
parent
commit
0ce6a54eb3
2 ha cambiato i file con 11 aggiunte e 33 eliminazioni
  1. 1 0
      netbox/dcim/filtersets.py
  2. 10 33
      netbox/dcim/tests/test_filtersets.py

+ 1 - 0
netbox/dcim/filtersets.py

@@ -1684,6 +1684,7 @@ class DeviceFilterSet(
     def _interfaces(self, queryset, name, value):
         # Query Interface directly. Excluding on interfaces__isnull self-joins Device, which
         # PostgreSQL can plan very poorly when most devices have no interfaces (#23721).
+        # False uses ~Exists too: a pk__in subquery would negate to NOT IN, which PostgreSQL can't run as an anti join.
         has_interfaces = Exists(Interface.objects.filter(device=OuterRef('pk')))
         return queryset.filter(has_interfaces if value else ~has_interfaces)
 

+ 10 - 33
netbox/dcim/tests/test_filtersets.py

@@ -1,11 +1,9 @@
+import re
 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.db.models import Exists
-from django.db.models.expressions import NegatedExpression
-from django.db.models.sql import Query
 from django.test import TestCase, tag
 
 from circuits.models import Circuit, CircuitTermination, CircuitType, Provider
@@ -3475,37 +3473,16 @@ class DeviceTestCase(TestCase, ChangeLoggedFilterSetTestMixin):
         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 walk(node):
-            yield node
-            for child in getattr(node, 'children', []):
-                yield from walk(child)
-
-        def tables_read(query):
-            # Django keeps joins it trimmed in alias_map with a zero refcount, so count only live aliases,
-            # and follow nested subqueries on either side of a lookup so a self-join can't hide in one
-            tables = set()
-            for alias, join in query.alias_map.items():
-                if query.alias_refcount[alias]:
-                    tables.add(join.table_name)
-            for node in walk(query.where):
-                for side in (getattr(node, 'lhs', None), getattr(node, 'rhs', None)):
-                    side = getattr(side, 'expression', side)
-                    side = getattr(side, 'query', side)
-                    if isinstance(side, Query):
-                        tables |= tables_read(side)
-            return tables
-
-        for value, negated in (('true', False), ('false', True)):
+        for value in ('true', 'false'):
             with self.subTest(interfaces=value):
-                qs = self.filterset({'interfaces': value}, self.queryset).qs
-                # The filter adds a single condition, stored with the Exists (or ~Exists) as its lhs
-                self.assertEqual(len(qs.query.where.children), 1)
-                exists = getattr(qs.query.where.children[0], 'lhs', None)
-                if negated:
-                    self.assertIsInstance(exists, NegatedExpression)
-                    exists = exists.expression
-                self.assertIsInstance(exists, Exists)
-                self.assertEqual(tables_read(exists.query), {Interface._meta.db_table})
+                sql = str(self.filterset({'interfaces': value}, self.queryset).qs.query)
+                # Device appears once, as the outer table, at any nesting depth
+                self.assertEqual(len(re.findall(r'(?:FROM|JOIN) "dcim_device"', sql)), 1)
+                if value == 'true':
+                    self.assertIn('EXISTS', sql)
+                    self.assertNotIn('NOT EXISTS', sql)
+                else:
+                    self.assertIn('NOT EXISTS', sql)
 
     def test_pass_through_ports(self):
         params = {'pass_through_ports': 'true'}