Coverage for target/native-coverage/profiles/11fb979bfcf049d7ab666c331dc8db2a/project/.venv/lib/python3.13/site-packages/pyshacl_turbo/__init__.py: 100%
459 statements
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-30 14:51 +0000
« prev ^ index » next coverage.py v7.17.2, created at 2026-11-30 14:51 +0000
1"""pySHACL compatibility layer. All SHACL execution happens in Rust."""
3import json
4import logging
5import sys
6import warnings
7from collections.abc import Iterable, Sequence
8from dataclasses import replace
9from functools import lru_cache, wraps
10from importlib.metadata import version
11from pathlib import Path
13from rdflib import BNode, Literal, URIRef
14from rdflib.graph import Dataset, Graph
16from . import _native
17from ._inference import inference_mode
18from .errors import (
19 ConstraintLoadError,
20 ReportableRuntimeError,
21 ShapeLoadError,
22 ShapeRecursionWarning,
23 ValidationWarning,
24)
25from .graph_abstraction import DataGraph, _reject_native_store_graph
26from .rdf import (
27 Input,
28 commit_serialized,
29 is_oxigraph_store,
30 load_from_source,
31 merge_graph,
32 shape_batches,
33 shape_graphs,
34 union,
35)
36from .rdf import decode as _graph
37from .rdf import input_graph as _input
38from .rule_expand_runner import RuleExpandRunner
39from .shape import Shape
40from .shapes_graph import ShapesGraph
41from .target_data import TargetData, prepare_target_data
42from .validator import Validator
44ValidationFailure = _native.ValidationFailure
45__version__ = version("pyshacl-turbo")
46SHARED_DATASET_PROTOCOL = 1
49def _shared_runtime(data):
50 runtime = sys.modules.get("rdflib_turbo")
51 if runtime is not None and (
52 isinstance(data, runtime.Dataset)
53 or callable(getattr(data, "_validate_shared_shapes", None))
54 ):
55 return runtime
56 return None
59def _check_rule_output(runtime, source, result, inplace):
60 while isinstance(source, DataGraph):
61 source = source._view
62 if inplace:
63 valid = result is source
64 elif isinstance(source, runtime.Dataset):
65 valid = isinstance(result, runtime.Dataset)
66 elif isinstance(source, runtime.Graph):
67 valid = isinstance(result, runtime.Graph) and not isinstance(result, runtime.Dataset)
68 if valid:
69 valid = result.identifier == source.identifier
70 elif isinstance(source, (runtime.Store, runtime.Transaction)):
71 valid = isinstance(result, runtime.Store)
72 else:
73 valid = False
74 if valid and not inplace:
75 source_owner = source.store.backend if isinstance(source, Graph) else source
76 result_owner = result.store.backend if isinstance(result, Graph) else result
77 valid = result_owner._native is not source_owner._native
78 if not valid:
79 raise RuntimeError("Invalid native rule expansion result ownership or graph scope")
82def _restore_selected_failure(function):
83 @wraps(function)
84 def wrapped(*args, **kwargs):
85 failure = None
86 try:
87 return function(*args, **kwargs)
88 except _native.SelectedSourceInterruption as carrier:
89 failure, traceback = carrier.args
90 raise BaseException.with_traceback(failure, traceback)
92 return wrapped
95def _failure_result(function):
96 @wraps(function)
97 def wrapped(*args, **kwargs):
98 try:
99 return function(*args, **kwargs)
100 except ValidationFailure as failure:
101 failure.message = str(failure)
102 return False, failure, f"Validation Failure - {failure}"
103 except (NotImplementedError, ReportableRuntimeError):
104 raise
105 except RuntimeError as error:
106 raise ReportableRuntimeError(str(error)) from error
108 return wrapped
111__all__ = [
112 "CompiledShapes",
113 "ReportableRuntimeError",
114 "RuleExpandRunner",
115 "Shape",
116 "ShapeRecursionWarning",
117 "ShapesGraph",
118 "TargetData",
119 "ValidationFailure",
120 "ValidationWarning",
121 "Validator",
122 "__version__",
123 "compile_shapes",
124 "evaluate_query_testcase",
125 "extract_query_and_expected_result",
126 "load_from_source",
127 "meta_validate",
128 "prepare_target_data",
129 "shacl_rules",
130 "validate",
131 "validate_each",
132]
135@lru_cache(maxsize=128)
136def _compile_native(source, advanced, numeric_booleans, namespaces):
137 try:
138 return (
139 _native.CompiledShapes.from_input(
140 source, advanced, numeric_booleans, list(namespaces), _policy=_native._REGEX_POLICY
141 ),
142 source,
143 )
144 except _native.ShapeLoadFailure as error:
145 raise ShapeLoadError(*error.args) from error
146 except _native.ConstraintLoadFailure as error:
147 raise ConstraintLoadError(*error.args) from error
150def _check_shared_engine(shared):
151 if getattr(shared, "SHARED_SHACL_PROTOCOL", None) != 1:
152 raise RuntimeError("rdflib-turbo does not implement shared SHACL protocol 1")
153 if shared.SHACL_ENGINE_FINGERPRINT != _native.SHACL_ENGINE_FINGERPRINT:
154 raise RuntimeError("rdflib-turbo and pyshacl-turbo have different SHACL engine sources")
157def _compile_for_data(shacl_graph, data_graph, shacl_graph_format, advanced, *, rules=False):
158 runtime = _shared_runtime(data_graph)
159 if runtime is not None and (not rules or isinstance(data_graph, runtime.Dataset)):
160 _check_shared_engine(runtime._native)
161 return compile_shapes(shacl_graph, shacl_graph_format=shacl_graph_format, advanced=advanced)
164def _document_source(data):
165 return (
166 not isinstance(data, (Graph, DataGraph, Input))
167 and _shared_runtime(data) is None
168 and not is_oxigraph_store(data)
169 )
172def _dataset_preparation(operation, *args):
173 try:
174 return operation(*args)
175 except RuntimeError as failure:
176 # Restore outside the public RuntimeError translator, preserving the
177 # actual first source exception without inspecting user error attributes.
178 raise _native.SelectedSourceInterruption(failure, sys.exc_info()[2]) from None
181def _dataset_view(data):
182 if (
183 not isinstance(data, DataGraph)
184 and issubclass(type(data), Dataset)
185 and _shared_runtime(data) is None
186 ):
187 return _dataset_preparation(DataGraph.from_rdflib_dataset, data)
188 return data
191def _prepare_public_shapes(
192 data,
193 shapes,
194 data_format,
195 shapes_format,
196 ontology,
197 inference,
198 imports,
199 *,
200 dataset_preparation=False,
201):
202 if _document_source(data):
203 data = load_from_source(
204 data,
205 rdf_format=data_format,
206 multigraph=ontology is not None or inference not in (None, "none"),
207 )
208 if dataset_preparation:
209 data = _dataset_view(data)
210 if isinstance(shapes, ShapesGraph):
211 return data, shapes
212 graph_input = isinstance(shapes, Graph)
213 if callable(getattr(shapes, "_compile_shared_shapes", None)):
214 if imports:
215 raise NotImplementedError("Native shapes OWL imports are not implemented")
216 graph = shapes
217 else:
218 _reject_native_store_graph(shapes)
219 graph = load_from_source(shapes, rdf_format=shapes_format, do_owl_imports=imports)
220 prepared = ShapesGraph(graph)
221 prepared._numeric_booleans = graph_input
222 return data, prepared
225class CompiledShapes:
226 """Reusable immutable shapes; native Dataset validation borrows its runtime."""
228 def __init__(self, shacl_graph, *, shacl_graph_format=None, advanced=False):
229 self._prepare(shacl_graph, shacl_graph_format, advanced)
230 if self._native is None:
231 source, advanced, namespaces, numeric_booleans = self._shared_spec
232 self._native, source = _compile_native(source, advanced, numeric_booleans, namespaces)
233 self._shared_spec = (source, advanced, namespaces, numeric_booleans)
235 def _prepare(self, shacl_graph, shacl_graph_format, advanced):
236 self._advanced = advanced
237 numeric_booleans = isinstance(shacl_graph, Graph)
238 if isinstance(shacl_graph, ShapesGraph):
239 numeric_booleans = shacl_graph._numeric_booleans
240 shacl_graph = shacl_graph.graph
241 compile_native = getattr(shacl_graph, "_compile_shared_shapes", None)
242 if callable(compile_native):
243 from rdflib_turbo import _native as shared
245 self.graph = shacl_graph
246 self._blank_nodes = {}
247 try:
248 self._native, self._shape_namespaces = compile_native(advanced)
249 except _native.ShapeLoadFailure as error:
250 raise ShapeLoadError(*error.args) from error
251 except _native.ConstraintLoadFailure as error:
252 raise ConstraintLoadError(*error.args) from error
253 except shared.SharedValidationFailure as failure:
254 # pySHACL reports unsupported SPARQL constraints as a ValidationFailure.
255 raise ValidationFailure(str(failure)) from failure
256 self._shared_spec = None
257 self._shared_program = None
258 return
259 _reject_native_store_graph(shacl_graph)
260 self.graph = load_from_source(shacl_graph, rdf_format=shacl_graph_format)
261 self._blank_nodes = {}
262 source = _native.ShapesInput(
263 shape_batches(self.graph, self._blank_nodes),
264 self.graph.context_aware,
265 shape_graphs(self.graph, self._blank_nodes),
266 )
267 namespaces = tuple((p, str(ns)) for p, ns in self.graph.namespaces())
268 self._shape_namespaces = namespaces
269 self._native = None
270 self._shared_spec = (
271 source,
272 advanced,
273 namespaces,
274 numeric_booleans,
275 )
276 self._shared_program = None
278 def targeting(
279 self,
280 data_graph,
281 node: URIRef | BNode | Literal,
282 *,
283 skip: Iterable[URIRef | BNode] = (),
284 ) -> list[URIRef | BNode]:
285 """Return active node-shape identifiers whose declared targets include node.
287 Reuse TargetData to share a native reverse index across node lookups.
288 Excluded shapes are not evaluated. Graph inputs read fresh data per call.
289 """
290 return prepare_target_data(data_graph)._targeting(self, node, skip)
292 def validate(
293 self,
294 data_graph,
295 *,
296 data_graph_format=None,
297 inplace=False,
298 inference=None,
299 iterate_rules=False,
300 max_rule_iterations=100,
301 max_validation_depth=15,
302 allow_infos=False,
303 allow_warnings=False,
304 abort_on_first=False,
305 focus_nodes=None,
306 use_shapes=None,
307 _normalize_report_literals=None,
308 _prepare_dataset=None,
309 _ontology=None,
310 ):
311 runtime = _shared_runtime(data_graph)
312 if _ontology is not None and runtime is None:
313 raise TypeError("Native ontology inoculation requires a native source")
314 if runtime is not None:
315 # Like pySHACL, a parsed graph ignores data_graph_format.
316 from rdflib_turbo import _native as shared
318 _check_shared_engine(shared)
319 if self._shared_program is None:
320 self._shared_program = shared.SharedShapes.from_compiled(
321 self._native, _comparison_policy=_native._VALUE_COMPARISON_POLICY
322 )
323 execute = getattr(data_graph, "_validate_shared_shapes", None)
324 if not callable(execute):
325 raise RuntimeError("Native source does not implement borrowed SHACL validation")
326 data_namespaces = (
327 dict(data_graph.namespaces())
328 if isinstance(data_graph, (runtime.Dataset, Graph))
329 else dict(self._shape_namespaces)
330 )
331 inference = inference_mode(inference)
332 settings = {
333 "iterate_rules": iterate_rules,
334 "max_rule_iterations": max_rule_iterations,
335 "max_validation_depth": 15
336 if max_validation_depth is None
337 else max_validation_depth,
338 "allow_infos": allow_infos,
339 "allow_warnings": allow_warnings,
340 "abort_on_first": abort_on_first,
341 "focus_nodes": _expand_names(data_namespaces, focus_nodes),
342 "use_shapes": _expand_names(dict(self._shape_namespaces), use_shapes),
343 }
344 if inference not in (None, "none"):
345 settings["inference"] = inference
346 try:
347 staged = () if _ontology is None else (_ontology,)
348 with execute(
349 self._shared_program, json.dumps(settings), inplace, *staged
350 ) as result:
351 conforms, report, text, recursion_warnings = result
352 if type(conforms) is not bool:
353 raise TypeError("Native report conformance must be a boolean")
354 _emit_recursion_warnings(recursion_warnings)
355 report_graph = _graph(
356 report,
357 self._blank_nodes,
358 preserve_ids=True,
359 report=True,
360 normalize=_normalize_report_literals,
361 _report_conforms=conforms,
362 )
363 for prefix, namespace in self._shape_namespaces:
364 report_graph.bind(prefix, namespace)
365 except shared.SharedValidationFailure as failure:
366 raise ValidationFailure(str(failure)) from failure
367 return conforms, report_graph, text
368 inference = inference_mode(inference)
369 if inference not in (None, "none"):
370 raise NotImplementedError(
371 "CompiledShapes.validate pre-inference requires a native source; use validate for serialized inputs"
372 )
373 if inplace and not (
374 isinstance(data_graph, (Graph, Input)) or is_oxigraph_store(data_graph)
375 ):
376 raise TypeError("inplace=True requires an RDFLib Graph or pyoxigraph Store")
377 dataset_factory = None
378 if _prepare_dataset is None:
379 _prepare_dataset = self._shared_spec is not None and not self._shared_spec[1]
380 if _prepare_dataset:
381 data_graph = _dataset_view(data_graph)
382 if isinstance(data_graph, DataGraph) and data_graph.is_multigraph():
383 _dataset_preparation(setattr, data_graph, "default_union", True)
384 if issubclass(type(data_graph.impl), Dataset):
385 dataset_factory = Dataset
386 data = _input(
387 data_graph,
388 data_graph_format,
389 direct=True,
390 observe_booleans=True,
391 _dataset_factory=dataset_factory,
392 _borrow=not self._advanced and self._native.selected_frames_only,
393 )
394 # Core validation cannot execute rules, so its input relation is unchanged.
395 write_data = inplace and self._advanced
397 conforms, report, text, expanded, recursion_warnings = self._native.validate(
398 data.source,
399 data.format,
400 data.base,
401 iterate_rules,
402 max_rule_iterations,
403 15 if max_validation_depth is None else max_validation_depth,
404 write_data,
405 allow_infos,
406 allow_warnings,
407 abort_on_first,
408 _expand_names(data.namespaces or dict(self._shape_namespaces), focus_nodes),
409 _expand_names(dict(self._shape_namespaces), use_shapes),
410 [(p, str(ns)) for p, ns in data.namespaces.items()],
411 _comparison_policy=_native._VALUE_COMPARISON_POLICY,
412 )
413 if type(conforms) is not bool:
414 raise TypeError("Native report conformance must be a boolean")
415 _emit_recursion_warnings(recursion_warnings)
416 nodes = self._blank_nodes | data.blank_nodes
417 report_graph = _graph(
418 report,
419 nodes,
420 preserve_ids=True,
421 report=True,
422 normalize=_normalize_report_literals,
423 _report_conforms=conforms,
424 )
425 for prefix, namespace in self._shape_namespaces:
426 report_graph.bind(prefix, namespace)
427 if write_data:
428 commit_serialized(data_graph, expanded, nodes, before=data)
429 return conforms, report_graph, text
431 _validate = validate
432 validate = _restore_selected_failure(validate)
434 def shacl_rules(
435 self,
436 data_graph,
437 *,
438 data_graph_format=None,
439 inplace=False,
440 iterate_rules=False,
441 max_rule_iterations=100,
442 max_validation_depth=15,
443 focus_nodes=None,
444 use_shapes=None,
445 inference=None,
446 _return_dataset=False,
447 _ontology=None,
448 ):
449 runtime = _shared_runtime(data_graph)
450 inference = inference_mode(inference)
451 if _ontology is not None and runtime is None:
452 raise TypeError("Native ontology inoculation requires a native source")
453 if runtime is not None:
454 # Like pySHACL, a parsed graph ignores data_graph_format.
455 shared = runtime._native
456 _check_shared_engine(shared)
457 if self._shared_program is None:
458 self._shared_program = shared.SharedShapes.from_compiled(
459 self._native, _comparison_policy=_native._VALUE_COMPARISON_POLICY
460 )
461 execute = getattr(data_graph, "_expand_shared_shapes", None)
462 if not callable(execute):
463 raise RuntimeError("Native source does not implement borrowed SHACL rules")
464 namespaces = (
465 dict(data_graph.namespaces())
466 if isinstance(data_graph, Graph)
467 else dict(self._shape_namespaces)
468 )
469 settings = {
470 "iterate_rules": iterate_rules,
471 "max_rule_iterations": max_rule_iterations,
472 "max_validation_depth": 15
473 if max_validation_depth is None
474 else max_validation_depth,
475 "focus_nodes": _expand_names(namespaces, focus_nodes),
476 "use_shapes": _expand_names(dict(self._shape_namespaces), use_shapes),
477 }
478 if inference is not None:
479 settings["inference"] = inference
480 staged = () if _ontology is None else (_ontology,)
481 try:
482 with execute(
483 self._shared_program, json.dumps(settings), inplace, *staged
484 ) as result:
485 expanded, recursion_warnings = result
486 _check_rule_output(runtime, data_graph, expanded, inplace)
487 _emit_recursion_warnings(recursion_warnings)
488 except shared.SharedValidationFailure as failure:
489 raise ValidationFailure(str(failure)) from failure
490 return expanded
491 if inference is not None:
492 raise NotImplementedError(
493 "CompiledShapes.shacl_rules pre-inference requires a native source; use shacl_rules for serialized inputs"
494 )
495 if inplace and not (
496 isinstance(data_graph, (Graph, Input)) or is_oxigraph_store(data_graph)
497 ):
498 raise TypeError("inplace=True requires an RDFLib Graph or pyoxigraph Store")
499 data = _input(data_graph, data_graph_format, direct=True)
500 expanded, recursion_warnings = self._native.expand(
501 data.source,
502 data.format,
503 data.base,
504 iterate_rules,
505 max_rule_iterations,
506 15 if max_validation_depth is None else max_validation_depth,
507 _expand_names(data.namespaces or dict(self._shape_namespaces), focus_nodes),
508 _expand_names(dict(self._shape_namespaces), use_shapes),
509 inplace and isinstance(data_graph, Graph),
510 _comparison_policy=_native._VALUE_COMPARISON_POLICY,
511 )
512 _emit_recursion_warnings(recursion_warnings)
513 if inplace and isinstance(data_graph, Graph):
514 commit_serialized(data_graph, expanded, data.blank_nodes)
515 return data_graph
516 result = _graph(
517 expanded,
518 data.blank_nodes,
519 multigraph=_return_dataset,
520 _bind_namespaces="core" if _return_dataset else "rdflib",
521 preserve_ids=True,
522 identifier=getattr(data_graph, "identifier", None),
523 )
524 for prefix, namespace in data.namespaces.items():
525 result.bind(prefix, namespace)
526 if inplace:
527 commit_serialized(data_graph, expanded, data.blank_nodes, before=data)
528 return result
531def compile_shapes(shacl_graph, *, shacl_graph_format=None, advanced=False):
532 return CompiledShapes(shacl_graph, shacl_graph_format=shacl_graph_format, advanced=advanced)
535def validate(
536 data_graph,
537 *args,
538 shacl_graph=None,
539 data_graph_format=None,
540 shacl_graph_format=None,
541 advanced=False,
542 inplace=False,
543 iterate_rules=False,
544 max_rule_iterations=100,
545 max_validation_depth=15,
546 inference=None,
547 ont_graph=None,
548 js=False,
549 debug=False,
550 allow_infos=False,
551 allow_warnings=False,
552 abort_on_first=False,
553 focus_nodes=None,
554 use_shapes=None,
555 multi_data_graphs_mode=None,
556 do_owl_imports=False,
557 ont_graph_format=None,
558 serialize_report_graph=False,
559 sparql_mode=False,
560 **kwargs,
561):
562 report_normalize = kwargs.pop("_normalize_report_literals", True)
563 check_dash = kwargs.pop("check_dash_result", False)
564 meta_shacl = kwargs.pop("meta_shacl", kwargs.pop("metashacl", False))
565 abort_on_first = kwargs.pop("abort_on_error", abort_on_first)
566 _options(js, kwargs)
567 if debug:
568 logging.getLogger("pyshacl-turbo").debug("Validating with the native Rust engine")
569 if sparql_mode:
570 if inference not in (None, "none") or ont_graph is not None or inplace:
571 raise RuntimeError(
572 "SPARQL Remote Graph Mode does not support inference, ontology inoculation or inplace"
573 )
574 if isinstance(data_graph, str) and data_graph.startswith(("http:", "https:")):
575 raise NotImplementedError("Remote SPARQL endpoint input")
576 if _is_multi_data_graph_input(data_graph):
577 if not data_graph:
578 raise RuntimeError("No data graphs were provided for validation.")
579 if multi_data_graphs_mode == "validate_each":
580 return validate_each(
581 data_graph,
582 *args,
583 shacl_graph=shacl_graph,
584 advanced=advanced,
585 data_graph_format=data_graph_format,
586 shacl_graph_format=shacl_graph_format,
587 inference=inference,
588 ont_graph=ont_graph,
589 inplace=inplace,
590 allow_infos=allow_infos,
591 allow_warnings=allow_warnings,
592 abort_on_first=abort_on_first,
593 focus_nodes=focus_nodes,
594 use_shapes=use_shapes,
595 do_owl_imports=do_owl_imports,
596 ont_graph_format=ont_graph_format,
597 serialize_report_graph=serialize_report_graph,
598 iterate_rules=iterate_rules,
599 max_rule_iterations=max_rule_iterations,
600 max_validation_depth=max_validation_depth,
601 debug=debug,
602 sparql_mode=sparql_mode,
603 )
604 if multi_data_graphs_mode not in (None, "combine"):
605 raise RuntimeError(f"Unknown multi_data_graphs_mode: {multi_data_graphs_mode}")
606 combined = Graph()
607 for source in data_graph:
608 source_graph = union(load_from_source(source, rdf_format=data_graph_format))
609 combined += source_graph
610 for prefix, namespace in source_graph.namespaces():
611 combined.bind(prefix, namespace)
612 data_graph, data_graph_format = combined, None
613 caller_shapes = shacl_graph is not None
614 if shacl_graph is None:
615 shacl_graph, shacl_graph_format = data_graph, data_graph_format
616 if meta_shacl:
617 conforms, _, text = meta_validate(shacl_graph, shacl_graph_format=shacl_graph_format)
618 if not conforms:
619 raise ReportableRuntimeError(
620 "SHACL File does not validate against the SHACL Shapes SHACL (MetaSHACL) file.\n"
621 + text
622 )
623 native_validation = _shared_runtime(data_graph) is not None
624 if (
625 native_validation
626 and check_dash
627 and (inference not in (None, "none") or ont_graph is not None)
628 ):
629 raise NotImplementedError("Native pre-inference with check_dash_result is not implemented")
630 original = data_graph
631 dataset_preparation = not advanced and ont_graph is None and inference in (None, "none")
632 if caller_shapes:
633 data_graph, shacl_graph = _prepare_public_shapes(
634 data_graph,
635 shacl_graph,
636 data_graph_format,
637 shacl_graph_format,
638 ont_graph,
639 inference,
640 do_owl_imports,
641 dataset_preparation=dataset_preparation,
642 )
643 original_snapshot = _input(data_graph) if is_oxigraph_store(data_graph) else None
644 inference = inference_mode(inference)
645 ontology = None
646 if native_validation and ont_graph is not None:
647 ontology = _ontology_inoculation(ont_graph, ont_graph_format, do_owl_imports)
648 if not native_validation:
649 data_graph = _prepare_data(
650 replace(original_snapshot) if original_snapshot is not None else data_graph,
651 data_graph_format,
652 ont_graph,
653 ont_graph_format,
654 inference,
655 do_owl_imports,
656 )
657 if check_dash:
658 snapshot = _input(data_graph, data_graph_format)
659 data_graph = Input(
660 snapshot.source,
661 snapshot.format,
662 snapshot.base,
663 snapshot.blank_nodes,
664 snapshot.namespaces,
665 snapshot.preserve_ids,
666 )
667 program = _compile_for_data(shacl_graph, data_graph, shacl_graph_format, advanced)
668 result = program._validate(
669 data_graph,
670 data_graph_format=data_graph_format,
671 inplace=inplace or check_dash,
672 inference=inference if native_validation else None,
673 iterate_rules=iterate_rules,
674 max_rule_iterations=max_rule_iterations,
675 max_validation_depth=max_validation_depth,
676 allow_infos=allow_infos,
677 allow_warnings=allow_warnings,
678 abort_on_first=abort_on_first,
679 focus_nodes=focus_nodes,
680 use_shapes=use_shapes,
681 _normalize_report_literals=report_normalize,
682 _prepare_dataset=dataset_preparation,
683 _ontology=ontology,
684 )
685 borrowed_original = isinstance(data_graph, DataGraph) and data_graph.impl is original
686 if (
687 inplace
688 and isinstance(original, Graph)
689 and original is not data_graph
690 and not borrowed_original
691 ):
692 merge_graph(original, load_from_source(data_graph))
693 elif inplace and is_oxigraph_store(original) and original is not data_graph:
694 snapshot = _input(data_graph)
695 commit_serialized(original, snapshot.source, before=original_snapshot)
696 if check_dash:
697 from .conformance import check_dash_result
699 _, report, text = result
700 return check_dash_result(report, program.graph, data_graph), report, text
701 if serialize_report_graph:
702 conforms, report, text = result
703 fmt = serialize_report_graph if isinstance(serialize_report_graph, str) else "turtle"
704 result = conforms, report.serialize(format=fmt, encoding="utf-8"), text
705 return result
708_validate_direct = _restore_selected_failure(validate)
709validate = _restore_selected_failure(_failure_result(validate))
712def shacl_rules(
713 data_graph,
714 *args,
715 shacl_graph=None,
716 data_graph_format=None,
717 shacl_graph_format=None,
718 advanced=True,
719 inplace=False,
720 iterate_rules=False,
721 max_rule_iterations=100,
722 max_validation_depth=15,
723 inference=None,
724 ont_graph=None,
725 js=False,
726 debug=False,
727 do_owl_imports=False,
728 ont_graph_format=None,
729 focus_nodes=None,
730 use_shapes=None,
731 serialize_expanded_graph=False,
732 serialize_expanded_graph_format=None,
733 **kwargs,
734):
735 _options(js, kwargs)
736 caller_shapes = shacl_graph is not None
737 if shacl_graph is None:
738 shacl_graph, shacl_graph_format = data_graph, data_graph_format
739 original = data_graph
740 public_input_view = None
741 if isinstance(original, DataGraph):
742 public_input_view = original
743 elif isinstance(original, Graph):
744 public_input_view = DataGraph.from_rdflib(original)
745 document = _document_source(original)
746 if document:
747 data_graph = load_from_source(
748 original, rdf_format=data_graph_format, multigraph=True, _bind_namespaces="core"
749 )
750 if caller_shapes:
751 data_graph, shacl_graph = _prepare_public_shapes(
752 data_graph,
753 shacl_graph,
754 data_graph_format,
755 shacl_graph_format,
756 ont_graph,
757 inference,
758 do_owl_imports,
759 )
760 original_snapshot = _input(data_graph) if is_oxigraph_store(data_graph) else None
761 native_rules = _shared_runtime(data_graph) is not None
762 ontology = None
763 if native_rules:
764 # The native owner stages inoculation and pre-inference privately (ADR 0082).
765 if ont_graph is not None:
766 ontology = _ontology_inoculation(ont_graph, ont_graph_format, do_owl_imports)
767 else:
768 data_graph = _prepare_data(
769 replace(original_snapshot) if original_snapshot is not None else data_graph,
770 data_graph_format,
771 ont_graph,
772 ont_graph_format,
773 inference,
774 do_owl_imports,
775 _bind_namespaces="core" if document else "rdflib",
776 )
777 expand_inplace = inplace
778 rdflib_object = isinstance(original, Graph) and _shared_runtime(original) is None
779 if rdflib_object:
780 owns_preparation = data_graph is not original
781 if owns_preparation:
782 prepared = public_input_view.clone()
783 merge_graph(prepared, data_graph)
784 data_graph = prepared
785 elif not isinstance(data_graph, DataGraph):
786 data_graph = public_input_view
787 if not inplace and not owns_preparation:
788 data_graph = data_graph.clone()
789 expand_inplace = True
790 result = _compile_for_data(
791 shacl_graph, data_graph, shacl_graph_format, advanced, rules=True
792 ).shacl_rules(
793 data_graph,
794 data_graph_format=data_graph_format,
795 inplace=expand_inplace,
796 iterate_rules=iterate_rules,
797 max_rule_iterations=max_rule_iterations,
798 max_validation_depth=max_validation_depth,
799 focus_nodes=focus_nodes,
800 use_shapes=use_shapes,
801 inference=inference if native_rules else None,
802 _ontology=ontology,
803 **({"_return_dataset": True} if document else {}),
804 )
805 borrowed_result = isinstance(result, DataGraph) and result.impl is original
806 if (
807 inplace
808 and isinstance(original, Graph)
809 and original is not data_graph
810 and not borrowed_result
811 ):
812 merge_graph(original, result)
813 result = original
814 elif inplace and is_oxigraph_store(original) and original is not data_graph:
815 commit_serialized(original, _input(data_graph).source, before=original_snapshot)
816 if document:
817 result = DataGraph.from_rdflib(result)
818 if serialize_expanded_graph:
819 if isinstance(result, DataGraph):
820 result = result._view
821 rdf_format = serialize_expanded_graph_format or "trig"
822 if (
823 rdf_format in {"json-ld", "nquads"}
824 and isinstance(result, Graph)
825 and not result.context_aware
826 ):
827 dataset = Dataset()
828 context = dataset.graph(result.identifier)
829 context += result
830 for prefix, namespace in result.namespaces():
831 dataset.bind(prefix, namespace)
832 result = dataset
833 return result.serialize(format=rdf_format)
834 if inplace and public_input_view is not None:
835 return public_input_view
836 if isinstance(original, Graph) and not isinstance(result, DataGraph):
837 result = DataGraph.from_rdflib(result)
838 return result
841def _emit_recursion_warnings(messages):
842 # Emit before committing rule/inference additions. A warnings-as-errors
843 # policy must leave the caller's Graph or Store untouched.
844 for message in messages:
845 warnings.warn(message, ShapeRecursionWarning, stacklevel=3)
848def _options(js, kwargs):
849 if js:
850 raise NotImplementedError("Unsupported SHACL-JS")
851 for option in ("meta_shacl", "check_dash_result", "metashacl"):
852 if kwargs.pop(option, False):
853 raise NotImplementedError(f"Unsupported option: {option}")
854 if kwargs:
855 raise TypeError(f"Unsupported options: {', '.join(sorted(kwargs))}")
858def _expand_names(graph, names):
859 result = []
860 namespaces = graph if isinstance(graph, dict) else dict(graph.namespaces())
861 for name in names or []:
862 prefix, sep, local = str(name).partition(":")
863 result.append(
864 str(namespaces[prefix]) + local if sep and prefix in namespaces else str(name)
865 )
866 return result
869def _prepare_data(
870 data, rdf_format, ontology, ontology_format, inference, imports, *, _bind_namespaces="rdflib"
871):
872 inference = inference_mode(inference)
873 if ontology is None and inference in (None, "none"):
874 return data
875 multigraph = not isinstance(data, Graph) or data.context_aware
876 if not isinstance(data, (Graph, Input)) and not is_oxigraph_store(data):
877 data = load_from_source(data, rdf_format=rdf_format, multigraph=True)
878 snapshot = _input(data, rdf_format)
879 source, source_format = snapshot.source, snapshot.format
880 namespaces = dict(snapshot.namespaces)
881 if ontology is not None:
882 ont = _input(
883 load_from_source(
884 ontology,
885 rdf_format=ontology_format,
886 do_owl_imports=imports,
887 _bind_namespaces=_bind_namespaces,
888 ),
889 flatten=True,
890 )
891 source = _native.inoculate(source, source_format, ont.source)
892 source_format = "nquads"
893 for prefix, namespace in ont.namespaces.items():
894 namespaces.setdefault(prefix, namespace)
895 if inference not in (None, "none"):
896 source = _native.infer(
897 source, source_format, inference, "urn:pyshacl:inference" if multigraph else None
898 )
899 source_format = "nquads"
900 if is_oxigraph_store(data) or isinstance(data, Input):
901 return Input(
902 source, source_format, None, snapshot.blank_nodes, namespaces, preserve_ids=True
903 )
904 result = _graph(
905 source, snapshot.blank_nodes, preserve_ids=True, _bind_namespaces=_bind_namespaces
906 )
907 for prefix, namespace in namespaces.items():
908 result.bind(prefix, namespace)
909 return result
912def _ontology_inoculation(ontology, ontology_format, imports):
913 """Parse ont_graph once for pySHACL inoculation staged on a native owner.
915 The ontology is held as one flattened N-Triples document (it is schema, read by
916 random access while copying); the data graph is never copied or serialized.
917 """
918 from rdflib_turbo._inoculation import OntologyInoculation
920 ont = _input(
921 load_from_source(ontology, rdf_format=ontology_format, do_owl_imports=imports),
922 flatten=True,
923 )
924 return OntologyInoculation(ont.source, ont.namespaces.items())
927def _is_multi_data_graph_input(value):
928 return not isinstance(value, (str, bytes, Graph)) and isinstance(
929 value, (Sequence, set, frozenset)
930 )
933def validate_each(data_graphs, *args, **kwargs):
934 if not _is_multi_data_graph_input(data_graphs):
935 raise ReportableRuntimeError("validate_each expects a sequence of data graphs to validate.")
936 data_graphs = list(data_graphs)
937 if not data_graphs:
938 raise ReportableRuntimeError("No data graphs were provided for validate_each.")
939 return {index: validate(data, *args, **kwargs) for index, data in enumerate(data_graphs)}
942def meta_validate(shacl_graph, inference="rdfs", **kwargs):
943 kwargs.pop("meta_shacl", None)
944 kwargs.pop("metashacl", None)
945 source_format = kwargs.pop("shacl_graph_format", None)
946 source = load_from_source(shacl_graph, rdf_format=source_format)
947 return validate(
948 source,
949 shacl_graph=Path(__file__).parent / "assets/shacl-shacl.ttl",
950 inference=inference,
951 **kwargs,
952 )
955from .conformance import evaluate_query_testcase, extract_query_and_expected_result