This document contains API documentation for the SPARQL Builder library.
Auto-generated from docstrings in sparqlbuilder/builder.py and sparqlbuilder/formatter.py
- Class:
SPARQLQuerybindbind_manyselectselect_distinctselect_reducedprefixselect_countselect_sumselect_avgselect_minselect_maxselect_sampleselect_group_concatfrom_graphfrom_named_graphwhereoptionalunionminusgraphvaluesfilterfilter_equalsfilter_regexfilter_existsfilter_not_existsproperty_pathorder_bygroup_byhavinglimitoffsetbuild
- Helper Functions
- Formatter
SPARQL Builder with fluent interface for constructing SPARQL SELECT queries.
This class provides a fluent, method-chaining interface for building SPARQL queries programmatically. It supports all major SPARQL features including prefixes, projections, graph patterns, filters, aggregations, ordering, and result modifiers.
The builder uses a context stack to handle nested patterns like OPTIONAL, UNION, MINUS, and GRAPH blocks, ensuring proper query structure and indentation.
Helper constructor functions select(), select_distinct(), and select_reduced()
are available for convenience. These functions are equivalent to creating a new
SPARQLQuery() instance and calling the corresponding SPARQLQuery method of the same name.
Note: the query builder includes unsafe methods filter() and having() that should
only be used with trusted input
bind(self, variable, value)Bind a value to a query variable.
Bound values can be consumed in two build modes:
- rdflib (default): passed as initBindings for Graph.query(...)
- inline: rendered as VALUES clauses in the generated query
Args:
- variable: Variable name with or without ?/$ prefix.
- value: Scalar rdflib/Python value, or list/tuple/set of values for inline mode.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
bind_many(self, bindings)Bind multiple values to query variables.
This is a convenience method equivalent to calling bind() repeatedly.
Args:
- bindings: Mapping of variable names to values. Variable names may be provided with or without ?/$ prefix.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
select(self)Specify variables to select in the SPARQL query.
This method adds variables to the SELECT clause of the SPARQL query being built.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Examples:
>>> query.select('?name', '?age', '?email')
SELECT ?name ?age ?email
>>> query.select()
SELECT *
select_distinct(self)SELECT DISTINCT query that removes duplicate results from the result set.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Raises:
- ValueError: If REDUCED is already set (DISTINCT and REDUCED are mutually exclusive).
Examples:
>>> query.select_distinct("?name", "?age")
SELECT DISTINCT ?name ?age
>>> query.select_distinct()
SELECT DISTINCT *
select_reduced(self)SELECT REDUCED query that eliminates duplicate solutions while allowing some duplicates to remain.
REDUCED is a weaker version of DISTINCT that may eliminate some duplicates but is not required to eliminate all duplicates. This can be more efficient than DISTINCT in some query engines.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Raises:
- ValueError: If DISTINCT is already set (DISTINCT and REDUCED are mutually exclusive).
Examples:
>>> query.select_reduced("?name", "?age")
SELECT REDUCED ?name ?age
>>> query.select_reduced()
SELECT REDUCED *
prefix(self, prefix, uri)Add a prefix declaration to the SPARQL query.
This method registers a namespace prefix that can be used to abbreviate URIs in the SPARQL query.
Args:
- prefix (str): The namespace prefix (e.g., 'foaf', 'rdf', 'rdfs')
- uri (str): The full URI for the namespace (e.g., 'http://xmlns.com/foaf/0.1/')
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.prefix('foaf', 'http://xmlns.com/foaf/0.1/')
>>> query.prefix('ex', 'http://example.org/')
select_count(self, variable, alias, distinct)Add COUNT aggregation to SELECT clause.
Use with GROUP BY to count items per group.
Args:
- variable (str): The variable to count (e.g., '?item'). Use '*' to count all rows.
- alias (str): The result variable name (e.g., '?count').
- distinct (bool): If True, count only distinct values. Default is False.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Examples:
>>> query.select('?category').select_count('?item', '?total')
SELECT ?category (COUNT(?item) AS ?total)
>>> query.select_count('*', '?total')
SELECT (COUNT(*) AS ?total)
>>> query.select_count('?item', '?unique', distinct=True)
SELECT (COUNT(DISTINCT ?item) AS ?unique)
select_sum(self, variable, alias)Add SUM aggregation to SELECT clause.
Use with GROUP BY to sum numeric values per group.
Args:
- variable (str): The variable to sum (e.g., '?price').
- alias (str): The result variable name (e.g., '?total').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.select('?category').select_sum('?price', '?total')
SELECT ?category (SUM(?price) AS ?total)
select_avg(self, variable, alias)Add AVG aggregation to SELECT clause.
Use with GROUP BY to calculate average of numeric values per group.
Args:
- variable (str): The variable to average (e.g., '?price').
- alias (str): The result variable name (e.g., '?average').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.select('?category').select_avg('?price', '?average')
SELECT ?category (AVG(?price) AS ?average)
select_min(self, variable, alias)Add MIN aggregation to SELECT clause.
Use with GROUP BY to find minimum value per group.
Args:
- variable (str): The variable to find minimum of (e.g., '?price').
- alias (str): The result variable name (e.g., '?lowest').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.select('?category').select_min('?price', '?lowest')
SELECT ?category (MIN(?price) AS ?lowest)
select_max(self, variable, alias)Add MAX aggregation to SELECT clause.
Use with GROUP BY to find maximum value per group.
Args:
- variable (str): The variable to find maximum of (e.g., '?price').
- alias (str): The result variable name (e.g., '?highest').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.select('?category').select_max('?price', '?highest')
SELECT ?category (MAX(?price) AS ?highest)
select_sample(self, variable, alias)Add SAMPLE aggregation to SELECT clause.
Use with GROUP BY to select an arbitrary value from the group.
Args:
- variable (str): The variable to sample (e.g., '?value').
- alias (str): The result variable name (e.g., '?example').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.select('?category').select_sample('?value', '?example')
SELECT ?category (SAMPLE(?value) AS ?example)
select_group_concat(self, variable, alias, separator)Add GROUP_CONCAT aggregation to SELECT clause.
Use with GROUP BY to concatenate values into a single string per group.
Args:
- variable (str): The variable to concatenate (e.g., '?name').
- alias (str): The result variable name (e.g., '?names').
- separator (str): String to separate values. Default is " " (space).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Examples:
>>> query.select('?person').select_group_concat('?interest', '?interests')
SELECT ?person (GROUP_CONCAT(?interest; SEPARATOR=" ") AS ?interests)
>>> query.select('?person').select_group_concat('?interest', '?interests', separator=", ")
SELECT ?person (GROUP_CONCAT(?interest; SEPARATOR=", ") AS ?interests)
from_graph(self, graph_uri)Add FROM clause to the SPARQL query.
The FROM clause specifies the default graph for the query. Multiple FROM clauses can be added to define a dataset consisting of the merge of the specified graphs.
See Also: SPARQL 1.1 Query Language specification: https://www.w3.org/TR/sparql11-query/#specifyingDataset
Args:
- graph_uri (str): The URI of the graph to add to the FROM clause.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.from_graph("http://example.org/graph1")
FROM <http://example.org/graph1>
from_named_graph(self, graph_uri)Add a FROM NAMED clause to the SPARQL query.
The FROM NAMED clause specifies a named graph that should be available for querying within the dataset. Named graphs can be referenced using the GRAPH keyword in query patterns.
See Also: SPARQL 1.1 Query Language specification: https://www.w3.org/TR/sparql11-query/#specifyingDataset
Args:
- graph_uri (str): The URI of the named graph to include in the dataset.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.from_named_graph("http://example.org/graph1")
FROM NAMED <http://example.org/graph1>
where(self, subject, predicate, obj, datatype, lang)Add a WHERE clause pattern to the SPARQL query.
Args:
- subject: The subject of the triple pattern. Can be a variable (string) or None for anonymous variable.
- predicate: The predicate of the triple pattern. Can be a variable (string) or None for anonymous variable.
- obj: The object of the triple pattern. Can be a variable (string), literal value (int, float, bool), or None for anonymous variable.
- datatype: Optional datatype for the object literal (e.g., 'xsd:string', 'xsd:int').
- lang: Optional language tag for string literals (e.g., 'en', 'fr').
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.where('?person', 'foaf:name', '?name')
WHERE { ?person foaf:name ?name }
>>> query.where('?person', 'foaf:age', 25, datatype='xsd:int')
WHERE { ?person foaf:age 25^^xsd:int }
>>> query.where('?person', 'rdfs:label', 'John', lang='en')
WHERE { ?person rdfs:label 'John'@en }
>>> query.where(None, 'rdf:type', 'foaf:Person')
WHERE { ?anon rdf:type foaf:Person }
optional(self, callback)Add an optional block to the SPARQL query.
This method creates an OPTIONAL block in the SPARQL query by executing the provided callback function within a new context. Any patterns added during the callback execution will be wrapped in an OPTIONAL clause.
Args:
- callback (Callable[['SPARQLQuery'], Any]): A function that takes a SPARQLQuery instance and adds patterns to it. These patterns will be made optional.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.optional(lambda q: q.where('?person', 'foaf:mbox', '?email'))
WHERE {
OPTIONAL {
?person foaf:mbox ?email .
}
}
Note: The callback function should use the passed SPARQLQuery instance to add the desired optional patterns. All patterns added within the callback will be grouped together in a single OPTIONAL block.
union(self)Create a UNION block in the SPARQL query.
A UNION block allows for alternative graph patterns, where the query will match if any of the patterns match. Each callback function defines one alternative pattern within the union.
Args:
*callbacks: Variable number of callback functions that each take a SPARQLQuery instance and define graph patterns for one branch of the union. Each callback is executed in its own context to build separate pattern groups.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.union(
... lambda q: q.where('?person', 'foaf:name', '?identifier'),
... lambda q: q.where('?person', 'foaf:mbox', '?identifier')
... )
WHERE {
{
?person foaf:name ?identifier .
}
UNION
{
?person foaf:mbox ?identifier .
}
}
minus(self, callback)Add a MINUS block to the SPARQL query.
The MINUS block removes solutions from the query results. It subtracts matches from the overall result set based on the patterns defined in the callback.
Args:
- callback (Callable[['SPARQLQuery'], Any]): A function that takes a SPARQLQuery instance and adds patterns to it. Solutions matching these patterns will be removed from the results.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.minus(lambda q: q.where('?person', 'foaf:status', '"inactive"'))
WHERE {
MINUS {
?person foaf:status "inactive" .
}
}
graph(self, graph_uri, callback)Add a GRAPH block to query a specific named graph.
The GRAPH keyword allows querying patterns within a specific named graph. This is used in conjunction with FROM NAMED to query named graphs within the dataset.
See Also: SPARQL 1.1 Query Language specification: https://www.w3.org/TR/sparql11-query/#specifyingDataset
Args:
- graph_uri (Union[str, None]): The URI of the named graph to query, or a variable (e.g., '?g') to match against any named graph. Can be None for an anonymous graph variable.
- callback (Callable[['SPARQLQuery'], Any]): A function that takes a SPARQLQuery instance and adds patterns to query within the specified graph.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.from_named_graph('http://example.org/contacts')
>>> query.graph('http://example.org/contacts', lambda q: q
... .where('?person', 'foaf:name', '?name')
... .where('?person', 'foaf:mbox', '?email')
... )
FROM NAMED <http://example.org/contacts>
WHERE {
GRAPH <http://example.org/contacts> {
?person foaf:name ?name .
?person foaf:mbox ?email .
}
}
values(self, variables, data)Add a VALUES clause for inline data binding.
The VALUES clause provides inline data that can be used in the query. This is useful for filtering results to a specific set of values or for providing data directly in the query.
Args:
- variables (Union[str, List[str]]): A single variable name or list of variable names (must include '?' or '$' prefix).
- data (List[Union[Any, tuple]]): List of values or tuples of values. For a single variable, provide a list of values. For multiple variables, provide a list of tuples. Use None for UNDEF values.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Examples: Single variable:
>>> query.values('?person', [
... 'http://example.org/person1',
... 'http://example.org/person2'
... ])
VALUES ?person { <http://example.org/person1> <http://example.org/person2> }
Multiple variables:
>>> query.values(['?name', '?age'], [
... ('Alice', 30),
... ('Bob', 25),
... ('Carol', None) # None becomes UNDEF
... ])
VALUES (?name ?age) { ("Alice" 30) ("Bob" 25) ("Carol" UNDEF) }
Using prefixed names:
>>> query.values('?type', ['foaf:Person', 'foaf:Organization'])
VALUES ?type { foaf:Person foaf:Organization }
filter(self, condition)Add a FILTER condition to constrain query results.
FILTER expressions are used to restrict the solutions based on boolean conditions. The condition can use SPARQL built-in functions and operators.
For user-provided values, use the safe alternatives:
- filter_equals() - for equality comparisons
- filter_regex() - for pattern matching (properly escapes patterns)
- Build filter expressions programmatically using validated variables
Args:
- condition (str): A SPARQL filter expression (e.g., '?age > 18', 'BOUND(?email)', 'REGEX(?name, "^A")').
⚠️ Must be from a trusted source, not user input.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.filter('?age > 18')
WHERE {
FILTER (?age > 18)
}
Warning:
>>> # UNSAFE - vulnerable to injection:
>>> user_input = "?age > 18) } DELETE { ?s ?p ?o } WHERE { (?x"
>>> query.filter(user_input) #危険 DANGER! Query structure compromised
>>> # SAFE - use validated methods:
>>> query.filter_equals('?age', 18) # ✓ Safe
filter_equals(self, variable, value, datatype)Add a FILTER condition for equality comparison.
This is a convenience method for filtering based on variable equality. The value is automatically formatted as a literal.
Args:
- variable (str): The variable name to filter (must include '?' or '$' prefix).
- value (Any): The value to compare against (string, int, float, or bool).
- datatype (Optional[str]): Optional datatype URI for the literal value.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.filter_equals('?age', 25)
WHERE {
FILTER (?age = 25)
}
filter_regex(self, variable, pattern, flags)Add a FILTER condition for regular expression matching.
This method creates a REGEX filter to match variable values against a pattern. The pattern is automatically escaped for safe use in SPARQL.
Args:
- variable (str): The variable name to filter (must include '?' or '$' prefix).
- pattern (str): The regular expression pattern to match.
- flags (Optional[str]): Optional regex flags ('i' for case-insensitive, etc.).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.filter_regex('?name', '^A', 'i')
WHERE {
FILTER (REGEX(?name, "^A", "i"))
}
filter_exists(self, callback)Add a FILTER EXISTS condition to require pattern matching.
FILTER EXISTS tests whether a pattern matches in the data. The query only returns results where the EXISTS pattern finds at least one match.
Args:
- callback (Callable[['SPARQLQuery'], Any]): A function that takes a SPARQLQuery instance and adds patterns that must exist for the filter to pass.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.filter_exists(lambda q: q
... .where('?person', 'foaf:interest', '?interest')
... )
WHERE {
FILTER (EXISTS {
?person foaf:interest ?interest .
})
}
filter_not_exists(self, callback)Add a FILTER NOT EXISTS condition to require pattern absence.
FILTER NOT EXISTS tests whether a pattern does NOT match in the data. The query only returns results where the NOT EXISTS pattern finds no matches.
Args:
- callback (Callable[['SPARQLQuery'], Any]): A function that takes a SPARQLQuery instance and adds patterns that must NOT exist for the filter to pass.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.filter_not_exists(lambda q: q
... .where('?person', 'foaf:status', '"banned"')
... )
WHERE {
FILTER (NOT EXISTS {
?person foaf:status "banned" .
})
}
property_path(self, subject, path, obj)Add a property path pattern to the query (e.g., foaf:knows+, etc.).
Property paths provide a way to match more complex patterns using path expressions. This method is a convenience wrapper around where() for property paths.
Property path operators: * : Zero or more occurrences + : One or more occurrences ? : Zero or one occurrence / : Sequence (path concatenation) | : Alternative paths ^ : Inverse property
Args:
- subject (Union[str, None]): The subject of the triple pattern (variable, URI, or None).
- path (str): The property path expression (e.g., 'foaf:knows+', 'foaf:knows/foaf:name').
- obj (Union[str, None]): The object of the triple pattern (variable, URI, or None).
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.property_path('?person', 'foaf:knows+', '?friend')
WHERE {
?person foaf:knows+ ?friend .
}
order_by(self, variable, descending)Add an ORDER BY clause to sort query results.
Results can be ordered by one or more variables in ascending or descending order. Call this method multiple times to order by multiple variables.
Args:
- variable (str): The variable name to order by (must include '?' or '$' prefix).
- descending (bool): If True, sort in descending order; if False (default), sort in ascending order.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.order_by('?name').order_by('?age', descending=True)
ORDER BY ?name DESC(?age)
group_by(self)Add a GROUP BY clause for result aggregation.
GROUP BY groups results by the specified variables, typically used with aggregate functions like COUNT, SUM, AVG, etc.
Args:
*variables(str): Variable names to group by (must include '?' or '$' prefix). Multiple variables can be provided.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.group_by('?category', '?type')
GROUP BY ?category ?type
having(self, condition)Add a HAVING clause to filter grouped results.
HAVING is used with GROUP BY to filter groups based on aggregate conditions. Multiple HAVING conditions are combined with AND.
Only use this method with trusted, hardcoded expressions or expressions built from validated components.
Args:
- condition (str): A SPARQL expression to filter groups (e.g., 'COUNT(?item) > 5', 'AVG(?price) < 100').
⚠️ Must be from a trusted source, not user input.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Example:
>>> query.group_by('category').having('COUNT(?item) > 10')
GROUP BY ?category
HAVING (COUNT(?item) > 10)
Warning:
>>> # UNSAFE - vulnerable to injection:
>>> user_input = "COUNT(?item) > 5) } INSERT { ?x ?y ?z } WHERE { (1=1"
>>> query.having(user_input) # 危険 DANGER! Query structure compromised
>>> # SAFE - construct from validated variables:
>>> validated_threshold = int(user_provided_number)
>>> validated_var = validate_variable(user_provided_var)
>>> query.having(f'COUNT({validated_var}) > {validated_threshold}') # ✓ Safe
limit(self, limit)Add a LIMIT clause to restrict the number of results.
LIMIT specifies the maximum number of solutions to return from the query.
Args:
- limit (int): Maximum number of results to return. Must be a non-negative integer.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Raises:
- ValueError: If limit is not a non-negative integer.
Example:
>>> query.limit(10)
LIMIT 10
offset(self, offset)Add an OFFSET clause to skip a number of results.
OFFSET specifies how many solutions to skip before returning results. Often used with LIMIT for pagination.
Args:
- offset (int): Number of results to skip. Must be a non-negative integer.
Returns:
- SPARQLQuery: Amended query instance to allow method chaining.
Raises:
- ValueError: If offset is not a non-negative integer.
Example:
>>> query.limit(10).offset(20)
LIMIT 10
OFFSET 20
build(self, param_mode)Build query for execution and return query text plus bindings.
This is the unified API for both parameter modes:
- rdflib: returns query text and initBindings mapping.
- inline: returns query text with inlined VALUES bindings and empty mapping.
Constructs a complete SPARQL SELECT query by combining all configured components including prefixes, query modifiers (DISTINCT/REDUCED), variables, FROM clauses, WHERE patterns, filters, GROUP BY, HAVING, ORDER BY, LIMIT, and OFFSET.
Args:
- param_mode: Either 'rdflib' (default) or 'inline'.
Returns:
- Tuple[str, Dict[str, Any]]: (query_text, init_bindings)
Raises:
- ValueError: If both DISTINCT and REDUCED are set, as they are mutually exclusive in SPARQL specification.
Example:
>>> builder = QueryBuilder()
>>> builder.select("name").where("?person foaf:name ?name")
>>> query_text, init_bindings = builder.build(param_mode="inline")
>>> print(query_text)
SELECT ?name
WHERE {
?person foaf:name ?name .
}
select()Convenience function to create a new SELECT query with the specified variables.
This function initializes a new SPARQLQuery instance and applies the SELECT clause with the provided variables.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: A new SPARQLQuery instance configured with the SELECT clause containing the specified variables.
Examples:
>>> select("?name", "?age", "?email")
SELECT ?name ?age ?email
>>> select()
SELECT *
select_distinct()Convenience function to create a new SELECT DISTINCT query with the specified variables.
This function initializes a new SPARQLQuery instance and applies the SELECT DISTINCT clause with the provided variables. SELECT DISTINCT ensures that duplicate result rows are eliminated from the query results.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: A new SPARQLQuery instance configured with the SELECT DISTINCT clause and the specified variables.
Examples:
>>> select_distinct('?subject', '?object')
SELECT DISTINCT ?subject ?object
>>> select_distinct()
SELECT DISTINCT *
select_reduced()Convenience function to create a new SELECT REDUCED query with the specified variables.
This function initializes a new SPARQLQuery instance and applies the SELECT REDUCED clause with the provided variables. SELECT REDUCED clause returns a solution sequence with duplicate solutions eliminated in an implementation-dependent way. Unlike SELECT DISTINCT, the order and method of duplicate elimination is not specified.
Args:
*variables(str): Variable names to select in the SPARQL query. Variables must include the '?' or '$' prefix (e.g., '?name', '?age'). If no variables are provided, the query will select all variables (SELECT *).
Returns:
- SPARQLQuery: A new SPARQLQuery instance configured with SELECT REDUCED clause for the specified variables.
Examples:
>>> select_reduced("?subject", "?predicate", "?object")
SELECT REDUCED ?subject ?predicate ?object
>>> select_reduced()
SELECT REDUCED *
SPARQL value formatting and validation using rdflib
This module provides formatting and validation for SPARQL values (subjects, predicates, objects) using rdflib for proper RDF handling.
format_subject(term)Format a subject term for SPARQL
Subjects can be:
- Variables: ?var or $var
- URIs: http://... or http://...
- Prefixed names: prefix:name
- Blank nodes: _:b1
Args:
- term: Subject term to format
Returns:
- Formatted subject safe for SPARQL
Raises:
- ValueError: If term is not a valid subject
format_predicate(term)Format a predicate term for SPARQL
Predicates can be:
- Variables: ?var or $var
- URIs: http://... or http://...
- Prefixed names: prefix:name
- 'a' shorthand for rdf:type
- Property paths: prefix:path+ or complex paths
Args:
- term: Predicate term to format
Returns:
- Formatted predicate safe for SPARQL
Raises:
- ValueError: If term is not a valid predicate
format_object(term, datatype, lang)Format an object term for SPARQL
Objects can be:
- Variables: ?var or $var
- URIs: http://... or http://...
- rdflib URI terms: URIRef(...)
- rdflib Literal terms: Literal(...)
- Prefixed names: prefix:name
- Blank nodes: _:b1
- Literals: strings, numbers, booleans
Args:
- term: Object term to format
- datatype: Optional datatype URI for literals
- lang: Optional language tag for string literals
Returns:
- Formatted object safe for SPARQL
Raises:
- ValueError: If term is not a valid object