-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSQLStatement.cpp
1002 lines (886 loc) · 42.6 KB
/
SQLStatement.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
//
// Created by Cao Zongheng on 4/24/20.
//
#include "SQLStatement.h"
#include <string>
#include "Attribute.hpp"
#include <sstream>
namespace ECE141{
StatusResult CreateTableStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
string theName = schema->getName();
if(database->hasTableName(theName)) return StatusResult(Errors::tableExists);
database->getMap()[theName] = schema;
// *********** check if the table has a primary key
string temp = schema->getPrimaryKey();
if(temp != ""){
//need create a index in the Toc by the primary key, and create an empty index
Index* tempIndex = new Index(temp,theName,DataType::int_type);
//add into memory
database->manager.addIndexIntoMap(*tempIndex,theName,temp);
int blockNum = database->getId() + 1;
database->manager.addIndexIntoToc(theName,temp, blockNum);
//add into db.file
database->saveIndex(theName,temp);
database->saveIndexInfo();
}
// **************
//store the table and meta info into hardware
database->getToc().list[theName] = database->getId() + 1;
if(database->saveSchema(*schema) && database->saveMetaInfo()){
std::cout << "Create Table "<< name << "\n";
database->setId(database->getId() + 1); //if success, let the id + 1
database->saveMetaInfo(); //save into database
return StatusResult();
}
else return StatusResult(Errors::writeError);
}
//drop table need to drop the table block and data block
//and index block and update index info(decrease the index of that table in index table)
StatusResult DropTableStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
//look if it has a primary key
string indexName = database->getMap()[name]->getPrimaryKey();
if(indexName == ""){ //right now, if no primary key, we assume that no other index
//iterate block and delete the related block
int id = database->getId();
for(int i = 1; i<=id; i++){
StorageBlock aBlock(BlockType::unknown_block);
database->getStorage().readBlock(aBlock,i);
if(aBlock.header.type == 'D'){
char table[data_size]; memcpy(&table,aBlock.data, sizeof(aBlock.data));
string table1 = table;
int index = table1.find(";");
string theName = table1.substr(0,index);
if(name == theName){
database->getStorage().writeBlank(i);
}
}
}
}
else{
//load and get the primary index
database->loadIndex(name,indexName);
Index temp = database->manager.getIndex(name,indexName);
//delete the data by index
for(auto it : temp.getList()){
int blockNum = it.second;
database->getStorage().writeBlank(blockNum); //write blank
}
}
//delete all index block
//delete the index of a table (meta index)
database->manager.deleteAllIndexOfTable(name, database->getStorage());
database->manager.getMap().erase(name);
database->manager.getToc().erase(name);
database->saveIndexInfo();
//delete in toc and map, also write a blank into disk
int index = database->getToc().list[name];
database->getToc().list.erase(name);
database->getMap().erase(name);
// save meta and write blank
if(database->getStorage().writeBlank(index) && database->saveMetaInfo()){
std::cout << "Drop Table "<< name << "\n";
return StatusResult();
}
else return StatusResult(Errors::unknownError);
}
StatusResult ShowTableStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
return database->showTables();
}
StatusResult DescribeTableStatement::run(std::ostream &aStream) const {
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
return database->describeTable(name);
}
//we need to add into the map
StatusResult InsertTableStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
//initialize a validator
Validator s(database->getMap());
if(!s.checkAttributeName(properties,name)) return StatusResult(Errors::syntaxError); //check name
if(!s.checkAttributeType(rowList,name)) return StatusResult(Errors::syntaxError); //check type
//maybe we need first load the index into memory?
IndexManager& tempManager = database->manager;
for(auto it : tempManager.getToc()){
if(!tempManager.isIndexLoaded(name, it.first)){
database->loadIndex(name, it.first);
}
}
for(Row* i : rowList){
int id = database->getTableId(name);
database->saveData(name,id,*i,-1); //save it into next block include id + 1
int blockNum = database->getId(); //store the blockNum quickly
//index stuff
map<string, Index> temp = database->manager.getMap()[name];
for(auto& it : temp){ //for all its indexes
string indexName = it.first;
ValueType* tempType = new ValueType();
*tempType = i->pair2[indexName];
tempManager.getMap()[name][indexName].addKeyValue(*tempType, blockNum); //add a ValueType and a blockNum
}
}
//save all the index
database->saveAllIndex();
//save meta and table into db file
database->saveSchema(*database->getMap()[name]);
database->saveMetaInfo(); //only because it increase.
return StatusResult();
}
StatusResult DeleteTableStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
Timer aTimer;
aTimer.start();
//delete all the data of the table and the index for the table, but not the index info
string indexName = database->getMap()[name]->getPrimaryKey();
if(indexName == "") { //if no primary data
int id = database->getId(); //how many block we have
for(int i = 1; i<=id; i++){
StorageBlock aBlock(BlockType::unknown_block);
database->getStorage().readBlock(aBlock,i);
if(aBlock.header.type == 'D'){
char table[data_size]; memcpy(&table,aBlock.data, sizeof(aBlock.data));
string table1 = table;
int index = table1.find(";");
string theName = table1.substr(0,index); //table's name
if(name == theName){
database->getStorage().writeBlank(i);
database->setTableId(-1,name); //this is necessary, at the end, it becomes 1 or 0?
}
}
}
}
else{
if(!database->manager.isIndexLoaded(name,indexName)) database->loadIndex(name,indexName);
Index temp = database->manager.getIndex(name,indexName); //get the primary index
for(auto it : temp.getList()){ //delete the data by index
int blockNum = it.second;
database->getStorage().writeBlank(blockNum); //write blank
database->setTableId(-1,name); //this is necessary, at the end, it becomes 1 or 0?
}
}
//delete the index itself in db.file, but not in index meta info
database->manager.deleteAllIndexOfTable(name, database->getStorage());
database->saveMetaInfo();
aTimer.stop();
double time = aTimer.elapsed();
cout <<"1 rows affected (" << time << " ms.)\n"; //now we don't realize delete where
return StatusResult();
}
StatusResult ShowIndexStatement::run(std::ostream &aStream) const{
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
else return database->manager.showIndexes();
}
Expression* getMatchExpression(IndexManager& indexManager, string name, const Filters& filters){
for(auto it : filters.getExpression()){
//check if this index exist
string indexName = it->lhs.name;
if(indexManager.isIndexExisted(name,indexName)){
return it; //find one, use it
}
}
return nullptr;
}
StatusResult addARow(StorageBlock& aBlock, RowColloection* aRowCollections, Database* database, string name, int blockNum){
if(aBlock.header.type == 'D'){ //check if it is data block
char data[data_size];
memcpy(data,aBlock.data,data_size);
string data1 = data;
int nameIndex = data1.find(";");
AttributeList list = database->getMap()[name]->getAttributes(); //get list
string theName = data1.substr(0,nameIndex);
int index = 0;
if(theName == name){
Row* aRow = new Row();
aRow->blockId = blockNum;
aRow->headerId = aBlock.header.id;
int start = nameIndex + 1;
for(int i = nameIndex+1; i<data1.length(); i++){
if(data1[i] == ','){
string temp = data1.substr(start,i-start);
int dataIndex = temp.find(":");
string tempData = temp.substr(dataIndex+1,temp.size() - dataIndex - 1);
DataType tempType = list[index].getType();
ValueType type = database->changeStringToDataType(tempData,tempType);
KeyValuePair tempPair = make_pair(list[index].getName(),type);
aRow->getPair().push_back(tempPair);
//used for order
aRow->pair2[list[index].getName()] = type;
start = i + 1;
index++;
}
}
aRowCollections->addRow(*aRow);
}
}
return StatusResult();
}
RowColloection& getRowColloections(Database* database, string name, const Filters& filters){
//case 1: check if the expressions match the index, include id
//case 2: if not 1, then 2, we use primary key to avoid iterate
RowColloection* aRowCollections = new RowColloection();
Expression* matchEx = getMatchExpression(database->manager, name, filters);
//case 1
if(matchEx != nullptr){
string matchIndex = matchEx->lhs.name;
if(!database->manager.isIndexLoaded(name,matchIndex)) database->loadIndex(name,matchIndex);
Index* tempIndex = &database->manager.getIndex(name, matchIndex);
//use filter first to delete some rows, so we don't need to load it from db file
//give a index, return a new index, then let tempIndex = newTemp
if(Expression* it = filters.hasThisFiled(tempIndex->getFieldName())){
Index* newTemp = filters.matchIndex(*tempIndex, it);
tempIndex = newTemp;
}
// do something, like = , < , >
for(auto it : tempIndex->getList()){
//check if each index satisfy the requirements
ValueType temp = it.first;
if((*matchEx)(temp)){
StorageBlock aBlock(BlockType::unknown_block);
//first, search cache
if(StorageBlock* tempBlock = database->blockCache.getABlock(it.second)){
//automatically move this block from its place to the last one
aBlock = *tempBlock;
}
else{
//cache miss, search db
database->getStorage().readBlock(aBlock, it.second);
//add into cache
database->blockCache.AddaBlock(it.second, aBlock);
}
//add into RowCollections
addARow(aBlock, aRowCollections, database, name, it.second); //use the function above
}
}
return *aRowCollections;
}
//case 2
else if(database->getMap()[name]->getPrimaryKey() != ""){
string key = database->getMap()[name]->getPrimaryKey();
if(!database->manager.isIndexLoaded(name,key)) database->loadIndex(name,key);
Index* tempIndex = &database->manager.getIndex(name, key);
if(Expression* it = filters.hasThisFiled(tempIndex->getFieldName())){
Index* newTemp = filters.matchIndex(*tempIndex, it);
tempIndex = newTemp;
}
for(auto it : tempIndex->getList()){
StorageBlock aBlock(BlockType::unknown_block);
//first, search cache
if(StorageBlock* tempBlock = database->blockCache.getABlock(it.second)){
aBlock = *tempBlock;
}
else{
//cache miss, search db
database->getStorage().readBlock(aBlock, it.second);
//add into cache
database->blockCache.AddaBlock(it.second, aBlock);
}
//add into RowCollections
addARow(aBlock, aRowCollections, database, name, it.second); //use the function above
}
}
else{ //no primary index
int id = database->getId();
for(int i = 2; i<=id; i++){ //界限
StorageBlock aBlock(BlockType::data_block);
if(StorageBlock* tempBlock = database->blockCache.getABlock(i)){
aBlock = *tempBlock;
}
else{
database->getStorage().readBlock(aBlock,i);
if(aBlock.header.type == 'D'){
char data[data_size];
memcpy(data,aBlock.data,data_size);
string data1 = data;
int nameIndex = data1.find(";");
AttributeList list = database->getMap()[name]->getAttributes(); //get list
string theName = data1.substr(0,nameIndex);
if(theName == name){
//add into cache
database->blockCache.AddaBlock(i, aBlock);
//add into RowCollections
addARow(aBlock, aRowCollections, database, name, i);
}
}
}
}
}
return *aRowCollections;
}
StatusResult SelectStatement::run(std::ostream &aStream) const{
//check table name and database
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
//initialize a validator
Validator s(database->getMap());
//add the join table name also in the fucntion. if not, add ""
string joiunTableName = joins.size() > 0 ? joins[0].table : "";
if(!s.checkTableViewName(name,tableView.getShowName(),joiunTableName)) return StatusResult(Errors::unknownAttribute);
if(filters.order) if(!s.checkWhereAndOrder(name,filters.orderName,joiunTableName)) return StatusResult(Errors::unknownAttribute);
for(auto it : filters.getExpression()){
if(!s.checkWhereAndOrder(name,it->lhs.name,joiunTableName)) return StatusResult(Errors::unknownAttribute);
}
Timer aTimer;
aTimer.start();
//add all the rows into row collection
RowColloection aRowCollections = getRowColloections(database, name, filters);
//if have join, we add the attribute of the join
if(joins.size() > 0){
if(!checkJoinName()) return StatusResult(Errors::syntaxError);
RowColloection aRowCollections1 = getRowColloections(database, joiunTableName, filters);
addJoinRowsToRows(aRowCollections, aRowCollections1);
}
aTimer.stop();
double time = aTimer.elapsed();
//filter
if(filters.getCount() > 0){
for(auto it = aRowCollections.list.begin(); it != aRowCollections.list.end(); ){
if(!filters.match(*it)){
aRowCollections.list.erase(it);
}
else it++;
}
}
//if we need order
if(filters.order){
filters.sortCollections(&aRowCollections);
}
//if we need limit and show
bool join = joins.size() > 0;
tableView.ShowRowList(aRowCollections,filters.limit ? filters.limitNumber : -1, time, join);
return StatusResult();
}
StatusResult SelectStatement::addJoinRowsToRows(RowColloection& aRowCollections, RowColloection& aRowCollections1) const{
Schema* schemaLeft = database->getMap()[name];
Schema* schemaRight = database->getMap()[joins[0].table];
bool isPrimaryLeft = schemaLeft->getPrimaryKey() == joins[0].getFieldName()[0];
bool isPrimaryRight = schemaRight->getPrimaryKey() == joins[0].getFieldName()[1];
if(joins[0].joinType == ECE141::Keywords::left_kw){
int size = aRowCollections.list.size(); int cnt = 0;
for(auto i = aRowCollections.list.begin(); i != aRowCollections.list.end() && cnt < size;){
bool match = false; Row tempRow = *i;
aRowCollections.list.erase(i);
for(Row& j : aRowCollections1.list){
if(matchJoinCondition(tempRow,j)){
addTwoRows(tempRow,j,aRowCollections);
match = true;
if(isPrimaryLeft && isPrimaryRight) break;
}
}
if(!match){
addEmptyAttributes(*i, schemaRight->getAttributes(), schemaRight->getPrimaryKey(),aRowCollections);
}
cnt++;
}
}
else if(joins[0].joinType == ECE141::Keywords::right_kw){
int size = aRowCollections.list.size();
for(auto i : aRowCollections1.list){
bool match = false; int cnt = 0;
for(auto j = aRowCollections.list.begin(); j != aRowCollections.list.end() && cnt < size; j++, cnt++){
if(matchJoinCondition(i,*j)){
addTwoRows(i,*j,aRowCollections);
match = true;
if(isPrimaryRight && isPrimaryLeft) break;
}
}
if(!match){
addEmptyAttributes(i, schemaLeft->getAttributes(), schemaLeft->getPrimaryKey(),aRowCollections);
}
}
//delete all origin rows in RowCollection
int cnt = 0;
for(auto i = aRowCollections.list.begin(); i != aRowCollections.list.end() && cnt < size; cnt++){
aRowCollections.list.erase(i);
}
}
else{ //normal join
for(auto i = aRowCollections.list.begin(); i != aRowCollections.list.end();){
bool match = false;
for(Row& j : aRowCollections1.list){
if(matchJoinCondition(*i,j)){
addTwoRows(*i,j,aRowCollections);
match = true;
break;
}
}
if(!match) aRowCollections.list.erase(i);
else i++;
}
}
return StatusResult();
}
StatusResult UpdateStatement::run(std::ostream &aStream) const{
//check table name and database
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
//initialize a validator
Validator s(database->getMap());
Timer aTimer;
aTimer.start();
RowColloection aRowCollections = getRowColloections(database, name, filters);
//check set name and where name
for(auto it : filters.getExpression()) if(!s.checkWhereAndOrder(name,it->lhs.name, "")) return StatusResult(Errors::unknownAttribute);
for(auto it : filters.updateValues) if(!s.checkWhereAndOrder(name,it.first, "")) return StatusResult(Errors::unknownAttribute);
if(filters.updateValues.size() != 0){ //need update
for(auto it = aRowCollections.list.begin(); it != aRowCollections.list.end(); ){
if(!filters.match1(*it)){
//if not, delete it from rowCollections
aRowCollections.list.erase(it);
}
else it++;
}
}
//need store
if(aRowCollections.list.size() != 0){
for(Row i : aRowCollections.list){
database->saveData(name,i.headerId,i,i.blockId); //store it into the previous index
}
}
aTimer.stop();
double time = aTimer.elapsed();
cout<< aRowCollections.list.size() <<" rows affected (" << time << " ms.)\n";
return StatusResult();
}
StatusResult AlterStatement::run(std::ostream &aStream) const{
//change the toc
if(database == nullptr) return StatusResult(Errors::noDatabaseSpecified);
if(!database->hasTableName(name)) return StatusResult(Errors::unknownTable);
Schema* s = database->getMap()[name];
s->addAttribute(attribute);
database->saveSchema(*s);
//load all the data and change it
RowColloection aRowCollections = getRowColloections(database, name, filters);
for(Row i : aRowCollections.list){
//添加这个KeyValuePair, string是null
database->addNULLToRow(i,attribute);
//save
database->saveData(name,i.headerId,i,i.blockId);
}
return StatusResult();
}
//parse//////////////
StatusResult CreateTableStatement::parse(Tokenizer &aTokenizer){
aTokenizer.next(); //jump the punc (
schema = new Schema(name);
schema->setId(1);
bool length = false;
bool IsDefault = false;
//seperate diff attributes
Attribute* pointer = nullptr;
while(aTokenizer.current().data != ")"){
while(aTokenizer.current().data != ","){
if(aTokenizer.current().type == TokenType::identifier && pointer == nullptr){
Attribute* temp = new Attribute(aTokenizer.current().data);
pointer = temp;
}
else if(aTokenizer.current().keyword == Keywords::integer_kw || aTokenizer.current().data == "TIMESTAMP" ||
aTokenizer.current().keyword == Keywords::float_kw || aTokenizer.current().keyword == Keywords::varchar_kw ||
aTokenizer.current().keyword == Keywords::boolean_kw){
switch(aTokenizer.current().keyword){
case Keywords::integer_kw:
pointer->setType(DataType::int_type); break;
case Keywords::float_kw:
pointer->setType(DataType::float_type); break;
case Keywords::varchar_kw:
pointer->setType(DataType::varchar_type); break;
case Keywords::boolean_kw:
pointer->setType(DataType::bool_type); break;
default:
pointer->setType(DataType::datetime_type); break;
}
}
//set auto_increment
else if(aTokenizer.current().keyword == Keywords::auto_increment_kw) pointer->setAutoIncrement(true);
//set key
else if(aTokenizer.current().keyword == Keywords::key_kw) pointer->setKey(true);
//set primary
else if(aTokenizer.current().keyword == Keywords::primary_kw) pointer->setPrimary(true);
// var char length
else if(aTokenizer.current().type == TokenType::number){
if(length){
std::stringstream ss;
ss << aTokenizer.current().data;
int x; ss >> x;
pointer->setLength(x);
length = false;
}
else if(IsDefault){
pointer->setdefault(std::string(aTokenizer.current().data));
IsDefault = false;
}
}
//
else if(aTokenizer.current().keyword == Keywords::not_kw) pointer->setNullable(true);
//(100) and 0.0
else if(aTokenizer.current().data == "("){
length = true;
}
else if(aTokenizer.current().data == "DEFAULT"){
IsDefault = true;
}
else if(aTokenizer.current().data == "FALSE" || aTokenizer.current().data == "TRUE"){
if(IsDefault){
pointer->setdefault(std::string(aTokenizer.current().data));
IsDefault = false;
}
}
//go to next token
if(!aTokenizer.next()){
schema->addAttribute(*pointer); // add in the schema
pointer = nullptr;
return StatusResult();
}
}
schema->addAttribute(*pointer); // add in the schema
pointer = nullptr;
if(!aTokenizer.next()) return StatusResult(); //jump the ,
}
return StatusResult();
}
StatusResult InsertTableStatement::parse(Tokenizer &aTokenizer){
//create the rowList by the token, it miss a syntax error, return error
//insert into users (id, name) values (9, 'foo'), (12, 'bar')
bool value = false; stringstream ss;
while(aTokenizer.current().data != ";" && aTokenizer.more()){
if(!value){
if(aTokenizer.current().keyword == Keywords::values_kw){
value = true;
aTokenizer.next(); continue;
}
else if(aTokenizer.current().type == TokenType::identifier){ // properties
properties.push_back(aTokenizer.current().data);
}
}
else{ //now go into record data
Row* temp = new Row(); int index = 0;
while(aTokenizer.current().data != ")"){ //separate by )
if(aTokenizer.current().type == TokenType::number){ //it maybe id
ss << aTokenizer.current().data; unsigned int num = 0; ss >> num;
ss.clear();
ValueType* x = new ValueType(); *x = num;
string tempName = properties[index];
KeyValuePair* y = new KeyValuePair(make_pair(properties[index++],*x));
temp->getPair().push_back(*y);
temp->pair2[tempName] = *x;
}
else if(aTokenizer.current().type == TokenType::identifier){
//bool and string
if(aTokenizer.current().data == "TRUE" || aTokenizer.current().data == "FALSE"){
bool tempBool = aTokenizer.current().data == "TRUE" ? true : false;
ValueType* x = new ValueType(); *x = tempBool;
string tempName = properties[index];
KeyValuePair* y = new KeyValuePair(make_pair(properties[index++],*x));
temp->getPair().push_back(*y);
temp->pair2[tempName] = *x;
}
else{
ValueType* x = new ValueType(); *x = aTokenizer.current().data;
string tempName = properties[index];
KeyValuePair* y = new KeyValuePair(make_pair(properties[index++],*x));
temp->getPair().push_back(*y);
temp->pair2[tempName] = *x;
}
}
if(!aTokenizer.next()) return StatusResult(Errors::syntaxError);
}
rowList.push_back(temp);
}
aTokenizer.next();
}
return StatusResult();
}
StatusResult SelectStatement::parse(Tokenizer &aTokenizer){
//here, the aToken is at the first element
vector<string> showName;
bool from = false;
while(aTokenizer.current().data != ";" && aTokenizer.more()){
if(!from){
if(aTokenizer.current().data == "*"){
tableView.setIsStar(true);
}
else if(aTokenizer.current().keyword == Keywords::from_kw){
from = true;
aTokenizer.next();
if(aTokenizer.current().type != TokenType::identifier) return StatusResult(Errors::syntaxError);
else{
name = aTokenizer.current().data; //table name
}
//add showname
tableView.addShowName(showName);
//now let's check if we face a join
if(!aTokenizer.more1() || aTokenizer.current().data == ";"){
aTokenizer.next();
return StatusResult();
}
parseJoin(aTokenizer);
}
//show name
else if(aTokenizer.current().type == TokenType::identifier){
showName.push_back(aTokenizer.current().data);
}
}
else{
if(aTokenizer.current().keyword == Keywords::where_kw){
aTokenizer.next();
while(aTokenizer.more() && aTokenizer.current().keyword != Keywords::order_kw && aTokenizer.current().data != "LIMIT"){
if(aTokenizer.current().type == TokenType::identifier){
Operand* operand1 = new Operand(); operand1->name = aTokenizer.current().data;
aTokenizer.next();
Operators operators = operatorChange[aTokenizer.current().data];
aTokenizer.next();
Operand* operand2 = new Operand(); operand2->name = aTokenizer.current().data;
//add value create a value by a string
DataType tempType = database->getMap()[name]->getAttribute(operand1->name)->getType();
operand2->value = database->changeStringToDataType(aTokenizer.current().data, tempType);
//
Expression* expression = new Expression(*operand1,operators,*operand2);
filters.add(expression);
}
aTokenizer.next();
}
}
if(aTokenizer.current().keyword == Keywords::order_kw){
filters.order = true;
while(aTokenizer.more() && aTokenizer.current().data != "LIMIT"){
//除了没了 或者 limit 否则 继续
if(aTokenizer.current().type == TokenType::identifier){ // 按什么排顺序
filters.orderName = aTokenizer.current().data;
filters.sorter.field = filters.orderName; //终于定义好了
}
aTokenizer.next();
}
}
if(aTokenizer.current().data == "LIMIT"){
filters.limit = true;
std::stringstream ss;
aTokenizer.next();
ss << aTokenizer.current().data;
ss >> filters.limitNumber;
}
}
aTokenizer.next();
}
return StatusResult();
}
StatusResult UpdateStatement::parse(Tokenizer &aTokenizer){
if(aTokenizer.current().keyword != Keywords::update_kw) return StatusResult(Errors::syntaxError);
aTokenizer.next();
name = aTokenizer.current().data; //record table name
aTokenizer.next();
if(aTokenizer.current().keyword != Keywords::set_kw) return StatusResult(Errors::syntaxError);
aTokenizer.next();
while(aTokenizer.current().keyword != Keywords::where_kw){
string name = aTokenizer.current().data; //name
if(!aTokenizer.next()) return StatusResult(Errors::syntaxError); //next
if(aTokenizer.current().data != "=") return StatusResult(Errors::syntaxError); // =
if(!aTokenizer.next()) return StatusResult(Errors::syntaxError); //next
filters.updateValues[name] = aTokenizer.current().data;
if(!aTokenizer.next()) return StatusResult(Errors::syntaxError); //next
}
aTokenizer.next(); //jump where
while(aTokenizer.current().data != ";" && aTokenizer.more()){
if(aTokenizer.current().type == TokenType::identifier){
Operand* operand1 = new Operand(); operand1->name = aTokenizer.current().data;
aTokenizer.next();
Operators operators = operatorChange[aTokenizer.current().data];
aTokenizer.next();
Operand* operand2 = new Operand(); operand2->name = aTokenizer.current().data;
Expression* expression = new Expression(*operand1,operators,*operand2);
filters.add(expression);
}
else if(aTokenizer.current().keyword == Keywords::and_kw) filters.And = true;
else if(aTokenizer.current().keyword == Keywords::or_kw) filters.Or = true;
if(!aTokenizer.next()) return StatusResult(Errors::syntaxError);
}
return StatusResult();
}
StatusResult ShowIndexStatement::parse(Tokenizer &aTokenizer){
if(aTokenizer.current().keyword != Keywords::show_kw) return StatusResult(Errors::syntaxError);
while(aTokenizer.current().data != ";" && aTokenizer.more()){
aTokenizer.next();
}
return StatusResult();
}
StatusResult AlterStatement::parse(Tokenizer &aTokenizer){
if(aTokenizer.current().keyword != Keywords::alter_kw) return StatusResult(Errors::syntaxError);
aTokenizer.next(2);
name = aTokenizer.current().data;
aTokenizer.next();
//onlu for add right now
if(aTokenizer.current().keyword != Keywords::add_kw) return StatusResult(Errors::syntaxError);
aTokenizer.next();
attribute.setName(aTokenizer.current().data);
aTokenizer.next();
//type
switch(aTokenizer.current().keyword){
case Keywords::integer_kw:
attribute.setType(DataType::int_type); break;
case Keywords::float_kw:
attribute.setType(DataType::float_type); break;
case Keywords::varchar_kw:
attribute.setType(DataType::varchar_type); break;
case Keywords::boolean_kw:
attribute.setType(DataType::bool_type); break;
default:
attribute.setType(DataType::datetime_type); break;
}
aTokenizer.next();
while(aTokenizer.current().data != ";" && aTokenizer.more()){
if(aTokenizer.current().type == TokenType::number){
//length
stringstream ss;
int num = 0;
ss << aTokenizer.current().data; ss >> num; ss.clear();
attribute.setLength(num);
}
else if(aTokenizer.current().keyword == Keywords::auto_increment_kw){
attribute.setAutoIncrement(true);
}
aTokenizer.next();
}
return StatusResult();
}
StatusResult SelectStatement::parseTableName(Tokenizer& aTokenizer, string& theTable){
if(aTokenizer.current().type == TokenType::identifier){
theTable = aTokenizer.current().data;
aTokenizer.next();
}
return StatusResult();
}
StatusResult SelectStatement::parseTableField(Tokenizer& aTokenizer, TableField& theField){
if(aTokenizer.current().type == TokenType::identifier){
theField = aTokenizer.current().data;
aTokenizer.next();
if(aTokenizer.current().data == "."){
theField += ".";
aTokenizer.next();
}
else return StatusResult(Errors::syntaxError);
if(aTokenizer.current().type == TokenType::identifier){
theField += aTokenizer.current().data;
aTokenizer.next();
}
else return StatusResult(Errors::syntaxError);
}
return StatusResult();
}
StatusResult SelectStatement::parseJoin(Tokenizer &aTokenizer) {
Keywords theKeyWord = aTokenizer.peek(1).keyword;
StatusResult theResult{joinTypeExpected}; //add joinTypeExpected to your errors file if missing...
Keywords theJoinType{Keywords::join_kw}; //could just be a plain join
if(in_array<Keywords>(gJoinTypes, theKeyWord)) {
theJoinType=theKeyWord;
aTokenizer.next(2); //yank the 'join-type' token (e.g. left, right)
if(aTokenizer.skipIf(Keywords::join_kw)) {
std::string theTable;
if((theResult=parseTableName(aTokenizer, theTable))) {
Join theJoin(theTable, theJoinType, std::string(""),std::string(""));
theResult.code=keywordExpected; //on...
if(aTokenizer.skipIf(Keywords::on_kw)) { //LHS field = RHS field
TableField LHS("");
if((theResult=parseTableField(aTokenizer, theJoin.lhs))) {
if(aTokenizer.current().data == "=") {
aTokenizer.next();
if((theResult=parseTableField(aTokenizer, theJoin.rhs))) {
joins.push_back(theJoin);
}
}
}
}
}
}
}
return theResult;
}
StatusResult SelectStatement::addEmptyAttributes(Row& aRow1, const AttributeList & aList, string primaryName, RowColloection& aRowCollections) const{
Row* tempRow = new Row();
//add all in the Row1
for(auto it : aRow1.getPair()){
tempRow->getPair().push_back(it);
tempRow->pair2[it.first] = it.second;
}
//add all empty in Row2
for(Attribute i : aList){
if(i.getName() == primaryName) continue;
database->addNULLToRow(*tempRow, i);
}
aRowCollections.addRow(*tempRow);
return StatusResult();
}
bool SelectStatement::matchJoinCondition(Row& aRow1, Row& aRow2) const{
string* fields = joins[0].getFieldName();
string fieldLeft = fields[0];
string fieldRight = fields[1];
return aRow1.pair2[fieldLeft] == aRow2.pair2[fieldRight];
}
StatusResult SelectStatement::addTwoRows(Row& aRow1, Row& aRow2, RowColloection& aRowCollections) const{
Row* tempRow = new Row();
for(KeyValuePair i : aRow1.getPair()){
tempRow->getPair().push_back(i);
tempRow->pair2[i.first] = i.second;
}
string* fields = joins[0].getFieldName();
string fieldRight = fields[1];
for(KeyValuePair i : aRow2.getPair()){
if(i.first != fieldRight){
tempRow->getPair().push_back(i);
tempRow->pair2[i.first] = i.second;
}
}
aRowCollections.addRow(*tempRow);
return StatusResult();
}
StatusResult SelectStatement::addRightRow(RowColloection& aRowCollections, Row& aRow2, const AttributeList & aList, string primaryName) const{
Row* tempRow = new Row();
for(Attribute i : aList){
uint32_t temp = 0;
float temp1 = 0.0;
string temp2 = "";
ValueType* x = new ValueType();
switch (i.getType()){
case DataType::int_type:
*x = temp;
break;
case DataType::float_type:
*x = temp1;
break;
case DataType::bool_type:
*x = false;
break;
case DataType::varchar_type:
*x = temp2;
break;
default:
break;
}
KeyValuePair* pair = new KeyValuePair(make_pair(i.getName(),*x));
tempRow->getPair().push_back(*pair);
tempRow->pair2[i.getName()] = *x;
}
for(auto it : aRow2.getPair()){
string name = it.first;
if(name == primaryName) continue;
tempRow->getPair().push_back(it);
tempRow->pair2[name] = it.second;
}
aRowCollections.addRow(*tempRow);
return StatusResult();
}
bool SelectStatement::checkJoinName() const{
string* table = joins[0].getTableName();
string tableLeft = table[0];
string tableRight = table[1];
string* fields = joins[0].getFieldName();
string fieldLeft = fields[0];
string fieldRight = fields[1];
if(name != tableLeft) return false;
if(joins[0].table != tableRight) return false;
if(!database->getMap()[name]->hasAttributes(fieldLeft)) return false;
if(!database->getMap()[joins[0].table]->hasAttributes(fieldRight)) return false;
return true;
}