diff --git a/arches_search/utils/search/compiler.py b/arches_search/utils/search/compiler.py index 45866e52..42d1f78c 100644 --- a/arches_search/utils/search/compiler.py +++ b/arches_search/utils/search/compiler.py @@ -156,23 +156,23 @@ def __init__( for graph_payload in search_payload.advanced_search_queries or [] } - def compile(self) -> SearchResult: + def compile(self, return_counts: bool = True) -> SearchResult: """ The matches in the graphs graph_slugs names, how many there are, and how many of them each of those graphs holds. + + With return_counts=False the counts are left as None and their grouped + COUNT is never run. """ - requested_slugs = set(self.search_payload.graph_slugs or []) - requested_graphs = [ - graph for graph in self._named_graphs if graph.slug in requested_slugs - ] + requested_graphs = self._requested_graphs() if not requested_graphs: - return SearchResult( - results=self._base_resources().none(), - scoped_count=0, - resource_type_counts=[], - ) + matches = self._base_resources().none() + else: + matches = self._permitted_matches(requested_graphs) + + if not return_counts: + return SearchResult(results=matches) - matches = self._permitted_matches(requested_graphs) # One grouped count gives both the per-graph counts and the total, so a # paginator can skip its own COUNT(*). counts_by_graph_id = _counts_by_graph_id(matches) @@ -184,6 +184,10 @@ def compile(self) -> SearchResult: ), ) + def _requested_graphs(self) -> List[SearchableGraph]: + requested_slugs = set(self.search_payload.graph_slugs or []) + return [graph for graph in self._named_graphs if graph.slug in requested_slugs] + @cached_property def _named_graphs(self) -> List[SearchableGraph]: """ diff --git a/arches_search/utils/search/types.py b/arches_search/utils/search/types.py index c6b4a9ff..c78a50a2 100644 --- a/arches_search/utils/search/types.py +++ b/arches_search/utils/search/types.py @@ -40,12 +40,12 @@ class SearchResult: What the compiler found in the graphs graph_slugs names, before any projection or paging. scoped_count is how many resources `results` holds, and what pagination is measured against; resource_type_counts splits it by - graph. + graph. Both are None when the compiler was asked not to count. """ results: QuerySet - scoped_count: int - resource_type_counts: List[Dict[str, Any]] + scoped_count: Optional[int] = None + resource_type_counts: Optional[List[Dict[str, Any]]] = None @dataclass(frozen=True) diff --git a/arches_search/views/api/search_export.py b/arches_search/views/api/search_export.py index 82ca2171..948615e4 100644 --- a/arches_search/views/api/search_export.py +++ b/arches_search/views/api/search_export.py @@ -30,7 +30,11 @@ def post(self, request): search_payload = SearchPayload.from_body(body) try: validate_search_payload(search_payload) - queryset = SearchCompiler(search_payload, request.user).compile().results + queryset = ( + SearchCompiler(search_payload, request.user) + .compile(return_counts=False) + .results + ) except ValidationError as error: return JSONResponse({"error": str(error)}, status=400) diff --git a/arches_search/views/api/search_mvt.py b/arches_search/views/api/search_mvt.py index 842086ce..782f7637 100644 --- a/arches_search/views/api/search_mvt.py +++ b/arches_search/views/api/search_mvt.py @@ -62,7 +62,9 @@ def post(self, request): try: search_payload = SearchPayload.from_body(body) validate_search_payload(search_payload) - SearchCompiler(search_payload, request.user).compile() + SearchCompiler(search_payload, request.user).compile( + return_counts=False + ).results except ValidationError as error: return JSONResponse({"error": str(error)}, status=400) @@ -86,15 +88,17 @@ def get(self, request, context_id, zoom, x, y): return HttpResponse(cached_tile, content_type="application/x-protobuf") try: - search_result = SearchCompiler( - SearchPayload.from_body(body), request.user - ).compile() + matches = ( + SearchCompiler(SearchPayload.from_body(body), request.user) + .compile(return_counts=False) + .results + ) except ValidationError: # The context was checked as the user who created it. Another user # may not be able to read a node it names, and gets nothing drawn. return HttpResponse(b"", content_type="application/x-protobuf") - search_results_queryset = search_result.results.values("resourceinstanceid") + search_results_queryset = matches.values("resourceinstanceid") mvt_tile = self._generate_tile(search_results_queryset, zoom, x, y) mvt_cache.set(tile_key, mvt_tile, settings.TILE_CACHE_TIMEOUT) diff --git a/arches_search/views/api/search_results_export.py b/arches_search/views/api/search_results_export.py index cce239c4..ead14feb 100644 --- a/arches_search/views/api/search_results_export.py +++ b/arches_search/views/api/search_results_export.py @@ -58,7 +58,11 @@ def post(self, request): try: validate_search_payload(search_payload) - queryset = SearchCompiler(search_payload, request.user).compile().results + queryset = ( + SearchCompiler(search_payload, request.user) + .compile(return_counts=False) + .results + ) except ValidationError as error: return JSONResponse({"error": str(error)}, status=400) diff --git a/tests/integration/utils/search/test_search_compiler.py b/tests/integration/utils/search/test_search_compiler.py index 35a8c23b..3974ec7c 100644 --- a/tests/integration/utils/search/test_search_compiler.py +++ b/tests/integration/utils/search/test_search_compiler.py @@ -14,8 +14,10 @@ from django.db import connection from django.test import TestCase, override_settings from django.test.utils import CaptureQueriesContext +from django.contrib.auth.models import Group from django.urls import reverse +from arches.app.utils.permission_backend import assign_perm from arches.app.models.models import ( GraphModel, ResourceInstance, @@ -209,6 +211,91 @@ def _search_models_payloads(self, search_models, operator, operands): for graph in (self.graph_a, self.graph_b) ] + def _compile_skipping_counts_ids(self, **kwargs): + slugs = kwargs.pop("graph_slugs", [self.graph_a.slug, self.graph_b.slug]) + payload = SearchPayload( + graph_slugs=slugs, + term_search=kwargs.get("term_search"), + advanced_search_queries=kwargs.get("advanced_search_queries"), + ) + compiler = SearchCompiler(payload, self.user) + return set( + compiler.compile(return_counts=False).results.values_list( + "resourceinstanceid", flat=True + ) + ), self._result_ids(SearchCompiler(payload, self.user).compile()) + + def test_compile_skipping_counts_matches_compile_with_no_requested_graphs(self): + results_ids, compile_ids = self._compile_skipping_counts_ids(graph_slugs=[]) + self.assertEqual(results_ids, set()) + self.assertEqual(results_ids, compile_ids) + + def test_compile_skipping_counts_matches_compile_for_a_term_search(self): + results_ids, compile_ids = self._compile_skipping_counts_ids( + term_search={"terms": ["amber"], "max_hops": 0} + ) + self.assertTrue(results_ids) + self.assertEqual(results_ids, compile_ids) + + def test_compile_skipping_counts_matches_compile_for_an_advanced_search(self): + results_ids, compile_ids = self._compile_skipping_counts_ids( + advanced_search_queries=self._search_models_payloads( + ["DateSearch", "DateRangeSearch"], + "BETWEEN", + [ + {"type": "LITERAL", "value": "1890-01-01"}, + {"type": "LITERAL", "value": "1910-01-01"}, + ], + ) + ) + self.assertEqual(results_ids, {self.amber_mineral.resourceinstanceid}) + self.assertEqual(results_ids, compile_ids) + + def test_compile_skipping_counts_refuses_a_payload_naming_an_unsearched_graph(self): + payload = SearchPayload( + graph_slugs=[self.graph_a.slug], + term_search=None, + advanced_search_queries=[ + { + "graph_slug": self.graph_a.slug + "-typo", + "scope": "RESOURCE", + "logic": "AND", + "clauses": [], + "groups": [], + "aggregations": [], + "relationship": None, + } + ], + ) + with self.assertRaises(ValidationError): + SearchCompiler(payload, self.user).compile(return_counts=False).results + + def test_compile_skipping_counts_leaves_the_counts_unset(self): + payload = SearchPayload( + graph_slugs=[self.graph_a.slug], + term_search=None, + advanced_search_queries=None, + ) + result = SearchCompiler(payload, self.user).compile(return_counts=False) + self.assertIsNone(result.scoped_count) + self.assertIsNone(result.resource_type_counts) + + def test_compile_skipping_counts_issues_no_count_query(self): + payload = SearchPayload( + graph_slugs=[self.graph_a.slug, self.graph_b.slug], + term_search={"terms": ["amber"], "max_hops": 0}, + advanced_search_queries=None, + ) + with CaptureQueriesContext(connection) as queries: + list( + SearchCompiler(payload, self.user) + .compile(return_counts=False) + .results.values("resourceinstanceid") + ) + self.assertTrue(queries.captured_queries) + for query in queries.captured_queries: + self.assertNotIn("COUNT(", query["sql"].upper()) + def test_text_match_direct_only_max_hops_zero(self): result = self._search(term_search={"terms": ["amber"], "max_hops": 0}) self.assertEqual( @@ -798,3 +885,46 @@ def test_pre_filter_narrows_addressed_and_unaddressed_graphs_alike(self): self.assertEqual(ids & self.DOG_IDS, {DOG_B_ID}) with self.subTest("the unaddressed graph is narrowed to it"): self.assertEqual(ids & self.PERSON_IDS, {PERSON_A_ID, PERSON_B_ID}) + + +class CompileResultsPermissionTests(TestCase): + @classmethod + def setUpTestData(cls): + cls.member = get_user_model().objects.create_user( + username="compile-results-member", password="password" + ) + cls.group = Group.objects.create(name="compile_skipping_counts_group") + cls.member.groups.add(cls.group) + cls.graph = GraphModel.objects.create( + graphid=uuid.uuid4(), + name="Permissioned", + slug="compile-results-permissioned", + isresource=True, + is_active=True, + ) + cls.granted = ResourceInstance.objects.create( + resourceinstanceid=uuid.uuid4(), graph=cls.graph + ) + cls.hidden = ResourceInstance.objects.create( + resourceinstanceid=uuid.uuid4(), graph=cls.graph + ) + assign_perm("view_resourceinstance", cls.group, cls.granted) + + def test_compile_skipping_counts_applies_the_permission_filter(self): + payload = SearchPayload( + graph_slugs=[self.graph.slug], + term_search=None, + advanced_search_queries=None, + ) + results_ids = set( + SearchCompiler(payload, self.member) + .compile(return_counts=False) + .results.values_list("resourceinstanceid", flat=True) + ) + compile_ids = set( + SearchCompiler(payload, self.member) + .compile() + .results.values_list("resourceinstanceid", flat=True) + ) + self.assertEqual(results_ids, {self.granted.resourceinstanceid}) + self.assertEqual(results_ids, compile_ids) diff --git a/tests/test_search_mvt_context_api.py b/tests/test_search_mvt_context_api.py new file mode 100644 index 00000000..02aef8bb --- /dev/null +++ b/tests/test_search_mvt_context_api.py @@ -0,0 +1,102 @@ +import json +import uuid +from unittest.mock import patch + +from django.contrib.auth import get_user_model +from django.db.models import QuerySet +from django.test import TestCase, override_settings +from django.urls import reverse + +from arches.app.models.models import GraphModel + +from arches_search.views.api.search_mvt import SearchMVTAPI + +# python manage.py test tests.test_search_mvt_context_api --settings="tests.test_settings" + +TILE_BYTES = b"fixed-tile" +SEARCHRESULTS_CACHES = { + "default": {"BACKEND": "django.core.cache.backends.dummy.DummyCache"}, + "searchresults": { + "BACKEND": "django.core.cache.backends.locmem.LocMemCache", + "LOCATION": "mvt-context-test", + }, +} + + +@override_settings(CACHES=SEARCHRESULTS_CACHES) +class SearchMVTSkipsCountTest(TestCase): + @classmethod + def setUpTestData(cls): + cls.user = get_user_model().objects.create_superuser( + username="mvt-context-admin", + email="mvt-context@example.com", + password="password", + ) + cls.graph = GraphModel.objects.create( + graphid=uuid.uuid4(), + name="MVT", + slug="mvt-context-graph", + isresource=True, + is_active=True, + ) + + def setUp(self): + self.client.force_login(self.user) + compile_patcher = patch( + "arches_search.utils.search.compiler._counts_by_graph_id", + side_effect=AssertionError("the counts should not be computed"), + ) + compile_patcher.start() + self.addCleanup(compile_patcher.stop) + + def _post_context(self, body): + return self.client.post( + reverse("search_mvt_context"), + json.dumps(body), + content_type="application/json", + ) + + def test_a_valid_context_is_created_without_counting(self): + response = self._post_context({"graph_slugs": [self.graph.slug]}) + + self.assertEqual(response.status_code, 200) + self.assertIn("context_id", response.json()) + + def test_an_invalid_payload_is_still_a_400(self): + response = self._post_context( + { + "graph_slugs": [self.graph.slug], + "advanced_search_queries": [ + { + "graph_slug": self.graph.slug + "-typo", + "scope": "RESOURCE", + "logic": "AND", + "clauses": [], + "groups": [], + "aggregations": [], + "relationship": None, + } + ], + } + ) + + self.assertEqual(response.status_code, 400) + + def test_a_tile_is_generated_from_the_matches_without_counting(self): + context_id = self._post_context({"graph_slugs": [self.graph.slug]}).json()[ + "context_id" + ] + + with patch.object( + SearchMVTAPI, "_generate_tile", return_value=TILE_BYTES + ) as generate_tile: + response = self.client.get( + reverse( + "search_mvt", + kwargs={"context_id": context_id, "zoom": 6, "x": 9, "y": 24}, + ) + ) + + self.assertEqual(response.status_code, 200) + self.assertEqual(response.content, TILE_BYTES) + self.assertIsInstance(generate_tile.call_args.args[0], QuerySet)