Skip to content

Commit

Permalink
refactor: implement inject_subquery with re.search and str slicing
Browse files Browse the repository at this point in the history
The regex with an absolute anchor + negated char set is more precise
than the original version. Also, indentation is completely unnecessary, a potential
source of bugs and clutters up the implementation.
  • Loading branch information
lu-pl committed Nov 11, 2024
1 parent d8e307b commit 9a735ce
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 11 deletions.
4 changes: 4 additions & 0 deletions rdfproxy/utils/_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,7 @@ class MissingModelConfigException(Exception):

class UnboundGroupingKeyException(Exception):
"""Exception for indicating that no SPARQL binding corresponds to the requested grouping key."""


class QueryConstructionException(Exception):
"""Exception for indicating failed SPARQL query construction."""
19 changes: 8 additions & 11 deletions rdfproxy/utils/sparql_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@
from contextlib import contextmanager
from functools import partial
import re
from textwrap import indent
from typing import cast

from SPARQLWrapper import QueryResult, SPARQLWrapper
from rdfproxy.utils._exceptions import QueryConstructionException
from rdfproxy.utils._types import ItemsQueryConstructor, _TModelInstance


Expand Down Expand Up @@ -35,17 +35,14 @@ def replace_query_select_clause(query: str, repl: str) -> str:
return modified_query


def inject_subquery(
query: str, subquery: str, indent_depth: int = 4, indent_char: str = " "
) -> str:
"""Inject a SPARQL query with a subquery.
def inject_subquery(query: str, subquery: str) -> str:
"""Inject a SPARQL query with a subquery."""
if (tail := re.search(r"}[^}]*\Z", query)) is None:
raise QueryConstructionException("Unable to inject subquery.")

Also apply some basic indentation.
"""
indent_value = indent_char * indent_depth
indented_subquery = indent(f"\n{subquery}\n", indent_value)
indented_subclause = indent(f"\n{{{indented_subquery}}}", indent_value)
return re.sub(r".*\}$", f"{indented_subclause}\n}}", query)
tail_index: int = tail.start()
injected: str = f"{query[:tail_index]} {{{subquery}}} {query[tail_index:]}"
return injected


def construct_grouped_pagination_query(
Expand Down

0 comments on commit 9a735ce

Please sign in to comment.