Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 71 additions & 10 deletions src/qlever/commands/benchmark_queries.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,25 +106,72 @@ def filter_queries(
return []


def parse_queries_tsv(queries_cmd: str) -> list[tuple[str, str, str]]:
def queries_from_tsv(tsv_queries_str: str) -> list[tuple[str, str, str]]:
"""
Execute the given bash command to fetch tsv queries and return a
list of queries i.e. tuple(query_name, "", full_sparql_query)
Parse the given TSV (one line for each query, with the name and the SPARQL
query separated by a tab) and return a list of queries i.e.
tuple(query_name, "", full_sparql_query)
Note: query_description is returned as empty to match the return
structure of parse_queries_yml.
"""
return [
(query_name, "", sparql_query)
for line in tsv_queries_str.strip().splitlines()
for query_name, sparql_query in [line.split("\t", 1)]
]


def parse_queries_tsv(queries_cmd: str) -> list[tuple[str, str, str]]:
"""
Execute the given bash command to fetch tsv queries and return a
list of queries, see `queries_from_tsv`.
"""
try:
tsv_queries_str = run_command(queries_cmd, return_output=True)
if len(tsv_queries_str) == 0:
log.error("No queries found in the TSV queries file")
return []
return queries_from_tsv(tsv_queries_str)
except Exception as exc:
log.error(f"Failed to read the TSV queries file: {exc}")
return []


def parse_example_queries(queries_cmd: str) -> list[tuple[str, str, str]]:
"""
Execute the given bash command to fetch the example queries of a UI and
return a list of queries i.e. tuple(query_name, "", full_sparql_query).
The format is detected from the output: a JSON array of objects with the
keys `name` and `query` (as provided by the QLever UI), or TSV (as provided
by the old QLever UI).

NOTE: The comment lines of a query from the JSON are dropped, because
queries are sent on a single line later, where a comment would hide the
rest of the query.
"""
try:
output = run_command(queries_cmd, return_output=True)
if len(output.strip()) == 0:
log.error("No example queries found")
return []
try:
examples = json.loads(output)
except json.JSONDecodeError:
return queries_from_tsv(output)
return [
(query_name, "", sparql_query)
for line in tsv_queries_str.strip().splitlines()
for query_name, sparql_query in [line.split("\t", 1)]
(
example["name"],
"",
"\n".join(
line
for line in example["query"].splitlines()
if not line.lstrip().startswith("#")
),
)
for example in examples
]
except Exception as exc:
log.error(f"Failed to read the TSV queries file: {exc}")
log.error(f"Failed to read the example queries: {exc}")
return []


Expand Down Expand Up @@ -595,6 +642,19 @@ def additional_arguments(self, subparser) -> None:
"instead of the benchmark queries from a TSV or YML file"
),
)
subparser.add_argument(
"--example-queries-url",
type=str,
default="https://ui.qlever.dev/ui-api/endpoints/{ui_config}/examples/",
help=(
"URL from which to get the example queries, where "
"`{ui_config}` is replaced by the value of --ui-config; the "
"response can be JSON (as provided by the QLever UI) or TSV "
"(as provided by the old QLever UI at "
"https://qlever.dev/api/examples/{ui_config}) "
"(default: %(default)s)"
),
)
subparser.add_argument(
"--download-or-count",
choices=["download", "count"],
Expand Down Expand Up @@ -852,9 +912,10 @@ def execute(self, args) -> bool:
args.clear_cache = "no"

# Show what the command will do.
example_queries_cmd = (
f"curl -sv https://qlever.dev/api/examples/{args.ui_config}"
example_queries_url = args.example_queries_url.replace(
"{ui_config}", str(args.ui_config)
)
example_queries_cmd = f"curl -s {shlex.quote(example_queries_url)}"
sparql_endpoint = (
args.sparql_endpoint
or f"{args.host_name}:{args.port}{args.endpoint_path}"
Expand All @@ -881,7 +942,7 @@ def execute(self, args) -> bool:
elif args.queries_tsv:
queries = parse_queries_tsv(f"cat {args.queries_tsv}")
else:
queries = parse_queries_tsv(example_queries_cmd)
queries = parse_example_queries(example_queries_cmd)

filtered_queries = filter_queries(
queries, args.query_ids, args.query_regex
Expand Down
34 changes: 34 additions & 0 deletions test/qlever/commands/test_benchmark_queries_methods.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
get_query_results,
get_result_size,
get_single_int_result,
parse_example_queries,
parse_queries_tsv,
parse_queries_yml,
resolve_benchmark_metadata,
Expand Down Expand Up @@ -453,6 +454,39 @@ def test_parse_queries_tsv_command_failure(mock_command):
assert parse_queries_tsv("cat queries.tsv") == []


def test_parse_example_queries_json(mock_command):
run_cmd_mock = mock_command(MODULE, "run_command")
run_cmd_mock.return_value = (
'[{"name": "q1", "query": "#+ result-plot:\\n'
'SELECT ?x WHERE {\\n # A comment\\n ?x ?y <http://x.org/a#b>\\n}"},'
' {"name": "q2", "query": "ASK { ?x ?y ?z }", "section": "s"}]'
)
result = parse_example_queries("curl -s https://example.org")
assert result == [
("q1", "", "SELECT ?x WHERE {\n ?x ?y <http://x.org/a#b>\n}"),
("q2", "", "ASK { ?x ?y ?z }"),
]


def test_parse_example_queries_tsv(mock_command):
run_cmd_mock = mock_command(MODULE, "run_command")
run_cmd_mock.return_value = (
"q1\tSELECT ?x WHERE { ?x ?y ?z }\nq2\tASK { ?x ?y ?z }\n"
)
result = parse_example_queries("curl -s https://example.org")
assert result == [
("q1", "", "SELECT ?x WHERE { ?x ?y ?z }"),
("q2", "", "ASK { ?x ?y ?z }"),
]


@pytest.mark.parametrize("output", ["", '{"detail": "Not found."}'])
def test_parse_example_queries_no_queries(mock_command, output):
run_cmd_mock = mock_command(MODULE, "run_command")
run_cmd_mock.return_value = output
assert parse_example_queries("curl -s https://example.org") == []


@pytest.mark.parametrize(
"case",
[
Expand Down
Loading