src/rdflib/plugins/stores/regexmatching.py
1"""
2This wrapper intercepts calls through the store interface which make use of
3the REGEXTerm class to represent matches by REGEX instead of literal
4comparison.
5
6Implemented for stores that don't support this and essentially
7provides the support by replacing the REGEXTerms by wildcards (None) and
8matching against the results from the store it's wrapping.
9"""
10
11import re
12
13from rdflib.graph import Graph
14from rdflib.store import Store
15
16# Store is capable of doing its own REGEX matching
17NATIVE_REGEX = 0
18# Store uses Python's re module internally for REGEX matching
19PYTHON_REGEX = 1
20
21
22class REGEXTerm(str):
23 """
24 REGEXTerm can be used in any term slot and is interpreted as a request to
25 perform a REGEX match (not a string comparison) using the value
26 (pre-compiled) for checking rdf:type matches
27 """
28
29 def __init__(self, expr):
30 self.compiledExpr = re.compile(expr)
31
32 def __reduce__(self):
33 return (REGEXTerm, ("",))
34
35
36def regexCompareQuad(quad, regexQuad): # noqa: N802, N803
37 for index in range(4):
38 if isinstance(regexQuad[index], REGEXTerm) and not regexQuad[
39 index
40 ].compiledExpr.match(quad[index]):
41 return False
42 return True
43
44
45class REGEXMatching(Store):
46 def __init__(self, storage):
47 self.storage = storage
48 self.context_aware = storage.context_aware
49 # NOTE: this store can't be formula_aware as it doesn't have enough
50 # info to reverse the removal of a quoted statement.
51 self.formula_aware = storage.formula_aware
52 self.transaction_aware = storage.transaction_aware
53
54 def open(self, configuration, create=True):
55 return self.storage.open(configuration, create)
56
57 def close(self, commit_pending_transaction=False):
58 self.storage.close()
59
60 def destroy(self, configuration):
61 self.storage.destroy(configuration)
62
63 def add(self, triple, context, quoted=False):
64 (subject, predicate, object_) = triple
65 self.storage.add((subject, predicate, object_), context, quoted)
66
67 def remove(self, triple, context=None):
68 (subject, predicate, object_) = triple
69 if (
70 isinstance(subject, REGEXTerm)
71 or isinstance(predicate, REGEXTerm)
72 or isinstance(object_, REGEXTerm)
73 or (context is not None and isinstance(context.identifier, REGEXTerm))
74 ):
75 # One or more of the terms is a REGEX expression, so we must
76 # replace it / them with wildcard(s)and match after we query.
77 s = not isinstance(subject, REGEXTerm) and subject or None
78 p = not isinstance(predicate, REGEXTerm) and predicate or None
79 o = not isinstance(object_, REGEXTerm) and object_ or None
80 c = (
81 (context is not None and not isinstance(context.identifier, REGEXTerm))
82 and context
83 or None
84 )
85
86 removeQuadList = [] # noqa: N806
87 for (s1, p1, o1), cg in self.storage.triples((s, p, o), c):
88 for ctx in cg:
89 ctx = ctx.identifier
90 if regexCompareQuad(
91 (s1, p1, o1, ctx),
92 (
93 subject,
94 predicate,
95 object_,
96 context is not None and context.identifier or context,
97 ),
98 ):
99 removeQuadList.append((s1, p1, o1, ctx))
100 for s, p, o, c in removeQuadList:
101 self.storage.remove((s, p, o), c and Graph(self, c) or c)
102 else:
103 self.storage.remove((subject, predicate, object_), context)
104
105 def triples(self, triple, context=None):
106 (subject, predicate, object_) = triple
107 if (
108 isinstance(subject, REGEXTerm)
109 or isinstance(predicate, REGEXTerm)
110 or isinstance(object_, REGEXTerm)
111 or (context is not None and isinstance(context.identifier, REGEXTerm))
112 ):
113 # One or more of the terms is a REGEX expression, so we must
114 # replace it / them with wildcard(s) and match after we query.
115 s = not isinstance(subject, REGEXTerm) and subject or None
116 p = not isinstance(predicate, REGEXTerm) and predicate or None
117 o = not isinstance(object_, REGEXTerm) and object_ or None
118 c = (
119 (context is not None and not isinstance(context.identifier, REGEXTerm))
120 and context
121 or None
122 )
123 for (s1, p1, o1), cg in self.storage.triples((s, p, o), c):
124 matchingCtxs = [] # noqa: N806
125 for ctx in cg:
126 if c is None:
127 if context is None or context.identifier.compiledExpr.match(
128 ctx.identifier
129 ):
130 matchingCtxs.append(ctx)
131 else:
132 matchingCtxs.append(ctx)
133 if matchingCtxs and regexCompareQuad(
134 (s1, p1, o1, None), (subject, predicate, object_, None)
135 ):
136 yield (s1, p1, o1), (c for c in matchingCtxs)
137 else:
138 for (s1, p1, o1), cg in self.storage.triples(
139 (subject, predicate, object_), context
140 ):
141 yield (s1, p1, o1), cg
142
143 def __len__(self, context=None):
144 # NOTE: If the context is a REGEX this could be an expensive
145 # proposition
146 return self.storage.__len__(context)
147
148 def contexts(self, triple=None):
149 # NOTE: There is no way to control REGEX matching for this method at
150 # this level as it only returns the contexts, not the matching
151 # triples.
152 for ctx in self.storage.contexts(triple):
153 yield ctx
154
155 def remove_context(self, identifier):
156 self.storage.remove((None, None, None), identifier)
157
158 def bind(self, prefix, namespace, override=True):
159 self.storage.bind(prefix, namespace, override=override)
160
161 def prefix(self, namespace):
162 return self.storage.prefix(namespace)
163
164 def namespace(self, prefix):
165 return self.storage.namespace(prefix)
166
167 def namespaces(self):
168 return self.storage.namespaces()
169
170 def commit(self):
171 self.storage.commit()
172
173 def rollback(self):
174 self.storage.rollback()