-
-
Save rcuhljr/6874229 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from collections import Counter | |
class State(dict): | |
def __init__(self, parent, counter, committed): | |
self.parent = parent | |
self.counter = counter | |
self.committed = committed | |
def fetch(self,var): | |
if var in self: | |
return self.get(var) | |
if self.parent is None: | |
return False | |
return self.parent.get(var) | |
def do_set(self,var,value): | |
if var in self: | |
self.counter[self[var]] -= 1 | |
self[var] = value | |
self.counter[value] += 1 | |
def unset(self,var): | |
if self.fetch(var): | |
self.counter[self.fetch(var)] -= 1 | |
self[var] = None | |
def numequalto(self,value): | |
if value in self.counter: | |
return self.counter[value] | |
if self.parent is None: | |
return 0 | |
return self.parent.numequalto(value) | |
def commit(self): | |
if self.committed: | |
return False | |
self.committed = True | |
return self.parent.commit() or True | |
def begin(self): | |
return State(self, self.counter.copy(), False) | |
def rollback(self): | |
return self.parent | |
def can_rollback(self): | |
return not self.committed | |
def CLI(): | |
"Simple CLI without error checking / input sanitizing" | |
db = State(None, Counter(), True) | |
while True: | |
line = input().upper() | |
if line == 'END': break | |
elif line == 'BEGIN': db = db.begin() | |
elif line == 'ROLLBACK': | |
if db.can_rollback(): | |
db = db.rollback() | |
else: | |
print("NO TRANSACTION") | |
elif line == "COMMIT": | |
if not db.commit(): | |
print("NO TRANSACTION") | |
else: | |
command,args = line.split(' ',1) | |
if command == "GET": | |
x = db.fetch(args) | |
if x: | |
print(x) | |
else: | |
print("NULL") | |
elif command == "UNSET": | |
db.unset(args) | |
elif command == "SET": | |
var,value = args.split() | |
db.do_set(var,int(value)) | |
elif command == "NUMEQUALTO": | |
print(db.numequalto(int(args))) | |
if __name__ == '__main__': | |
CLI() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment