-
Notifications
You must be signed in to change notification settings - Fork 3
/
14-buzzdb.cpp
521 lines (429 loc) · 15.5 KB
/
14-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
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <iostream>
#include <chrono>
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <sstream>
#include <limits>
#include <thread> // For std::this_thread::sleep_for
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;
// a vector of Slotted Pages acting as a table
std::vector<std::unique_ptr<SlottedPage>> pages;
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 << "Num pages: " << num_pages << "\n";
if(num_pages == 0){
extend();
}
else{
std::cout << "Loading " << num_pages << " pages \n";
for (size_t page_itr = 0; page_itr < num_pages; page_itr++) {
auto page(load(page_itr));
pages.push_back(std::move(page));
}
}
}
~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) {
size_t page_offset = page_id * PAGE_SIZE;
// Move the write pointer
fileStream.seekp(page_offset, std::ios::beg);
fileStream.write(pages[page_id]->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;
std::cout << "Loading page \n";
// Load page into memory
auto page_itr = num_pages - 1;
auto page(load(page_itr));
pages.push_back(std::move(page));
}
};
class BuzzDB {
public:
// a map is an ordered key-value container
std::map<int, std::vector<int>> index;
// Storage manager
StorageManager sm;
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;
for (size_t page_itr = 0; page_itr < sm.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));
status = sm.pages[page_itr]->addTuple(std::move(newTuple));
if (status == true){
//std::cout << "Inserted into page: " << page_itr << "\n";
sm.flush(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){
sm.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){
sm.pages[0]->deleteTuple(0);
sm.flush(0);
}
}
void scanTableToBuildIndex(){
std::cout << "Scanning table to build index \n";
for (size_t page_itr = 0; page_itr < sm.num_pages; page_itr++) {
char* page_buffer = sm.pages[page_itr]->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.sm.num_pages << "\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;
}