Skip to content

Instantly share code, notes, and snippets.

@chelseatroy
Created May 27, 2019 03:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chelseatroy/c6e3a197334e88f8d30eb6608523fb80 to your computer and use it in GitHub Desktop.
Save chelseatroy/c6e3a197334e88f8d30eb6608523fb80 to your computer and use it in GitHub Desktop.
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