-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgraphydb.py
1797 lines (1489 loc) · 60.5 KB
/
graphydb.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
#!/usr/bin/env python
#
# GraphyDB
#
# A python graph database implemented on top of SQLite.
#
# Alexei Gilchrist
# Copyright 2021
#
# (Python 3 required)
#
#
'''
# Overview
GraphyDB is a graph database for Python 3 built ontop of SQLite.
There are many cases where a graph structure is a better fit to a problem domain than a set of tables.
GraphyDB was designed to fill a niche where a flexible embedded graph database was needed
for a moderate sized problem (~10,000 edges and nodes). GraphyDB is not designed to handle terrabytes
of data, and has not been particularly optimised for speed.
# Quick start
For example. let's instantiate a graph in memory and add some nodes then connect them, saving them immediately.
from graphydb import Graph
g = Graph()
anne = g.Node('Person', name="Anne").save()
bob = g.Node('Person', name="Bob", nickname='Bobby').save()
charlie = g.Node('Person', name="Charlie").save()
coffee = g.Node('Drink', sort="Coffee").save()
tea = g.Node('Drink', sort="Tea").save()
g.Edge(anne, 'Likes', bob).save()
g.Edge(charlie, 'Likes', bob).save()
g.Edge(anne, 'Drinks', coffee, strength='weak').save()
g.Edge(charlie, 'Drinks', coffee, strength='weak').save()
Now we can find who drinks coffee. If we have the node we can fetch the incoming references
p1=coffee.inN('e.kind = "Drinks"')
> {[(Y7YQHVNCVUZ9AHH2YH3UVIH86:Person), (3ZKZI0PQAF3CNMEQ7WLUVTW6F:Person)]}
Or we can query the database directly (and build more sophisticated queries)
p2=g.fetch('[p:Person,strength] -(e:Drinks)> (d:Drink)', 'd.data.sort = "Coffee"', strength='e.data.strength')
> {[(Y7YQHVNCVUZ9AHH2YH3UVIH86:Person), (3ZKZI0PQAF3CNMEQ7WLUVTW6F:Person)]}
p2[0].data
> {'_strength': 'weak',
'ctime': 1474270482.224738,
'kind': 'Person',
'mtime': 1474270482.224739,
'name': 'Anne',
'uid': 'Y7YQHVNCVUZ9AHH2YH3UVIH86'}
# SQLite structure
Two tables hold most of the data, one for nodes and one for edges.
Additional tables provide a key-value stores for preferences and a cache. FTS indices are
also held in the database.
## Nodes
Nodes are held in the table `nodes` with the columns
- `uid` [TEXT PRIMARY KEY] A 25 character UUID assumed to be unique across all items past and future
- `kind` [TEXT] The node kind, e.g. "Person", "Document" etc
- `ctime` [REAL] Item creation time in seconds since the epoch as a floating point number
- `mtime` [REAL] Item last modification time in seconds since the epoch as a floating point number
- `data` [TEXT] A JSON encoded distionary of keys and values
## Edges
Edges are held in the table `edges` with the columns
- `uid` [TEXT PRIMARY KEY] A 25 character UUID assumed to be unique across all items past and future
- `kind` [TEXT] The edge kind e.g. "Likes", "Authored" etc
- `startuid` [TEXT NOT NULL REFERENCES nodes(uid)]
- `enduid` [TEXT NOT NULL REFERENCES nodes(uid)]
- `ctime` [REAL] Item creation time in seconds since the epoch as a floating point number
- `mtime` [REAL] Item last modification time in seconds since the epoch as a floating point number
- `data` [TEXT] A JSON encoded distionary of keys and values
Note that any two nodes can be connected by multiple edges so the structure is not a simple graph but
a directed multigraph with the possibility of loops.
This makes it possible to have metadata associated with each edge kind. It's up to the application to
deal with multiple edges.
## Additional tables
Two additional tables `settings` and `cache` provide simple key-value stores with the columns
- `key` [TEXT PRIMARY KEY] Some unique string for the key
- `value` [TEXT] JSON encoded data for the value
# Installing
## Dependencies
1. apsw (with fts5 and json1 extensions)
# Module details
'''
import json, re, os, random, fnmatch, time, copy
from collections import MutableMapping
import apsw
import logging
from datetime import datetime
import functools, itertools
logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
__version__ = 0.42
RESERVED = ['uid','kind','ctime','mtime','startuid','enduid']
'''Reserved keyword that cannot be used in node and edge data.'''
FETCHKEYWORDS = ['WHERE','CHAIN','ORDER','LIMIT','GROUP', 'COUNT', 'DISTINCT', 'OFFSET', 'DEBUG']
'''Keywords used in `graphydb.Graph.fetch`, everything else is a parameter.'''
#--------------------------------------------------------------------------------
def generateUUID():
'''
Generate a random UUID.
Make as short as possible by encoding in all numbers and letters.
Sequence has to be case insensitive to support any filesystem and web.
'''
## the standard uuid is 16 bytes. this has
## 256**16 = 340282366920938463463374607431768211456 possible values
## In hex with the alphabet '0123456789abcdef' this is
## 16**32 = 340282366920938463463374607431768211456
## encoding with the alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
## can be done in 25 characters:
## 36**25 = 808281277464764060643139600456536293376
## keep case insensitive for robustness in URLS etc
## (case sensitivity would only drop it to 22 characters)
alphabet = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
N = len(alphabet)
# emulate how uuid4 grabs entropy
try:
# first try to use the system urandom module if available
# this should be more cryptographically secure than random
rand = random.SystemRandom().random
uu = ''.join([alphabet[(rand()*N).__int__()] for i in range(25)])
except:
# fall back on random
rand = random.random
uu = ''.join([alphabet[(rand()*N).__int__()] for i in range(25)])
return uu
#--------------------------------------------------------------------------------
def jsonextract(param):
'''
Helper function to wrap json extractions.
e.g. `x.data.y` becomes `json_extract(x.data, "$.y")`
'''
return re.sub('(\w+)\.data\.(\w+)',r'json_extract(\1.data, "$.\2")', param)
def ensurelist(x):
'''
Helper function to ensure argument is a list.
'''
if x is None:
x = []
elif type(x) != type([]):
x = [x]
return x
def conditionalyield(keys,A,B):
'''
Iterator over values A[k] | B[k]
'''
for k in keys:
yield (A[k] if k in A else B[k])
def cleandata(fulldata):
'''
Return dict without keys that start with underscore (which are treated as temporary local variables).
'''
data = {k:v for k,v in fulldata.items() if k[0] != '_'}
return data
def diff(d1,d2,changedkeys):
'''
Calculate a simple diff that takes dict d1 to d2.
Only keys in the set changedkeys are considered.
Keys starting with underscore are ignored.
'''
remove = {}
add = {}
for k in d1.keys()|d2.keys():
if k[0] == '_':
continue
elif k in changedkeys:
## only consider keys explicitly marked as changed
if k not in d2:
remove[k] = d1[k]
elif k not in d1:
add[k] = d2[k]
elif d1[k]!=d2[k]:
## only stored if values are actually different
remove[k] = d1[k]
add[k] = d2[k]
if len(remove) == 1 and 'mtime' in remove and len(add) == 1 and 'mtime' in add:
remove = {}
add = {}
change = {}
if len(add)>0:
change['+'] = add
if len(remove)>0:
change['-'] = remove
return change
def patch(d, change, reverse=False):
'''
Patch a dict based on a change dict.
Return a patched shallow copy.
'''
d2=dict(d)
if reverse:
for k in change.get('+',{}).keys():
del d2[k]
d2.update(change.get('-',{}))
else:
for k in change.get('-',{}).keys():
del d2[k]
d2.update(change.get('+',{}))
return d2
#--------------------------------------------------------------------------------
class GraphyDBException(Exception):
'''
Any exceptions thrown by `graphydb`.
'''
pass
#--------------------------------------------------------------------------------
class IndexedSet:
'''
Implements an indexed and sorted set.
The collection supports a subset of list, set, and dict operations.
The objects in the collection must expose a `__uid__()` method that returns a unique string uid
for the object. This uid is what will be used to index the object and in set comparisons.
Items are maintained in order and are indexed so can be looked up by uid. Internally, the data is
stored in a dict `_index` *and* list `_list`, but these shouldn't be modified directly as
they need to be kept in sync.
Speed of set operations are about 10x slower than native sets but with a much faster
creation time for populating the collection. Since set operations are already really fast,
the collection has been optimised to reduce the creation time to have overall performance.
'''
def __init__(self, iterable=[]):
'''
Takes an interable of objects with a `__uid__()` method.
'''
self._index = {n.__uid__():n for n in iterable}
self._list = list(iterable)
if len(self._list) != len(self._index.keys()):
## iterable contains duplicates. Base the list on the _index.
self._list = list(self._index.values())
def copy(self):
'''
Return a shallow copy.
This means any mutable objects inside the
collected object with be references to the original.
'''
## N.B. in __init__ a shallow copy is made anyway
## but it's faster to copy the parsed structures
new = self.__class__()
new._index = self._index.copy()
new._list = self._list.copy()
return new
#
# list methods
#
def sort(self, key=None, reverse=False):
'''
Sort items in place. Returns reference.
'''
self._list.sort(key=key, reverse=reverse)
return self
def __getitem__(self, key):
if isinstance(key, slice):
return self.__class__(self._list[key])
elif isinstance(key, str):
return self._index[key]
else:
return self._list[key]
def __iter__(self):
return iter(self._list)
def reverse(self):
'''
Reverse item order in place. Returns reference.
'''
self._list.reverse()
return self
def __delitem__(self, i):
if isinstance(i, slice):
values = self._list[i]
else:
values = [self._list[i]]
for v in values:
del self._index[v.__uid__()]
del self._list[i]
def __repr__(self):
return "{{{}}}".format(self._list.__repr__())
def append(self, item):
'''
Append an item to collection,
overwriting and moving to end if present (by uid).
Returns reference.
'''
self.discard(item)
uid = item.__uid__()
self._index[uid] = item
self._list.append(item)
return self
#
# set methods
#
def clear(self):
'''
Clear all the contents. Returns reference.
'''
self._list = list()
self._index = dict()
return self
def add(self, item):
'''
Add an item to collection,
overwriting if already present (by uid) and keeping position.
Returns reference.
'''
uid = item.__uid__()
if uid in self._index:
current = self._index[uid]
self._index[uid] = item
idx = self._list.index(current)
self._list[idx] = item
else:
self._list.append(item)
self._index[uid]=item
return self
def remove(self, item):
'''
Remove item (with same uid) from the collection.
Raise KeyError if item not present.
Returns reference.
'''
uid = item.__uid__()
## make sure it is the item in collection with same uid
actualitem = self._index[uid]
self._list.remove(actualitem)
del self._index[uid]
return self
def discard(self, item):
'''
Remove item (with same uid) from the collection.
Ignore if item not present.
Returns reference.
'''
uid = item.__uid__()
if uid in self._index:
## make sure it is the item in collection with same uid
actualitem = self._index[uid]
self._list.remove(actualitem)
del self._index[uid]
return self
def __lt__(self, other):
return self._index.keys().__lt__(other._index.keys())
def __le__(self, other):
return self._index.keys().__le__(other._index.keys())
def __eq__(self, other):
return self._index.keys().__eq__(other._index.keys())
def __ne__(self, other):
return self._index.keys().__ne__(other._index.keys())
def __gt__(self, other):
return self._index.keys().__gt__(other._index.keys())
def __ge__(self, other):
return self._index.keys().__ge__(other._index.keys())
def __cmp__(self, other):
return self._index.keys().__cmp__(other._index.keys())
def union(self, *others):
return functools.reduce(lambda x,y:x|y,others, self)
def intersection(self, *others):
return functools.reduce(lambda x,y:x&y,others, self)
def difference(self, *others):
return functools.reduce(lambda x,y:x-y,others, self)
def symmetric_difference(self, other):
## N.B. keys() has no symmetric_difference() so convert to full set first
keys = set(self._index.keys()).symmetric_difference(other._index.keys())
return self.__class__(conditionalyield(keys,self._index,other._index))
def __and__(self, other):
keys = self._index.keys().__and__(other._index.keys())
return self.__class__(conditionalyield(keys,self._index,other._index))
def __xor__(self, other):
keys = self._index.keys().__xor__(other._index.keys())
return self.__class__(conditionalyield(keys,self._index,other._index))
def __or__(self, other):
keys = self._index.keys().__or__(other._index.keys())
return self.__class__(conditionalyield(keys, self._index, other._index))
def __sub__(self, other):
keys = self._index.keys().__sub__(other._index.keys())
return self.__class__(conditionalyield(keys, self._index, other._index))
#
# common methods
#
def __len__(self):
return self._index.__len__()
def __contains__(self, item):
'''
Based on uid only.
'''
return self._index.__contains__(item)
def pop(self, idx=-1):
'''
Retrieves the item at location `idx` and also removes it. Defaults to end of list.
'''
item = self._list.pop(idx)
del self._index[item.__uid__()]
return item
def update(self, *iterables):
'''
Uodate the existing items with the items in `*iterables`.
Returns reference.
'''
_add = self.add
for iterable in iterables:
for value in iterable:
_add(value)
return self
#--------------------------------------------------------------------------------
class Graph:
'''
A graph composed of nodes and edges, both stored in SQLite database.
'''
def __init__(self, path=':memory:'):
'''
Instantiating it without argument creates an in-memory database,
pass in a path to create or open a database in a file
memdb = Graph()
filedb = Graph(path)
'''
self.path = path
if os.path.exists(path):
## connect to existing database
self.connection = apsw.Connection(self.path)
else:
## create new database and set up tables
self.connection = apsw.Connection(self.path)
self.reset()
self.resetfts()
def reset(self):
'''
Drop the tables and recreate them.
*All data will be lost!*
'''
cursor=self.cursor()
cursor.execute('''
DROP TABLE IF EXISTS nodes;
DROP TABLE IF EXISTS edges;
DROP TABLE IF EXISTS settings;
DROP TABLE IF EXISTS cache;
DROP TABLE IF EXISTS changes;
CREATE TABLE IF NOT EXISTS nodes(uid TEXT PRIMARY KEY, kind TEXT, ctime REAL, mtime REAL, data TEXT);
CREATE TABLE IF NOT EXISTS edges(uid TEXT PRIMARY KEY, kind TEXT, startuid TEXT NOT NULL REFERENCES nodes(uid), enduid TEXT NOT NULL REFERENCES nodes(uid), ctime REAL, mtime REAL, data TEXT);
CREATE TABLE IF NOT EXISTS settings(key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS cache(key TEXT PRIMARY KEY, value TEXT);
CREATE TABLE IF NOT EXISTS changes(id INTEGER PRIMARY KEY AUTOINCREMENT, change TEXT);
''')
## store GraphyDB version that was used to create the database
self.savesetting('GraphyDB version', __version__)
def countchanges(self):
cursor=self.cursor()
n=cursor.execute('SELECT COUNT(*) FROM changes').fetchone()[0]
return n
def clearchanges(self):
## recreate table so it resets the IDs
cursor=self.cursor()
cursor.execute('''
DROP TABLE IF EXISTS changes;
CREATE TABLE changes(id INTEGER PRIMARY KEY AUTOINCREMENT, change TEXT);
VACUUM;
''')
def lastchanges(self):
if self.countchanges()==0:
## no changes
out = []
else:
cursor=self.cursor()
cid, change = cursor.execute('''
SELECT id, change FROM changes
ORDER BY id DESC LIMIT 1
''').fetchone()
change = json.loads(change)
if 'batch' not in change:
## single change item
out = [(cid, change)]
else:
## possibly multiple change items in same batch
rows = cursor.execute('''
SELECT id, change FROM changes
WHERE json_extract(change, "$.batch") = ? ORDER BY id''', [change['batch']]).fetchall()
out = [(cid, json.loads(change)) for cid, change in rows]
return out
def deletechange(self, id):
cursor=self.cursor()
cursor.execute('DELETE FROM changes WHERE id = ?', [id])
def addchange(self, new=None, old=None, batch=None):
if new is None and old is None:
return
change = {}
if new is None:
## this is a delete
change['uid'] = old['uid']
change['-'] = cleandata(old.data)
elif old is None:
## this is add
change['uid'] = new['uid']
change['+'] = cleandata(new.data)
else:
## item internals have changed
d = diff(old.data, new.data, new._changedkeys)
if len(d) == 0:
return
change['uid'] = new['uid']
change.update(d)
change.setdefault('time', time.time())
change.setdefault('rev', generateUUID())
if batch is not None:
change['batch'] = batch
change = json.dumps(change)
cursor=self.cursor()
row=cursor.execute('''INSERT INTO changes (change) VALUES (?)''', [change])
def undo(self):
'''
Undo the last change to the graph.
'''
changes = []
changebatch=reversed(self.lastchanges())
for i, change in changebatch:
if '+' in change and '-' not in change:
## change was to add item so undo removes it
action = "-"
item = self.getuid(change['uid'])
item.delete(setchange=False)
elif '-' in change and '+' not in change:
## change was to remove item so undo adds it
action = "+"
data = change['-']
if 'startuid' in data:
item = Edge(data, graph=self)
else:
item = Node(data, graph=self)
item.save(setchange=False)
elif '-' in change and '+' in change:
## change was to add and remove internals so undo reverses them
action = "*"
item = self.getuid(change['uid'])
item.data = patch(item.data, change, reverse=True)
item.save(setchange=False, force=True)
else:
raise GraphyDBException('Unknown undo action')
changes.append((action, change['uid']))
self.deletechange(i)
return changes
def resetfts(self, nodefields=None, edgefields=None):
## remove tables
cursor=self.cursor()
cursor.execute('''
DROP TABLE IF EXISTS nodefts;
DROP TABLE IF EXISTS edgefts;
''')
## create node table
if nodefields is not None:
nodefields = set(nodefields)
VSTR = ",".join(nodefields) + ",uid UNINDEXED"
cursor.execute('CREATE VIRTUAL TABLE IF NOT EXISTS nodefts USING fts5({});'.format(VSTR))
## create edge table
if edgefields is not None:
edgefields = set(edgefields)
ESTR = ",".join(edgefields)+",uid UNINDEXED"
cursor.execute('CREATE VIRTUAL TABLE IF NOT EXISTS edgefts USING fts5({});'.format(ESTR))
def getsetting(self, key, default=None):
'''
Read back a previously saved setting. Value will be de-jsonified.
'''
cursor=self.cursor()
row = cursor.execute('SELECT value FROM settings WHERE key = ?',[key]).fetchone()
if row is None:
return default
value = json.loads(row[0])
return value
def savesetting(self, key, value):
'''
A simple key-value store to save settings. Values will be jsonified.
'''
cursor=self.cursor()
settings = cursor.execute('INSERT OR REPLACE INTO settings(key, value) VALUES(?,?)', (key, json.dumps(value)) )
def cached(self, key):
'''
Read back a previously cached item. Value will be de-jsonified.
'''
cursor=self.cursor()
row = cursor.execute('SELECT value FROM cache WHERE key = ?',[key]).fetchone()
if row is None:
raise KeyError
return json.loads(row[0])
def cache(self, key, value):
'''
A simple key-value store to serve as a cache. Values will be stored jsonified under the given key.
'''
cursor=self.cursor()
settings = cursor.execute('INSERT OR REPLACE INTO cache(key, value) VALUES(?,?)', (key, json.dumps(value)) )
def cursor(self):
'''
Return an APSW cursor.
This can be used to excute SQL queries directly on the database.
'''
return self.connection.cursor()
@property
def stats(self):
'''
Return basic stats of the graph such as the number of edges and nodes.
'''
cursor=self.cursor()
Nn = cursor.execute('SELECT COUNT(*) FROM nodes').fetchone()[0]
Ne = cursor.execute('SELECT COUNT(*) FROM edges').fetchone()[0]
nkinds = {}
for k,n in cursor.execute('SELECT kind, COUNT(kind) FROM nodes GROUP BY kind'):
nkinds[k]=n
ekinds = {}
for k,n in cursor.execute('SELECT kind, COUNT(kind) FROM edges GROUP BY kind'):
ekinds[k]=n
S = {"Total nodes":Nn, "Total edges":Ne, "Node kinds":nkinds, "Edge kinds":ekinds}
if self.path!=':memory:':
stat = os.stat(self.path)
size = stat.st_size
if size < 1000:
sizestr = "%dB"%size
elif size < 1000000:
sizestr = "%dK"%(size/1000)
else:
sizestr = "%dM"%(size/1000000)
S['File size']= sizestr
sversion = cursor.execute('SELECT sqlite_version()').fetchone()[0]
S['SQLite version'] = sversion
S['GraphyDB version'] = self.getsetting('GraphyDB version')
S['Changes'] = self.countchanges()
return S
def _parsechain(self, CHAIN, PARAM):
'''
Break down the chain of edges and nodes.
'''
aliases = {}
collect = None
left = None
search1 = re.compile('\(([\w:]+)\)')
search2 = re.compile('\[([\w:,]+)\]')
for p in CHAIN.split():
## parse kind of item
if p[-1] == '>':
item = {'type':'right','table':'edges','leftuid':'startuid','rightuid':'enduid','ftstable':'edgefts','columns':['data']}
elif p[0] == '<':
item = {'type':'left','table':'edges','leftuid':'enduid','rightuid':'startuid','ftstable':'edgefts','columns':['data']}
else:
item = {'type':'node','table':'nodes','leftuid':'uid','rightuid':'uid','ftstable':'nodefts','columns':['data']}
## parse aliases, extra parameters and kinds
so1=search1.search(p)
so2=search2.search(p)
if so1:
tmp = so1.group(1).split(':')
alias=tmp[0]
if len(tmp)==2:
item["kind"]=tmp[1]
elif so2:
s = so2.group(1).split(",")
tmp = s[0].split(':')
alias=tmp[0]
collect = item
if len(s)>1:
item['extra'] = {}
for c in s[1:]:
try:
col = '{} AS "{}"'.format(PARAM[c],c)
except KeyError:
raise GraphyDBException('Item "{}" not given an expansion'.format(c))
item['extra'][c]=col
## remove these extra columns from parameters
del PARAM[c]
if len(tmp)==2:
item["kind"]=tmp[1]
else:
raise GraphyDBException("Error in parsing format: '{}'".format(p) )
if alias in aliases:
raise GraphyDBException("Aliases must be unique ({} multiply defined)".format(alias) )
item['alias'] = alias
## link
if left is not None:
item['leftlink'] = left['alias']
left['rightlink'] = item['alias']
aliases[alias]=item
left = item
if collect is None:
collect = item
return aliases, collect
def fetch(self, CHAIN='(n)', WHERE=None, **args):
'''
This is the workhorse for fetching nodes and edges from the database. It's a thin wrapper around
SQL so most of the SQL operators are available.
**Keywords**
- `CHAIN`: Description of how to join together nodes and edges for the query.
A chain is composed of links read from left to right separated by spaces.
Each link can be a node "(n)" or and edge "-(e)>" or "<(e)-".
e.g. "(n1) -[e:Document,title]> (n2)".
The variable in the brackets is an alias for the link that can then be used
in other parts of the query and should be unique.
Square brackets indicate the link to be collected (otherwise defaults to right-most link).
Square brackets can also have other aliases separated by commas, these should be defined in parameters passed
to the function.
- `WHERE`: A string, or list of strings with SQL conditions. If it's a list the items will be ANDed together
- `GROUP`: String to follow SQLs GROUP BY
- `ORDER`: String to follow SQLs ORDER BY
- `LIMIT`: An interger to limit the numer of items returned
- `OFFSET`: Return items from offset, used in combination with `LIMIT`
- `COUNT`: The number of items satisfying the query will be returned
- `DISTINCT`: Distinct uids will be collected. [Defaults to `True`]
- `DEBUG`: If this is set to `True` the generated SQL and parameters will be returned without making the query.
For convenience `CHAIN` and `WHERE` are the first two implicit parameters.
**Parameters**
Every other keyword is treated as a parameter for defining returned values, FTS searches or SQL escaped parameters.
Any extra aliases in the collected item should be defined as a parameter. The result will be available as a key
in the item with the alias preceded by an underscore (i.e. an unsaved value).
If a parameter is the same as a link-alias with "_fts" appended then the value is to be
used in an FTS match.
Values to be SQL escaped whould be inserted by name (e.g. ':p1') where appropriate and the value given by a parameter
(e.g. p1=10).
**Example**
# Fetch the nodes of kind "Person" that are
# connected by edges of kind "Author" to other
# nodes of kind "Document" with tiles containing "Quantum"
# and also collect the author order
g.fetch('(n:Document) <(e:Author)- [p:Person,aorder]', n_fts='title: Quantum', aorder='e.data.order')
'''
## extract the SQL pieces with sensible defaults
WHERE=ensurelist(WHERE)
ORDER=args.get('ORDER', None)
GROUP=args.get('GROUP', None)
LIMIT=args.get('LIMIT', None)
OFFSET=args.get('OFFSET', None)
COUNT=args.get('COUNT', False)
DISTINCT=args.get('DISTINCT', True)
DEBUG=args.get('DEBUG', False)
## everything else is a parameter of some sort
PARAM = {k:v for k,v in args.items() if k not in FETCHKEYWORDS}
## interpret table joins
aliases, collect = self._parsechain(CHAIN, PARAM)
SQL = []
SQLFTS = []
## SQL to attach FTS tables ... need to do this fist so we can expand fts aliases with tablename
ftsexpansions = {}
for k in aliases.keys():
ftskey = k+'_fts'
if ftskey in list(PARAM.keys()):
## N.B. want a copy of PARAM.keys() as we might modify PARAM
item = aliases[k]
SQLFTS.append('\nJOIN {ftstable} "{ftskey}" ON {alias}.uid = {ftskey}.uid'.format(
ftstable=item['ftstable'], ftskey=ftskey, alias=k))
## add an item to PARAM with the FTS term so it's SQL escaped
valuekey = ftskey+'_value'
## N.B. proper reference using alias has to have table name, e.g. n1_fts.nodefts
WHERE.append('{ftskey}.{ftstable} MATCH :{ftsvalue}'.format(
ftskey=ftskey, ftstable=aliases[k]['ftstable'], ftsvalue=valuekey))
PARAM[valuekey] = PARAM[ftskey]
del PARAM[ftskey]
ftsexpansions[ftskey] = "{}.{}".format(ftskey,aliases[k]['ftstable'])
def expandfts(ftsstring, ftsexpansions):
for ftskey, ftsexpanded in ftsexpansions.items():
ftsstring = ftsstring.replace(ftskey, ftsexpanded)
return ftsstring
##
## SELECT
##
collect['distinct'] = 'DISTINCT' if DISTINCT else ''
colkeys = collect['columns'].copy()
colsql = ['{}.{}'.format(collect['alias'],c) for c in colkeys]
for k,v in collect.get('extra',{}).items():
colkeys.append(k)
v = jsonextract(v)
v = expandfts(v, ftsexpansions)
colsql.append(v)
collect['collectcolumns'] = ', '.join(colsql)
if COUNT:
SQL.append('SELECT COUNT({distinct} {alias}.uid) FROM {table} {alias}'.format(**collect))
else:
SQL.append('SELECT {distinct} {collectcolumns} FROM {table} {alias}'.format(**collect))
##
## JOINs
##
## link tables together
l = collect
while 'rightlink' in l:
r = aliases[l['rightlink']]
r['join'] = '{}.{} = {}.{}'.format(r['alias'], r['leftuid'], l['alias'], l['rightuid'])
if 'kind' in r:
r['join'] += ' AND {}.kind = "{}"'.format(r['alias'],r['kind'])
SQL.append('\nJOIN {table} {alias} ON {join}'.format(**r))
l=r
r = collect
while 'leftlink' in r:
l = aliases[r['leftlink']]
l['join'] = '{}.{} = {}.{}'.format(l['alias'], l['rightuid'], r['alias'], r['leftuid'] )
if 'kind' in l:
l['join'] += ' AND {alias}.kind = "{kind}"'.format(**l)
SQL.append('\nJOIN {table} {alias} ON {join}'.format(**l))
r=l
SQL.extend(SQLFTS)
##
## WHERE
##
if 'kind' in collect:
WHERE.append('{alias}.kind = "{kind}"'.format(**collect))
if len(WHERE)>0:
SQL.append('\nWHERE '+ ' AND '.join([jsonextract(w) for w in WHERE]))
##
## GROUP BY
##
if GROUP is not None:
SQL.append('\nGROUP BY {}'.format(expandfts(jsonextract(GROUP), ftsexpansions)))
##
## ORDER BY
##
if ORDER is not None:
SQL.append('\nORDER BY {}'.format(expandfts(jsonextract(ORDER),ftsexpansions)))
##
## LIMIT and OFFSET
##
if LIMIT is not None:
SQL.append('\nLIMIT {}'.format(LIMIT))
if OFFSET is not None:
SQL.append(' OFFSET {}'.format(OFFSET))
SQL = ''.join(SQL)
##
## Return sql statement if debug
##
if DEBUG:
return SQL, PARAM
cursor=self.cursor()
## faster to first create list
items = []
##
## COUNT
##
if COUNT:
c = cursor.execute(SQL, PARAM).fetchone()[0]
return c
##
## COLLECT
##
elif collect['type']=='node':
for row in cursor.execute(SQL, PARAM):
args = json.loads(row[colkeys.index('data')])
for c,v in zip(colkeys, row):
if c == 'data':
continue