Skip to content

Instantly share code, notes, and snippets.

@zh4ngx
Created October 2, 2013 07:59
Show Gist options
  • Save zh4ngx/6790403 to your computer and use it in GitHub Desktop.
Save zh4ngx/6790403 to your computer and use it in GitHub Desktop.
Simple key-value datastore. Basic data & transaction commands.
## SUMMARY
# Use Hash($db) to maintain state
# Track # open transactions
# Memoize modified vars per transaction ($history)
# Be naught, use globals (not thread-safe)
$db = {}
$transactions = 0
$history = {}
# Utility for taking snapshot of var
def memoize k
$history[$transactions][k] = $history[$transactions].fetch k, get(k)
end
# Data commands
def set k, v
memoize k if $transactions > 0
$db[k] = v
end
def get k
$db.fetch k, "NULL"
end
def unset k
memoize k if $transactions > 0
$db.delete k
end
def num_eql_to v
$db.select { |k,val| v == val }.length
end
# Transaction commands
def _begin
$transactions += 1
$history[$transactions] = {}
end
def rollback
# Guard against empty transactions
if $transactions == 0
puts "NO TRANSACTION"
return
end
# Restore state from last transaction
$db.merge! $history[$transactions]
# Scrub this transaction
$history.delete $transactions
$transactions -= 1
end
def commit
if $transactions == 0
puts "NO TRANSACTION"
else
$transactions = 0
$history = {}
end
end
# Main runner
while cmd = gets
case cmd
when /SET (?<key>\w+) (?<value>\w+)/
set $~[:key], $~[:value]
when cmd = /GET (?<key>\w+)/
puts get $~[:key]
when /UNSET (?<key>\w+)/
unset $~[:key]
when /NUMEQUALTO (?<value>\w+)/
puts num_eql_to $~[:value]
when /BEGIN/
_begin
when /ROLLBACK/
rollback
when /COMMIT/
commit
when /END/
exit 0
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment