-
Notifications
You must be signed in to change notification settings - Fork 0
/
database_prompt.rb
executable file
·84 lines (68 loc) · 1.59 KB
/
database_prompt.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# frozen_string_literal: true
require 'singleton'
class DatabasePrompt
include Singleton
PROMPT = '>> '
def self.start
print PROMPT
while (input = gets.chomp)
command, *args = input.split
case command
when 'SET'
instance.set(*args)
when 'GET'
puts instance.get(*args)
when 'DELETE'
instance.delete(*args)
when 'COUNT'
puts instance.count(*args)
when 'END'
break
when 'BEGIN'
instance.transaction
when 'ROLLBACK'
instance.rollback || puts('TRANSACTION NOT FOUND')
when 'COMMIT'
instance.commit
end
print PROMPT
end
end
def initialize
@destructive_commands = []
@transactions = []
@database = {}
end
def set(name, value)
@destructive_commands << [:set, name, @database[name]]
@database[name] = value
end
def get(name)
@database.fetch(name, 'NULL')
end
def delete(name)
@destructive_commands << [:delete, name, @database.delete(name)]
end
def count(value)
@database.values.tally.fetch(value, 0)
end
def transaction
@transactions.push(@destructive_commands.size).uniq!
end
def rollback
return if @transactions.empty?
transaction_commands = @destructive_commands.slice!(@transactions.pop..-1)
transaction_commands.reverse_each do |command|
case command
in :set | :delete, name, String => previous_value
@database[name] = previous_value
else
@database.delete(name)
end
end
end
def commit
@transactions.clear
end
end
DatabasePrompt.start