Created
May 27, 2019 03:21
-
-
Save chelseatroy/c6e3a197334e88f8d30eb6608523fb80 to your computer and use it in GitHub Desktop.
Space Inefficient Transactions
This file contains hidden or 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
class Database | |
def initialize | |
@count_versions = [Hash.new(0)] | |
@db_versions = [Hash.new()] | |
end | |
# CRUD COMMANDS | |
def set(key, value) | |
@db_versions[-1][key] = value | |
@count_versions[-1][value] += 1 | |
puts "Current state of database: #{@db_versions.inspect}" | |
return nil | |
end | |
def get(key) | |
puts "Current state of database: #{@db_versions.inspect}" | |
@db_versions[-1].fetch(key, "NULL") | |
end | |
def count(value) | |
@count_versions[-1].fetch(value, 0) | |
end | |
#TRANSACTION MANAGEMENT | |
def begin() | |
@draft = @db_versions[-1].clone | |
@draft_count = @count_versions[-1].clone | |
@db_versions.push(@draft) | |
@count_versions.push(@draft_count) | |
puts "Current state of database: #{@db_versions.inspect}" | |
return nil | |
end | |
def rollback() | |
if @db_versions.length == 1 | |
return "No transaction in progress" | |
end | |
@db_versions.pop | |
@count_versions.pop | |
puts "Current state of database: #{@db_versions.inspect}" | |
return nil | |
end | |
def commit() | |
if @db_versions.length == 1 | |
return "No transaction in progress" | |
end | |
@db_versions[-2] = @db_versions[-1] | |
@count_versions[-2] = @count_versions[-1] | |
@db_versions.pop | |
@count_versions.pop | |
puts "Current state of database: #{@db_versions.inspect}" | |
return nil | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment