forked from terminusdb/terminusdb-client-python
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwoql_query.py
More file actions
4620 lines (4112 loc) · 157 KB
/
woql_query.py
File metadata and controls
4620 lines (4112 loc) · 157 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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import datetime as dt
import json
# import pprint
import re
import warnings
from .woql_core import _copy_dict, _path_tokenize, _path_tokens_to_json
UPDATE_OPERATORS = [
"AddTriple",
"DeleteTriple",
"AddQuad",
"DeleteQuad",
"DeleteObject",
"UpdateObject",
]
SHORT_NAME_MAPPING = {
"type": "rdf:type",
"label": "rdfs:label",
"Class": "owl:Class",
"DatatypeProperty": "owl:DatatypeProperty",
"ObjectProperty": "owl:ObjectProperty",
"Document": "terminus:Document",
"abstract": "terminus:Document",
"comment": "rdfs:comment",
"range": "rdfs:range",
"domain": "rdfs:domain",
"subClassOf": "rdfs:subClassOf",
"boolean": "xsd:boolean",
"string": "xsd:string",
"integer": "xsd:integer",
"decimal": "xsd:decimal",
"email": "xdd:email",
"json": "xdd:json",
"dateTime": "xsd:dateTime",
"date": "xsd:date",
"coordinate": "xdd:coordinate",
"line": "xdd:coordinatePolyline",
"polygon": "xdd:coordinatePolygon",
}
class Var:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
def to_dict(self):
return {"@type": "Value", "variable": self.name}
class Vars:
def __init__(self, *args):
for arg in args:
setattr(self, arg, Var(arg))
# Global counter for unique variable names
_unique_var_counter = 0
def _reset_unique_var_counter(value=0):
"""Reset the unique variable counter to a specific value.
Parameters
----------
value : int
The value to reset the counter to (default 0)
"""
global _unique_var_counter
_unique_var_counter = value
class VarsUnique:
"""Generate unique variable names to prevent variable name collisions.
Unlike Vars which uses the provided names directly, VarsUnique appends
a unique counter suffix to each variable name. This is useful for
library functions that need to avoid variable name collisions with
the calling context.
Example
-------
>>> v = VarsUnique('x', 'y', 'z')
>>> print(v.x.name) # 'x_1'
>>> print(v.y.name) # 'y_2'
>>> v2 = VarsUnique('x') # Different call
>>> print(v2.x.name) # 'x_3' (different from v.x)
"""
def __init__(self, *args):
global _unique_var_counter
for arg in args:
_unique_var_counter += 1
unique_name = f"{arg}_{_unique_var_counter}"
setattr(self, arg, Var(unique_name))
class Doc:
def __init__(self, dictionary):
self.dictionary = dictionary
self.encoded = self._convert(dictionary)
def __str__(self):
return str(self.dictionary)
def to_dict(self):
return self.encoded
def _convert(self, obj):
if type(obj) is str:
return {"@type": "Value", "data": {"@type": "xsd:string", "@value": obj}}
elif type(obj) is bool:
return {"@type": "Value", "data": {"@type": "xsd:boolean", "@value": obj}}
elif type(obj) is int:
return {"@type": "Value", "data": {"@type": "xsd:integer", "@value": obj}}
elif type(obj) is float:
return {"@type": "Value", "data": {"@type": "xsd:decimal", "@value": obj}}
elif obj is None:
return None
elif type(obj) is list:
ls = []
for elt in obj:
ls.append(self._convert(elt))
return {"@type": "Value", "list": ls}
elif isinstance(obj, Var):
return {"@type": "Value", "variable": obj.name}
elif type(obj) is dict:
keys = obj.keys()
pairs = []
for key in keys:
v = obj[key]
val = self._convert(v)
pairs.append({"@type": "FieldValuePair", "field": key, "value": val})
return {
"@type": "Value",
"dictionary": {"@type": "DictionaryTemplate", "data": pairs},
}
class WOQLQuery:
def __init__(self, query=None, graph="schema"):
"""defines the internal functions of the woql query object - the language API is defined in WOQLQuery
Parameters
----------
query: dict
json-ld query for initialisation
graph: str
graph that this query is appled to, default to be schema/main"""
if query:
self._query = query
else:
self._query = {}
self._cursor = self._query
self._chain_ended = False
self._contains_update = False
self._triple_builder_context = {}
self._vocab = SHORT_NAME_MAPPING
self._update_operators = UPDATE_OPERATORS
# alias
self.subsumption = self.sub
self.equals = self.eq
self.substring = self.substr
self.update = self.update_document # self.update_object
self.delete = self.delete_document # self.delete_object
self.read = self.read_document # self.read_object
self.insert = self.insert_document
self.optional = self.opt
self.idgenerator = self.idgen
self.concatenate = self.concat
self.typecast = self.cast
# attribute for schema
self._graph = graph
def __add__(self, other):
"""Creates a logical AND with the argument passed, for WOQLQueries.
Parameters
----------
other : WOQLQuery object
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
return WOQLQuery().woql_and(self, other)
def __and__(self, other):
"""Creates a logical AND with the argument passed, for WOQLQueries.
Parameters
----------
other : WOQLQuery object
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
return WOQLQuery().woql_and(self, other)
def __or__(self, other):
"""Creates a logical OR with the argument passed, for WOQLQueries.
Parameters
----------
other : WOQLQuery object
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
return WOQLQuery().woql_or(self, other)
def __invert__(self):
"""Creates a logical Not with the argument passed, for WOQLQueries.
Parameters
----------
other : WOQLQuery object
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
return WOQLQuery().woql_not(self)
def _add_sub_query(self, sub_query=None):
"""Internal library function which adds a subquery and sets the cursor"""
if sub_query:
self._cursor["query"] = self._coerce_to_dict(sub_query)
else:
initial_object = {}
self._cursor["query"] = initial_object
self._cursor = initial_object
return self
def _contains_update_check(self, json=None):
"""Does this query contain an update"""
if not json:
json = self._query
if not isinstance(json, dict):
return False
if json["@type"] in self._update_operators: # won't work
return True
if json.get("consequent") and self._contains_update_check(json["consequent"]):
return True
if json.get("query"):
return self._contains_update_check(json["query"])
if json.get("and"):
for item in json["and"]:
if self._contains_update_check(item):
return True
if json.get("or"):
for item in json["or"]:
if self._contains_update_check(item):
return True
return False
def _updated(self):
"""Called to inidicate that this query will cause an update to the DB"""
self._contains_update = True
return self
# A bunch of internal functions for formatting values for JSON-LD translation
def _jlt(self, val, val_type=None):
"""Wraps the passed value in a json-ld literal carriage"""
if not val_type:
val_type = "xsd:string"
elif ":" not in val_type:
val_type = "xsd:" + val_type
return {"@type": val_type, "@value": val}
def _varj(self, varb):
if isinstance(varb, Var):
return {"@type": "Value", "variable": varb.name}
if varb[:2] == "v:":
varb = varb[2:]
if type(varb) is str:
return {"@type": "Value", "variable": varb}
return varb
def _coerce_to_dict(self, qobj):
"""Transforms a object representation of a query into a dictionary object if needs be"""
if hasattr(qobj, "to_dict"):
return qobj.to_dict()
if qobj is True:
return {"@type": "True"}
return qobj
def _raw_var(self, varb):
if isinstance(varb, Var):
return varb.name
if varb[:2] == "v:":
return varb[2:]
return varb
def _raw_var_list(self, vl):
ret = []
for v in vl:
ret.append(self._raw_var(v))
return ret
def _data_list(self, wvar):
# TODO: orig is Nonetype
"""takes input that can be either a string (variable name)
or an array - each element of the array is a member of the list"""
if type(wvar) is str or isinstance(wvar, Var):
return self._expand_data_variable(wvar, True)
if type(wvar) is list:
ret = []
for item in wvar:
co_item = self._clean_data_value(item)
ret.append(co_item)
return {"@type": "DataValue", "list": ret}
def _value_list(self, wvar):
# TODO: orig is Nonetype
"""takes input that can be either a string (variable name)
or an array - each element of the array is a member of the list"""
if type(wvar) is str or isinstance(wvar, Var):
return self._expand_value_variable(wvar, True)
if type(wvar) is list:
ret = []
for item in wvar:
co_item = self._clean_object(item)
ret.append(co_item)
return ret
def _asv(self, colname_or_index, vname, obj_type=None):
"""Wraps the elements of an AS variable in the appropriate json-ld"""
asvar = {}
if type(colname_or_index) is int:
asvar["@type"] = "Column"
asvar["indicator"] = {"@type": "Indicator", "index": colname_or_index}
elif type(colname_or_index) is str:
asvar["@type"] = "Column"
asvar["indicator"] = {"@type": "Indicator", "name": colname_or_index}
if isinstance(vname, Var):
vname = vname.name
elif vname[:2] == "v:":
vname = vname[2:]
asvar["variable"] = vname
if obj_type:
asvar["type"] = obj_type
return asvar
def _wfrom(self, opts):
"""JSON LD Format Descriptor"""
if opts and opts.get("format"):
self._cursor["format"] = {
"@type": "Format",
"format_type": {"@value": opts["format"], "@type": "xsd:string"},
}
if opts.get("format_header"):
self._cursor["format"]["format_header"] = {
"@value": True,
"@type": "xsd:boolean",
}
return self
def _arop(self, arg):
"""Wraps arithmetic operators in the appropriate json-ld"""
if type(arg) is dict:
if hasattr(arg, "to_dict"):
return arg.to_dict()
else:
return arg
var = self._clean_arithmetic_value(arg, "xsd:decimal")
return var
def _vlist(self, target_list):
"""Wraps value lists in the appropriate json-ld"""
vl = []
for item in target_list:
v = self._expand_value_variable(item)
vl.append(v)
return vl
def _data_value_list(self, target_list):
"""DEPRECATED: Dead code - never called anywhere in the codebase.
Use _value_list() instead. This method will be removed in a future release.
"""
dvl = []
for item in target_list:
o = self._clean_data_value(item)
dvl.append(o)
return dvl
def _clean_subject(self, obj):
"""Transforms whatever is passed in as the subject into the appropriate json-ld for variable or id"""
subj = False
if type(obj) is dict:
return obj
elif type(obj) is str:
if ":" in obj:
subj = obj
elif self._vocab and (obj in self._vocab):
subj = self._vocab[obj]
else:
subj = obj
return self._expand_node_variable(subj)
elif isinstance(obj, Var):
return self._expand_node_variable(obj)
raise ValueError("Subject must be a URI string")
def _clean_predicate(self, obj):
"""Transforms whatever is passed in as the predicate (id or variable) into the appropriate json-ld form"""
pred = False
if type(obj) is dict:
return obj
elif type(obj) is str:
if ":" in obj:
pred = obj
elif self._vocab and (obj in self._vocab):
pred = self._vocab[obj]
else:
pred = obj
return self._expand_node_variable(pred)
elif isinstance(obj, Var):
return self._expand_node_variable(obj)
raise ValueError("Predicate must be a URI string")
def _clean_path_predicate(self, predicate=None):
pred = False
if predicate is not None:
if ":" in predicate:
pred = predicate
elif self._vocab and (predicate in self._vocab):
pred = self._vocab[predicate]
else:
pred = predicate
return pred
def _clean_object(self, user_obj, target=None):
"""Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)"""
obj = {"@type": "Value"}
if type(user_obj) is str:
if user_obj[:2] == "v:":
return self._expand_value_variable(user_obj)
else:
obj["node"] = user_obj
elif type(user_obj) is list:
elts = []
for item in user_obj:
elts.append(self._clean_object(item))
return elts
elif isinstance(user_obj, Var):
return self._expand_value_variable(user_obj)
elif isinstance(user_obj, Doc):
return user_obj.encoded
elif type(user_obj) is float:
if not target:
target = "xsd:decimal"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is int:
if not target:
target = "xsd:integer"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is bool:
if not target:
target = "xsd:boolean"
obj["data"] = self._jlt(user_obj, target)
elif isinstance(user_obj, dt.date):
if not target:
target = "xsd:dateTime"
obj["data"] = self._jlt(user_obj.isoformat(), target)
elif type(user_obj) is dict:
if "@value" in user_obj:
obj["data"] = user_obj
else:
return user_obj
else:
obj["data"] = self._jlt(str(user_obj))
return obj
def _clean_data_value(self, user_obj, target=None):
"""Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)"""
obj = {"@type": "DataValue"}
if type(user_obj) is str:
if user_obj[:2] == "v:":
return self._expand_data_variable(user_obj)
else:
if not target:
target = "xsd:string"
obj["data"] = self._jlt(user_obj, target)
elif isinstance(user_obj, Var):
return self._expand_data_variable(user_obj)
elif type(user_obj) is float:
if not target:
target = "xsd:decimal"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is int:
if not target:
target = "xsd:integer"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is bool:
if not target:
target = "xsd:boolean"
obj["data"] = self._jlt(user_obj, target)
elif isinstance(user_obj, dt.date):
if not target:
target = "xsd:dateTime"
obj["data"] = self._jlt(user_obj.isoformat(), target)
elif type(user_obj) is dict:
if "@value" in user_obj:
obj["data"] = user_obj
else:
return user_obj
else:
obj["data"] = self._jlt(str(user_obj))
return obj
def _clean_arithmetic_value(self, user_obj, target=None):
"""Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)"""
obj = {"@type": "ArithmeticValue"}
if type(user_obj) is str:
if user_obj[:2] == "v:":
return self._expand_arithmetic_variable(user_obj)
else:
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is float:
if not target:
target = "xsd:decimal"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is int:
if not target:
target = "xsd:integer"
obj["data"] = self._jlt(user_obj, target)
elif type(user_obj) is bool:
if not target:
target = "xsd:boolean"
obj["data"] = self._jlt(user_obj, target)
elif isinstance(user_obj, dt.date):
if not target:
target = "xsd:dateTime"
obj["data"] = self._jlt(user_obj.isoformat(), target)
elif type(user_obj) is dict:
if "@value" in user_obj:
obj["data"] = user_obj
else:
return user_obj
else:
obj["data"] = self._jlt(str(user_obj))
return obj
def _clean_node_value(self, user_obj, target=None):
"""Transforms whatever is passed in as the object of a triple into the appropriate json-ld form (variable, literal or id)"""
obj = {"@type": "NodeValue"}
if type(user_obj) is str:
if user_obj[:2] == "v:":
return self._expand_node_variable(user_obj)
else:
obj["node"] = user_obj
elif isinstance(user_obj, Var):
return self._expand_node_variable(user_obj)
elif type(user_obj) is dict:
return user_obj
else:
obj["node"] = user_obj
return obj
def _clean_graph(self, graph):
"""Transforms a graph filter by doing nothing"""
return graph
def _expand_variable(self, varname, target_type, always=False):
"""Transforms strings that start with v: into variable json-ld structures
Parameters
----------
varname : str
will be transformed if it starts with 'v:'
always : bool
if True it will be transformed no matter it starts with 'v:' or not. Default to be False
"""
if isinstance(varname, Var):
return {"@type": target_type, "variable": varname.name}
if varname[:2] == "v:" or always:
if varname[:2] == "v:":
varname = varname[2:]
return {"@type": target_type, "variable": varname}
else:
return {"@type": target_type, "node": varname}
def _expand_value_variable(self, varname, always=False):
return self._expand_variable(varname, "Value", always)
def _expand_node_variable(self, varname, always=False):
return self._expand_variable(varname, "NodeValue", always)
def _expand_data_variable(self, varname, always=False):
return self._expand_variable(varname, "DataValue", always)
def _expand_arithmetic_variable(self, varname, always=False):
return self._expand_variable(varname, "ArithmeticValue", always)
def execute(self, client, commit_msg=None, file_dict=None):
"""Executes the query using the passed client to connect to a server
Parameters
----------
client: Client object
client that provide connection to the database for the query to execute.
commit_msg: str
optional, commit message for this query. Recommended for query that carrries an update.
file_dict:
File dictionary to be associated with post name => filename, for multipart POST
"""
if commit_msg is None:
return client.query(self)
else:
return client.query(self, commit_msg)
def to_json(self):
"""Dumps the JSON-LD format of the query in a json string"""
return self._json()
def from_json(self, input_json):
"""Set a query from a JSON-LD json string"""
return self._json(input_json)
def _json(self, input_json=None):
"""converts back and forward from json
if the argument is present, the current query is set to it,
if the argument is not present, the current json version of this query is returned
"""
if input_json:
self.from_dict(json.loads(input_json))
return self
else:
return json.dumps(self.to_dict(), sort_keys=True)
def to_dict(self):
"""Give the dictionary that represents the query in JSON-LD format."""
return _copy_dict(self._query, True)
def from_dict(self, dictdata):
"""Set a query from a dictionary that represents the query in JSON-LD format."""
self._query = _copy_dict(dictdata)
return self
def _find_last_subject(self, json):
"""Finds the last woql element that has a subject in it and returns the json for that
used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries
Parameters
----------
json : dict
dictionary that representing the query in josn-ld"""
if "and" in json:
for item in json["and"][::-1]:
subitem = self._find_last_subject(item)
if subitem:
return subitem
if "or" in json:
for item in json["or"][::-1]:
subitem = self._find_last_subject(item)
if subitem:
return subitem
if "query" in json:
item = self._find_last_subject(json["query"])
if item:
return item
if "subject" in json:
return json
return False
def _find_last_property(self, json):
"""Finds the last woql property that has a subject in it and returns the json for that
used for triplebuilder to chain further calls - when they may be inside ands or ors or subqueries
Parameters
----------
json : dict
dictionary that representing the query in josn-ld"""
if "and" in json:
for item in json["and"][::-1]:
subitem = self._find_last_property(item)
if subitem:
return subitem
if "or" in json:
for item in json["or"][::-1]:
subitem = self._find_last_property(item)
if subitem:
return subitem
if "query" in json:
item = self._find_last_property(json["query"])
if item:
return item
if "subject" in json and self._is_property_triple(
json.get("predicate"), json.get("object")
):
return json
return False
def _is_property_triple(self, pred, obj):
if isinstance(pred, dict):
p = pred.get("node")
else:
p = pred
if isinstance(obj, dict):
o = obj.get("node")
else:
o = obj
if o == "owl:ObjectProperty" or o == "owl:DatatypeProperty":
return True
if p == "rdfs:domain" or p == "rdfs:range":
return True
return False
def _compile_path_pattern(self, pat):
"""Turns a textual path pattern into a JSON-LD description"""
toks = _path_tokenize(pat)
if toks:
return _path_tokens_to_json(toks)
else:
raise ValueError("Pattern error - could not be parsed " + pat)
def load_vocabulary(self, client):
"""Queries the schema graph and loads all the ids found there as vocabulary that can be used without prefixes
ignoring blank node ids"""
new_woql = WOQLQuery().quad("v:S", "v:P", "v:O", "schema")
result = new_woql.execute(client)
bindings = result.get("bindings", [])
for each_result in bindings:
for item in each_result:
if type(item) is str:
spl = item.split(":")
if len(spl) == 2 and spl[1] and spl[0] != "_":
self._vocab[spl[0]] = spl[1]
def _wrap_cursor_with_and(self):
if self._cursor.get("@type") == "And" and self._cursor.get("and"):
next_item = len(self._cursor.get("and"))
self.woql_and({})
self._cursor = self._cursor["and"][next_item]
else:
new_json = WOQLQuery().from_dict(self._cursor)
self._cursor.clear()
self.woql_and(new_json, {})
self._cursor = self._cursor["and"][1]
def using(self, collection, subq=None):
"""Use a specific data product for the enclosed query
Parameters
----------
collection : str
the name of the data product
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
if collection and collection == "args":
return ["collection", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Using"
if not collection or not isinstance(collection, str):
raise ValueError(
"The first parameter to using must be a Collection ID (string)"
)
self._cursor["collection"] = collection
return self._add_sub_query(subq)
def comment(self, comment, subq=None):
"""Adds a text comment to a query - can also be used to wrap any part of a query to turn it off
Parameters
----------
comment : str
text comment
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
if comment and comment == "args":
return ["comment", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Comment"
self._cursor["comment"] = self._jlt(comment)
return self._add_sub_query(subq)
def select(self, *args):
"""Filters the query so that only the variables included in [V1...Vn] are returned in the bindings
Parameters
----------
args
only these variables are returned
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
"""Select the set of variables that the result will return"""
queries = list(args)
if queries and queries[0] == "args":
return ["variables", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Select"
if queries != [] and not queries:
raise ValueError("Select must be given a list of variable names")
if queries == []:
embedquery = False
elif hasattr(queries[-1], "to_dict"):
embedquery = queries.pop()
else:
embedquery = False
self._cursor["variables"] = self._raw_var_list(queries)
return self._add_sub_query(embedquery)
def distinct(self, *args):
"""Ensures that the solutions for the variables [V1...Vn] are distinct
Parameters
----------
args
The variables to make distinct with the final argument being a query.
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
Example
-------
To load a local csv file:
>>> x,y = WOQLQUery().vars("X","Y")
>>> WOQLQuery().distinct(x).triple(x,'foo',y)
See Also
"""
"""Select the set of variables that the result will return"""
queries = list(args)
if queries and queries[0] == "args":
return ["variables", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Distinct"
if queries != [] and not queries:
raise ValueError("Distinct must be given a list of variable names")
if queries == []:
embedquery = False
elif hasattr(queries[-1], "to_dict"):
embedquery = queries.pop()
else:
embedquery = False
self._cursor["variables"] = self._raw_var_list(queries)
return self._add_sub_query(embedquery)
def woql_and(self, *args):
"""Creates a logical AND of the arguments
Commonly used to combine WOQLQueries.
Parameters
----------
args : WOQLQuery objects
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
queries = list(args)
if self._cursor.get("@type") and self._cursor["@type"] != "And":
new_json = WOQLQuery().from_dict(self._cursor)
self._cursor.clear()
queries = [new_json] + queries
if queries and queries[0] == "args":
return ["and"]
self._cursor["@type"] = "And"
if "and" not in self._cursor:
self._cursor["and"] = []
for item in queries:
onevar = self._coerce_to_dict(item)
if "@type" in onevar and onevar["@type"] == "And" and onevar["and"]:
for each in onevar["and"]:
if each:
subvar = self._coerce_to_dict(each)
self._cursor["and"].append(subvar)
else:
self._cursor["and"].append(onevar)
return self
def woql_or(self, *args):
"""Creates a logical OR of the arguments
Parameters
----------
args : WOQLQuery objects
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
queries = list(args)
if queries and queries[0] == "args":
return ["or"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Or"
if "or" not in self._cursor:
self._cursor["or"] = []
for item in queries:
onevar = self._coerce_to_dict(item)
self._cursor["or"].append(onevar)
return self
def woql_from(self, graph, query=None):
"""Specifies the database URL that will be the default database for the enclosed query
Parameters
----------
graph : str
url of the database
query : WOQLQuery object, optional
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
if graph and graph == "args":
return ["graph", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "From"
if not graph or not isinstance(graph, str):
raise ValueError(
"The first parameter to from must be a Graph Filter Expression (string)"
)
self._cursor["graph"] = graph
return self._add_sub_query(query)
def into(self, graph_descriptor, query):
"""Sets the current output graph for writing output to.
Parameters
----------
graph_descriptor : str
output graph
query : WOQLQuery object, optional
Returns
-------
WOQLQuery object
query object that can be chained and/or execute
"""
if graph_descriptor and graph_descriptor == "args":
return ["graph", "query"]
if self._cursor.get("@type"):
self._wrap_cursor_with_and()
self._cursor["@type"] = "Into"
if not graph_descriptor or not isinstance(graph_descriptor, str):
raise ValueError(
"The first parameter to from must be a Graph Filter Expression (string)"
)
self._cursor["graph"] = graph_descriptor
return self._add_sub_query(query)
def triple(self, sub, pred, obj, opt=False):
"""Creates a triple pattern matching rule for the triple [S, P, O] (Subject, Predicate, Object)
Parameters
----------
sub : str
Subject, has to be a node (URI)
pred : str
Predicate, can be variable (prefix with "v:") or node
obj : str
Object, can be variable or node or value
opt : bool
whether or not this triple is optional, default to be False
Returns
-------
WOQLQuery object
query object that can be chained and/or execute