From 5b3f1711fe9f2aa0b50c890bce57c09728f6b5c9 Mon Sep 17 00:00:00 2001 From: Lukas Plank Date: Thu, 5 Dec 2024 08:57:33 +0100 Subject: [PATCH] fix: resolve group_by config values for SPARQL binding aliases Currently, query constructors naively inject the 'group_by' value from the model_config into SPARQL queries. This works until a field name does not correspond to a SPARQL binding name, i.e. until rdfproxy.SPARQLBinding aliases are used. So, field-based grouping obviously requires 'group_by' values to resolve SPARQL binding aliases - which this change implements. Note: The change introduces duplication for resolving SPARQL binding aliases. The planned QueryConstructor class (issue #134) will get rid of this and other design flaws. Fixes #161 --- rdfproxy/utils/sparql_utils.py | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/rdfproxy/utils/sparql_utils.py b/rdfproxy/utils/sparql_utils.py index fa192cc..a064898 100644 --- a/rdfproxy/utils/sparql_utils.py +++ b/rdfproxy/utils/sparql_utils.py @@ -8,7 +8,7 @@ from SPARQLWrapper import QueryResult, SPARQLWrapper from rdfproxy.utils._exceptions import QueryConstructionException -from rdfproxy.utils._types import ItemsQueryConstructor, _TModelInstance +from rdfproxy.utils._types import ItemsQueryConstructor, SPARQLBinding, _TModelInstance def construct_ungrouped_pagination_query(query: str, limit: int, offset: int) -> str: @@ -79,6 +79,12 @@ def get_items_query_constructor( if (group_by_value := model.model_config.get("group_by", None)) is None: return construct_ungrouped_pagination_query + + elif meta := model.model_fields[group_by_value].metadata: + group_by_value = next( + filter(lambda x: isinstance(x, SPARQLBinding), meta), group_by_value + ) + return partial(construct_grouped_pagination_query, group_by_value=group_by_value) @@ -96,7 +102,14 @@ def construct_count_query(query: str, model: type[_TModelInstance]) -> str: """Construct a generic count query from a SELECT query.""" try: group_by: str = model.model_config["group_by"] - count_query = construct_grouped_count_query(query, group_by) + group_by_binding = next( + filter( + lambda x: isinstance(x, SPARQLBinding), + model.model_fields[group_by].metadata, + ), + group_by, + ) + count_query = construct_grouped_count_query(query, group_by_binding) except KeyError: count_query = replace_query_select_clause(query, "select (count(*) as ?cnt)")