-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy path078-buzzdb.cpp
More file actions
5683 lines (4983 loc) · 188 KB
/
Copy path078-buzzdb.cpp
File metadata and controls
5683 lines (4983 loc) · 188 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
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
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <iostream>
#include <map>
#include <vector>
#include <fstream>
#include <iostream>
#include <chrono>
#include <list>
#include <sstream>
#include <optional>
#include <regex>
#include <algorithm>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <thread>
#include <stdexcept>
#include <cassert>
#include <cerrno>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <fcntl.h>
#include <set>
#include <functional>
#include <utility>
#include <unistd.h>
enum FieldType { INT, FLOAT, STRING };
// Define a basic Field variant class that can hold different types
class Field {
public:
FieldType type;
size_t data_length;
std::unique_ptr<char[]> data;
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;
}
// Copy constructor
Field(const Field& other) : type(other.type), data_length(other.data_length), data(new char[data_length]) {
std::memcpy(data.get(), other.data.get(), data_length);
}
// Move constructor - If you already have one, ensure it's correctly implemented
Field(Field&& other) noexcept : type(other.type), data_length(other.data_length), data(std::move(other.data)) {
// Optionally reset other's state if needed
}
// Clone method
std::unique_ptr<Field> clone() const {
// Use the copy constructor
return std::make_unique<Field>(*this);
}
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;
}
}
};
bool operator==(const Field& lhs, const Field& rhs) {
if (lhs.type != rhs.type) return false; // Different types are never equal
switch (lhs.type) {
case INT:
return *reinterpret_cast<const int*>(lhs.data.get()) == *reinterpret_cast<const int*>(rhs.data.get());
case FLOAT:
return *reinterpret_cast<const float*>(lhs.data.get()) == *reinterpret_cast<const float*>(rhs.data.get());
case STRING:
return std::string(lhs.data.get(), lhs.data_length - 1) == std::string(rhs.data.get(), rhs.data_length - 1);
default:
throw std::runtime_error("Unsupported field type for comparison.");
}
}
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;
}
std::unique_ptr<Tuple> clone() const {
auto tuple = std::make_unique<Tuple>();
for (const auto& field : fields) {
tuple->addField(field->clone());
}
return tuple;
}
};
std::string fieldToString(const Field& field) {
std::ostringstream output;
switch (field.getType()) {
case INT:
output << field.asInt();
break;
case FLOAT:
output << field.asFloat();
break;
case STRING:
output << field.asString();
break;
}
return output.str();
}
std::string tupleToString(const Tuple& tuple) {
std::ostringstream output;
output << "[";
for (size_t i = 0; i < tuple.fields.size(); i++) {
if (i != 0) {
output << ", ";
}
output << fieldToString(*tuple.fields[i]);
}
output << "]";
return output.str();
}
static constexpr size_t PAGE_SIZE = 4096;
static constexpr size_t MAX_SLOTS = 512;
uint16_t INVALID_VALUE = std::numeric_limits<uint16_t>::max(); // Sentinel value
using PageID = uint16_t;
using TableId = uint16_t;
using LSN = uint64_t;
constexpr PageID CATALOG_PAGE_ID = 0;
constexpr PageID INVALID_PAGE_ID = std::numeric_limits<PageID>::max();
constexpr TableId INVALID_TABLE_ID = 0;
constexpr TableId SYS_TABLES_ID = 1;
constexpr TableId SYS_COLUMNS_ID = 2;
constexpr TableId FIRST_USER_TABLE_ID = 100;
const std::string BOOTSTRAP_MAGIC = "BUZZDB_BOOTSTRAP";
enum class CrashPoint {
NONE,
AFTER_STEAL_PAGE_FLUSH
};
struct PageHeader {
TableId table_id = INVALID_TABLE_ID;
PageID next_page = INVALID_PAGE_ID;
LSN page_lsn = 0;
};
// Single-version TO metadata stored next to the current tuple image.
struct TupleTimestampHeader {
uint64_t read_ts = 0;
uint64_t write_ts = 0;
};
static constexpr uint32_t TUPLE_TIMESTAMP_MAGIC = 0x544F5453; // "TOTS"
static constexpr size_t TUPLE_TIMESTAMP_HEADER_BYTES =
sizeof(uint32_t) + sizeof(uint64_t) + sizeof(uint64_t);
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
};
static_assert(sizeof(Slot) * MAX_SLOTS + sizeof(PageHeader) < PAGE_SIZE,
"Slot directory and page header must leave tuple space.");
// Slotted Page class
class SlottedPage {
public:
std::unique_ptr<char[]> page_data = std::make_unique<char[]>(PAGE_SIZE);
struct StoredTuple {
TupleTimestampHeader header;
std::unique_ptr<Tuple> tuple;
};
SlottedPage(){
reset();
}
void reset() {
std::memset(page_data.get(), 0, PAGE_SIZE);
Slot* slot_array = slots();
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;
}
header()->table_id = INVALID_TABLE_ID;
header()->next_page = INVALID_PAGE_ID;
header()->page_lsn = 0;
}
TableId getTableId() const {
return header()->table_id;
}
void setTableId(TableId table_id) {
header()->table_id = table_id;
}
PageID getNextPage() const {
return header()->next_page;
}
void setNextPage(PageID page_id) {
header()->next_page = page_id;
}
LSN getPageLSN() const {
return header()->page_lsn;
}
void setPageLSN(LSN page_lsn) {
header()->page_lsn = page_lsn;
}
bool addTuple(std::unique_ptr<Tuple> tuple) {
return addTupleAndReturnSlot(std::move(tuple)).has_value();
}
std::optional<size_t> addTupleAndReturnSlot(std::unique_ptr<Tuple> tuple) {
auto bytes = serializeTupleRecord({}, *tuple);
auto slot_id = findAvailableSlot(bytes.size());
if (!slot_id || !putSerializedTupleAtSlot(*slot_id, bytes)) {
return std::nullopt;
}
return slot_id;
}
bool putTupleAtSlot(size_t slot_id, std::unique_ptr<Tuple> tuple) {
TupleTimestampHeader header;
auto current = getTupleRecord(slot_id);
if (current) {
header = current->header;
}
return putSerializedTupleAtSlot(
slot_id,
serializeTupleRecord(header, *tuple)
);
}
std::unique_ptr<Tuple> getTuple(size_t slot_id) const {
auto record = getTupleRecord(slot_id);
if (!record) {
return nullptr;
}
return std::move(record->tuple);
}
std::optional<StoredTuple> getTupleRecord(size_t slot_id) const {
auto bytes = getRawRecord(slot_id);
if (!bytes) {
return std::nullopt;
}
return deserializeTupleRecord(*bytes);
}
std::optional<TupleTimestampHeader> getTupleHeader(size_t slot_id) const {
auto record = getTupleRecord(slot_id);
if (!record) {
return std::nullopt;
}
return record->header;
}
bool hasTuple(size_t slot_id) const {
return slot_id < MAX_SLOTS && !slots()[slot_id].empty;
}
bool updateTuple(size_t slot_id, std::unique_ptr<Tuple> tuple) {
if (slot_id >= MAX_SLOTS || slots()[slot_id].empty) {
return false;
}
TupleTimestampHeader header;
auto current = getTupleRecord(slot_id);
if (current) {
header = current->header;
}
return putSerializedTupleAtSlot(
slot_id,
serializeTupleRecord(header, *tuple)
);
}
bool updateTupleHeader(size_t slot_id,
const TupleTimestampHeader& header) {
auto current = getTupleRecord(slot_id);
if (!current) {
return false;
}
return putSerializedTupleAtSlot(
slot_id,
serializeTupleRecord(header, *current->tuple)
);
}
void deleteTuple(size_t slot_id) {
if (slot_id < MAX_SLOTS) {
slots()[slot_id].empty = true;
}
}
private:
static constexpr size_t SLOT_ARRAY_SIZE = sizeof(Slot) * MAX_SLOTS;
static constexpr size_t HEADER_OFFSET = SLOT_ARRAY_SIZE;
static constexpr size_t DATA_START = HEADER_OFFSET + sizeof(PageHeader);
Slot* slots() {
return reinterpret_cast<Slot*>(page_data.get());
}
const Slot* slots() const {
return reinterpret_cast<const Slot*>(page_data.get());
}
PageHeader* header() {
return reinterpret_cast<PageHeader*>(page_data.get() + HEADER_OFFSET);
}
const PageHeader* header() const {
return reinterpret_cast<const PageHeader*>(page_data.get() + HEADER_OFFSET);
}
std::optional<std::string> getRawRecord(size_t slot_id) const {
if (slot_id >= MAX_SLOTS || slots()[slot_id].empty) {
return std::nullopt;
}
const auto& slot = slots()[slot_id];
assert(slot.offset != INVALID_VALUE);
assert(slot.length != INVALID_VALUE);
const char* tuple_data = page_data.get() + slot.offset;
return std::string(tuple_data, slot.length);
}
static void appendBytes(std::string& bytes,
const void* value,
size_t size) {
const char* raw = reinterpret_cast<const char*>(value);
bytes.append(raw, size);
}
template <typename T>
static T readBytes(const std::string& bytes, size_t& offset) {
if (offset + sizeof(T) > bytes.size()) {
throw std::runtime_error("Corrupt tuple timestamp header.");
}
T value{};
std::memcpy(&value, bytes.data() + offset, sizeof(T));
offset += sizeof(T);
return value;
}
static std::string serializeTupleRecord(
const TupleTimestampHeader& header,
Tuple& tuple) {
std::string bytes;
bytes.reserve(TUPLE_TIMESTAMP_HEADER_BYTES + tuple.getSize() + 32);
uint32_t magic = TUPLE_TIMESTAMP_MAGIC;
appendBytes(bytes, &magic, sizeof(magic));
appendBytes(bytes, &header.read_ts, sizeof(header.read_ts));
appendBytes(bytes, &header.write_ts, sizeof(header.write_ts));
bytes += tuple.serialize();
return bytes;
}
static StoredTuple deserializeTupleRecord(const std::string& bytes) {
TupleTimestampHeader header;
size_t tuple_offset = 0;
if (bytes.size() >= TUPLE_TIMESTAMP_HEADER_BYTES) {
size_t header_offset = 0;
uint32_t magic = readBytes<uint32_t>(bytes, header_offset);
if (magic == TUPLE_TIMESTAMP_MAGIC) {
header.read_ts = readBytes<uint64_t>(bytes, header_offset);
header.write_ts = readBytes<uint64_t>(bytes, header_offset);
tuple_offset = header_offset;
}
}
std::istringstream tuple_input(bytes.substr(tuple_offset));
return {header, Tuple::deserialize(tuple_input)};
}
std::optional<size_t> findAvailableSlot(size_t tuple_size) const {
const Slot* slot_array = slots();
for (size_t slot_itr = 0; slot_itr < MAX_SLOTS; slot_itr++) {
if (!slot_array[slot_itr].empty) {
continue;
}
if (slot_array[slot_itr].length == INVALID_VALUE ||
slot_array[slot_itr].length >= tuple_size) {
return slot_itr;
}
}
return std::nullopt;
}
size_t nextFreeOffset() const {
size_t offset = DATA_START;
const Slot* slot_array = slots();
for (size_t slot_itr = 0; slot_itr < MAX_SLOTS; slot_itr++) {
if (slot_array[slot_itr].offset == INVALID_VALUE ||
slot_array[slot_itr].length == INVALID_VALUE) {
continue;
}
size_t slot_end = static_cast<size_t>(slot_array[slot_itr].offset) +
slot_array[slot_itr].length;
if (slot_end > offset) {
offset = slot_end;
}
}
return offset;
}
bool putSerializedTupleAtSlot(size_t slot_itr,
const std::string& bytes) {
if (slot_itr >= MAX_SLOTS) {
return false;
}
size_t tuple_size = bytes.size();
auto& slot = slots()[slot_itr];
if (slot.length != INVALID_VALUE && tuple_size > slot.length) {
return false;
}
size_t offset = slot.offset;
if (offset == INVALID_VALUE) {
offset = nextFreeOffset();
}
if (offset < DATA_START || offset + tuple_size > PAGE_SIZE) {
return false;
}
assert(offset != INVALID_VALUE);
assert(offset >= DATA_START);
assert(offset + tuple_size <= PAGE_SIZE);
slot.empty = false;
slot.offset = static_cast<uint16_t>(offset);
if (slot.length == INVALID_VALUE) {
slot.length = static_cast<uint16_t>(tuple_size);
}
std::memcpy(page_data.get() + offset, bytes.c_str(), tuple_size);
return true;
}
};
const std::string database_filename = "buzzdb.dat";
const std::string log_filename = "buzzdb.log";
const std::string master_record_filename = "buzzdb.master";
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::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::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;
}
};
class Policy {
public:
virtual bool touch(PageID page_id) = 0;
virtual PageID evict() = 0;
virtual ~Policy() = default;
};
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) {}
bool touch(PageID page_id) override {
bool found = false;
// If page already in the list, remove it
if (map.find(page_id) != map.end()) {
found = true;
lruList.erase(map[page_id]);
map.erase(page_id);
}
// If cache is full, evict
if(lruList.size() == cacheSize){
evict();
}
if(lruList.size() < cacheSize){
// Add the page to the front of the list
lruList.emplace_front(page_id);
map[page_id] = lruList.begin();
}
return found;
}
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;
}
};
constexpr size_t MAX_PAGES_IN_MEMORY = 10;
class LogManager;
class BufferManager {
private:
using PageMap = std::unordered_map<PageID, std::unique_ptr<SlottedPage>>;
StorageManager storage_manager;
PageMap pageMap;
LogManager& log_manager;
std::unique_ptr<Policy> policy;
std::set<PageID> pinned_pages;
std::function<void(PageID, LSN)> page_flush_callback;
public:
explicit BufferManager(LogManager& log_manager)
: log_manager(log_manager),
policy(std::make_unique<LruPolicy>(MAX_PAGES_IN_MEMORY)) {}
void setPageFlushCallback(std::function<void(PageID, LSN)> callback) {
page_flush_callback = std::move(callback);
}
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) {
evictUnpinnedPage();
}
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, const std::string& reason = "page flush") {
auto& page = getPage(page_id);
forceLogBeforePageFlush(page_id, reason);
LSN page_lsn = page->getPageLSN();
storage_manager.flush(page_id, page);
if (page_flush_callback) {
page_flush_callback(page_id, page_lsn);
}
}
void pinPage(PageID page_id) {
pinned_pages.insert(page_id);
}
void unpinPage(PageID page_id) {
pinned_pages.erase(page_id);
}
void extend(){
storage_manager.extend();
}
PageID appendPage(TableId table_id) {
storage_manager.extend();
auto page_id = static_cast<PageID>(storage_manager.num_pages - 1);
resetPage(page_id, table_id);
return page_id;
}
void resetPage(PageID page_id, TableId table_id) {
auto& page = getPage(page_id);
page->reset();
page->setTableId(table_id);
page->setNextPage(INVALID_PAGE_ID);
flushPage(page_id);
}
size_t getNumPages(){
return storage_manager.num_pages;
}
private:
void forceLogBeforePageFlush(PageID page_id, const std::string&);
void evictUnpinnedPage() {
size_t attempts = pageMap.size();
while (attempts-- > 0) {
auto evictedPageId = policy->evict();
if(evictedPageId == INVALID_VALUE){
break;
}
if (pinned_pages.find(evictedPageId) != pinned_pages.end()) {
policy->touch(evictedPageId);
continue;
}
forceLogBeforePageFlush(evictedPageId, "eviction");
LSN page_lsn = pageMap[evictedPageId]->getPageLSN();
storage_manager.flush(evictedPageId, pageMap[evictedPageId]);
if (page_flush_callback) {
page_flush_callback(evictedPageId, page_lsn);
}
pageMap.erase(evictedPageId);
return;
}
throw std::runtime_error("All buffer pages are pinned.");
}
};
enum class LogRecordType {
BEGIN,
UPDATE,
INSERT,
DELETE,
CLR,
COMMIT,
ABORT,
END,
BEGIN_CHECKPOINT,
END_CHECKPOINT
};
bool isTupleChangeRecord(LogRecordType type);
struct RecoveryAnalysis {
enum class TxnStatus {
RUNNING,
COMMITTING,
ABORTING
};
struct ActiveTransactionEntry {
TxnStatus status = TxnStatus::RUNNING;
LSN last_lsn = 0;
};
using ActiveTransactionTable = std::map<int, ActiveTransactionEntry>;
using DirtyPageTable = std::map<PageID, LSN>;
ActiveTransactionTable active_transaction_table;
DirtyPageTable dirty_page_table;
int next_txn_id = 1;
};
struct LogRecord {
LSN lsn = 0;
LSN prev_lsn = 0;
LogRecordType type;
int txn_id = 0;
TableId table_id = INVALID_TABLE_ID;
PageID page_id = INVALID_PAGE_ID;
size_t slot_id = 0;
LogRecordType undo_type = LogRecordType::UPDATE;
LSN undo_next_lsn = 0;
std::unique_ptr<Tuple> before_tuple;
std::unique_ptr<Tuple> after_tuple;
RecoveryAnalysis::ActiveTransactionTable checkpoint_att;
RecoveryAnalysis::DirtyPageTable checkpoint_dpt;
LogRecord(LogRecordType type, int txn_id)
: type(type), txn_id(txn_id) {}
LogRecord(LogRecordType type,
int txn_id,
TableId table_id,
PageID page_id,
size_t slot_id,
std::unique_ptr<Tuple> before_tuple,
std::unique_ptr<Tuple> after_tuple)
: type(type),
txn_id(txn_id),
table_id(table_id),
page_id(page_id),
slot_id(slot_id),
before_tuple(std::move(before_tuple)),
after_tuple(std::move(after_tuple)) {}
};
bool isTupleChangeRecord(LogRecordType type) {
return type == LogRecordType::UPDATE ||
type == LogRecordType::INSERT ||
type == LogRecordType::DELETE;
}
bool isRedoableRecord(LogRecordType type) {
return isTupleChangeRecord(type) || type == LogRecordType::CLR;
}
std::string logRecordName(LogRecordType type) {
switch (type) {
case LogRecordType::BEGIN:
return "BEGIN";
case LogRecordType::UPDATE:
return "UPDATE";
case LogRecordType::INSERT:
return "INSERT";
case LogRecordType::DELETE:
return "DELETE";
case LogRecordType::CLR:
return "CLR";
case LogRecordType::COMMIT:
return "COMMIT";
case LogRecordType::ABORT:
return "ABORT";
case LogRecordType::END:
return "END";
case LogRecordType::BEGIN_CHECKPOINT:
return "BEGIN_CHECKPOINT";
case LogRecordType::END_CHECKPOINT:
return "END_CHECKPOINT";
}
throw std::runtime_error("Unknown log record.");
}
std::string recoveryTxnStatusName(RecoveryAnalysis::TxnStatus status) {
switch (status) {
case RecoveryAnalysis::TxnStatus::RUNNING:
return "RUNNING";
case RecoveryAnalysis::TxnStatus::COMMITTING:
return "COMMITTING";
case RecoveryAnalysis::TxnStatus::ABORTING:
return "ABORTING";
}
throw std::runtime_error("Unknown transaction status.");
}
RecoveryAnalysis::TxnStatus parseRecoveryTxnStatus(
const std::string& status) {
if (status == "RUNNING") {
return RecoveryAnalysis::TxnStatus::RUNNING;
}
if (status == "COMMITTING") {
return RecoveryAnalysis::TxnStatus::COMMITTING;
}
if (status == "ABORTING") {
return RecoveryAnalysis::TxnStatus::ABORTING;
}
throw std::runtime_error("Unknown transaction status in checkpoint: " + status);
}
bool parseLogRecordType(const std::string& type,
LogRecordType& record_type) {
if (type == "BEGIN") {
record_type = LogRecordType::BEGIN;
return true;
}
if (type == "UPDATE") {
record_type = LogRecordType::UPDATE;
return true;
}
if (type == "INSERT") {
record_type = LogRecordType::INSERT;
return true;
}
if (type == "DELETE") {
record_type = LogRecordType::DELETE;
return true;
}
if (type == "CLR") {
record_type = LogRecordType::CLR;
return true;
}
if (type == "COMMIT") {
record_type = LogRecordType::COMMIT;
return true;
}
if (type == "ABORT") {
record_type = LogRecordType::ABORT;
return true;
}
if (type == "END") {
record_type = LogRecordType::END;
return true;
}
if (type == "BEGIN_CHECKPOINT") {
record_type = LogRecordType::BEGIN_CHECKPOINT;
return true;
}
if (type == "END_CHECKPOINT") {
record_type = LogRecordType::END_CHECKPOINT;
return true;
}
return false;
}
struct MasterRecord {
LSN checkpoint_begin_lsn = 0;
size_t checkpoint_begin_offset = 0;
};
MasterRecord readMasterRecordFile() {
std::ifstream input(master_record_filename);
MasterRecord master_record;
if (!input) {
return master_record;
}
std::string key;