-
Notifications
You must be signed in to change notification settings - Fork 24
/
triplelite.py
1954 lines (1645 loc) · 90.4 KB
/
triplelite.py
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
# -*- coding: utf-8 -*-
# Owlready2
# Copyright (C) 2017-2019 Jean-Baptiste LAMY
# LIMICS (Laboratoire d'informatique médicale et d'ingénierie des connaissances en santé), UMR_S 1142
# University Paris 13, Sorbonne paris-Cité, Bobigny, France
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
# You should have received a copy of the GNU Lesser General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys, os, os.path, sqlite3, time, re, threading
from collections import defaultdict
from itertools import chain
import owlready2
from owlready2.base import *
from owlready2.driver import BaseMainGraph, BaseSubGraph
from owlready2.driver import _guess_format, _save
from owlready2.util import FTS, _LazyListMixin
from owlready2.base import _universal_abbrev_2_iri
def all_combinations(l):
"""returns all the combinations of the sublist in the given list (i.e. l[0] x l[1] x ... x l[n])."""
if len(l) == 0: return ()
if len(l) == 1: return [(a,) for a in l[0]]
r = []
for a in l[0]: r.extend((a,) + b for b in all_combinations(l[1:]))
return r
# def group_iters(quad_cursor, data_cursor):
# s = None
# quad = next(quad_cursor, None)
# data = next(data_cursor, None)
# while quad or data:
# if quad and data:
# if quad[0] < data[0]: s = quad[0]
# else: s = data[0]
# elif quad: s = quad[0]
# else: s = data[0]
# while quad:
# if quad[0] != s: break
# yield quad
# quad = next(quad_cursor, None)
# while data:
# if data[0] != s: break
# yield data
# data = next(data_cursor, None)
class Graph(BaseMainGraph):
_SUPPORT_CLONING = True
def __init__(self, filename, clone = None, exclusive = True, sqlite_tmp_dir = "", world = None, profiling = False):
exists = os.path.exists(filename) and os.path.getsize(filename) # BEFORE creating db!
initialize_db = (clone is None) and ((filename == ":memory:") or (not exists))
if clone and (filename != ":memory:"):
if exists: raise ValueError("Cannot save existent quadstore in '%s': File already exists! Use a new filename for saving quadstore or, for opening an already existent quadstore, do not create any triple before calling set_backend()." % filename)
if sqlite_tmp_dir: os.environ["SQLITE_TMPDIR"] = sqlite_tmp_dir
if exclusive:
self.db = sqlite3.connect(filename, isolation_level = "EXCLUSIVE", check_same_thread = False)
self.db.execute("""PRAGMA locking_mode = EXCLUSIVE""")
else:
self.db = sqlite3.connect(filename, check_same_thread = False)
self.db.execute("""PRAGMA locking_mode = NORMAL""")
if sqlite_tmp_dir:
try: self.db.execute("""PRAGMA temp_store_directory = '%s'""" % sqlite_tmp_dir)
except: pass # Deprecated PRAGMA
if profiling:
import time
from collections import Counter
self.requests_counts = Counter()
self.requests_times = Counter()
def execute(s, args = ()):
if "SELECT" in s:
self.requests_counts[s] += 1
t0 = time.time()
r = list(self.db.execute(s, args))
t = time.time() - t0
self.requests_times[s] += t
return self.db.execute(s, args)
self.execute = execute
def reset_profiling():
self.requests_counts = Counter()
self.requests_times = Counter()
self.reset_profiling = reset_profiling
def show_profiling():
print(file = sys.stderr)
print("Request counts:", file = sys.stderr)
for s, nb in self.requests_counts.most_common():
print(" ", nb, "\t", s.replace("\n", " "), file = sys.stderr)
print(file = sys.stderr)
print("Request total times:", file = sys.stderr)
for s, nb in self.requests_times.most_common():
print(" ", nb, "\t", s.replace("\n", " "), file = sys.stderr)
print(file = sys.stderr)
print("Request mean times:", file = sys.stderr)
rmt = Counter()
for s, nb in self.requests_counts.most_common():
rmt[s] = self.requests_times[s] / nb
for s, nb in rmt.most_common():
print(" ", nb, "\t", s.replace("\n", " "), file = sys.stderr)
self.show_profiling = show_profiling
else:
self.execute = self.db.execute
self.c_2_onto = {}
self.onto_2_subgraph = {}
self.last_numbered_iri = {}
self.world = world
self.c = None
self.lock = threading.RLock()
self.lock_level = 0
if initialize_db:
self.current_blank = 0
self.current_resource = 300 # 300 first values are reserved
self.prop_fts = set()
self.execute("""CREATE TABLE store (version INTEGER, current_blank INTEGER, current_resource INTEGER)""")
self.execute("""INSERT INTO store VALUES (8, 0, 300)""")
self.execute("""CREATE TABLE objs (c INTEGER, s INTEGER, p INTEGER, o INTEGER)""")
self.execute("""CREATE TABLE datas (c INTEGER, s INTEGER, p INTEGER, o BLOB, d INTEGER)""")
#self.execute("""CREATE VIEW quads (c,s,p,o,d) AS SELECT c,s,p,o,NULL FROM objs UNION ALL SELECT c,s,p,o,d FROM datas""")
self.execute("""CREATE VIEW quads AS SELECT c,s,p,o,NULL AS d FROM objs UNION ALL SELECT c,s,p,o,d FROM datas""")
# self.execute("""CREATE TABLE equivs (rowid INTEGER, c INTEGER, s TEXT, o TEXT)""")
# self.db.cursor().executescript("""
# CREATE TRIGGER equivs_insert AFTER INSERT ON objs WHEN new.p='x' BEGIN
# INSERT INTO equivs VALUES (new.rowid * 2, new.c, new.s, new.o), (new.rowid * 2 + 1, new.c, new.o, new.s);
# END;
# CREATE TRIGGER equivs_delete AFTER DELETE ON objs WHEN old.p='x' BEGIN
# DELETE FROM equivs WHERE rowid IN (old.rowid * 2, old.rowid * 2 + 1);
# END;
# CREATE TRIGGER equivs_update AFTER UPDATE ON objs WHEN new.p='%s' BEGIN
# UPDATE equivs SET s=new.s, o=new.o WHERE rowid = new.rowid * 2;
# UPDATE equivs SET s=new.o, o=new.s WHERE rowid = new.rowid * 2;
# END;
# """)
# self.execute("""CREATE INDEX index_equivs_s ON equivs(s)""")
# """
# INSERT INTO equivs VALUES SELECT c,s,o FROM objs WHERE p='x';
# INSERT INTO equivs VALUES SELECT c,o,s FROM objs WHERE p='x';
# """
self.execute("""CREATE TABLE ontologies (c INTEGER PRIMARY KEY, iri TEXT, last_update DOUBLE)""")
self.execute("""CREATE TABLE ontology_alias (iri TEXT, alias TEXT)""")
self.execute("""CREATE TABLE prop_fts (storid INTEGER)""")
try:
self.execute("""CREATE TABLE resources (storid INTEGER PRIMARY KEY, iri TEXT) WITHOUT ROWID""")
except sqlite3.OperationalError: # Old SQLite3 does not support WITHOUT ROWID -- here it is just an optimization
self.execute("""CREATE TABLE resources (storid INTEGER PRIMARY KEY, iri TEXT)""")
self.db.executemany("INSERT INTO resources VALUES (?,?)", _universal_abbrev_2_iri.items())
self.execute("""CREATE UNIQUE INDEX index_resources_iri ON resources(iri)""")
#self.set_indexed(True)
self.execute("""CREATE INDEX index_objs_sp ON objs(s,p)""")
#self.execute("""CREATE INDEX index_objs_op ON objs(o,p,c)""") # c is for onto.classes(), etc
self.execute("""CREATE UNIQUE INDEX index_objs_op ON objs(o,p,c,s)""") # c is for onto.classes(), etc
self.execute("""CREATE INDEX index_datas_sp ON datas(s,p)""")
#self.execute("""CREATE INDEX index_datas_op ON datas(o,p)""")
self.execute("""CREATE UNIQUE INDEX index_datas_op ON datas(o,p,c,d,s)""")
self.indexed = True
self.db.commit()
else:
self.indexed = True
if clone:
s = "\n".join(clone.db.iterdump())
self.db.cursor().executescript(s)
version, self.current_blank, self.current_resource = self.execute("SELECT version, current_blank, current_resource FROM store").fetchone()
self.current_resource = self.execute("SELECT MAX(storid) FROM resources").fetchone()[0]
if clone:
self.current_blank = clone.current_blank
self.current_resource = clone.current_resource
if version == 1:
print("* Owlready2 * Converting quadstore to internal format 2...", file = sys.stderr)
self.execute("""CREATE TABLE ontology_alias (iri TEXT, alias TEXT)""")
self.execute("""UPDATE store SET version=2""")
self.db.commit()
if version == 2:
print("* Owlready2 * Converting quadstore to internal format 3...", file = sys.stderr)
self.execute("""CREATE TABLE prop_fts (fts INTEGER PRIMARY KEY, storid TEXT)""")
self.execute("""UPDATE store SET version=3""")
self.db.commit()
if version == 3:
print("* Owlready2 * Converting quadstore to internal format 4 (this can take a while)...", file = sys.stderr)
self.execute("""CREATE TABLE objs (c INTEGER, s TEXT, p TEXT, o TEXT)""")
self.execute("""CREATE TABLE datas (c INTEGER, s TEXT, p TEXT, o BLOB, d TEXT)""")
objs = []
datas = []
for c,s,p,o in self.execute("""SELECT c,s,p,o FROM quads"""):
if o.endswith('"'):
o, d = o.rsplit('"', 1)
o = o[1:]
if d in {'H', 'N', 'R', 'O', 'J', 'I', 'M', 'P', 'K', 'Q', 'S', 'L'}: o = int(o)
elif d in {'U', 'X', 'V', 'W'}: o = float(o)
datas.append((c,s,p,o,d))
else:
objs.append((c,s,p,o))
self.db.executemany("INSERT INTO objs VALUES (?,?,?,?)", objs)
self.db.executemany("INSERT INTO datas VALUES (?,?,?,?,?)", datas)
self.execute("""DROP TABLE quads""")
self.execute("""DROP INDEX IF EXISTS index_quads_s """)
self.execute("""DROP INDEX IF EXISTS index_quads_o""")
self.execute("""CREATE VIEW quads AS SELECT c,s,p,o,NULL AS d FROM objs UNION ALL SELECT c,s,p,o,d FROM datas""")
self.execute("""CREATE INDEX index_objs_sp ON objs(s,p)""")
self.execute("""CREATE INDEX index_objs_po ON objs(p,o)""")
self.execute("""CREATE INDEX index_datas_sp ON datas(s,p)""")
self.execute("""CREATE INDEX index_datas_po ON datas(p,o)""")
self.execute("""UPDATE store SET version=4""")
self.db.commit()
if version == 4:
print("* Owlready2 * Converting quadstore to internal format 5 (this can take a while)...", file = sys.stderr)
self.execute("""CREATE TABLE objs2 (c INTEGER, s INTEGER, p INTEGER, o INTEGER)""")
self.execute("""CREATE TABLE datas2 (c INTEGER, s INTEGER, p INTEGER, o BLOB, d INTEGER)""")
_BASE_62 = { c : i for (i, c) in enumerate("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") }
def _base_62_2_int(storid):
if storid.startswith("_"): sgn = -1; storid = storid[1:]
else: sgn = 1
r = 0
for (i, c) in enumerate(storid):
r += _BASE_62[c] * (62 ** (len(storid) - i - 1))
return sgn * r
try:
self.execute("""CREATE TABLE resources2 (storid INTEGER PRIMARY KEY, iri TEXT) WITHOUT ROWID""")
except sqlite3.OperationalError: # Old SQLite3 does not support WITHOUT ROWID -- here it is just an optimization
self.execute("""CREATE TABLE resources2 (storid INTEGER PRIMARY KEY, iri TEXT)""")
l = []
for storid, iri in self.execute("""SELECT storid, iri FROM resources"""):
l.append((_base_62_2_int(storid), iri))
self.db.executemany("INSERT INTO resources2 VALUES (?,?)", l)
l = []
for c,s,p,o in self.execute("""SELECT c,s,p,o FROM objs"""):
s = _base_62_2_int(s)
p = _base_62_2_int(p)
o = _base_62_2_int(o)
l.append((c,s,p,o))
self.db.executemany("INSERT INTO objs2 VALUES (?,?,?,?)", l)
l = []
for c,s,p,o,d in self.execute("""SELECT c,s,p,o,d FROM datas"""):
s = _base_62_2_int(s)
p = _base_62_2_int(p)
if not d: d = 0
elif d.startswith("@"): pass
else: d = _base_62_2_int(d)
l.append((c,s,p,o,d))
self.db.executemany("INSERT INTO datas2 VALUES (?,?,?,?,?)", l)
self.execute("""DROP INDEX IF EXISTS index_resources_iri""")
self.execute("""DROP INDEX IF EXISTS index_quads_s""")
self.execute("""DROP INDEX IF EXISTS index_quads_o""")
self.execute("""DROP INDEX IF EXISTS index_objs_sp""")
self.execute("""DROP INDEX IF EXISTS index_objs_po""")
self.execute("""DROP INDEX IF EXISTS index_datas_sp""")
self.execute("""DROP INDEX IF EXISTS index_datas_po""")
self.execute("""DROP VIEW IF EXISTS quads""")
self.execute("""DROP TABLE resources""")
self.execute("""DROP TABLE objs""")
self.execute("""DROP TABLE datas""")
self.execute("""ALTER TABLE resources2 RENAME TO resources""")
self.execute("""ALTER TABLE objs2 RENAME TO objs""")
self.execute("""ALTER TABLE datas2 RENAME TO datas""")
self.execute("""CREATE VIEW quads AS SELECT c,s,p,o,NULL AS d FROM objs UNION ALL SELECT c,s,p,o,d FROM datas""")
self.execute("""CREATE UNIQUE INDEX index_resources_iri ON resources(iri)""")
self.execute("""CREATE INDEX index_objs_sp ON objs(s,p)""")
self.execute("""CREATE INDEX index_objs_po ON objs(p,o)""")
self.execute("""CREATE INDEX index_datas_sp ON datas(s,p)""")
self.execute("""CREATE INDEX index_datas_po ON datas(p,o)""")
prop_fts = { storid : fts for (fts, storid) in self.execute("""SELECT fts, storid FROM prop_fts;""") }
prop_fts2 = { _base_62_2_int(storid) : fts for (storid, fts) in prop_fts.items() }
for fts in prop_fts.values():
self.execute("""DROP TABLE fts_%s""" % fts)
self.execute("""DROP TRIGGER IF EXISTS fts_%s_after_insert""" % fts)
self.execute("""DROP TRIGGER IF EXISTS fts_%s_after_delete""" % fts)
self.execute("""DROP TRIGGER IF EXISTS fts_%s_after_update""" % fts)
self.execute("""DROP TABLE prop_fts""")
self.execute("""CREATE TABLE prop_fts(storid INTEGER)""")
self.prop_fts = set()
for storid in prop_fts2: self.enable_full_text_search(storid)
self.execute("""UPDATE store SET version=5""")
self.db.commit()
if version == 5:
print("* Owlready2 * Converting quadstore to internal format 6 (this can take a while)...", file = sys.stderr)
self.execute("""DROP INDEX IF EXISTS index_objs_po""")
self.execute("""DROP INDEX IF EXISTS index_datas_po""")
self.execute("""CREATE INDEX index_objs_op ON objs(o,p)""")
self.execute("""CREATE INDEX index_datas_op ON datas(o,p)""")
self.execute("""UPDATE store SET version=6""")
self.db.commit()
if version == 6:
print("* Owlready2 * Converting quadstore to internal format 7 (this can take a while)...", file = sys.stderr)
prop_fts2 = { storid for (storid,) in self.execute("""SELECT storid FROM prop_fts;""") }
for prop_storid in prop_fts2:
self.execute("""DELETE FROM prop_fts WHERE storid = ?""", (prop_storid,))
self.execute("""DROP TABLE fts_%s""" % prop_storid)
self.execute("""DROP TRIGGER fts_%s_after_insert""" % prop_storid)
self.execute("""DROP TRIGGER fts_%s_after_delete""" % prop_storid)
self.execute("""DROP TRIGGER fts_%s_after_update""" % prop_storid)
self.prop_fts = set()
for prop_storid in prop_fts2: self.enable_full_text_search (prop_storid)
self.execute("""UPDATE store SET version=7""")
self.db.commit()
if version == 7:
print("* Owlready2 * Converting quadstore to internal format 8...", file = sys.stderr)
import owlready2.base
self.db.executemany("""INSERT INTO resources VALUES (?,?)""", [
(owlready2.base.swrl_variable, "http://www.w3.org/2003/11/swrl#Variable"),
(owlready2.base.swrl_imp, "http://www.w3.org/2003/11/swrl#Imp"),
(owlready2.base.swrl_body, "http://www.w3.org/2003/11/swrl#body"),
(owlready2.base.swrl_head, "http://www.w3.org/2003/11/swrl#head"),
(owlready2.base.swrl_class_atom, "http://www.w3.org/2003/11/swrl#ClassAtom"),
(owlready2.base.swrl_class_predicate, "http://www.w3.org/2003/11/swrl#classPredicate"),
(owlready2.base.swrl_dataprop_atom, "http://www.w3.org/2003/11/swrl#DatavaluedPropertyAtom"),
(owlready2.base.swrl_objprop_atom, "http://www.w3.org/2003/11/swrl#IndividualPropertyAtom"),
(owlready2.base.swrl_property_predicate, "http://www.w3.org/2003/11/swrl#propertyPredicate"),
(owlready2.base.swrl_builtin_atom, "http://www.w3.org/2003/11/swrl#BuiltinAtom"),
(owlready2.base.swrl_builtin, "http://www.w3.org/2003/11/swrl#builtin"),
(owlready2.base.swrl_datarange_atom, "http://www.w3.org/2003/11/swrl#DataRangeAtom"),
(owlready2.base.swrl_datarange, "http://www.w3.org/2003/11/swrl#dataRange"),
(owlready2.base.swrl_argument1, "http://www.w3.org/2003/11/swrl#argument1"),
(owlready2.base.swrl_argument2, "http://www.w3.org/2003/11/swrl#argument2"),
(owlready2.base.swrl_arguments, "http://www.w3.org/2003/11/swrl#arguments"),
(owlready2.base.swrl_equivalentindividual, "http://www.w3.org/2003/11/swrl#SameIndividualAtom"),
(owlready2.base.swrl_differentfrom, "http://www.w3.org/2003/11/swrl#DifferentIndividualsAtom"),
])
self.execute("""UPDATE store SET version=8""")
self.db.commit()
self.prop_fts = { storid for (storid,) in self.execute("""SELECT storid FROM prop_fts;""") }
self.current_changes = self.db.total_changes
self.select_abbreviate_method()
def set_indexed(self, indexed):
pass
#self.indexed = indexed
#if indexed:
# self.execute("""CREATE INDEX index_objs_sp ON objs(s,p)""")
# #self.execute("""CREATE INDEX index_objs_op ON objs(o,p,c)""") # c is for onto.classes(), etc
# self.execute("""CREATE UNIQUE INDEX index_objs_op ON objs(o,p,c,s)""") # c is for onto.classes(), etc
#
# self.execute("""CREATE INDEX index_datas_sp ON datas(s,p)""")
# #self.execute("""CREATE INDEX index_datas_op ON datas(o,p)""")
# self.execute("""CREATE UNIQUE INDEX index_datas_op ON datas(o,p,c,d,s)""")
#
# for onto in self.world.ontologies.values():
# onto._load_properties()
#else:
# self.execute("""DROP INDEX IF EXISTS index_objs_sp""")
# self.execute("""DROP INDEX IF EXISTS index_objs_op""")
# self.execute("""DROP INDEX IF EXISTS index_datas_sp""")
# self.execute("""DROP INDEX IF EXISTS index_datas_op""")
def close(self):
self.db.close()
def acquire_write_lock(self):
self.lock.acquire()
self.lock_level += 1
def release_write_lock(self):
self.lock_level -= 1
self.lock.release()
def has_write_lock(self): return self.lock_level
def select_abbreviate_method(self):
nb = self.execute("SELECT count(*) FROM resources").fetchone()[0]
if nb < 100000:
iri_storid = self.execute("SELECT iri, storid FROM resources").fetchall()
self. _abbreviate_d = dict(iri_storid)
self._unabbreviate_d = dict((storid, iri) for (iri, storid) in iri_storid)
self._abbreviate = self._abbreviate_dict
self._unabbreviate = self._unabbreviate_dict
self._refactor = self._refactor_dict
else:
self. _abbreviate_d = None
self._unabbreviate_d = None
self._abbreviate = self._abbreviate_sql
self._unabbreviate = self._unabbreviate_sql
self._refactor = self._refactor_sql
if self.world:
self.world._abbreviate = self._abbreviate
self.world._unabbreviate = self._unabbreviate
for subgraph in self.onto_2_subgraph.values():
subgraph.onto._abbreviate = subgraph._abbreviate = self._abbreviate
subgraph.onto._unabbreviate = subgraph._unabbreviate = self._unabbreviate
def fix_base_iri(self, base_iri, c = None):
if base_iri.endswith("#") or base_iri.endswith("/"): return base_iri
use_slash = self.execute("SELECT iri FROM resources WHERE iri=? LIMIT 1", ("%s/" % base_iri,)).fetchone()
if use_slash: return "%s/" % base_iri
use_hash = self.execute("SELECT resources.iri FROM resources WHERE SUBSTR(resources.iri, 1, ?)=? LIMIT 1", (len(base_iri) + 1, "%s#" % base_iri,)).fetchone()
if use_hash: return "%s#" % base_iri
use_slash = self.execute("SELECT resources.iri FROM resources WHERE SUBSTR(resources.iri, 1, ?)=? LIMIT 1", (len(base_iri) + 1, "%s/" % base_iri,)).fetchone()
if use_slash: return "%s/" % base_iri
return "%s#" % base_iri
def sub_graph(self, onto):
new_in_quadstore = False
c = self.execute("SELECT c FROM ontologies WHERE iri=?", (onto.base_iri,)).fetchone()
if c is None:
c = self.execute("SELECT ontologies.c FROM ontologies, ontology_alias WHERE ontology_alias.alias=? AND ontologies.iri=ontology_alias.iri", (onto.base_iri,)).fetchone()
if c is None:
new_in_quadstore = True
self.execute("INSERT INTO ontologies VALUES (NULL, ?, 0)", (onto.base_iri,))
c = self.execute("SELECT c FROM ontologies WHERE iri=?", (onto.base_iri,)).fetchone()
c = c[0]
self.c_2_onto[c] = onto
return SubGraph(self, onto, c, self.db), new_in_quadstore
def ontologies_iris(self):
for (iri,) in self.execute("SELECT iri FROM ontologies").fetchall(): yield iri
def _abbreviate_sql(self, iri, create_if_missing = True):
r = self.execute("SELECT storid FROM resources WHERE iri=? LIMIT 1", (iri,)).fetchone()
if r: return r[0]
if create_if_missing:
self.current_resource += 1
storid = self.current_resource
self.execute("INSERT INTO resources VALUES (?,?)", (storid, iri))
return storid
def _unabbreviate_sql(self, storid):
return self.execute("SELECT iri FROM resources WHERE storid=? LIMIT 1", (storid,)).fetchone()[0]
def _abbreviate_dict(self, iri, create_if_missing = True):
storid = self._abbreviate_d.get(iri)
if (storid is None) and create_if_missing:
self.current_resource += 1
storid = self._abbreviate_d[iri] = self.current_resource
self._unabbreviate_d[storid] = iri
self.execute("INSERT INTO resources VALUES (?,?)", (storid, iri))
return storid
def _unabbreviate_dict(self, storid):
return self._unabbreviate_d[storid]
def get_storid_dict(self):
return dict(self.execute("SELECT storid, iri FROM resources").fetchall())
def _new_numbered_iri(self, prefix):
if prefix in self.last_numbered_iri:
i = self.last_numbered_iri[prefix] = self.last_numbered_iri[prefix] + 1
return "%s%s" % (prefix, i)
else:
cur = self.execute("SELECT iri FROM resources WHERE iri GLOB ? ORDER BY LENGTH(iri) DESC, iri DESC", ("%s*" % prefix,))
while True:
iri = cur.fetchone()
if not iri: break
num = iri[0][len(prefix):]
if num.isdigit():
self.last_numbered_iri[prefix] = i = int(num) + 1
return "%s%s" % (prefix, i)
self.last_numbered_iri[prefix] = 1
return "%s1" % prefix
def _refactor_sql(self, storid, new_iri):
self.execute("UPDATE resources SET iri=? WHERE storid=?", (new_iri, storid,))
def _refactor_dict(self, storid, new_iri):
self.execute("UPDATE resources SET iri=? WHERE storid=?", (new_iri, storid,))
del self._abbreviate_d[self._unabbreviate_d[storid]]
self. _abbreviate_d[new_iri] = storid
self._unabbreviate_d[storid] = new_iri
def commit(self):
if self.current_changes != self.db.total_changes:
self.current_changes = self.db.total_changes
self.execute("UPDATE store SET current_blank=?, current_resource=?", (self.current_blank, self.current_resource))
self.db.commit()
def context_2_user_context(self, c):
user_c = self.c_2_onto.get(c)
if user_c is None:
iri = self.execute("SELECT iri FROM ontologies WHERE c=? LIMIT 1", (c,)).fetchone()[0]
return self.world.get_ontology(iri)
return user_c
def new_blank_node(self):
self.current_blank += 1
return -self.current_blank
def _get_obj_triples_spo_spo(self, s, p, o):
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o FROM objs")
else: cur = self.execute("SELECT s,p,o FROM objs WHERE o=?", (o,))
else:
if o is None: cur = self.execute("SELECT s,p,o FROM objs WHERE p=?", (p,))
else: cur = self.execute("SELECT s,p,o FROM objs WHERE p=? AND o=?", (p, o,))
else:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o FROM objs WHERE s=?", (s,))
else: cur = self.execute("SELECT s,p,o FROM objs WHERE s=? AND o=?", (s, o,))
else:
if o is None: cur = self.execute("SELECT s,p,o FROM objs WHERE s=? AND p=?", (s, p,))
else: cur = self.execute("SELECT s,p,o FROM objs INDEXED BY index_objs_sp WHERE s=? AND p=? AND o=?", (s, p, o,))
return cur.fetchall()
def _get_data_triples_spod_spod(self, s, p, o, d):
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o,d FROM datas")
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM datas WHERE o=?", (o,))
else:
cur = self.execute("SELECT s,p,o,d FROM datas WHERE o=? AND d=?", (o,d,))
else:
if o is None: cur = self.execute("SELECT s,p,o,d FROM datas WHERE p=?", (p,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM datas WHERE p=? AND o=?", (p, o,))
else:
cur = self.execute("SELECT s,p,o,d FROM datas WHERE p=? AND o=? AND d=?", (p, o, d,))
else:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o,d FROM datas WHERE s=?", (s,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=?", (s, o,))
else:
cur = self.execute("SELECT s,p,o,d FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=? AND d=?", (s, o, d,))
else:
if o is None: cur = self.execute("SELECT s,p,o,d FROM datas WHERE s=? AND p=?", (s, p,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=?", (s, p, o))
else:
cur = self.execute("SELECT s,p,o,d FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=? AND d=?", (s, p, o, d,))
return cur.fetchall()
def _get_triples_spod_spod(self, s, p, o, d):
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o,d FROM quads")
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE o=?", (o,))
else:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE o=? AND d=?", (o,d,))
else:
if o is None: cur = self.execute("SELECT s,p,o,d FROM quads WHERE p=?", (p,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE p=? AND o=?", (p, o,))
else:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE p=? AND o=? AND d=?", (p, o, d,))
else:
if p is None:
if o is None: cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=?", (s,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=? AND o=?", (s, o,))
else:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=? AND o=? AND d=?", (s, o, d,))
else:
if o is None: cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=? AND p=?", (s, p,))
else:
if d is None:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=? AND p=? AND o=?", (s, p, o))
else:
cur = self.execute("SELECT s,p,o,d FROM quads WHERE s=? AND p=? AND o=? AND d=?", (s, p, o, d,))
return cur.fetchall()
def _get_obj_triples_cspo_cspo(self, c, s, p, o):
if c is None:
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs")
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE o=?", (o,))
else:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE p=?", (p,))
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE p=? AND o=?", (p, o,))
else:
if p is None:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE s=?", (s,))
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE INDEXED BY index_objs_sp s=? AND o=?", (s, o,))
else:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE s=? AND p=?", (s, p,))
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE INDEXED BY index_objs_sp s=? AND p=? AND o=?", (s, p, o,))
else:
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE c=?", (c,))
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE c=? AND o=?", (c, o,))
else:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE c=? AND p=?", (c, p,))
else: cur = self.execute("SELECT c,s,p,o FROM objs WHERE c=? AND p=? AND o=?", (c, p, o,))
else:
if p is None:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs WHERE c=? AND s=?", (c, s,))
else: cur = self.execute("SELECT c,s,p,o FROM objs INDEXED BY index_objs_sp WHERE c=? AND s=? AND o=?", (c, s, o,))
else:
if o is None: cur = self.execute("SELECT c,s,p,o FROM objs INDEXED BY index_objs_sp WHERE c=? AND s=? AND p=?", (c, s, p,))
else: cur = self.execute("SELECT c,s,p,o FROM objs INDEXED BY index_objs_sp WHERE c=? AND s=? AND p=? AND o=?", (c, s, p, o,))
return cur.fetchall()
def _get_obj_triples_sp_co(self, s, p):
return self.execute("SELECT c,o FROM objs WHERE s=? AND p=?", (s, p)).fetchall()
def _get_triples_s_p(self, s):
for (x,) in self.execute("SELECT DISTINCT p FROM quads WHERE s=?", (s,)).fetchall(): yield x
def _get_obj_triples_o_p(self, o):
for (x,) in self.execute("SELECT DISTINCT p FROM quads WHERE o=?", (o,)).fetchall(): yield x
def _get_obj_triples_s_po(self, s):
return self.execute("SELECT p,o FROM objs WHERE s=?", (s,)).fetchall()
def _get_obj_triples_sp_o(self, s, p):
for (x,) in self.execute("SELECT o FROM objs WHERE s=? AND p=?", (s, p)).fetchall(): yield x
def _get_data_triples_sp_od(self, s, p):
return self.execute("SELECT o,d FROM datas WHERE s=? AND p=?", (s, p)).fetchall()
def _get_triples_sp_od(self, s, p):
return self.execute("SELECT o,d FROM quads WHERE s=? AND p=?", (s, p)).fetchall()
def _get_data_triples_s_pod(self, s):
return self.execute("SELECT p,o,d FROM datas WHERE s=?", (s,)).fetchall()
def _get_triples_s_pod(self, s):
return self.execute("SELECT p,o,d FROM quads WHERE s=?", (s,)).fetchall()
def _get_obj_triples_po_s(self, p, o):
for (x,) in self.execute("SELECT s FROM objs WHERE p=? AND o=?", (p, o)).fetchall(): yield x
def _get_obj_triples_spi_o(self, s, p, i):
for (x,) in self.execute("SELECT o FROM objs WHERE s=? AND p=? UNION SELECT s FROM objs WHERE p=? AND o=?", (s, p, i, s)).fetchall(): yield x
def _get_obj_triples_pio_s(self, p, i, o):
for (x,) in self.execute("SELECT s FROM objs WHERE p=? AND o=? UNION SELECT o FROM objs WHERE s=? AND p=?", (p, o, o, i)).fetchall(): yield x
def _get_obj_triple_sp_o(self, s, p):
r = self.execute("SELECT o FROM objs WHERE s=? AND p=? LIMIT 1", (s, p)).fetchone()
if r: return r[0]
return None
def _get_triple_sp_od(self, s, p):
return self.execute("SELECT o,d FROM quads WHERE s=? AND p=? LIMIT 1", (s, p)).fetchone()
def _get_data_triple_sp_od(self, s, p):
return self.execute("SELECT o,d FROM datas WHERE s=? AND p=? LIMIT 1", (s, p)).fetchone()
def _get_obj_triple_po_s(self, p, o):
r = self.execute("SELECT s FROM objs WHERE p=? AND o=? LIMIT 1", (p, o)).fetchone()
if r: return r[0]
return None
def _has_obj_triple_spo(self, s = None, p = None, o = None):
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT s FROM objs LIMIT 1")
else: cur = self.execute("SELECT s FROM objs WHERE o=? LIMIT 1", (o,))
else:
if o is None: cur = self.execute("SELECT s FROM objs WHERE p=? LIMIT 1", (p,))
else: cur = self.execute("SELECT s FROM objs WHERE p=? AND o=? LIMIT 1", (p, o))
else:
if p is None:
if o is None: cur = self.execute("SELECT s FROM objs WHERE s=? LIMIT 1", (s,))
else: cur = self.execute("SELECT s FROM objs INDEXED BY index_objs_sp WHERE s=? AND o=? LIMIT 1", (s, o))
else:
if o is None: cur = self.execute("SELECT s FROM objs WHERE s=? AND p=? LIMIT 1", (s, p))
else: cur = self.execute("SELECT s FROM objs INDEXED BY index_objs_sp WHERE s=? AND p=? AND o=? LIMIT 1", (s, p, o))
return not cur.fetchone() is None
def _has_data_triple_spod(self, s = None, p = None, o = None, d = None):
if s is None:
if p is None:
if o is None: cur = self.execute("SELECT s FROM datas LIMIT 1")
elif d is None: cur = self.execute("SELECT s FROM datas WHERE o=? LIMIT 1", (o,))
else: cur = self.execute("SELECT s FROM datas WHERE o=? AND d=? LIMIT 1", (o,d,))
else:
if o is None: cur = self.execute("SELECT s FROM datas WHERE p=? LIMIT 1", (p,))
elif d is None: cur = self.execute("SELECT s FROM datas WHERE p=? AND o=? LIMIT 1", (p, o))
else: cur = self.execute("SELECT s FROM datas WHERE p=? AND o=? AND d=? LIMIT 1", (p, o, d))
else:
if p is None:
if o is None: cur = self.execute("SELECT s FROM datas WHERE s=? LIMIT 1", (s,))
elif d is None: cur = self.execute("SELECT s FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=? LIMIT 1", (s, o))
else: cur = self.execute("SELECT s FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=? AND d=? LIMIT 1", (s, o, d))
else:
if o is None: cur = self.execute("SELECT s FROM datas WHERE s=? AND p=? LIMIT 1", (s, p))
elif d is None: cur = self.execute("SELECT s FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=? LIMIT 1", (s, p, o))
else: cur = self.execute("SELECT s FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=? AND d=? LIMIT 1", (s, p, o, d))
return not cur.fetchone() is None
def _del_obj_triple_raw_spo(self, s, p, o):
if s is None:
if p is None:
if o is None: self.execute("DELETE FROM objs")
else: self.execute("DELETE FROM objs WHERE o=?", (o,))
else:
if o is None: self.execute("DELETE FROM objs WHERE p=?", (p,))
else: self.execute("DELETE FROM objs WHERE p=? AND o=?", (p, o,))
else:
if p is None:
if o is None: self.execute("DELETE FROM objs WHERE s=?", (s,))
else: self.execute("DELETE FROM objs INDEXED BY index_objs_sp WHERE s=? AND o=?", (s, o,))
else:
if o is None: self.execute("DELETE FROM objs WHERE s=? AND p=?", (s, p,))
else: self.execute("DELETE FROM objs INDEXED BY index_objs_sp WHERE s=? AND p=? AND o=?", (s, p, o,))
def _del_data_triple_raw_spod(self, s, p, o, d):
if s is None:
if p is None:
if o is None: self.execute("DELETE FROM datas")
elif d is None: self.execute("DELETE FROM datas WHERE o=?", (o,))
else: self.execute("DELETE FROM datas WHERE o=? AND d=?", (o, d,))
else:
if o is None: self.execute("DELETE FROM datas WHERE p=?", (p,))
elif d is None: self.execute("DELETE FROM datas WHERE p=? AND o=?", (p, o,))
else: self.execute("DELETE FROM datas WHERE p=? AND o=? AND d=?", (p, o, d,))
else:
if p is None:
if o is None: self.execute("DELETE FROM datas WHERE s=?", (s,))
elif d is None: self.execute("DELETE FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=?", (s, o,))
else: self.execute("DELETE FROM datas INDEXED BY index_datas_sp WHERE s=? AND o=? AND d=?", (s, o, d,))
else:
if o is None: self.execute("DELETE FROM datas WHERE s=? AND p=?", (s, p,))
elif d is None: self.execute("DELETE FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=?", (s, p, o,))
else: self.execute("DELETE FROM datas INDEXED BY index_datas_sp WHERE s=? AND p=? AND o=? AND d=?", (s, p, o, d,))
def _punned_entities(self):
from owlready2.base import rdf_type, owl_class, owl_named_individual
cur = self.execute("SELECT q1.s FROM objs q1, objs q2 WHERE q1.s=q2.s AND q1.p=? AND q2.p=? AND q1.o=? AND q2.o=?", (rdf_type, rdf_type, owl_class, owl_named_individual))
return [storid for (storid,) in cur.fetchall()]
def __bool__(self): return True # Reimplemented to avoid calling __len__ in this case
def __len__(self):
return self.execute("SELECT COUNT() FROM quads").fetchone()[0]
# def get_equivs_s_o(self, s):
# for (x,) in self.execute("""
#WITH RECURSIVE transit(x)
#AS ( SELECT o FROM equivs WHERE s=?
#UNION SELECT equivs.o FROM equivs, transit WHERE equivs.s=transit.x)
#SELECT DISTINCT x FROM transit""", (s,)).fetchall(): yield x
# def _get_obj_triples_transitive_sp(self, s, p):
# for (x,) in self.execute("""
# WITH RECURSIVE transit(x)
# AS ( SELECT o FROM objs WHERE s=? AND p=?
# UNION ALL SELECT objs.o FROM objs, transit WHERE objs.s=transit.x AND objs.p=?)
# SELECT DISTINCT x FROM transit""", (s, p, p)).fetchall(): yield x
# def _get_obj_triples_transitive_po(self, p, o):
# for (x,) in self.execute("""
# WITH RECURSIVE transit(x)
# AS ( SELECT s FROM objs WHERE p=? AND o=?
# UNION ALL SELECT objs.s FROM objs, transit WHERE objs.p=? AND objs.o=transit.x)
# SELECT DISTINCT x FROM transit""", (p, o, p)).fetchall(): yield x
def _get_obj_triples_transitive_sp(self, s, p):
for (x,) in self.execute("""
WITH RECURSIVE transit(x)
AS ( SELECT o FROM objs WHERE s=? AND p=?
UNION SELECT objs.o FROM objs, transit WHERE objs.s=transit.x AND objs.p=?)
SELECT x FROM transit""", (s, p, p)).fetchall(): yield x
def _get_obj_triples_transitive_po(self, p, o):
for (x,) in self.execute("""
WITH RECURSIVE transit(x)
AS ( SELECT s FROM objs WHERE p=? AND o=?
UNION SELECT objs.s FROM objs, transit WHERE objs.p=? AND objs.o=transit.x)
SELECT x FROM transit""", (p, o, p)).fetchall(): yield x
# Slower than Python implementation
# def _get_obj_triples_transitive_sym2(self, s, p):
# r = { s }
# for (s, o) in self.execute("""
#WITH RECURSIVE transit(s,o)
#AS ( SELECT s,o from objs WHERE (s=? OR o=?) AND (p=?)
# UNION SELECT objs.s,quads.o FROM objs, transit WHERE (quads.s=transit.s OR objs.o=transit.o OR objs.s=transit.o OR objs.o=transit.s) AND objs.p=?)
#SELECT s, o FROM transit""", (s, s, p, p)):
# r.add(s)
# r.add(o)
# yield from r
def _destroy_collect_storids(self, destroyed_storids, modified_relations, storid):
for (blank_using,) in list(self.execute("""SELECT s FROM quads WHERE o=? AND p IN (
%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s) AND s < 0""" % (
SOME,
ONLY,
VALUE,
owl_onclass,
owl_onproperty,
owl_complementof,
owl_inverse_property,
owl_ondatarange,
owl_annotatedsource,
owl_annotatedproperty,
owl_annotatedtarget,
), (storid,))):
if not blank_using in destroyed_storids:
destroyed_storids.add(blank_using)
self._destroy_collect_storids(destroyed_storids, modified_relations, blank_using)
for (c, blank_using) in list(self.execute("""SELECT c, s FROM objs WHERE o=? AND p=%s AND s < 0""" % (
rdf_first,
), (storid,))):
list_user, root, previouss, nexts, length = self._rdf_list_analyze(blank_using)
destroyed_storids.update(previouss)
destroyed_storids.add (blank_using)
destroyed_storids.update(nexts)
if not list_user in destroyed_storids:
destroyed_storids.add(list_user)
self._destroy_collect_storids(destroyed_storids, modified_relations, list_user)
def _rdf_list_analyze(self, blank):
previouss = []
nexts = []
length = 1
b = self._get_obj_triple_sp_o(blank, rdf_rest)
while b != rdf_nil:
nexts.append(b)
length += 1
b = self._get_obj_triple_sp_o(b, rdf_rest)
b = self._get_obj_triple_po_s(rdf_rest, blank)
if b:
while b:
previouss.append(b)
length += 1
root = b
b = self._get_obj_triple_po_s(rdf_rest, b)
else:
root = blank
list_user = self.execute("SELECT s FROM objs WHERE o=? LIMIT 1", (root,)).fetchone()
if list_user: list_user = list_user[0]
return list_user, root, previouss, nexts, length
def restore_iri(self, storid, iri):
self.execute("INSERT INTO resources VALUES (?,?)", (storid, iri))
if self._abbreviate_d:
self._unabbreviate_d[storid] = iri
self._abbreviate_d [iri] = storid
def destroy_entity(self, storid, destroyer, relation_updater, undoer_objs = None, undoer_datas = None):
self.execute("DELETE FROM resources WHERE storid=?", (storid,))
if self._abbreviate_d and (storid > 0):
del self._abbreviate_d [self._unabbreviate_d[storid]]
del self._unabbreviate_d[storid]
destroyed_storids = { storid }
modified_relations = defaultdict(set)
self._destroy_collect_storids(destroyed_storids, modified_relations, storid)
for s,p in self.execute("SELECT DISTINCT s,p FROM objs WHERE o IN (%s)" % ",".join(["?" for i in destroyed_storids]), tuple(destroyed_storids)):
if not s in destroyed_storids:
modified_relations[s].add(p)
# Two separate loops because high level destruction must be ended before removing from the quadstore (high level may need the quadstore)
for storid in destroyed_storids:
destroyer(storid)
for storid in destroyed_storids:
if undoer_objs is not None:
undoer_objs .extend(self.execute("SELECT c,s,p,o FROM objs WHERE s=? OR o=?", (storid, storid)))
undoer_datas.extend(self.execute("SELECT c,s,p,o,d FROM datas WHERE s=?", (storid,)))
self.execute("DELETE FROM objs WHERE s=? OR o=?", (storid, storid))
self.execute("DELETE FROM datas WHERE s=?", (storid,))
for s, ps in modified_relations.items():
relation_updater(destroyed_storids, s, ps)
return destroyed_storids
def _iter_ontology_iri(self, c = None):
if c:
return self.execute("SELECT iri FROM ontologies WHERE c=?", (c,)).fetchone()[0]
else:
return self.execute("SELECT c, iri FROM ontologies").fetchall()
# def _iter_triples(self, quads = False, sort_by_s = False, c = None):
# quad_cursor = self.db.cursor() # Use a new cursor => can iterate without loading all data in a big list, while still being able to query the default cursor
# data_cursor = self.db.cursor() # Use a new cursor => can iterate without loading all data in a big list, while still being able to query the default cursor
# sql = ""
# if c: sql += " WHERE c=%s" % c
# if sort_by_s: sql += " ORDER BY s"
# if quads:
# quad_cursor.execute("SELECT s,p,o,NULL,c FROM quads %s" % sql)
# data_cursor.execute("SELECT s,p,o,d,c FROM datas %s" % sql)
# else:
# quad_cursor.execute("SELECT s,p,o,NULL FROM quads %s" % sql)
# data_cursor.execute("SELECT s,p,o,d FROM datas %s" % sql)
# if sort_by_s:
# yield from group_iters(quad_cursor, data_cursor)
# else:
# yield from quad_cursor
# yield from data_cursor
def _iter_triples(self, quads = False, sort_by_s = False, c = None):
cursor = self.db.cursor() # Use a new cursor => can iterate without loading all data in a big list, while still being able to query the default cursor
sql = ""
if c: sql += " WHERE c=%s" % c
if sort_by_s: sql += " ORDER BY s"
if quads:
cursor.execute("SELECT c,s,p,o,d FROM quads %s" % sql)
else:
cursor.execute("SELECT s,p,o,d FROM quads %s" % sql)
return cursor
def get_fts_prop_storid(self): return self.prop_fts
# def enable_full_text_search(self, prop_storid):
# self.prop_fts.add(prop_storid)
# self.execute("""INSERT INTO prop_fts VALUES (?)""", (prop_storid,));
# self.execute("""CREATE VIRTUAL TABLE fts_%s USING fts5(o, d, content=datas, content_rowid=rowid)""" % prop_storid)
# self.execute("""INSERT INTO fts_%s(rowid, o) SELECT rowid, o FROM datas WHERE p=%s""" % (prop_storid, prop_storid))
# self.db.cursor().executescript("""
# CREATE TRIGGER fts_%s_after_insert AFTER INSERT ON datas WHEN new.p=%s BEGIN
# INSERT INTO fts_%s(rowid, o) VALUES (new.rowid, new.o);
# END;
# CREATE TRIGGER fts_%s_after_delete AFTER DELETE ON datas WHEN old.p=%s BEGIN
# INSERT INTO fts_%s(fts_%s, rowid, o) VALUES('delete', old.rowid, old.o);
# END;
# CREATE TRIGGER fts_%s_after_update AFTER UPDATE ON datas WHEN new.p=%s BEGIN
# INSERT INTO fts_%s(fts_%s, rowid, o) VALUES('delete', new.rowid, new.o);
# INSERT INTO fts_%s(rowid, o) VALUES (new.rowid, new.o);
# END;""" % (prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid, prop_storid))
def enable_full_text_search(self, prop_storid):
self.prop_fts.add(prop_storid)