-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathupdate.py
More file actions
436 lines (342 loc) 路 11.8 KB
/
Copy pathupdate.py
File metadata and controls
436 lines (342 loc) 路 11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
"""
Code for carrying out Update Operations
"""
import functools
from rdflib import Graph, Variable, URIRef
from rdflib.term import Node
from rdflib.plugins.sparql.sparql import QueryContext
from rdflib.plugins.sparql.evalutils import _fillTemplate, _join
from rdflib.plugins.sparql.evaluate import evalBGP, evalPart
from collections import defaultdict
from itertools import tee
from quit.exceptions import UnSupportedQuery
def _append(dct, identifier, action, items):
if items:
if not isinstance(identifier, Node):
identifier = URIRef(identifier)
changes = dct.get(identifier, [])
changes.append((action, items))
dct[identifier] = changes
def _graphOrDefault(ctx, g):
if g == 'DEFAULT':
return ctx.graph
else:
return ctx.dataset.get_context(g)
def _graphAll(ctx, g):
"""
return a list of graphs
"""
if g == 'DEFAULT':
return [ctx.graph]
elif g == 'NAMED':
return [c for c in ctx.dataset.contexts()
if c.identifier != ctx.graph.identifier]
elif g == 'ALL':
return list(ctx.dataset.contexts())
else:
return [ctx.dataset.get_context(g)]
def evalLoad(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#load
"""
res = {}
res["type"] = "LOAD"
res["source"] = u.iri
res["delta"] = {}
if not u.graphiri:
raise UnSupportedQuery("For load queries we need a iriref for a target graph")
success = False
loadedGraph = None
exceptions = []
formats = [None, 'n3', 'nt', 'turtle']
for format in formats:
loadedGraph = Graph()
try:
if not format:
loadedGraph.load(u.iri)
else:
loadedGraph.load(u.iri, format=format)
success = True
break
except Exception as e:
pass
if not success:
raise Exception(
"Could not load %s as either RDF/XML, N3, Turtle, or NTriples" % (
u.iri))
graph = ctx.dataset.get_context(u.graphiri)
graph += loadedGraph
_append(res["delta"], u.graphiri, 'additions', loadedGraph)
return res
def evalCreate(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#create
"""
g = ctx.datset.get_context(u.graphiri)
if len(g) > 0:
raise Exception("Graph %s already exists." % g.identifier)
raise Exception("Create not implemented!")
def evalClear(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#clear
"""
for g in _graphAll(ctx, u.graphiri):
g.remove((None, None, None))
def evalDrop(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#drop
"""
res = {}
res["type"] = "DROP"
res["delta"] = {}
if ctx.dataset.store.graph_aware:
for g in _graphAll(ctx, u.graphiri):
_append(res["delta"], u.graphiri, 'removals', g)
ctx.dataset.store.remove_graph(g)
graph = ctx.dataset.get_context(u.graphiri)
graph -= g
else:
_append(res["delta"], u.graphiri, 'removals', list(u.triples))
evalClear(ctx, u)
return res
def evalInsertData(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#insertData
"""
res = {}
res["type"] = "INSERT"
res["delta"] = {}
# add triples
g = ctx.graph
filled = list(filter(lambda triple: triple not in g, u.triples))
if filled:
_append(res["delta"], 'default', 'additions', filled)
g += filled
# add quads
# u.quads is a dict of graphURI=>[triples]
for g in u.quads:
cg = ctx.dataset.get_context(g)
filledq = list(filter(lambda triple: triple not in cg, u.quads[g]))
if filledq:
_append(res["delta"], cg.identifier, 'additions', filledq)
cg += filledq
return res
def evalDeleteData(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#deleteData
"""
res = {}
res["type"] = "DELETE"
res["delta"] = {}
# remove triples
g = ctx.graph
filled = list(filter(lambda triple: triple in g, u.triples))
if filled:
_append(res["delta"], 'default', 'removals', filled)
g -= filled
# remove quads
# u.quads is a dict of graphURI=>[triples]
for g in u.quads:
cg = ctx.dataset.get_context(g)
filledq = list(filter(lambda triple: triple in cg, u.quads[g]))
if filledq:
_append(res["delta"], cg.identifier, 'removals', filledq)
cg -= filledq
return res
def evalDeleteWhere(ctx, u):
"""
http://www.w3.org/TR/sparql11-update/#deleteWhere
"""
res = {}
res["type"] = "DELETEWHERE"
res["delta"] = {}
_res = evalBGP(ctx, u.triples)
for g in u.quads:
cg = ctx.dataset.get_context(g)
c = ctx.pushGraph(cg)
_res = _join(_res, list(evalBGP(c, u.quads[g])))
for c in _res:
g = ctx.graph
filled, filled_delta = tee(_fillTemplate(u.triples, c))
_append(res["delta"], 'default', 'removals', list(filled_delta))
g -= filled
for g in u.quads:
cg = ctx.dataset.get_context(c.get(g))
filledq, filledq_delta = tee(_fillTemplate(u.quads[g], c))
_append(res["delta"], cg.identifier, 'removals', list(filledq_delta))
cg -= filledq
return res
def evalModify(ctx, u):
originalctx = ctx
res = {}
res["type"] = "MODIFY"
res["delta"] = {}
# Using replaces the dataset for evaluating the where-clause
if u.using:
otherDefault = False
for d in u.using:
if d.default:
if not otherDefault:
# replace current default graph
dg = Graph()
ctx = ctx.pushGraph(dg)
otherDefault = True
ctx.load(d.default, default=True)
# TODO re-enable original behaviour if USING NAMED works with named graphs
# https://github.com/AKSW/QuitStore/issues/144
elif d.named:
if otherDefault:
ctx = originalctx # restore original default graph
raise UnSupportedQuery
# g = d.named
# ctx.load(g, default=False)
# "The WITH clause provides a convenience for when an operation
# primarily refers to a single graph. If a graph name is specified
# in a WITH clause, then - for the purposes of evaluating the
# WHERE clause - this will define an RDF Dataset containing a
# default graph with the specified name, but only in the absence
# of USING or USING NAMED clauses. In the presence of one or more
# graphs referred to in USING clauses and/or USING NAMED clauses,
# the WITH clause will be ignored while evaluating the WHERE
# clause."
graphName = 'default'
if not u.using and u.withClause:
g = ctx.dataset.get_context(u.withClause)
graphName = str(g.identifier)
ctx = ctx.pushGraph(g)
_res = evalPart(ctx, u.where)
if u.using:
if otherDefault:
ctx = originalctx # restore original default graph
if u.withClause:
g = ctx.dataset.get_context(u.withClause)
graphName = str(g.identifier)
ctx = ctx.pushGraph(g)
for c in _res:
dg = ctx.graph
if u.delete:
filled, filled_delta = tee(_fillTemplate(u.delete.triples, c))
_append(res["delta"], graphName, 'removals', list(filled_delta))
dg -= filled
for g, q in u.delete.quads.items():
cg = ctx.dataset.get_context(c.get(g))
filledq, filledq_delta = tee(_fillTemplate(q, c))
_append(res["delta"], cg.identifier, 'removals', list(filledq_delta))
cg -= filledq
if u.insert:
filled, filled_delta = tee(_fillTemplate(u.insert.triples, c))
_append(res["delta"], graphName, 'additions', list(filled_delta))
dg += filled
for g, q in u.insert.quads.items():
cg = ctx.dataset.get_context(c.get(g))
filledq, filledq_delta = tee(_fillTemplate(q, c))
_append(res["delta"], cg.identifier, 'additions', list(filledq_delta))
cg += filledq
return res
def evalAdd(ctx, u):
"""
add all triples from src to dst
http://www.w3.org/TR/sparql11-update/#add
"""
src, dst = u.graph
srcg = _graphOrDefault(ctx, src)
dstg = _graphOrDefault(ctx, dst)
if srcg.identifier == dstg.identifier:
return
dstg += srcg
def evalMove(ctx, u):
"""
remove all triples from dst
add all triples from src to dst
remove all triples from src
http://www.w3.org/TR/sparql11-update/#move
"""
src, dst = u.graph
srcg = _graphOrDefault(ctx, src)
dstg = _graphOrDefault(ctx, dst)
if srcg.identifier == dstg.identifier:
return
dstg.remove((None, None, None))
dstg += srcg
if ctx.dataset.store.graph_aware:
ctx.dataset.store.remove_graph(srcg)
else:
srcg.remove((None, None, None))
def evalCopy(ctx, u):
"""
remove all triples from dst
add all triples from src to dst
http://www.w3.org/TR/sparql11-update/#copy
"""
src, dst = u.graph
srcg = _graphOrDefault(ctx, src)
dstg = _graphOrDefault(ctx, dst)
if srcg.identifier == dstg.identifier:
return
dstg.remove((None, None, None))
dstg += srcg
def evalUpdate(graph, update, initBindings=None, actionLog=False):
"""
http://www.w3.org/TR/sparql11-update/#updateLanguage
'A request is a sequence of operations [...] Implementations MUST
ensure that operations of a single request are executed in a
fashion that guarantees the same effects as executing them in
lexical order.
Operations all result either in success or failure.
If multiple operations are present in a single request, then a
result of failure from any operation MUST abort the sequence of
operations, causing the subsequent operations to be ignored.'
This will return None on success and raise Exceptions on error
"""
res = []
for u in update:
ctx = QueryContext(graph)
ctx.prologue = u.prologue
if initBindings:
for k, v in initBindings.items():
if not isinstance(k, Variable):
k = Variable(k)
ctx[k] = v
try:
if u.name == 'Load':
result = evalLoad(ctx, u)
if result:
res.append(result)
elif u.name == 'Clear':
evalClear(ctx, u)
elif u.name == 'Drop':
result = evalDrop(ctx, u)
if result:
res.append(result)
elif u.name == 'Create':
evalCreate(ctx, u)
elif u.name == 'Add':
evalAdd(ctx, u)
elif u.name == 'Move':
evalMove(ctx, u)
elif u.name == 'Copy':
evalCopy(ctx, u)
elif u.name == 'InsertData':
result = evalInsertData(ctx, u)
if result:
res.append(result)
elif u.name == 'DeleteData':
result = evalDeleteData(ctx, u)
if result:
res.append(result)
elif u.name == 'DeleteWhere':
result = evalDeleteWhere(ctx, u)
if result:
res.append(result)
elif u.name == 'Modify':
result = evalModify(ctx, u)
if result:
res.append(result)
else:
raise Exception('Unknown update operation: %s' % (u,))
except UnSupportedQuery as e:
return res, e
except Exception:
if not u.silent:
raise
return res, None