-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSQL_PARSER.hpp
More file actions
1863 lines (1578 loc) · 68.6 KB
/
Copy pathSQL_PARSER.hpp
File metadata and controls
1863 lines (1578 loc) · 68.6 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
#ifndef __PARSER_AST_HPP
#define __PARSER_AST_HPP
#include <algorithm>
#include <charconv>
#include "IndicatorHandler.hpp"
#include "strategyHandler.hpp"
#include <cmath>
#include <cstdint>
#include "hft.hpp"
#include <cstdio>
#include <exception>
#include <iostream>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include <memory>
#include <stdexcept>
#include "SQL_LEXER.hpp"
#include <filesystem> // Include for std::filesystem
#include <fstream>
#include "json.hpp"
#include "global.hpp"
#include "utility.hpp"
#include "generator.hpp"
#include "selectAstEvaluator.hpp"
#include "FastIndicators.hpp"
#include "initialLoad.hpp"
#include "batchWriter.hpp"
namespace fs = std::filesystem; // Shorthand for std::filesystem
bool fileExists(const std::string &filename)
{
return fs::exists(filename);
}
// ==== Parser ====
class Parser
{
private:
std::vector<Token *> tokens;
size_t position = 0;
Token *peek(int offset = 0)
{
if (position + offset >= tokens.size())
return nullptr;
return tokens[position + offset];
}
Token *current() { return peek(0); }
Token *advance()
{
if (position < tokens.size())
position++;
return previous();
}
Token *previous()
{
if (position == 0)
return nullptr;
return tokens[position - 1];
}
void rewind()
{
if (position > 0)
position--;
}
bool match(TokenType expected)
{
if (current() && current()->TYPE == expected)
{
advance();
return true;
}
return false;
}
Token *expect(TokenType expected, const std::string &message)
{
if (match(expected))
return previous();
throw std::runtime_error("Parse error: " + message);
}
public:
std::string currentDb = "";
Parser(const std::vector<Token *> &tokens) : tokens(tokens)
{
ensureCurrentDbFile(currentDbPath);
}
void ensureCurrentDbFile(const std::string &filePath)
{
fs::path parentDir = fs::path(filePath).parent_path();
if (!parentDir.empty() && !fs::exists(parentDir))
{
std::error_code ec;
if (fs::create_directories(parentDir, ec))
{
// std::cout << "Created directory: " << parentDir << std::endl;
}
else
{
throw std::runtime_error("Error creating directory: " + ec.message());
}
}
if (!fs::exists(filePath))
{
std::ofstream outfile(filePath);
if (outfile.is_open())
{
outfile << "{\"current_db\":\"test\"}" << std::endl; // JSON-style default
// std::cout << "File '" << filePath << "' created and initialized." << std::endl;
outfile.close();
currentDatabase = "test";
}
else
{
throw std::runtime_error("Error: Could not create file '" + filePath + "'");
}
}
else
{
std::ifstream in(filePath);
std::stringstream buffer;
buffer << in.rdbuf();
in.close();
std::string jsonContent = buffer.str();
JSONParser jsonParser;
if (!jsonParser.appendFromString(jsonContent))
{
throw std::runtime_error("Failed to parse current_db.meta JSON.");
}
JSONParser::JSONValue obj = jsonParser.getObject(0);
if (std::holds_alternative<JSONParser::JSONObject>(obj.value))
{
auto jsonObj = std::get<JSONParser::JSONObject>(obj.value);
if (jsonObj.find("current_db") != jsonObj.end())
{
const auto &val = jsonObj["current_db"];
if (std::holds_alternative<std::string>(val.value))
{
this->currentDb = std::get<std::string>(val.value); // store it inside parser
currentDatabase = this->currentDb;
}
}
}
}
}
std::unique_ptr<InsertStatement> parseInsertStatement() {
expect(TokenType::INSERT, "Expected 'INSERT'");
expect(TokenType::INTO, "Expected 'INTO'");
Token *tableToken = expect(TokenType::IDENTIFIER, "Expected table name");
std::unique_ptr<InsertStatement> stmt = std::make_unique<InsertStatement>();
stmt->tableName = tableToken->VALUE;
expect(TokenType::OPEN_PAREN, "Expected '(' before column list");
// Parse columnsParse
do {
Token *col = expect(TokenType::IDENTIFIER, "Expected column name");
stmt->columns.push_back(col->VALUE);
} while (match(TokenType::COMMA));
expect(TokenType::CLOSE_PAREN, "Expected ')' after column list");
expect(TokenType::VALUES, "Expected 'VALUES'");
expect(TokenType::OPEN_PAREN, "Expected '(' before values");
// Parse values
do {
if (match(TokenType::STRING) || match(TokenType::NUMBER)) {
stmt->values.push_back(previous()->VALUE);
} else {
throw std::runtime_error("Expected a STRING in quotes or a NUMBER");
}
} while (match(TokenType::COMMA));
expect(TokenType::CLOSE_PAREN, "Expected ')' after values");
expect(TokenType::SEMICOLON, "Expected ';' at end");
if (stmt->columns.size() != stmt->values.size()) {
throw std::runtime_error("Number of columns and values do not match make "
"sure you does not pass the primary key column");
}
std::pair<bool, std::string> check =
MyUtility::checkIfTableExist(stmt->tableName);
if (!check.first)
throw std::runtime_error(check.second);
else {
// std::cout << "#### BEFORE COMMAND RUNNER #### \n";
CommandRunner::generateInsertTableStatement(stmt);
// std::cout << "#### AFTER COMMAND RUNNER #### \n";
}
return stmt;
}
std::unique_ptr<UpdateStatement> parseUpdateStatement() {
std::lock_guard<std::mutex> dbLock(dbMutex);
auto stmt = std::make_unique<UpdateStatement>();
// UPDATE
expect(TokenType::UPDATE, "Expected UPDATE keyword");
// table name
Token* tableToken = expect(TokenType::IDENTIFIER, "Expected table name");
stmt->tableName = tableToken->VALUE;
// SET
expect(TokenType::SET, "Expected SET keyword");
// Parse assignments: col = value [, col = value]*
while (true) {
// column name
Token* column = expect(TokenType::IDENTIFIER, "Expected column name");
// =
expect(TokenType::EQUAL, "Expected '=' in SET clause");
// value
Token* value;
if (match(TokenType::STRING) || match(TokenType::NUMBER) || match(TokenType::IDENTIFIER)) {
value = previous();
} else {
throw std::runtime_error("Invalid value in UPDATE SET clause");
}
stmt->assignments.push_back({
column->VALUE,
value->VALUE
});
if (!match(TokenType::COMMA))
break;
}
// WHERE (mandatory)
if (!match(TokenType::WHERE)) {
throw std::runtime_error("UPDATE without WHERE is not allowed");
}
auto condition = parseExpression();
stmt->where = std::make_unique<WhereClause>(std::move(condition));
expect(TokenType::SEMICOLON, "Expected ';' after UPDATE statement");
return stmt;
}
std::string parseUseStatement(){
std::lock_guard<std::mutex> dbLock(dbMutex);
expect(TokenType::USE, "Expected USE keyword");
Token* dbName = expect(TokenType::IDENTIFIER, "Expected database name after USE");
expect(TokenType::SEMICOLON, "Expected ';' after USE statement");
std::string newDb = dbName->VALUE;
std::stringstream filename;
filename << dbDirectoryPath << "/" << newDb << ".shivam.db";
if (!MyUtility::checkIfFileExist(filename.str()))
{
throw std::runtime_error("Database does not exist: " + newDb);
}
globalJsonCache.clear();
globalTableCache.clear();
dbBtrees.clear();
currentDatabase = newDb;
this->currentDb=newDb;
MyUtility::changeCurrentDb(newDb);
initialDatabseLoad();
return newDb;
}
void parseDeleteStatement()
{
expect(TokenType::DELETE, "Expected DELETE keyword");
expect(TokenType::FROM, "Expected FROM keyword");
Token *table = expect(TokenType::IDENTIFIER, "Expected table name");
std::string tableName = table->VALUE;
// Create DELETE statement AST
auto stmt = std::make_unique<DeleteStatement>();
stmt->table = tableName;
// Optional WHERE clause
if (match(TokenType::WHERE))
{
auto condition = parseExpression();
stmt->whereClause = std::make_unique<WhereClause>(std::move(condition));
}
expect(TokenType::SEMICOLON, "Expected ';' after DELETE statement");
CommandRunner::handleDelete(stmt);
}
std::unique_ptr<CreateStatement> parseHFTCreateStatement(){
if(currentDb.empty()){
throw std::runtime_error("No database selected. Use USE <db_name>;");
}
std::unique_ptr<CreateStatement> stmt = std::make_unique<CreateStatement>();
expect(TokenType::HFT, "Expected HFT KEYWORD");
expect(TokenType::TABLE, "Expected TABLE KEYWORD");
Token * tableName = expect(TokenType::IDENTIFIER, "Expected table name");
stmt->name = tableName->VALUE;
expect(TokenType::OPEN_PAREN, "Expected '(' after table name");
while (!match(TokenType::CLOSE_PAREN)) {
Token * colName = expect(TokenType::IDENTIFIER,"Expected column name");
expect(TokenType::DOUBLE, "ONLY SUPPORT DOUBLE");
Token * typeToken = previous(); // DOUBLE
expect(TokenType::PRECISION, "use keyword precision after double");
expect(TokenType::NUMBER, "expected bit precision to be a number");
Token * bitToken = previous(); // BIT VALUE
// // std::cout<<"BIT TOKEN VALUE "<<bitToken->VALUE<<"\n";
ColumnDefinition column(colName->VALUE,typeToken->VALUE,static_cast<int16_t>(std::stoi(bitToken->VALUE)));
// column.print();
stmt->columns.push_back(column);
if (match(TokenType::COMMA))
{
continue;
}
else if (peek()->TYPE == TokenType::CLOSE_PAREN)
{
continue;
}
else
{
throw std::runtime_error("Expected ',' or ')' in column list");
}
}
expect(TokenType::SYMBOL, "use the symbol keyword\n");
expect(TokenType::NUMBER, "the symbol should be a number");
Token * sym = previous();
int32_t symbol = static_cast<int>(std::stoi(sym->VALUE));
if(symbol>(HFT::MAXHFTSYMBOL -1)){
std::stringstream s;
s<<"the symbol value is not more than "<<(HFT::MAXHFTSYMBOL -1) <<"\n";
std::runtime_error(s.str());
}
stmt->symbol = symbol;
stmt->print();
if (match(TokenType::AGGREGATES)){
expect(TokenType::OPEN_PAREN, "Expected '(' after AGGREGATES");
while(!match(TokenType::CLOSE_PAREN)){
if (match(TokenType::MEAN)){
expect(TokenType::NUMBER, "expected time value after mean");
Token * timeToken = previous();
int64_t time = static_cast<int64_t>(std::stoi(timeToken->VALUE));
expect(TokenType::NUMBER, "expected column index after time");
Token * colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("mean", time, colIdx, -1));
}
else if (match(TokenType::STDDEV)){
expect(TokenType::NUMBER, "expected time value after stddev");
Token * timeToken = previous();
int64_t time = static_cast<int64_t>(std::stoi(timeToken->VALUE));
expect(TokenType::NUMBER, "expected column index after time");
Token * colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("stddev", time, colIdx, -1));
}
else if (match(TokenType::MAX)){
expect(TokenType::NUMBER, "expected time value after max");
Token * timeToken = previous();
int64_t time = static_cast<int64_t>(std::stoi(timeToken->VALUE));
expect(TokenType::NUMBER, "expected column index after time");
Token * colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("max", time, colIdx, -1));
}
else if (match(TokenType::MIN)){
expect(TokenType::NUMBER, "expected time value after min");
Token * timeToken = previous();
int64_t time = static_cast<int64_t>(std::stoi(timeToken->VALUE));
expect(TokenType::NUMBER, "expected column index after time");
Token * colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("min", time, colIdx, -1));
}else if (match(TokenType::COUNT)){
expect(TokenType::NUMBER, "expected time value after count");
Token * timeToken = previous();
int64_t time = static_cast<int64_t>(std::stoi(timeToken->VALUE));
expect(TokenType::NUMBER, "expected column index after time");
Token * colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
expect(TokenType::NUMBER, "expected threshold value after column index");
Token * thresholdToken = previous();
int64_t threshold = static_cast<int64_t>(std::stoi(thresholdToken->VALUE));
stmt->aggregates.push_back(Aggregates("count", time, colIdx, threshold));
}else if (match(TokenType::MEAN_N)){
expect(TokenType::NUMBER, "Expect n after mean_n");
Token* nToken = previous();
int64_t n = static_cast<int64_t>(std::stoi(nToken->VALUE));
expect(TokenType::NUMBER, "Expect column index after n");
Token* colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("mean_n", n, colIdx, -1));
}else if (match(TokenType::STDDEV_N)){
expect(TokenType::NUMBER, "Expect n after stddev_n");
Token* nToken = previous();
int64_t n = static_cast<int64_t>(std::stoi(nToken->VALUE));
expect(TokenType::NUMBER, "Expect column index after n");
Token* colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("stddev_n", n, colIdx, -1));
}else if (match(TokenType::MAX_N)){
expect(TokenType::NUMBER, "Expect n after max_n");
Token* nToken = previous();
int64_t n = static_cast<int64_t>(std::stoi(nToken->VALUE));
expect(TokenType::NUMBER, "Expect column index after n");
Token* colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("max_n", n, colIdx, -1));
}else if (match(TokenType::MIN_N)){
expect(TokenType::NUMBER, "Expect n after min_n");
Token* nToken = previous();
int64_t n = static_cast<int64_t>(std::stoi(nToken->VALUE));
expect(TokenType::NUMBER, "Expect column index after n");
Token* colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
stmt->aggregates.push_back(Aggregates("min_n", n, colIdx, -1));
}else if (match(TokenType::COUNT_N)){
expect(TokenType::NUMBER, "EXpected n after count_n");
Token*ntoken=previous();
int64_t n = static_cast<int64_t>(std::stoi(ntoken->VALUE));
expect(TokenType::NUMBER, "Expect column index after n");
Token* colIdxToken = previous();
int32_t colIdx = static_cast<int32_t>(std::stoi(colIdxToken->VALUE));
expect(TokenType::NUMBER, "Expect threshold value after column index");
Token* thresholdToken = previous();
int64_t threshold = static_cast<int64_t>(std::stoi(thresholdToken->VALUE));
stmt->aggregates.push_back(Aggregates("count_n", n, colIdx, threshold));
}else{
throw std::runtime_error("Unexpected keyword found");
}
}
}
Token * curr = current();
if(curr->TYPE != TokenType::SEMICOLON){
expect(TokenType::TOP, "expected top variable for best bid and best ask price");
stmt->top = true;
}else stmt->top = false;
// std::cout<<"Create HFT Parsed\n";
CommandRunner::generateHFTCreateStatement(stmt);
return stmt;
}
std::unique_ptr<LISTStatement> parseListStatement(){
rewind();
std::unique_ptr<LISTStatement> statment = std::make_unique<LISTStatement>();
expect(TokenType::LIST, "expect key word list");
std::stringstream message;
if(match(TokenType::STRATEGY)){
for(auto it = HFT::InitalStorage::Indicators.begin(); it!=HFT::InitalStorage::Indicators.end();it++){
std::string name = it->first;
std::string file_path = it->second.first;
message << "indicator ";
message <<GREEN<< name << RESET <<" file path is "<<GREEN<<file_path<< RESET << "\n";
}
statment->isStrategy = true;
statment->message = message.str();
expect(TokenType::SEMICOLON, "epect token type semi colon at end");
return statment;
}else if(match(TokenType::TABLE)){
}
throw std::runtime_error("error expect either strategy or TABLE TABLE_NAME with LIST");
}
std::unique_ptr<StatisticsStatement> parseStatisticsStatement(){
expect(TokenType::STATISTICS, "Expected statistics keyword");
std::unique_ptr<StatisticsStatement>stmt=std::make_unique<StatisticsStatement>();
if (match(TokenType::MEAN)) stmt->type="mean";
else if (match(TokenType::COUNT)) stmt->type="count";
else if (match(TokenType::MAX))stmt->type="max";
else if (match(TokenType::MIN)) stmt->type="min";
else throw std::runtime_error("Unexpected Keyword");
expect(TokenType::FROM, "Expected from keyword");
Token*tableName=expect(TokenType::IDENTIFIER,"Expected table name");
stmt->tableName=tableName->VALUE;
expect(TokenType::ON, "Expected ON Keyword");
Token*colName=expect(TokenType::IDENTIFIER, "Expected column name");
stmt->colName=colName->VALUE;
if (match(TokenType::WHERE)){
auto condition = parseExpression();
stmt->whereClause = std::make_unique<WhereClause>(std::move(condition));
}
return stmt;
}
std::unique_ptr<CreateStatement> parseCreateStatement()
{
expect(TokenType::CREATE, "Expected CREATE keyword");
std::unique_ptr<CreateStatement> stmt = std::make_unique<CreateStatement>();
if (match(TokenType::TABLE))
{
if (currentDb.empty()){
throw std::runtime_error("No database selected. Use USE <db_name>;");
}
Token *tableName = expect(TokenType::IDENTIFIER, "Expected table name");
stmt->name = tableName->VALUE;
expect(TokenType::OPEN_PAREN, "Expected '(' after table name");
while (!match(TokenType::CLOSE_PAREN))
{
Token *colName = expect(TokenType::IDENTIFIER, "Expected column name");
Token *typeToken = current();
if (match(TokenType::INT) || match(TokenType::VARCHAR))
{
typeToken = previous();
}
else
{
throw std::runtime_error("Parse error: Expected column type (int or varchar)");
}
ColumnDefinition column(colName->VALUE, typeToken->VALUE);
// Handle VARCHAR(255) size syntax
if (typeToken->TYPE == TokenType::VARCHAR && match(TokenType::OPEN_PAREN))
{
Token *size = expect(TokenType::NUMBER, "Expected size in VARCHAR()");
expect(TokenType::CLOSE_PAREN, "Expected ')' after VARCHAR size");
column.type += "(" + size->VALUE + ")";
// // std::cout<<"PARSER COLUMN TYPE \n" << "COLUMN TYPE "<< column.type <<" size value "<<size->VALUE<<"\n";
}
// Parse optional constraints
while (true)
{
if (match(TokenType::NOT))
{
expect(TokenType::NULL_T, "Expected NULL after NOT");
column.constraints.push_back(ColumnConstraint::NOT_NULL);
}
else if (match(TokenType::PRIMARY))
{
expect(TokenType::KEY, "Expected KEY after PRIMARY");
column.constraints.push_back(ColumnConstraint::PRIMARY_KEY);
}
else if (match(TokenType::AUTO_INCREMENT))
{
column.constraints.push_back(ColumnConstraint::AUTO_INCREMENT);
}
else if (match(TokenType::UNIQUE))
{
column.constraints.push_back(ColumnConstraint::UNIQUE);
}
else
{
break;
}
}
stmt->columns.push_back(column);
if (match(TokenType::COMMA))
{
continue;
}
else if (peek()->TYPE == TokenType::CLOSE_PAREN)
{
continue;
}
else
{
throw std::runtime_error("Expected ',' or ')' in column list");
}
}
CommandRunner::generateCreateTableStatement(stmt);
}
else if (match(TokenType::DATABASE))
{
stmt->isDatabase = true;
stmt->name = expect(TokenType::IDENTIFIER, "Expected database name")->VALUE;
std::stringstream filename;
filename << dbDirectoryPath << "/";
filename << stmt->name;
filename << ".shivam.db";
if (MyUtility::checkIfFileExist(filename.str()))
{
throw std::runtime_error("Database already exists");
}
else
{
std::stringstream s;
s << R"(
{
"name": ")" << stmt->name
<< R"(",
"tables": []
}
)";
MyUtility::createFile(filename.str(), s.str());
currentDatabase = stmt->name;
MyUtility::changeCurrentDb(currentDatabase);
}
}
else
{
throw std::runtime_error("Expected TABLE or DATABASE keyword");
}
return stmt;
}
void parseMemoryStatement()
{
expect(TokenType::MEMORY, "Expected MEMORY keyword");
std::string key;
std::string value;
int ttl = -1; // -1 means no expiry
while (!match(TokenType::SEMICOLON))
{
if (match(TokenType::KEY))
{
expect(TokenType::EQUAL, "Expected '=' after KEY");
if (match(TokenType::IDENTIFIER) || match(TokenType::STRING) || match(TokenType::NUMBER))
{
key = previous()->VALUE;
}
else
{
throw std::runtime_error("Expected identifier or string after KEY=");
}
}
else if (match(TokenType::VALUES))
{
expect(TokenType::EQUAL, "Expected '=' after VALUE");
if (match(TokenType::IDENTIFIER) || match(TokenType::STRING) || match(TokenType::NUMBER))
{
value = previous()->VALUE;
}
else
{
throw std::runtime_error("Expected identifier or string after VALUE=");
}
}
else if (match(TokenType::TTL))
{
expect(TokenType::EQUAL, "Expected '=' after TTL");
Token *num = expect(TokenType::NUMBER, "Expected number after TTL=");
ttl = std::stoi(num->VALUE);
}
else
{
throw std::runtime_error(
"Unexpected token in MEMORY statement: " +
typeToString(current()->TYPE));
}
}
if (key.empty())
throw std::runtime_error("MEMORY command missing KEY");
if (value.empty())
throw std::runtime_error("MEMORY command missing VALUE");
CommandRunner::memorySet(key, value, ttl);
// std::cout << "MEMORY SET: " << key << " = " << value;
/* if (ttl >= 0)
// std::cout << " (TTL=" << ttl << "s)";
// std::cout << "\n"; */
}
void parseGetMemoryStatement()
{
expect(TokenType::MEMORY, "Expected MEMORY keyword");
if (match(TokenType::GET))
{
expect(TokenType::KEY, "Expected KEY after MEMORY GET");
expect(TokenType::EQUAL, "Expected '=' after KEY");
Token* keyTok;
if (match(TokenType::IDENTIFIER) || match(TokenType::STRING) || match(TokenType::NUMBER)) {
keyTok = previous();
} else {
throw std::runtime_error("Expected identifier/string/number after KEY=");
}
expect(TokenType::SEMICOLON, "Expected ';'");
const std::string& key = keyTok->VALUE;
std::string value;
if (CommandRunner::memoryGet(key, value)) {
// std::cout << "MEMORY GET: " << key << " = " << value << "\n";
} else {
// std::cout << "MEMORY GET: key '" << key << "' not found or expired\n";
}
}
}
std::unique_ptr<DropStatement> parseDropStatement()
{
expect(TokenType::DROP, "Expected drop keyword");
if (currentDb.empty()){
throw std::runtime_error("No database selected. Use USE <db_name>;");
}
auto stmt = std::make_unique<DropStatement>();
Token *token = advance();
switch (token->TYPE)
{
case TokenType::TABLE:
{
Token *identifier = expect(TokenType::IDENTIFIER, "not a identifier\n");
stmt->name = identifier->VALUE;
stmt->istable = true;
CommandRunner::generateDropStatement(stmt);
break;
}
break;
case TokenType::DATABASE:
{
Token *identifier = expect(TokenType::IDENTIFIER, "not a identifier\n");
stmt->name = identifier->VALUE;
stmt->istable = false;
CommandRunner::generateDropStatement(stmt);
globalJsonCache.clear();
globalTableCache.clear();
dbBtrees.clear();
MyUtility::changeCurrentDb("");
currentDatabase="";
currentDb="";
break;
}
default:
throw std::runtime_error("error in drop ");
}
return stmt;
}
std::unique_ptr<DisableStatement> parseDisableStatement(){
expect(TokenType::DISABLE, "expect token type disable");
expect(TokenType::BATCH, "expect token type batch");
expect(TokenType::WRITING, "expect token type writing");
expect(TokenType::ON, "expect token type on");
expect(TokenType::TABLE, "expect token type table");
Token * table =expect(TokenType::STRING, "expect table name to be string");
std::string table_name = table->VALUE;
std::unique_ptr<DisableStatement> statement = std::make_unique<DisableStatement>();
statement->tableName = table_name;
return statement;
}
std::unique_ptr<FetchIndicatorStatement> parseFetchIndicatorStatement(){
expect(TokenType::FETCH, "expect token type fetch");
expect(TokenType::INDICATOR, "expect token type indicator");
expect(TokenType::FROM, "expect token type from");
expect(TokenType::HFT, "expect token type hft");
expect(TokenType::SYMBOL, "expect token type symbol");
Token * token = expect(TokenType::NUMBER, "the symbol should be no");
int64_t symbol;
std::from_chars(token->VALUE.data(), token->VALUE.data() + token->VALUE.size(),symbol);
std::unique_ptr<FetchIndicatorStatement> statement = std::make_unique<FetchIndicatorStatement>();
statement->symbol = symbol;
return statement;
}
std::unique_ptr<Executebyfile> parseExecuteByFileStatement(){
expect(TokenType::EXECUTE, "expect token execute");
expect(TokenType::DB, "expect token db");
expect(TokenType::FILE, "expect token file");
Token * file_name = expect(TokenType::STRING, "expect file path to be string");
std::string file_path = file_name->VALUE;
fs::path p(file_path);
if (p.extension() != ".nanodb") {
throw std::runtime_error("Error: the file's extension should be .nanodb");
}
auto statement = std::make_unique<Executebyfile>();
std::ifstream file(file_path);
if (!file.is_open()) {
throw std::runtime_error("Error: Could not open file '" + file_path + "'");
}
std::string content((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
file.close();
std::vector<std::string> raw_commands;
std::string current_cmd;
for (char c : content) {
if (c == ';') {
std::string trimmed = current_cmd;
trimmed.erase(trimmed.begin(), std::find_if(trimmed.begin(), trimmed.end(), [](unsigned char ch) {
return ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n';
}));
trimmed.erase(std::find_if(trimmed.rbegin(), trimmed.rend(), [](unsigned char ch) {
return ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n';
}).base(), trimmed.end());
if (!trimmed.empty()) {
raw_commands.push_back(trimmed);
}
current_cmd.clear();
} else {
current_cmd += c;
}
}
std::string trimmed = current_cmd;
trimmed.erase(trimmed.begin(), std::find_if(trimmed.begin(), trimmed.end(), [](unsigned char ch) {
return ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n';
}));
trimmed.erase(std::find_if(trimmed.rbegin(), trimmed.rend(), [](unsigned char ch) {
return ch != ' ' && ch != '\t' && ch != '\r' && ch != '\n';
}).base(), trimmed.end());
if (!trimmed.empty()) {
raw_commands.push_back(trimmed);
}
for (auto &cmd : raw_commands) {
statement->commands.push_back(cmd);
std::string cmd_with_semicolon = cmd + ";";
Lexer file_lexer(cmd_with_semicolon);
std::vector<Token *> file_tokens = file_lexer.tokenize();
Parser file_parser(file_tokens);
file_parser.parse();
}
match(TokenType::SEMICOLON);
return statement;
}
std::unique_ptr<EnableStatement> parseEnableStatement(){
expect(TokenType::ENABLE, "expect token type enable");
expect(TokenType::BATCH, "expect token type batch");
expect(TokenType::WRITING, "expect token type writing");
expect(TokenType::ON, "expect token type on");
expect(TokenType::TABLE, "expect token type table");
Token * table =expect(TokenType::STRING, "expect table name to be string");
std::string table_name = table->VALUE;
expect(TokenType::TICKS, "expect tokens ticks");
Token * token = expect(TokenType::NUMBER, "expect ticks to be a number");
int64_t ticks_value;
std::from_chars(token->VALUE.data(),token->VALUE.data() + token->VALUE.size(),ticks_value);
std::unique_ptr<EnableStatement> statement = std::make_unique<EnableStatement>();
statement->tableName = table_name;
statement->ticks = ticks_value;
return statement;
}
// ENABLE strategy
std::unique_ptr<AddStrategyOnTableStatement> parseAddStrategystatement(){
expect(TokenType::ENABLE, "expect token type enable");
expect(TokenType::STRATEGY, "expect token type strategy");
Token * name = expect(TokenType::STRING, "the strategy name should be string");
std::string strategyName;
strategyName = name->VALUE;
std::vector<std::string> params;
if(match(TokenType::OPEN_PAREN)){
while (!match(TokenType::CLOSE_PAREN)) {
std::string val = expect(TokenType::STRING, "expect argument to be string")->VALUE;
// // std::cout<<"val is "<<val<<"\n";
params.push_back(val);
if (match(TokenType::COMMA)) {
continue;
} else if (peek(0) && peek(0)->TYPE == TokenType::CLOSE_PAREN) {
continue;
} else {
throw std::runtime_error("Parse error: expect ',' or ')' in parameter list");
}
}
}
expect(TokenType::ON, "expect token type ON");
expect(TokenType::SYMBOL, "expect token type symbol");
Token * symbol_token = expect(TokenType::NUMBER, "expect token type number");
int64_t symbol;
std::from_chars(symbol_token->VALUE.data(),symbol_token->VALUE.data() + symbol_token->VALUE.size(),symbol);
expect(TokenType::COLUMN_NO, "expect toekn type column_no");
Token * column_token = expect(TokenType::NUMBER, "expect column type number");
int64_t column;
std::from_chars(column_token->VALUE.data(),column_token->VALUE.data() + column_token->VALUE.size(),column);
expect(TokenType::TICKS, "expect token type ticks");
Token * tick = expect(TokenType::NUMBER, "token type tick should be number");
int64_t ticks;
std::from_chars(tick->VALUE.data(),tick->VALUE.data() + tick->VALUE.size(),ticks);
expect(TokenType::SEMICOLON, "expect token type semi colon");
std::unique_ptr<AddStrategyOnTableStatement> statement = std::make_unique<AddStrategyOnTableStatement>();
statement->strategy.first = strategyName;
statement->symbol = symbol;
statement->ticks = ticks;
statement->paramas = std::move(params);
return statement;
}
std::unique_ptr<WebSocketCommand> parseWebSocketCommand(){
expect(TokenType::APPLY, "expect token type Apply");
expect(TokenType::WEBSOCKET, "expect token webscoket");
expect(TokenType::ON,"expect token type on");
expect(TokenType::STRATEGY, "expect token type strategy ");
Token * strategy_name = expect(TokenType::STRING, "expect token type string ");
expect(TokenType::URL, "expect token type url");
Token * websocket_url = expect(TokenType::STRING,"expect the websocket url to be string");
std::unique_ptr<WebSocketCommand> statement = std::make_unique<WebSocketCommand>();
statement->url = websocket_url->VALUE;
statement->strategyName = strategy_name->VALUE;
return statement;
}
std::unique_ptr<AddIndicatorOnTableStatement> parseAddIndicatorOnTableStatement(){
std::unique_ptr<AddIndicatorOnTableStatement> statement = std::make_unique<AddIndicatorOnTableStatement>();
expect(TokenType::ADD, "expect Token type add");
expect(TokenType::INDICATOR, "expect token type indictor");
std::string indicatorName ;
Token * indicator = expect(TokenType::STRING, "expect indicator name as string");
indicatorName = indicator->VALUE;
std::vector<std::string> params;
if(match(TokenType::OPEN_PAREN)){
while (!match(TokenType::CLOSE_PAREN)) {
std::string val = expect(TokenType::STRING, "expect argument to be string")->VALUE;
// // std::cout<<"val is "<<val<<"\n";
params.push_back(val);
if (match(TokenType::COMMA)) {
continue;
} else if (peek(0) && peek(0)->TYPE == TokenType::CLOSE_PAREN) {
continue;
} else {
throw std::runtime_error("Parse error: expect ',' or ')' in parameter list");
}