public
Created — forked from MDamien/gist:6863909

  • Download Gist
gistfile1.py
Python
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
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()

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.