-
Notifications
You must be signed in to change notification settings - Fork 3
/
43-buzzdb.cpp
1393 lines (1163 loc) · 45.7 KB
/
43-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
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 <unordered_map>
#include <iostream>
#include <map>
#include <string>
#include <memory>
#include <sstream>
#include <limits>
#include <thread>
#include <queue>
#include <optional>
#include <regex>
#include <stdexcept>
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;
}
void print() const {
for (const auto& field : fields) {
field->print();
std::cout << " ";
}
std::cout << "\n";
}
};
static constexpr size_t PAGE_SIZE = 4096; // Fixed page size
static constexpr size_t MAX_SLOTS = 512; // 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::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 bool touch(PageID page_id) = 0;
virtual PageID evict() = 0;
virtual ~Policy() = default;
};
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';
}
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 {
//printList("LRU", lruList);
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 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<LruPolicy>(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 HashIndex {
private:
struct HashEntry {
int key;
int value;
int position; // Final position within the array
bool exists; // Flag to check if entry exists
// Default constructor
HashEntry() : key(0), value(0), position(-1), exists(false) {}
// Constructor for initializing with key, value, and exists flag
HashEntry(int k, int v, int pos) : key(k), value(v), position(pos), exists(true) {}
};
static const size_t capacity = 100; // Hard-coded capacity
HashEntry hashTable[capacity]; // Static-sized array
size_t hashFunction(int key) const {
return key % capacity; // Simple modulo hash function
}
public:
HashIndex() {
// Initialize all entries as non-existing by default
for (size_t i = 0; i < capacity; ++i) {
hashTable[i] = HashEntry();
}
}
void insertOrUpdate(int key, int value) {
size_t index = hashFunction(key);
size_t originalIndex = index;
bool inserted = false;
int i = 0; // Attempt counter
do {
if (!hashTable[index].exists) {
hashTable[index] = HashEntry(key, value, true);
hashTable[index].position = index;
inserted = true;
break;
} else if (hashTable[index].key == key) {
hashTable[index].value += value;
hashTable[index].position = index;
inserted = true;
break;
}
i++;
index = (originalIndex + i*i) % capacity; // Quadratic probing
} while (index != originalIndex && !inserted);
if (!inserted) {
std::cerr << "HashTable is full or cannot insert key: " << key << std::endl;
}
}
int getValue(int key) const {
size_t index = hashFunction(key);
size_t originalIndex = index;
do {
if (hashTable[index].exists && hashTable[index].key == key) {
return hashTable[index].value;
}
if (!hashTable[index].exists) {
break; // Stop if we find a slot that has never been used
}
index = (index + 1) % capacity;
} while (index != originalIndex);
return -1; // Key not found
}
// This method is not efficient for range queries
// as this is an unordered index
// but is included for comparison
std::vector<int> rangeQuery(int lowerBound, int upperBound) const {
std::vector<int> values;
for (size_t i = 0; i < capacity; ++i) {
if (hashTable[i].exists && hashTable[i].key >= lowerBound && hashTable[i].key <= upperBound) {
std::cout << "Key: " << hashTable[i].key <<
", Value: " << hashTable[i].value << std::endl;
values.push_back(hashTable[i].value);
}
}
return values;
}
void print() const {
for (size_t i = 0; i < capacity; ++i) {
if (hashTable[i].exists) {
std::cout << "Position: " << hashTable[i].position <<
", Key: " << hashTable[i].key <<
", Value: " << hashTable[i].value << std::endl;
}
}
}
};
class Operator {
public:
virtual ~Operator() = default;
/// Initializes the operator.
virtual void open() = 0;
/// Tries to generate the next tuple. Return true when a new tuple is
/// available.
virtual bool next() = 0;
/// Destroys the operator.
virtual void close() = 0;
/// This returns the pointers to the Fields of the generated tuple. When
/// `next()` returns true, the Fields will contain the values for the
/// next tuple. Each `Field` pointer in the vector stands for one attribute of the tuple.
virtual std::vector<std::unique_ptr<Field>> getOutput() = 0;
};
class UnaryOperator : public Operator {
protected:
Operator* input;
public:
explicit UnaryOperator(Operator& input) : input(&input) {}
~UnaryOperator() override = default;
};
class BinaryOperator : public Operator {
protected:
Operator* input_left;
Operator* input_right;
public:
explicit BinaryOperator(Operator& input_left, Operator& input_right)
: input_left(&input_left), input_right(&input_right) {}
~BinaryOperator() override = default;
};
class ScanOperator : public Operator {
private:
BufferManager& bufferManager;
size_t currentPageIndex = 0;
size_t currentSlotIndex = 0;
std::unique_ptr<Tuple> currentTuple;
size_t tuple_count = 0;
public:
ScanOperator(BufferManager& manager) : bufferManager(manager) {}
void open() override {
currentPageIndex = 0;
currentSlotIndex = 0;
currentTuple.reset(); // Ensure currentTuple is reset
loadNextTuple();
}
bool next() override {
if (!currentTuple) return false; // No more tuples available
loadNextTuple();
return currentTuple != nullptr;
}
void close() override {
std::cout << "Scan Operator tuple_count: " << tuple_count << "\n";
currentPageIndex = 0;
currentSlotIndex = 0;
currentTuple.reset();
}
std::vector<std::unique_ptr<Field>> getOutput() override {
if (currentTuple) {
return std::move(currentTuple->fields);
}
return {}; // Return an empty vector if no tuple is available
}
private:
void loadNextTuple() {
while (currentPageIndex < bufferManager.getNumPages()) {
auto& currentPage = bufferManager.getPage(currentPageIndex);
if (!currentPage || currentSlotIndex >= MAX_SLOTS) {
currentSlotIndex = 0; // Reset slot index when moving to a new page
}
char* page_buffer = currentPage->page_data.get();
Slot* slot_array = reinterpret_cast<Slot*>(page_buffer);
while (currentSlotIndex < MAX_SLOTS) {
if (!slot_array[currentSlotIndex].empty) {
assert(slot_array[currentSlotIndex].offset != INVALID_VALUE);
const char* tuple_data = page_buffer + slot_array[currentSlotIndex].offset;
std::istringstream iss(std::string(tuple_data, slot_array[currentSlotIndex].length));
currentTuple = Tuple::deserialize(iss);
currentSlotIndex++; // Move to the next slot for the next call
tuple_count++;
return; // Tuple loaded successfully
}
currentSlotIndex++;
}
// Increment page index after exhausting current page
currentPageIndex++;
}
// No more tuples are available
currentTuple.reset();
}
};
class IPredicate {
public:
virtual ~IPredicate() = default;
virtual bool check(const std::vector<std::unique_ptr<Field>>& tupleFields) const = 0;
};
void printTuple(const std::vector<std::unique_ptr<Field>>& tupleFields) {
std::cout << "Tuple: [";
for (const auto& field : tupleFields) {
field->print(); // Assuming `print()` is a method that prints field content
std::cout << " ";
}
std::cout << "]";
}
class SimplePredicate: public IPredicate {
public:
enum OperandType { DIRECT, INDIRECT };
enum ComparisonOperator { EQ, NE, GT, GE, LT, LE }; // Renamed from PredicateType
struct Operand {
std::unique_ptr<Field> directValue;
size_t index;
OperandType type;
Operand(std::unique_ptr<Field> value) : directValue(std::move(value)), type(DIRECT) {}
Operand(size_t idx) : index(idx), type(INDIRECT) {}
};
Operand left_operand;
Operand right_operand;
ComparisonOperator comparison_operator;
SimplePredicate(Operand left, Operand right, ComparisonOperator op)
: left_operand(std::move(left)), right_operand(std::move(right)), comparison_operator(op) {}
bool check(const std::vector<std::unique_ptr<Field>>& tupleFields) const {
const Field* leftField = nullptr;
const Field* rightField = nullptr;
if (left_operand.type == DIRECT) {
leftField = left_operand.directValue.get();
} else if (left_operand.type == INDIRECT) {
leftField = tupleFields[left_operand.index].get();
}
if (right_operand.type == DIRECT) {
rightField = right_operand.directValue.get();
} else if (right_operand.type == INDIRECT) {
rightField = tupleFields[right_operand.index].get();
}
if (leftField == nullptr || rightField == nullptr) {
std::cerr << "Error: Invalid field reference.\n";
return false;
}
if (leftField->getType() != rightField->getType()) {
std::cerr << "Error: Comparing fields of different types.\n";
return false;
}
// Perform comparison based on field type
switch (leftField->getType()) {
case FieldType::INT: {
int left_val = leftField->asInt();
int right_val = rightField->asInt();
return compare(left_val, right_val);
}
case FieldType::FLOAT: {
float left_val = leftField->asFloat();
float right_val = rightField->asFloat();
return compare(left_val, right_val);
}
case FieldType::STRING: {
std::string left_val = leftField->asString();
std::string right_val = rightField->asString();
return compare(left_val, right_val);
}
default:
std::cerr << "Invalid field type\n";
return false;
}
}
private:
// Compares two values of the same type
template<typename T>
bool compare(const T& left_val, const T& right_val) const {
switch (comparison_operator) {
case ComparisonOperator::EQ: return left_val == right_val;
case ComparisonOperator::NE: return left_val != right_val;
case ComparisonOperator::GT: return left_val > right_val;
case ComparisonOperator::GE: return left_val >= right_val;
case ComparisonOperator::LT: return left_val < right_val;
case ComparisonOperator::LE: return left_val <= right_val;
default: std::cerr << "Invalid predicate type\n"; return false;
}
}
};
class ComplexPredicate : public IPredicate {
public:
enum LogicOperator { AND, OR };
private:
std::vector<std::unique_ptr<IPredicate>> predicates;
LogicOperator logic_operator;
public:
ComplexPredicate(LogicOperator op) : logic_operator(op) {}
void addPredicate(std::unique_ptr<IPredicate> predicate) {
predicates.push_back(std::move(predicate));
}
bool check(const std::vector<std::unique_ptr<Field>>& tupleFields) const {
if (logic_operator == AND) {
for (const auto& pred : predicates) {
if (!pred->check(tupleFields)) {
return false; // If any predicate fails, the AND condition fails
}
}
return true; // All predicates passed
} else if (logic_operator == OR) {
for (const auto& pred : predicates) {
if (pred->check(tupleFields)) {
return true; // If any predicate passes, the OR condition passes
}
}
return false; // No predicates passed
}
return false;
}
};
class SelectOperator : public UnaryOperator {
private:
std::unique_ptr<IPredicate> predicate;
bool has_next;
std::vector<std::unique_ptr<Field>> currentOutput; // Store the current output here
public:
SelectOperator(Operator& input, std::unique_ptr<IPredicate> predicate)
: UnaryOperator(input), predicate(std::move(predicate)), has_next(false) {}
void open() override {
input->open();
has_next = false;
currentOutput.clear(); // Ensure currentOutput is cleared at the beginning
}
bool next() override {
while (input->next()) {
const auto& output = input->getOutput(); // Temporarily hold the output
if (predicate->check(output)) {
// If the predicate is satisfied, store the output in the member variable
currentOutput.clear(); // Clear previous output
for (const auto& field : output) {
// Assuming Field class has a clone method or copy constructor to duplicate fields
currentOutput.push_back(field->clone());
}
has_next = true;
return true;
}
}
has_next = false;
currentOutput.clear(); // Clear output if no more tuples satisfy the predicate
return false;
}
void close() override {
input->close();
currentOutput.clear(); // Ensure currentOutput is cleared at the end
}
std::vector<std::unique_ptr<Field>> getOutput() override {
if (has_next) {
// Since currentOutput already holds the desired output, simply return it
// Need to create a deep copy to return since we're returning by value
std::vector<std::unique_ptr<Field>> outputCopy;
for (const auto& field : currentOutput) {
outputCopy.push_back(field->clone()); // Clone each field
}
return outputCopy;
} else {
return {}; // Return an empty vector if no matching tuple is found
}
}
};
enum class AggrFuncType { COUNT, MAX, MIN, SUM };
struct AggrFunc {
AggrFuncType func;
size_t attr_index; // Index of the attribute to aggregate
};
class HashAggregationOperator : public UnaryOperator {
private:
std::vector<size_t> group_by_attrs;
std::vector<AggrFunc> aggr_funcs;
std::vector<Tuple> output_tuples; // Use your Tuple class for output
size_t output_tuples_index = 0;
struct FieldVectorHasher {
std::size_t operator()(const std::vector<Field>& fields) const {
std::size_t hash = 0;
for (const auto& field : fields) {
std::hash<std::string> hasher;
std::size_t fieldHash = 0;
// Depending on the type, hash the corresponding data
switch (field.type) {
case INT: {
// Convert integer data to string and hash
int value = *reinterpret_cast<const int*>(field.data.get());
fieldHash = hasher(std::to_string(value));
break;
}
case FLOAT: {
// Convert float data to string and hash
float value = *reinterpret_cast<const float*>(field.data.get());
fieldHash = hasher(std::to_string(value));
break;
}
case STRING: {
// Directly hash the string data
std::string value(field.data.get(), field.data_length - 1); // Exclude null-terminator
fieldHash = hasher(value);
break;
}
default:
throw std::runtime_error("Unsupported field type for hashing.");
}
// Combine the hash of the current field with the hash so far
hash ^= fieldHash + 0x9e3779b9 + (hash << 6) + (hash >> 2);
}
return hash;
}
};
public:
HashAggregationOperator(Operator& input, std::vector<size_t> group_by_attrs, std::vector<AggrFunc> aggr_funcs)
: UnaryOperator(input), group_by_attrs(group_by_attrs), aggr_funcs(aggr_funcs) {}
void open() override {
input->open(); // Ensure the input operator is opened
output_tuples_index = 0;
output_tuples.clear();
// Assume a hash map to aggregate tuples based on group_by_attrs
std::unordered_map<std::vector<Field>, std::vector<Field>, FieldVectorHasher> hash_table;
while (input->next()) {
const auto& tuple = input->getOutput(); // Assume getOutput returns a reference to the current tuple
// Extract group keys and initialize aggregation values
std::vector<Field> group_keys;
for (auto& index : group_by_attrs) {
group_keys.push_back(*tuple[index]); // Deep copy the Field object for group key
}