Skip to content

SPARQL commands

Validate syntax

kurra sparql validate 'SELECT * WHERE { ?s ?p ?o }'
kurra sparql validate 'INSERT DATA { <urn:s> <urn:p> <urn:o> }'
kurra sparql validate query.sparql

The required positional argument q accepts SPARQL text or a path to a file containing a query or update, just like q in kurra sparql <path-or-url> <q>. Quote inline SPARQL text so the shell passes it as one argument.

Successful validation prints Valid SPARQL syntax and exits with status 0. Invalid syntax produces an error with the line and column and exits with a nonzero status. The command checks syntax without executing the statement or contacting an endpoint.

Run queries and updates

The existing invocation remains supported:

kurra sparql data.ttl 'SELECT * WHERE { ?s ?p ?o }'

An explicit query subcommand is also available:

kurra sparql query data.ttl 'SELECT * WHERE { ?s ?p ?o }'

Use kurra sparql --help, kurra sparql query --help, or kurra sparql validate --help for command help.

Command reference

kurra.cli.commands.sparql

CLI commands for running SPARQL queries.

SparqlGroup

Bases: TyperGroup

Keep the original positional query invocation alongside subcommands.

validate_command

validate_command(q: str) -> None

Validate Q, a SPARQL query/update string or a path to a file containing one.

Source code in kurra/cli/commands/sparql.py
@app.command(name="validate")
def validate_command(q: str) -> None:
    """Validate Q, a SPARQL query/update string or a path to a file containing one."""
    try:
        validate(q)
    except ParseBaseException as exc:
        raise typer.BadParameter(
            f"Invalid SPARQL syntax at line {exc.lineno}, column {exc.col}: {exc.msg}",
            param_hint="q",
        ) from exc
    console.print("Valid SPARQL syntax")

sparql_command

sparql_command(path_or_url: Path, q: str, response_format: str = typer.Option('table', '--response-format', '-f', help="The response format of the SPARQL query. Either 'table' (default), 'json' or 'csv'"), username: str | None = None, password: str | None = None, timeout: int = 60) -> None

Run a SPARQL query against a local RDF file or a SPARQL endpoint, and print the result.

Parameters:

Name Type Description Default
path_or_url Path

A local RDF file path or a SPARQL endpoint URL to query.

required
q str

A SPARQL query string, or the path to a file containing one.

required
response_format str

The response format of the SPARQL query. Either table (default), json, or csv.

Option('table', '--response-format', '-f', help="The response format of the SPARQL query. Either 'table' (default), 'json' or 'csv'")
username str | None

Fuseki username, if the endpoint requires authentication.

None
password str | None

Fuseki password, if the endpoint requires authentication.

None
timeout int

Timeout per request, in seconds.

60

Raises:

Type Description
BadParameter

If response_format is not one of table, json, or csv.

Source code in kurra/cli/commands/sparql.py
@app.command(name="query", help="SPARQL queries to local RDF files or a database")
def sparql_command(
    path_or_url: Path,
    q: str,
    response_format: str = typer.Option(
        "table",
        "--response-format",
        "-f",
        help="The response format of the SPARQL query. Either 'table' (default), 'json' or 'csv'",
    ),
    username: Annotated[
        str | None, typer.Option("--username", "-u", help="Fuseki username.")
    ] = None,
    password: Annotated[
        str | None, typer.Option("--password", "-p", help="Fuseki password.")
    ] = None,
    timeout: Annotated[
        int, typer.Option("--timeout", "-t", help="Timeout per request")
    ] = 60,
) -> None:
    """Run a SPARQL query against a local RDF file or a SPARQL endpoint, and print the result.

    Args:
        path_or_url: A local RDF file path or a SPARQL endpoint URL to query.
        q: A SPARQL query string, or the path to a file containing one.
        response_format: The response format of the SPARQL query. Either `table` (default), `json`, or `csv`.
        username: Fuseki username, if the endpoint requires authentication.
        password: Fuseki password, if the endpoint requires authentication.
        timeout: Timeout per request, in seconds.

    Raises:
        typer.BadParameter: If `response_format` is not one of `table`, `json`, or `csv`.
    """
    if str(path_or_url).startswith("http"):
        path_or_url = str(path_or_url).replace(":/", "://")

    if len(q) < 260 and Path(q).is_file():
        q = Path(q).read_text()

    if response_format not in ["table", "json", "csv"]:
        raise typer.BadParameter(
            "response_format must be either 'table' (default), 'json' or 'csv'"
        )

    with make_httpx_client(username, password, timeout=timeout) as http_client:
        r = query(path_or_url, q, http_client=http_client, return_format="python")

        if r == "":
            console.print("Operation completed successfully")
            return

        # if it is a graph, just print return the serialized form plainly, not via console.print()
        # to avoid terminal width breaking long literals, as per Issue 37
        if isinstance(r, rdflib.Graph):
            print(r.serialize(format="longturtle"))
        elif response_format == "table":
            console.print(format_sparql_response_as_rich_table(r, q))
        elif response_format == "csv":
            console.print(format_sparql_response_as_csv(r, q))
        else:
            print(format_sparql_response_as_json(r))