Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Space Inefficient Transactions
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
You can’t perform that action at this time.