-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmemoryDB.cpp
More file actions
53 lines (47 loc) · 1.49 KB
/
memoryDB.cpp
File metadata and controls
53 lines (47 loc) · 1.49 KB
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
#include "memoryDB.h"
#include <iostream>
using namespace std;
class memoryDB : public InMemoryDB {
private:
unordered_map<string, int> mainStore;
unique_ptr<unordered_map<string, int>> transactionStore;
bool inTransaction = false;
public:
int get(const string& key) override {
if (inTransaction && transactionStore->count(key))
return (*transactionStore)[key];
if (mainStore.count(key))
return mainStore[key];
throw runtime_error("Key not found");
}
void put(const string& key, int value) override {
if (!inTransaction) {
throw runtime_error("No transaction is in progress.");
}
(*transactionStore)[key] = value;
}
void begin_transaction() override {
if (inTransaction) {
throw runtime_error("Transaction already in progress.");
}
inTransaction = true;
transactionStore.reset(new unordered_map<string, int>);
}
void commit() override {
if (!inTransaction) {
throw runtime_error("No transaction is in progress.");
}
for (const auto& kv : *transactionStore) {
mainStore[kv.first] = kv.second;
}
transactionStore.reset(nullptr);
inTransaction = false;
}
void rollback() override {
if (!inTransaction) {
throw runtime_error("No transaction is in progress.");
}
transactionStore.reset(nullptr);
inTransaction = false;
}
};