-
Notifications
You must be signed in to change notification settings - Fork 3
/
17-buzzdb.cpp
716 lines (584 loc) · 20.7 KB
/
17-buzzdb.cpp
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <iostream>
#include <chrono>
#include <list>
#include <unordered_map>
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <sstream>
#include <limits>
#include <thread>
#include <queue>
enum FieldType { INT, FLOAT, STRING };
// Define a basic Field variant class that can hold different types
class Field {
public:
FieldType type;
std::unique_ptr<char[]> data;
size_t data_length;
public:
Field(int i) : type(INT) {
data_length = sizeof(int);
data = std::make_unique<char[]>(data_length);
std::memcpy(data.get(), &i, data_length);
}
Field(float f) : type(FLOAT) {
data_length = sizeof(float);
data = std::make_unique<char[]>(data_length);
std::memcpy(data.get(), &f, data_length);
}
Field(const std::string& s) : type(STRING) {
data_length = s.size() + 1; // include null-terminator
data = std::make_unique<char[]>(data_length);
std::memcpy(data.get(), s.c_str(), data_length);
}
Field& operator=(const Field& other) {
if (&other == this) {
return *this;
}
type = other.type;
data_length = other.data_length;
std::memcpy(data.get(), other.data.get(), data_length);
return *this;
}
Field(Field&& other){
type = other.type;
data_length = other.data_length;
std::memcpy(data.get(), other.data.get(), data_length);
}
FieldType getType() const { return type; }
int asInt() const {
return *reinterpret_cast<int*>(data.get());
}
float asFloat() const {
return *reinterpret_cast<float*>(data.get());
}
std::string asString() const {
return std::string(data.get());
}
std::string serialize() {
std::stringstream buffer;
buffer << type << ' ' << data_length << ' ';
if (type == STRING) {
buffer << data.get() << ' ';
} else if (type == INT) {
buffer << *reinterpret_cast<int*>(data.get()) << ' ';
} else if (type == FLOAT) {
buffer << *reinterpret_cast<float*>(data.get()) << ' ';
}
return buffer.str();
}
void serialize(std::ofstream& out) {
std::string serializedData = this->serialize();
out << serializedData;
}
static std::unique_ptr<Field> deserialize(std::istream& in) {
int type; in >> type;
size_t length; in >> length;
if (type == STRING) {
std::string val; in >> val;
return std::make_unique<Field>(val);
} else if (type == INT) {
int val; in >> val;
return std::make_unique<Field>(val);
} else if (type == FLOAT) {
float val; in >> val;
return std::make_unique<Field>(val);
}
return nullptr;
}
void print() const{
switch(getType()){
case INT: std::cout << asInt(); break;
case FLOAT: std::cout << asFloat(); break;
case STRING: std::cout << asString(); break;
}
}
};
class Tuple {
public:
std::vector<std::unique_ptr<Field>> fields;
void addField(std::unique_ptr<Field> field) {
fields.push_back(std::move(field));
}
size_t getSize() const {
size_t size = 0;
for (const auto& field : fields) {
size += field->data_length;
}
return size;
}
std::string serialize() {
std::stringstream buffer;
buffer << fields.size() << ' ';
for (const auto& field : fields) {
buffer << field->serialize();
}
return buffer.str();
}
void serialize(std::ofstream& out) {
std::string serializedData = this->serialize();
out << serializedData;
}
static std::unique_ptr<Tuple> deserialize(std::istream& in) {
auto tuple = std::make_unique<Tuple>();
size_t fieldCount; in >> fieldCount;
for (size_t i = 0; i < fieldCount; ++i) {
tuple->addField(Field::deserialize(in));
}
return tuple;
}
void print() const {
for (const auto& field : fields) {
field->print();
std::cout << " ";
}
std::cout << "\n";
}
};
static constexpr size_t PAGE_SIZE = 1024; // Fixed page size
static constexpr size_t MAX_SLOTS = 100; // Fixed number of slots
uint16_t INVALID_VALUE = std::numeric_limits<uint16_t>::max(); // Sentinel value
struct Slot {
bool empty = true; // Is the slot empty?
uint16_t offset = INVALID_VALUE; // Offset of the slot within the page
uint16_t length = INVALID_VALUE; // Length of the slot
};
// Slotted Page class
class SlottedPage {
public:
std::unique_ptr<char[]> page_data = std::make_unique<char[]>(PAGE_SIZE);
size_t metadata_size = sizeof(Slot) * MAX_SLOTS;
SlottedPage(){
// Empty page -> initialize slot array inside page
Slot* slot_array = reinterpret_cast<Slot*>(page_data.get());
for (size_t slot_itr = 0; slot_itr < MAX_SLOTS; slot_itr++) {
slot_array[slot_itr].empty = true;
slot_array[slot_itr].offset = INVALID_VALUE;
slot_array[slot_itr].length = INVALID_VALUE;
}
}
// Add a tuple, returns true if it fits, false otherwise.
bool addTuple(std::unique_ptr<Tuple> tuple) {
// Serialize the tuple into a char array
auto serializedTuple = tuple->serialize();
size_t tuple_size = serializedTuple.size();
//std::cout << "Tuple size: " << tuple_size << " bytes\n";
assert(tuple_size == 38);
// Check for first slot with enough space
size_t slot_itr = 0;
Slot* slot_array = reinterpret_cast<Slot*>(page_data.get());
for (; slot_itr < MAX_SLOTS; slot_itr++) {
if (slot_array[slot_itr].empty == true and
slot_array[slot_itr].length >= tuple_size) {
break;
}
}
if (slot_itr == MAX_SLOTS){
//std::cout << "Page does not contain an empty slot with sufficient space to store the tuple.";
return false;
}
// Identify the offset where the tuple will be placed in the page
// Update slot meta-data if needed
slot_array[slot_itr].empty = false;
size_t offset = INVALID_VALUE;
if (slot_array[slot_itr].offset == INVALID_VALUE){
if(slot_itr != 0){
auto prev_slot_offset = slot_array[slot_itr - 1].offset;
auto prev_slot_length = slot_array[slot_itr - 1].length;
offset = prev_slot_offset + prev_slot_length;
}
else{
offset = metadata_size;
}
slot_array[slot_itr].offset = offset;
}
else{
offset = slot_array[slot_itr].offset;
}
if(offset + tuple_size >= PAGE_SIZE){
slot_array[slot_itr].empty = true;
slot_array[slot_itr].offset = INVALID_VALUE;
return false;
}
assert(offset != INVALID_VALUE);
assert(offset >= metadata_size);
assert(offset + tuple_size < PAGE_SIZE);
if (slot_array[slot_itr].length == INVALID_VALUE){
slot_array[slot_itr].length = tuple_size;
}
// Copy serialized data into the page
std::memcpy(page_data.get() + offset,
serializedTuple.c_str(),
tuple_size);
return true;
}
void deleteTuple(size_t index) {
Slot* slot_array = reinterpret_cast<Slot*>(page_data.get());
size_t slot_itr = 0;
for (; slot_itr < MAX_SLOTS; slot_itr++) {
if(slot_itr == index and
slot_array[slot_itr].empty == false){
slot_array[slot_itr].empty = true;
break;
}
}
//std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void print() const{
Slot* slot_array = reinterpret_cast<Slot*>(page_data.get());
for (size_t slot_itr = 0; slot_itr < MAX_SLOTS; slot_itr++) {
if (slot_array[slot_itr].empty == false){
assert(slot_array[slot_itr].offset != INVALID_VALUE);
const char* tuple_data = page_data.get() + slot_array[slot_itr].offset;
std::istringstream iss(tuple_data);
auto loadedTuple = Tuple::deserialize(iss);
std::cout << "Slot " << slot_itr << " : [";
std::cout << (uint16_t)(slot_array[slot_itr].offset) << "] :: ";
loadedTuple->print();
}
}
std::cout << "\n";
}
};
const std::string database_filename = "buzzdb.dat";
class StorageManager {
public:
std::fstream fileStream;
size_t num_pages = 0;
public:
StorageManager(){
fileStream.open(database_filename, std::ios::in | std::ios::out);
if (!fileStream) {
// If file does not exist, create it
fileStream.clear(); // Reset the state
fileStream.open(database_filename, std::ios::binary | std::ios::out);
}
fileStream.close();
fileStream.open(database_filename, std::ios::in | std::ios::out);
fileStream.seekg(0, std::ios::end);
num_pages = fileStream.tellg() / PAGE_SIZE;
std::cout << "Storage Manager :: Num pages: " << num_pages << "\n";
if(num_pages == 0){
extend();
}
}
~StorageManager() {
if (fileStream.is_open()) {
fileStream.close();
}
}
// Read a page from disk
std::unique_ptr<SlottedPage> load(uint16_t page_id) {
fileStream.seekg(page_id * PAGE_SIZE, std::ios::beg);
auto page = std::make_unique<SlottedPage>();
// Read the content of the file into the page
if(fileStream.read(page->page_data.get(), PAGE_SIZE)){
//std::cout << "Page read successfully from file." << std::endl;
}
else{
std::cerr << "Error: Unable to read data from the file. \n";
exit(-1);
}
return page;
}
// Write a page to disk
void flush(uint16_t page_id, const std::unique_ptr<SlottedPage>& page) {
size_t page_offset = page_id * PAGE_SIZE;
// Move the write pointer
fileStream.seekp(page_offset, std::ios::beg);
fileStream.write(page->page_data.get(), PAGE_SIZE);
fileStream.flush();
}
// Extend database file by one page
void extend() {
std::cout << "Extending database file \n";
// Create a slotted page
auto empty_slotted_page = std::make_unique<SlottedPage>();
// Move the write pointer
fileStream.seekp(0, std::ios::end);
// Write the page to the file, extending it
fileStream.write(empty_slotted_page->page_data.get(), PAGE_SIZE);
fileStream.flush();
// Update number of pages
num_pages += 1;
}
};
using PageID = uint16_t;
class Policy {
public:
virtual void touch(PageID page_id) = 0;
virtual PageID evict() = 0;
virtual ~Policy() = default;
};
class FifoPolicy : public Policy {
private:
std::queue<PageID> queue;
size_t cacheSize;
public:
FifoPolicy(size_t cacheSize) : cacheSize(cacheSize) {}
void touch(PageID page_id) override {
if(queue.size() < cacheSize){
// For FIFO, we simply enqueue a newly touched page
queue.push(page_id);
}
}
PageID evict() override {
// Dequeue the oldest page and return its ID
PageID evictedPageId = INVALID_VALUE;
if(queue.size() != 0){
evictedPageId = queue.front();
queue.pop();
}
return evictedPageId;
}
};
class LruPolicy : public Policy {
private:
// List to keep track of the order of use
std::list<PageID> lruList;
// Map to find a page's iterator in the list efficiently
std::unordered_map<PageID, std::list<PageID>::iterator> map;
size_t cacheSize;
public:
LruPolicy(size_t cacheSize) : cacheSize(cacheSize) {}
void touch(PageID page_id) override {
// If page already in the list, remove it
if (map.find(page_id) != map.end()) {
lruList.erase(map[page_id]);
map.erase(page_id);
}
if(lruList.size() < cacheSize){
// Add the page to the front of the list
lruList.emplace_front(page_id);
map[page_id] = lruList.begin();
}
}
PageID evict() override {
// Evict the least recently used page
PageID evictedPageId = INVALID_VALUE;
if(lruList.size() != 0){
evictedPageId = lruList.back();
map.erase(evictedPageId);
lruList.pop_back();
}
return evictedPageId;
}
};
class TwoQPolicy : public Policy {
private:
size_t cacheSize;
std::list<PageID> FIFO; // Read-once pages (FIFO)
std::list<PageID> LRU; // Hot pages (LRU)
std::unordered_map<PageID, std::list<PageID>::iterator> pageMap;
public:
TwoQPolicy(size_t cache_size) : cacheSize(cache_size) {}
void touch(PageID page_id) {
printList("FIFO", FIFO);
printList("LRU", LRU);
// Check if page is already in cache
if (pageMap.find(page_id) != pageMap.end()) {
auto it = pageMap[page_id];
// If it's in FIFO, move to LRU
if (std::find(FIFO.begin(), FIFO.end(), page_id) != FIFO.end()) {
FIFO.erase(it);
LRU.push_front(page_id);
pageMap[page_id] = LRU.begin();
} else {
// If it's in LRU, move to the front
LRU.erase(it);
LRU.push_front(page_id);
pageMap[page_id] = LRU.begin();
}
} else {
// If cache is full, evict
if (FIFO.size() + LRU.size() >= cacheSize) {
evict();
}
// Add page to FIFO
FIFO.push_back(page_id);
pageMap[page_id] = std::prev(FIFO.end());
}
}
PageID evict() {
printList("FIFO", FIFO);
printList("LRU", LRU);
PageID evictedPageId = INVALID_VALUE;
if (!FIFO.empty()) {
evictedPageId = FIFO.front();
std::cout << "FIFO:: Evicting page " << evictedPageId << "\n";
FIFO.pop_front();
pageMap.erase(evictedPageId);
} else {
evictedPageId = LRU.back();
std::cout << "LRU:: Evicting page " << evictedPageId << "\n";
LRU.pop_back();
pageMap.erase(evictedPageId);
}
return evictedPageId;
}
void printList(std::string list_name, const std::list<PageID>& myList) {
std::cout << list_name << " :: ";
for (const PageID& value : myList) {
std::cout << value << ' ';
}
std::cout << '\n';
}
};
constexpr size_t MAX_PAGES_IN_MEMORY = 5;
class BufferManager {
private:
using PageMap = std::unordered_map<PageID, std::unique_ptr<SlottedPage>>;
StorageManager storage_manager;
PageMap pageMap;
std::unique_ptr<Policy> policy;
public:
BufferManager():
policy(std::make_unique<TwoQPolicy>(MAX_PAGES_IN_MEMORY)) {}
std::unique_ptr<SlottedPage>& getPage(int page_id) {
auto it = pageMap.find(page_id);
if (it != pageMap.end()) {
policy->touch(page_id);
return pageMap.find(page_id)->second;
}
if (pageMap.size() >= MAX_PAGES_IN_MEMORY) {
auto evictedPageId = policy->evict();
if(evictedPageId != INVALID_VALUE){
std::cout << "Evicting page " << evictedPageId << "\n";
storage_manager.flush(evictedPageId,
pageMap[evictedPageId]);
}
}
auto page = storage_manager.load(page_id);
policy->touch(page_id);
std::cout << "Loading page: " << page_id << "\n";
pageMap[page_id] = std::move(page);
return pageMap[page_id];
}
void flushPage(int page_id) {
//std::cout << "Flush page " << page_id << "\n";
storage_manager.flush(page_id, pageMap[page_id]);
}
void extend(){
storage_manager.extend();
}
size_t getNumPages(){
return storage_manager.num_pages;
}
};
class BuzzDB {
public:
// a map is an ordered key-value container
std::map<int, std::vector<int>> index;
BufferManager buffer_manager;
public:
size_t max_number_of_tuples = 5000;
size_t tuple_insertion_attempt_counter = 0;
BuzzDB(){
// Storage Manager automatically created
}
bool try_to_insert(int key, int value){
bool status = false;
auto num_pages = buffer_manager.getNumPages();
for (size_t page_itr = 0; page_itr < num_pages; page_itr++) {
auto newTuple = std::make_unique<Tuple>();
auto key_field = std::make_unique<Field>(key);
auto value_field = std::make_unique<Field>(value);
float float_val = 132.04;
auto float_field = std::make_unique<Field>(float_val);
auto string_field = std::make_unique<Field>("buzzdb");
newTuple->addField(std::move(key_field));
newTuple->addField(std::move(value_field));
newTuple->addField(std::move(float_field));
newTuple->addField(std::move(string_field));
auto& page = buffer_manager.getPage(page_itr);
status = page->addTuple(std::move(newTuple));
if (status == true){
//std::cout << "Inserted into page: " << page_itr << "\n";
buffer_manager.flushPage(page_itr);
break;
}
}
return status;
}
// insert function
void insert(int key, int value) {
tuple_insertion_attempt_counter += 1;
if(tuple_insertion_attempt_counter >= max_number_of_tuples){
return;
}
bool status = try_to_insert(key, value);
// Try again after extending the database file
if(status == false){
buffer_manager.extend();
bool status2 = try_to_insert(key, value);
assert(status2 == true);
}
//newTuple->print();
// Skip deleting tuples only once every hundred tuples
if (tuple_insertion_attempt_counter % 100 != 0){
auto& page = buffer_manager.getPage(0);
page->deleteTuple(0);
buffer_manager.flushPage(0);
}
}
void scanTableToBuildIndex(){
std::cout << "Scanning table to build index \n";
auto num_pages = buffer_manager.getNumPages();
for (size_t page_itr = 0; page_itr < num_pages; page_itr++) {
auto& page = buffer_manager.getPage(page_itr);
char* page_buffer = page->page_data.get();
Slot* slot_array = reinterpret_cast<Slot*>(page_buffer);
for (size_t slot_itr = 0; slot_itr < MAX_SLOTS; slot_itr++) {
if (slot_array[slot_itr].empty == false){
assert(slot_array[slot_itr].offset != INVALID_VALUE);
const char* tuple_data = page_buffer + slot_array[slot_itr].offset;
std::istringstream iss(tuple_data);
auto loadedTuple = Tuple::deserialize(iss);
int key = loadedTuple->fields[0]->asInt();
int value = loadedTuple->fields[1]->asInt();
// Build index
index[key].push_back(value);
}
}
}
}
// perform a SELECT ... GROUP BY ... SUM query
void selectGroupBySum() {
for (auto const& pair : index) { // for each unique key
int sum = 0;
for (auto const& value : pair.second) {
sum += value; // sum all values for the key
}
std::cout << "key: " << pair.first << ", sum: " << sum << '\n';
}
}
};
int main() {
// Get the start time
auto start = std::chrono::high_resolution_clock::now();
BuzzDB db;
std::ifstream inputFile("output.txt");
if (!inputFile) {
std::cerr << "Unable to open file" << std::endl;
return 1;
}
int field1, field2;
while (inputFile >> field1 >> field2) {
db.insert(field1, field2);
}
db.scanTableToBuildIndex();
db.selectGroupBySum();
std::cout << "Num Pages: " << db.buffer_manager.getNumPages() << "\n";
// Get the end time
auto end = std::chrono::high_resolution_clock::now();
// Calculate and print the elapsed time
std::chrono::duration<double> elapsed = end - start;
std::cout << "Elapsed time: " << elapsed.count() << " seconds" << std::endl;
return 0;
}