From affe933f3332386285ddce0f47db6d0bd1d99e1a Mon Sep 17 00:00:00 2001 From: Lukas Plank Date: Fri, 18 Oct 2024 07:11:50 +0200 Subject: [PATCH] fix: adapt count query generator to correctly count grouped models Fixes #99. --- rdfproxy/adapter.py | 2 +- rdfproxy/utils/sparql_utils.py | 10 ++++++++-- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/rdfproxy/adapter.py b/rdfproxy/adapter.py index 38f2718..0b3fe48 100644 --- a/rdfproxy/adapter.py +++ b/rdfproxy/adapter.py @@ -49,7 +49,7 @@ def query( size: int = 100, ) -> Page[_TModelInstance]: """Run a query against an endpoint and return a Page model object.""" - count_query: str = construct_count_query(self._query) + count_query: str = construct_count_query(query=self._query, model=self._model) items_query: str = ungrouped_pagination_base_query.substitute( query=self._query, offset=calculate_offset(page, size), limit=size ) diff --git a/rdfproxy/utils/sparql_utils.py b/rdfproxy/utils/sparql_utils.py index a401a8a..b76cb45 100644 --- a/rdfproxy/utils/sparql_utils.py +++ b/rdfproxy/utils/sparql_utils.py @@ -8,6 +8,7 @@ from typing import cast from SPARQLWrapper import QueryResult, SPARQLWrapper +from rdfproxy.utils._types import _TModelInstance ungrouped_pagination_base_query: Annotated[ @@ -35,9 +36,14 @@ def replace_query_select_clause(query: str, repl: str) -> str: return count_query -def construct_count_query(query: str) -> str: +def construct_count_query(query: str, model: type[_TModelInstance]) -> str: """Construct a generic count query from a SELECT query.""" - count_query = replace_query_select_clause(query, "select (count(*) as ?cnt)") + try: + group_by: str = model.model_config["group_by"] + count_query = construct_grouped_count_query(query, group_by) + except KeyError: + count_query = replace_query_select_clause(query, "select (count(*) as ?cnt)") + return count_query