src/rdflib/contrib/rdf4j/util.py
1"""RDF4J utility functions."""
2
3from __future__ import annotations
4
5import io
6import typing as t
7
8from rdflib.graph import DATASET_DEFAULT_GRAPH_ID, Dataset, Graph
9from rdflib.plugins.sparql.processor import prepareQuery
10from rdflib.term import BNode, IdentifiedNode, URIRef
11
12if t.TYPE_CHECKING:
13 from rdflib.contrib.rdf4j.client import ObjectType, PredicateType, SubjectType
14
15
16def build_context_param(
17 params: dict[str, str],
18 graph_name: IdentifiedNode | t.Iterable[IdentifiedNode] | str | None = None,
19) -> None:
20 """Build the RDF4J http context query parameters dictionary.
21
22 !!! Note
23 This mutates the params dictionary key `context`.
24
25 Parameters:
26 params: The `httpx.Request` parameter dictionary.
27 graph_name: The graph name or iterable of graph names.
28
29 This is the `context` query parameter value.
30 """
31 if graph_name is not None and isinstance(graph_name, IdentifiedNode):
32 if graph_name == DATASET_DEFAULT_GRAPH_ID:
33 # Special RDF4J null value for context-less statements.
34 params["context"] = "null"
35 else:
36 params["context"] = graph_name.n3()
37 elif graph_name is not None and isinstance(graph_name, str):
38 params["context"] = URIRef(graph_name).n3()
39 elif graph_name is not None and isinstance(graph_name, t.Iterable):
40 # type error: "str" has no attribute "n3"
41 graph_names = ",".join([x.n3() for x in graph_name]) # type: ignore[attr-defined]
42 params["context"] = graph_names
43
44
45def build_spo_param(
46 params: dict[str, str],
47 subj: SubjectType = None,
48 pred: PredicateType = None,
49 obj: ObjectType = None,
50) -> None:
51 """Build the RDF4J http subj, predicate, and object query parameters dictionary.
52
53 !!! Note
54 This mutates the params dictionary key `subj`, `pred`, and `obj`.
55
56 Parameters:
57 params: The `httpx.Request` parameter dictionary.
58 subj: The `subj` query parameter value.
59 pred: The `pred` query parameter value.
60 obj: The `obj` query parameter value.
61 """
62 if subj is not None:
63 params["subj"] = subj.n3()
64 if pred is not None:
65 params["pred"] = pred.n3()
66 if obj is not None:
67 params["obj"] = obj.n3()
68
69
70def build_infer_param(
71 params: dict[str, str],
72 infer: bool = True,
73) -> None:
74 """Build the RDF4J http infer query parameters dictionary.
75
76 !!! Note
77 This mutates the params dictionary key `infer`.
78
79 Parameters:
80 params: The `httpx.Request` parameter dictionary.
81 infer: The `infer` query parameter value.
82 """
83 if not infer:
84 params["infer"] = "false"
85
86
87def rdf_payload_to_stream(
88 data: str | bytes | t.BinaryIO | Graph | Dataset,
89) -> tuple[t.BinaryIO, bool]:
90 """Convert an RDF payload into a file-like object.
91
92 Parameters:
93 data: The RDF payload.
94
95 This can be a python `str`, `bytes`, `BinaryIO`, or a
96 [`Graph`][rdflib.graph.Graph] or [`Dataset`][rdflib.graph.Dataset].
97
98 Returns:
99 A tuple containing the file-like object and a boolean indicating whether the
100 immediate caller should close the stream.
101 """
102 stream: t.BinaryIO
103 if isinstance(data, str):
104 # Check if it looks like a file path. Assumes file path length is less than 260.
105 if "\n" not in data and len(data) < 260:
106 try:
107 stream = open(data, "rb")
108 should_close = True
109 except (FileNotFoundError, OSError):
110 # Treat as raw string content
111 stream = io.BytesIO(data.encode("utf-8"))
112 should_close = False
113 else:
114 # Treat as raw string content
115 stream = io.BytesIO(data.encode("utf-8"))
116 should_close = False
117 elif isinstance(data, bytes):
118 stream = io.BytesIO(data)
119 should_close = False
120 elif isinstance(data, (Graph, Dataset)):
121 if data.context_aware:
122 stream = io.BytesIO(
123 data.serialize(format="application/n-quads", encoding="utf-8")
124 )
125 else:
126 stream = io.BytesIO(
127 data.serialize(format="application/n-triples", encoding="utf-8")
128 )
129 should_close = True
130 else:
131 # Assume it's already a file-like object
132 stream = data
133 should_close = False
134
135 return stream, should_close
136
137
138def build_sparql_query_accept_header(query: str, headers: dict[str, str]):
139 """Build the SPARQL query accept header.
140
141 !!! Note
142 This mutates the headers dictionary key `Accept`.
143
144 Parameters:
145 query: The SPARQL query.
146 """
147 prepared_query = prepareQuery(query)
148 if prepared_query.algebra.name in ("SelectQuery", "AskQuery"):
149 headers["Accept"] = "application/sparql-results+json"
150 elif prepared_query.algebra.name in ("ConstructQuery", "DescribeQuery"):
151 headers["Accept"] = "application/n-triples"
152 else:
153 raise ValueError(f"Unsupported query type: {prepared_query.algebra.name}")
154
155
156def validate_graph_name(graph_name: URIRef | t.Iterable[URIRef] | str | None):
157 if (
158 isinstance(graph_name, BNode)
159 or isinstance(graph_name, t.Iterable)
160 and any(isinstance(x, BNode) for x in graph_name)
161 ):
162 raise ValueError("Graph name must not be a BNode.")
163
164
165def validate_no_bnodes(
166 subj: SubjectType,
167 pred: PredicateType,
168 obj: ObjectType,
169 graph_name: URIRef | t.Iterable[URIRef] | str | None,
170) -> None:
171 """Validate that the subject, predicate, and object are not BNodes."""
172 if (
173 isinstance(subj, BNode)
174 or isinstance(pred, BNode)
175 or isinstance(obj, BNode)
176 or isinstance(graph_name, BNode)
177 ):
178 raise ValueError(
179 "Subject, predicate, and object must not be a BNode: "
180 f"{subj}, {pred}, {obj}"
181 )
182 validate_graph_name(graph_name)