changeset 101:05492457f04b

new Patch ctor and error type
author drewp@bigasterisk.com
date Mon, 30 May 2022 20:32:08 -0700
parents 27dcc13f9958
children 0f921dd06887
files rdfdb/patch.py
diffstat 1 files changed, 13 insertions(+), 3 deletions(-) [+]
line wrap: on
line diff
--- a/rdfdb/patch.py	Mon May 30 20:31:15 2022 -0700
+++ b/rdfdb/patch.py	Mon May 30 20:32:08 2022 -0700
@@ -1,5 +1,5 @@
 import json
-from typing import Optional
+from typing import Iterable, Optional, Tuple
 
 from rdflib import ConjunctiveGraph, Graph, Literal, Namespace, URIRef
 
@@ -9,6 +9,10 @@
 
 ALLSTMTS = (None, None, None)
 
+class EmptyPatch(ValueError):
+    pass
+
+
 
 def quadsWithContextUris(quads):
     """
@@ -78,6 +82,12 @@
         new = set(quadsWithContextUris(newGraph))
         return cls(addQuads=list(new - old), delQuads=list(old - new))
 
+    @classmethod
+    def fromTriplesDiff(cls, prev: Iterable[Tuple], new: Iterable[Tuple], ctx: URIRef):
+        adds = set((s, p, o, ctx) for s, p, o in new)
+        prevSet = set((s, p, o, ctx) for s, p, o in prev)
+        return cls.fromDiff(prevSet, adds)
+
     def __bool__(self):
         """
         does this patch do anything to a graph?
@@ -169,14 +179,14 @@
     def getContext(self):
         """assumes that all the edits are on the same context"""
         ctx = None
-        for q in self.addQuads + self.delQuads:
+        for q in set(self.addQuads).union(self.delQuads):
             if ctx is None:
                 ctx = q[3]
 
             if ctx != q[3]:
                 raise ValueError("patch applies to multiple contexts, at least %r and %r" % (ctx, q[3]))
         if ctx is None:
-            raise ValueError("patch affects no contexts")
+            raise EmptyPatch()
         assert isinstance(ctx, URIRef), ctx
         return ctx