src/rdflib/extras/shacl.py
1"""
2Utilities for interacting with SHACL Shapes Graphs more easily.
3"""
4
5from __future__ import annotations
6
7from typing import TYPE_CHECKING, Optional, Union
8
9from rdflib import BNode, Graph, Literal, URIRef, paths
10from rdflib.collection import Collection
11from rdflib.namespace import RDF, SH
12from rdflib.paths import Path
13from rdflib.term import Node
14
15if TYPE_CHECKING:
16 from rdflib.term import IdentifiedNode
17
18
19class SHACLPathError(Exception):
20 pass
21
22
23# Map the variable length path operators to the corresponding SHACL path predicates
24_PATH_MOD_TO_PRED = {
25 paths.ZeroOrMore: SH.zeroOrMorePath,
26 paths.OneOrMore: SH.oneOrMorePath,
27 paths.ZeroOrOne: SH.zeroOrOnePath,
28}
29
30
31# This implementation is roughly based on
32# pyshacl.helper.sparql_query_helper::SPARQLQueryHelper._shacl_path_to_sparql_path
33def parse_shacl_path(
34 shapes_graph: Graph,
35 path_identifier: Node,
36) -> Union[URIRef, Path]:
37 """
38 Parse a valid SHACL path (e.g. the object of a triple with predicate sh:path)
39 from a [`Graph`][rdflib.graph.Graph] as a [`URIRef`][rdflib.term.URIRef] if the path
40 is simply a predicate or a [`Path`][rdflib.paths.Path] otherwise.
41
42 Args:
43 shapes_graph: A [`Graph`][rdflib.graph.Graph] containing the path to be parsed
44 path_identifier: A [`Node`][rdflib.term.Node] of the path
45
46 Returns:
47 A [`URIRef`][rdflib.term.URIRef] or a [`Path`][rdflib.paths.Path]
48 """
49 path: Optional[Union[URIRef, Path]] = None
50
51 # Literals are not allowed.
52 if isinstance(path_identifier, Literal):
53 raise TypeError("Literals are not a valid SHACL path.")
54
55 # If a path is a URI, that's the whole path.
56 elif isinstance(path_identifier, URIRef):
57 if path_identifier == RDF.nil:
58 raise SHACLPathError(
59 "A list of SHACL Paths must contain at least two path items."
60 )
61 path = path_identifier
62
63 # Handle Sequence Paths
64 elif shapes_graph.value(path_identifier, RDF.first) is not None:
65 sequence = list(shapes_graph.items(path_identifier))
66 if len(sequence) < 2:
67 raise SHACLPathError(
68 "A list of SHACL Sequence Paths must contain at least two path items."
69 )
70 path = paths.SequencePath(
71 *(parse_shacl_path(shapes_graph, path) for path in sequence)
72 )
73
74 # Handle sh:inversePath
75 elif inverse_path := shapes_graph.value(path_identifier, SH.inversePath):
76 path = paths.InvPath(parse_shacl_path(shapes_graph, inverse_path))
77
78 # Handle sh:alternativePath
79 elif alternative_path := shapes_graph.value(path_identifier, SH.alternativePath):
80 alternatives = list(shapes_graph.items(alternative_path))
81 if len(alternatives) < 2:
82 raise SHACLPathError(
83 "List of SHACL alternate paths must have at least two path items."
84 )
85 path = paths.AlternativePath(
86 *(
87 parse_shacl_path(shapes_graph, alternative)
88 for alternative in alternatives
89 )
90 )
91
92 # Handle sh:zeroOrMorePath
93 elif zero_or_more_path := shapes_graph.value(path_identifier, SH.zeroOrMorePath):
94 path = paths.MulPath(parse_shacl_path(shapes_graph, zero_or_more_path), "*")
95
96 # Handle sh:oneOrMorePath
97 elif one_or_more_path := shapes_graph.value(path_identifier, SH.oneOrMorePath):
98 path = paths.MulPath(parse_shacl_path(shapes_graph, one_or_more_path), "+")
99
100 # Handle sh:zeroOrOnePath
101 elif zero_or_one_path := shapes_graph.value(path_identifier, SH.zeroOrOnePath):
102 path = paths.MulPath(parse_shacl_path(shapes_graph, zero_or_one_path), "?")
103
104 # Raise error if none of the above options were found
105 elif path is None:
106 raise SHACLPathError(f"Cannot parse {repr(path_identifier)} as a SHACL Path.")
107
108 return path
109
110
111def _build_path_component(
112 graph: Graph, path_component: URIRef | Path
113) -> IdentifiedNode:
114 """
115 Helper method that implements the recursive component of SHACL path
116 triple construction.
117
118 Args:
119 graph: A [`Graph`][rdflib.graph.Graph] into which to insert triples
120 graph_component: A [`URIRef`][rdflib.term.URIRef] or
121 [`Path`][rdflib.paths.Path] that is part of a path expression
122
123 Returns:
124 The [`IdentifiedNode`][rdflib.term.IdentifiedNode] of the resource in the
125 graph that corresponds to the provided path_component
126 """
127 # Literals or other types are not allowed
128 if not isinstance(path_component, (URIRef, Path)):
129 raise TypeError(
130 f"Objects of type {type(path_component)} are not valid "
131 + "components of a SHACL path."
132 )
133
134 # If the path component is a URI, return it
135 elif isinstance(path_component, URIRef):
136 return path_component
137 # Otherwise, the path component is represented as a blank node
138 bnode = BNode()
139
140 # Handle Sequence Paths
141 if isinstance(path_component, paths.SequencePath):
142 # Sequence paths are a Collection directly with at least two items
143 if len(path_component.args) < 2:
144 raise SHACLPathError(
145 "A list of SHACL Sequence Paths must contain at least two path items."
146 )
147 Collection(
148 graph,
149 bnode,
150 [_build_path_component(graph, arg) for arg in path_component.args],
151 )
152
153 # Handle Inverse Paths
154 elif isinstance(path_component, paths.InvPath):
155 graph.add(
156 (bnode, SH.inversePath, _build_path_component(graph, path_component.arg))
157 )
158
159 # Handle Alternative Paths
160 elif isinstance(path_component, paths.AlternativePath):
161 # Alternative paths are a Collection but referenced by sh:alternativePath
162 # with at least two items
163 if len(path_component.args) < 2:
164 raise SHACLPathError(
165 "List of SHACL alternate paths must have at least two path items."
166 )
167 coll = Collection(
168 graph,
169 BNode(),
170 [_build_path_component(graph, arg) for arg in path_component.args],
171 )
172 graph.add((bnode, SH.alternativePath, coll.uri))
173
174 # Handle Variable Length Paths
175 elif isinstance(path_component, paths.MulPath):
176 # Get the predicate corresponding to the path modifiier
177 pred = _PATH_MOD_TO_PRED.get(path_component.mod)
178 if pred is None:
179 raise SHACLPathError(f"Unknown path modifier {path_component.mod}")
180 graph.add((bnode, pred, _build_path_component(graph, path_component.path)))
181
182 # Return the blank node created for the provided path_component
183 return bnode
184
185
186def build_shacl_path(
187 path: URIRef | Path, target_graph: Graph | None = None
188) -> tuple[IdentifiedNode, Graph | None]:
189 """
190 Build the SHACL Path triples for a path given by a [`URIRef`][rdflib.term.URIRef] for
191 simple paths or a [`Path`][rdflib.paths.Path] for complex paths.
192
193 Returns an [`IdentifiedNode`][rdflib.term.IdentifiedNode] for the path (which should be
194 the object of a triple with predicate `sh:path`) and the graph into which any
195 new triples were added.
196
197 Args:
198 path: A [`URIRef`][rdflib.term.URIRef] or a [`Path`][rdflib.paths.Path]
199 target_graph: Optionally, a [`Graph`][rdflib.graph.Graph] into which to put
200 constructed triples. If not provided, a new graph will be created
201
202 Returns:
203 A (path_identifier, graph) tuple where:
204 - path_identifier: If path is a [`URIRef`][rdflib.term.URIRef], this is simply
205 the provided path. If path is a [`Path`][rdflib.paths.Path], this is
206 the [`BNode`][rdflib.term.BNode] corresponding to the root of the SHACL
207 path expression added to the graph.
208 - graph: None if path is a [`URIRef`][rdflib.term.URIRef] (as no new triples
209 are constructed). If path is a [`Path`][rdflib.paths.Path], this is either the
210 target_graph provided or a new graph into which the path triples were added.
211 """
212 # If a path is a URI, that's the whole path. No graph needs to be constructed.
213 if isinstance(path, URIRef):
214 return path, None
215
216 # Create a graph if one was not provided
217 if target_graph is None:
218 target_graph = Graph()
219
220 # Recurse through the path to build the graph representation
221 return _build_path_component(target_graph, path), target_graph