Repository navigation
Expand file tree
/
Copy pathcli.py
More file actions
153 lines (125 loc) · 4.34 KB
/
Copy pathcli.py
File metadata and controls
153 lines (125 loc) · 4.34 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
import sys
import argparse
from collections import defaultdict
class GhostDB:
def __init__(self, debug=False):
self.db = {}
self.value_counts = defaultdict(int)
self.transactions = []
self.debug = debug
def _debug_print(self, *args):
if self.debug:
print("[DEBUG]:", *args)
def _set(self, key, value):
old_value = self.db.get(key)
if old_value:
self.value_counts[old_value] -= 1
self.db[key] = value
self.value_counts[value] += 1
self._debug_print(f"SET {key} = {value}")
def _unset(self, key):
if key in self.db:
old_value = self.db[key]
self.value_counts[old_value] -= 1
del self.db[key]
self._debug_print(f"UNSET {key}")
def set(self, key, value):
if self.transactions:
if key not in self.transactions[-1]:
self.transactions[-1][key] = self.db.get(key)
self._set(key, value)
def get(self, key):
return self.db.get(key, "NULL")
def unset(self, key):
if self.transactions:
if key not in self.transactions[-1]:
self.transactions[-1][key] = self.db.get(key)
self._unset(key)
def counts(self, value):
return self.value_counts[value]
def find(self, value):
return [k for k, v in self.db.items() if v == value]
def begin(self):
self.transactions.append({})
self._debug_print("BEGIN")
def rollback(self):
if not self.transactions:
print("NO TRANSACTION")
return
changes = self.transactions.pop()
for key, old_value in changes.items():
if old_value is None:
self._unset(key)
else:
self._set(key, old_value)
self._debug_print("ROLLBACK")
def commit(self):
if not self.transactions:
print("NO TRANSACTION")
return
current = self.transactions.pop()
if self.transactions:
parent = self.transactions[-1]
for key, old_value in current.items():
if key not in parent:
parent[key] = old_value
self._debug_print("COMMIT (merged with parent)")
else:
self._debug_print("COMMIT (top level, applied)")
def process(self, line):
parts = line.strip().split()
if not parts:
return False
cmd = parts[0].upper()
if cmd == 'END':
return True
elif cmd == 'SET' and len(parts) == 3:
self.set(parts[1], parts[2])
elif cmd == 'GET' and len(parts) == 2:
print(self.get(parts[1]))
elif cmd == 'UNSET' and len(parts) == 2:
self.unset(parts[1])
elif cmd == 'COUNTS' and len(parts) == 2:
print(self.counts(parts[1]))
elif cmd == 'FIND' and len(parts) == 2:
print(" ".join(self.find(parts[1])) or "NULL")
elif cmd == 'BEGIN':
self.begin()
elif cmd == 'ROLLBACK':
self.rollback()
elif cmd == 'COMMIT':
self.commit()
else:
print("INVALID COMMAND")
return False
def interactive_mode(db):
print("Interactive DB started. Type END or Ctrl+D/Z to exit.")
try:
for line in sys.stdin:
if db.process(line):
break
except (EOFError, KeyboardInterrupt):
print("\nGoodbye!")
def script_mode(db, filepath):
try:
with open(filepath, 'r') as f:
for line in f:
print(f"> {line.strip()}")
if db.process(line):
break
except FileNotFoundError:
print(f"File not found: {filepath}")
def main():
parser = argparse.ArgumentParser(description="In-Memory DB CLI")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('--interactive', action='store_true', help='Run in interactive mode')
group.add_argument('--script', type=str, help='Path to script file')
parser.add_argument('--debug', action='store_true', help='Enable debug output')
args = parser.parse_args()
db = GhostDB(debug=args.debug)
if args.interactive:
interactive_mode(db)
elif args.script:
script_mode(db, args.script)
if __name__ == '__main__':
main()