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?
More Space Efficient Transaction Management
class Database
def initialize
@count_versions = [Hash.new(0)]
@db_versions = [Hash.new()]
@tier = 0
end
# CRUD COMMANDS
def set(key, value)
@db_versions[@tier][key] = value
@count_versions[@tier][value] += 1
puts "Current state of database: #{@db_versions.inspect}"
return nil
end
def get(key)
puts "Current state of database: #{@db_versions.inspect}"
merge_candidate.fetch(key, "NULL")
end
def count(value)
puts "Current state of database: #{@db_versions.inspect}"
count_candidate.fetch(value, 0)
end
#TRANSACTION MANAGEMENT
def begin()
@db_versions.push(Hash.new())
@count_versions.push(Hash.new(0))
@tier += 1
puts "Current state of database: #{@db_versions.inspect}"
return nil
end
def rollback()
if @tier == 0
return "No transaction in progress"
end
@db_versions.pop
@count_versions.pop
@tier -= 1
puts "Current state of database: #{@db_versions.inspect}"
return nil
end
def commit()
if @tier == 0
return "No transaction in progress"
end
@db_versions[-2] = merge_candidate(@tier, @tier-1, @db_versions[0])
@count_versions[-2] = count_candidate(@tier, @tier-1, @count_versions[0])
@db_versions.pop
@count_versions.pop
@tier -= 1
puts "Current state of database: #{@db_versions.inspect}"
return nil
end
def merge_candidate(start_tier=@tier, end_tier=0, merge_item=@db_versions[end_tier])
if start_tier == end_tier
return merge_item
else
step = @db_versions[start_tier].merge(@db_versions[start_tier-1]) { |key, canonical_value, transactional_value|
transactional_value || canonical_value
}
return merge_candidate start_tier-1, end_tier,step
end
end
def count_candidate(start_tier=@tier, end_tier=0, merge_item=@count_versions[end_tier])
if start_tier == end_tier
return merge_item
else
step = @count_versions[start_tier].merge(@count_versions[start_tier-1]) { |key, canonical_value, transactional_value|
canonical_value + transactional_value
}
return count_candidate start_tier-1, step
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment