Skip to content

Instantly share code, notes, and snippets.

@ihercowitz
Last active November 12, 2015 13:08
Show Gist options
  • Save ihercowitz/bc03efe7830df15f76c2 to your computer and use it in GitHub Desktop.
Save ihercowitz/bc03efe7830df15f76c2 to your computer and use it in GitHub Desktop.
A very simple memory DB like REDIS
def set(variable, value, varmap):
varmap[variable]=int(value)
def get(variable, varmap):
try:
ret=varmap[variable]
except:
ret="NULL"
print(ret)
def unset(variable, varmap):
del varmap[variable]
def numequalto(value, varmap):
print(len([k for k,v in varmap.iteritems() if varmap[k]==int(value)]))
def begin(varmap, level):
return REPL(varmap, level=(level+1))
def commit(varmap, level):
if level > 0:
return varmap
else:
print("NO TRANSACTION")
common_fn = {
'SET':set,
'GET':get,
'UNSET':unset,
'NUMEQUALTO':numequalto,
}
transaction_fn = {
'BEGIN':begin,
'COMMIT':commit
}
def REPL(varmap=dict(), level=0):
while True:
cmd=raw_input("=>> ").split()
if cmd[0] == "END":
return False
elif cmd[0] == "ROLLBACK":
if level > 0:
return
else:
print("NO TRANSACTION")
elif cmd[0] in common_fn:
cmd.append(varmap)
common_fn[cmd[0]](*cmd[1::])
elif cmd[0] in transaction_fn:
x = transaction_fn[cmd[0]](varmap, level)
if type(x) == dict:
varmap.update(x)
while level > 0:
return varmap
else:
print("Invalid Command")
if __name__=="__main__":
try:
REPL()
except:
print("Goodbye")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment