Skip to content

Commit

Permalink
fix: resolve group_by config values for SPARQL binding aliases
Browse files Browse the repository at this point in the history
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
  • Loading branch information
lu-pl authored and kevinstadler committed Dec 5, 2024
1 parent b962af6 commit 5b3f171
Showing 1 changed file with 15 additions and 2 deletions.
17 changes: 15 additions & 2 deletions rdfproxy/utils/sparql_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down Expand Up @@ -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)


Expand All @@ -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)")

Expand Down

0 comments on commit 5b3f171

Please sign in to comment.