src/rdflib/plugins/serializers/patch.py
1from __future__ import annotations
2
3import warnings
4from typing import IO, Any, Optional
5from uuid import uuid4
6
7from rdflib import Dataset
8from rdflib.plugins.serializers.nquads import _nq_row
9from rdflib.plugins.serializers.nt import _nt_row
10from rdflib.serializer import Serializer
11
12add_remove_methods = {"add": "A", "remove": "D"}
13
14
15class PatchSerializer(Serializer):
16 """
17 Creates an RDF patch file to add and remove triples/quads.
18 Can either:
19 - Create an add or delete patch for a single Dataset.
20 - Create a patch to represent the difference between two Datasets.
21 """
22
23 def __init__(
24 self,
25 store: Dataset,
26 ):
27 self.store: Dataset = store
28 super().__init__(store)
29
30 def serialize(
31 self,
32 stream: IO[bytes],
33 base: Optional[str] = None,
34 encoding: Optional[str] = None,
35 **kwargs: Any,
36 ) -> None:
37 """Serialize the store to the given stream.
38
39 Args:
40 stream: The stream to serialize to.
41 base: The base URI to use for the serialization.
42 encoding: The encoding to use for the serialization.
43 kwargs: Additional keyword arguments.
44
45 Supported keyword arguments:
46
47 - operation: The operation to perform. Either 'add' or 'remove'.
48 - target: The target Dataset to compare against.
49 NB: Only one of 'operation' or 'target' should be provided.
50 - header_id: The header ID to use.
51 - header_prev: The previous header ID to use.
52 """
53 operation = kwargs.get("operation")
54 target = kwargs.get("target")
55 header_id = kwargs.get("header_id")
56 header_prev = kwargs.get("header_prev")
57 if not header_id:
58 header_id = f"uuid:{uuid4()}"
59 encoding = self.encoding
60 if base is not None:
61 warnings.warn("PatchSerializer does not support base.")
62 if encoding is not None and encoding.lower() != self.encoding.lower():
63 warnings.warn(
64 "PatchSerializer does not use custom encoding. "
65 f"Given encoding was: {encoding}"
66 )
67
68 def write_header():
69 stream.write(f"H id <{header_id}> .\n".encode(encoding, "replace"))
70 if header_prev:
71 stream.write(f"H prev <{header_prev}>\n".encode(encoding, "replace"))
72 stream.write("TX .\n".encode(encoding, "replace"))
73
74 def write_triples(contexts, op_code, use_passed_contexts=False):
75 for context in contexts:
76 if not use_passed_contexts:
77 context = self.store.get_context(context.identifier)
78 for triple in context:
79 stream.write(
80 self._patch_row(triple, context.identifier, op_code).encode(
81 encoding, "replace"
82 )
83 )
84
85 if operation:
86 assert operation in add_remove_methods, f"Invalid operation: {operation}"
87 elif not target:
88 # No operation specified and no target specified
89 # Fall back to default operation of "add" to prevent a no-op
90 operation = "add"
91 write_header()
92 if operation:
93 operation_code = add_remove_methods.get(operation)
94 write_triples(self.store.contexts(), operation_code)
95 elif target:
96 to_add, to_remove = self._diff(target)
97 write_triples(to_add.contexts(), "A", use_passed_contexts=True)
98 write_triples(to_remove.contexts(), "D", use_passed_contexts=True)
99
100 stream.write("TC .\n".encode(encoding, "replace"))
101
102 def _diff(self, target):
103 rows_to_add = target - self.store
104 rows_to_remove = self.store - target
105 return rows_to_add, rows_to_remove
106
107 def _patch_row(self, triple, context_id, operation):
108 if context_id == self.store.default_context.identifier:
109 return f"{operation} {_nt_row(triple)}"
110 else:
111 return f"{operation} {_nq_row(triple, context_id)}"