Skip to content

Instantly share code, notes, and snippets.

@chelseatroy

chelseatroy/database.rb

Last active May 27, 2019
Embed
What would you like to do?
First Pass at 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()
@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
You can’t perform that action at this time.