Last active
May 27, 2019 03:01
-
-
Save chelseatroy/63a25a991b969238ff95dc0fde4a413b to your computer and use it in GitHub Desktop.
First Pass at Transactions
This file contains 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() | |
@db_versions.push(Hash.new()) | |
@count_versions.push(Hash.new(0)) | |
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[-2].merge(@db_versions[-1]) | |
@count_versions[-2] = @count_versions[-2].merge(@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