-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.py
More file actions
78 lines (66 loc) · 2.21 KB
/
Copy pathdb.py
File metadata and controls
78 lines (66 loc) · 2.21 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
class MemDB:
def __init__(self):
self.disk = {}
self.dirty = {} # items not committed to disk yet
self.log = list() # maintains state/changes during transactions
self.trans_count = 0
def set(self, key, value):
if self.trans_count == 0:
self.disk[key] = value
else:
if key in self.dirty:
self.log.append((key, self.dirty.get(key), value)) # (key, oldvalue, newvalue)
else:
self.log.append((key, self.disk.get(key), value))
self.dirty[key] = value
def get(self, key):
if key in self.dirty:
return self.dirty[key]
return self.disk.get(key, None)
def remove(self, key):
if self.trans_count == 0:
del self.disk[key]
else:
if key in self.dirty:
self.log.append((key, self.dirty.get(key), None))
else:
self.log.append((key, self.disk.get(key), None))
self.dirty[key] = None
def begin(self):
"""
Opens a new transaction block. Transaction blocks can be nested. Any data command run outside
of a transaction block committed immediately.
"""
self.log.append("BEGIN")
self.trans_count += 1
def rollback(self):
"""
Undo all commands in most recent transaction block and close block.
"""
if self.trans_count == 0:
return "NO TRANSACTION"
cur = self.log.pop()
while cur != "BEGIN":
key, old, new = cur
self.dirty[key] = old
cur = self.log.pop()
self.trans_count -= 1
if not self.trans_count:
self.clear()
def commit(self):
"""
Closes all open transaction blocks and commits all changes to disk.
"""
if self.trans_count == 0:
return "NO TRANSACTION"
for key in self.dirty:
value = self.dirty[key]
if value == None:
del self.disk[key]
else:
self.disk[key] = value
self.clear()
def clear(self):
self.trans_count = 0
del self.log[:]
self.dirty.clear()