Skip to content

Commit

Permalink
fixes #8
Browse files Browse the repository at this point in the history
  • Loading branch information
WolfgangFahl committed May 4, 2024
1 parent aa01c5e commit 14fb833
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 11 deletions.
16 changes: 11 additions & 5 deletions snapquery/snapquery_cmd.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ def getArgParser(self, description: str, version_msg) -> ArgumentParser:
action="store_true",
help="show the list of available endpoints",
)
parser.add_argument(
"--limit", type=int, default=None, help="set limit parameter of query"
)
parser.add_argument(
"--namespace", type=str, default="wikidata-examples", help="namespace to filter queries"
)
parser.add_argument("-qn", "--queryName", help="run a named query")
parser.add_argument("-f", "--format", type=Format, choices=list(Format))
return parser
Expand All @@ -61,14 +67,14 @@ def handle_args(self) -> bool:
handled = True # Operation handled
elif self.args.queryName is not None:
nqm = NamedQueryManager()
namespace=self.args.namespace
name = self.args.queryName
endpoint_name = self.args.endpointName
r_format = self.args.format
sparql_query = nqm.get_sparql(name=name, endpoint_name=endpoint_name)
qlod = nqm.query(endpoint_name=endpoint_name, name=name)
query = Query(name=name, query=sparql_query, lang="sparql")
nqm.format_result(qlod, query, r_format, endpoint_name=endpoint_name)
return handled
limit=self.args.limit
formatted_result=nqm.formatted_query(name, namespace=namespace,endpoint_name=endpoint_name, r_format=r_format,limit=limit)
print(formatted_result)
return handled


def main(argv: list = None):
Expand Down
45 changes: 42 additions & 3 deletions snapquery/snapquery_core.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
@author: wf
"""
import json
import re
import os
from dataclasses import field
from pathlib import Path
Expand Down Expand Up @@ -228,6 +229,7 @@ def query(
name: str,
namespace: str = "wikidata-examples",
endpoint_name: str = "wikidata",
limit:int=None
):
"""
Execute a named SPARQL query using a specified endpoint and return the results.
Expand All @@ -236,6 +238,7 @@ def query(
name (str): The name of the named query to execute.
namespace (str): The namespace of the named query, default is 'wikidata-examples'.
endpoint_name (str): The name of the endpoint to send the SPARQL query to, default is 'wikidata'.
limit(int): the query limit (if any)
Returns:
Dict[str, Any]: The results of the SPARQL query in JSON format.
Expand All @@ -250,15 +253,52 @@ def query(
msg = f"Invalid endpoint {endpoint_name}"
ValueError(msg)
endpoint = self.endpoints.get(endpoint_name)
self.query = Query(name=name, query=sparql_query, lang="sparql",limit=limit)

sparql = SPARQL(endpoint.endpoint)
if limit:
# @TODO - this is to naive for cases where there are
# SPARQL elements hat have a "limit" in the name e.g. "height_limit"
if "limit" in sparql_query or "LIMIT" in sparql_query:
sparql_query = re.sub(
r"(limit|LIMIT)\s+(\d+)", f"LIMIT {limit}", sparql_query
)
else:
sparql_query += f"\nLIMIT {limit}"
lod = sparql.queryAsListOfDicts(sparql_query)
return lod

def formatted_query(self,
name: str,
namespace: str = "wikidata-examples",
endpoint_name: str = "wikidata",
r_format: Format = Format.html,
limit:int=None)->str:
"""
Execute a named SPARQL query using a specified endpoint and return the results formatted .
Args:
name (str): The name of the named query to execute.
namespace (str): The namespace of the named query, default is 'wikidata-examples'.
endpoint_name (str): The name of the endpoint to send the SPARQL query to, default is 'wikidata'.
r_format: (Format): the format to result should be returned in
limit(int): the query limit (if any)
Returns:
str: The results of the SPARQL query in the given format.
Raises:
ValueError: If no named query matches the given name and namespace.
Exception: If the SPARQL query execution fails or the endpoint returns an error.
"""
qlod = self.query(endpoint_name=endpoint_name, name=name,namespace=namespace,limit=limit)
formatted_result=self.format_result(qlod=qlod, query=self.query, r_format=r_format, endpoint_name=endpoint_name)
return formatted_result

def format_result(
self,
qlod: List[Dict[str, Any]],
query: Query,
r_format_str: str,
r_format: Format,
endpoint_name: str = "wikidata",
) -> Optional[str]:
"""
Expand All @@ -267,7 +307,7 @@ def format_result(
Args:
qlod (List[Dict[str, Any]]): The list of dictionaries that represent the query results.
query (Query): The query object which contains details like the endpoint and the database.
r_format_str: The format in which to print the results.
r_format_str(Format): The format in which to print the results.
endpoint_name (str): The name of the endpoint to be used, defaults to "wikidata".
Returns:
Expand All @@ -277,7 +317,6 @@ def format_result(
endpointConf = self.endpoints.get(endpoint_name, Endpoint.getDefault())
query.tryItUrl = endpointConf.website
query.database = endpointConf.database
r_format = Format[r_format_str]

if r_format == Format.csv:
csv_output = CSV.toCSV(qlod)
Expand Down
7 changes: 4 additions & 3 deletions snapquery/snapquery_webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"""
from fastapi import HTTPException
from fastapi.responses import HTMLResponse, PlainTextResponse
from lodstorage.query import Query
from lodstorage.query import Query, Format
from ngwidgets.input_webserver import InputWebserver, InputWebSolution, WebserverConfig
from nicegui import app
from nicegui.client import Client
Expand Down Expand Up @@ -87,10 +87,10 @@ def query(self, namespace: str, name: str):
# content negotiation
# Determine response format by extension in the name or Accept header
if "." in name:
r_format = name.split(".")[-1]
r_format_str = name.split(".")[-1]
name = name[: name.rfind(".")]
else:
r_format = "html"
r_format_str = "html"

# Retrieve the SPARQL query string using the namespace and name.
try:
Expand All @@ -104,6 +104,7 @@ def query(self, namespace: str, name: str):
raise HTTPException(status_code=404, detail=str(e))

# Format the results and generate HTML content
r_format = Format[r_format_str]
content = self.nqm.format_result(
qlod, query, r_format, endpoint_name=endpoint_name
)
Expand Down

0 comments on commit 14fb833

Please sign in to comment.