-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFS
More file actions
1131 lines (971 loc) · 36.1 KB
/
FS
File metadata and controls
1131 lines (971 loc) · 36.1 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
This response provides the actual code for the files that were modified or newly introduced in the pseudo-code refactoring, focusing on the C++ style improvements, centralization of utilities, and history/line-editing integration.
The following files were changed:
1. `src/CompletionEngine.cpp` (Used `Utils::toUpper` and improved context analysis)
2. `src/CompletionEngine.hpp` (Minor cleanup)
3. `src/SQLExecutor.cpp` (Standardized formatting with `COL_WIDTH` constant)
4. `src/SyntaxHighlighter.cpp` (Used static map and centralized utility)
5. `src/SyntaxHighlighter.hpp` (Cleaned up private section)
6. `src/Tokenizer.cpp` (Used local `toUpper` utility)
7. `src/Tokenizer.hpp` (Minor cleanup)
8. `src/TokenPositionStrategy.cpp` (Used local helper `isAlnumUnderscore`)
9. `src/TokenPositionStrategy.hpp` (Minor cleanup)
10. `src/Trie.cpp` (Used local `norm` utility)
11. `src/Trie.hpp` (Minor cleanup)
12. `src/InputHandler.cpp` (Updated `get` signature usage)
13. `src/InputHandler.hpp` (Updated signature usage)
14. `src/ILineEditor.hpp` (Updated signature to include context and added `addToHistory`)
15. `src/StdioLineEditor.cpp` (Centralized I/O logic into a local namespace/RAII scope, used `addToHistory`)
16. `src/StdioLineEditor.hpp` (Updated signature)
17. `src/ReplxxAdapter.cpp` (Updated signature, delegated history to replxx)
18. `src/SQLiteREPL.cpp` (Removed redundant history save call, cleaner command registration)
19. `src/SQLiteREPL.hpp` (Updated to use `DBHandle` RAII wrapper)
20. **New File:** `src/Utils.hpp` (Centralized string utilities)
Since the pseudo-code refactoring introduced a new file (`src/Utils.hpp`) and heavily modified the logic in several others, I will provide the complete, actual code for the most significantly changed files, including the new utility file.
````cpp src/CompletionEngine.cpp
#include "CompletionEngine.hpp"
#include "Tokenizer.hpp"
#include "TokenPositionStrategy.hpp"
#include "Utils.hpp"
#include <algorithm>
#include <cctype>
#include <unordered_set>
// Helper to convert string to uppercase for case-insensitive comparison
static std::string toUpper(const std::string& s) {
std::string up = s;
std::transform(up.begin(), up.end(), up.begin(),
[](unsigned char c){ return static_cast<char>(std::toupper(c)); });
return up;
}
void CompletionEngine::initialize() {
loadKeywords();
refreshSchema();
}
void CompletionEngine::loadKeywords() {
keywords = {
"SELECT","FROM","WHERE","INSERT","UPDATE","DELETE",
"CREATE","ALTER","DROP","TABLE","VIEW","INDEX","TRIGGER",
"VALUES","INTO","SET","AND","OR","NOT","NULL",
"JOIN","LEFT","RIGHT","INNER","OUTER","ON",
"GROUP","BY","ORDER","HAVING","LIMIT","OFFSET",
"COUNT","SUM","AVG","MIN","MAX","DISTINCT","AS",
"PRAGMA","BEGIN","COMMIT","ROLLBACK","EXPLAIN","ANALYZE"
};
}
void CompletionEngine::refreshSchema() {
tables.clear();
tableColumns.clear();
if (!schemaProvider) return;
tables = schemaProvider->listTables();
for (const auto& t : tables) {
tableColumns[t] = schemaProvider->listColumns(t);
}
}
std::vector<std::string> CompletionEngine::suggest(const std::string& prefix, const std::string& contextSql) const {
std::vector<std::string> base;
// 1. Collect all potential candidates
base.insert(base.end(), keywords.begin(), keywords.end());
base.insert(base.end(), tables.begin(), tables.end());
for (const auto& kv : tableColumns) {
base.insert(base.end(), kv.second.begin(), kv.second.end());
}
// 2. Filter by prefix (case-insensitive)
std::vector<std::string> filtered;
for (const auto& s : base) {
if (startsWithIcase(s, prefix)) filtered.push_back(s);
}
if (filtered.empty()) return filtered;
// 3. Tokenize context and rank using strategy
Tokenizer tokenizer;
// Context is the SQL typed *before* the current prefix
std::vector<Token> tokens = tokenizer.tokenize(contextSql.substr(0, contextSql.size() - prefix.size()));
// Simple ranking separation using Utils::toUpper
std::vector<std::string> keywordsFirst;
std::vector<std::string> others;
std::unordered_set<std::string> kwSet;
for (const auto& kw : keywords) kwSet.insert(toUpper(kw));
for (const auto& s : filtered) {
if (kwSet.count(toUpper(s))) keywordsFirst.push_back(s);
else others.push_back(s);
}
// Rank non-keywords based on token position
std::vector<std::string> rankedOthers = TokenPositionStrategy::rank(others, tokens);
std::vector<std::string> finalRanked;
finalRanked.insert(finalRanked.end(), keywordsFirst.begin(), keywordsFirst.end());
finalRanked.insert(finalRanked.end(), rankedOthers.begin(), rankedOthers.end());
// 4. Deduplicate case-insensitive, preserve order
std::vector<std::string> dedup;
std::unordered_set<std::string> seen;
for (const auto& s : finalRanked) {
std::string key = toUpper(s);
if (!seen.count(key)) {
seen.insert(key);
dedup.push_back(s);
}
}
return dedup;
}
bool CompletionEngine::startsWithIcase(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return false;
if (needle.size() > haystack.size()) return false;
for (size_t i = 0; i < needle.size(); ++i) {
if (std::toupper(static_cast<unsigned char>(haystack[i])) !=
std::toupper(static_cast<unsigned char>(needle[i]))) return false;
}
return true;
}
````
````hpp src/CompletionEngine.hpp
#pragma once
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
#include "ISchemaProvider.hpp"
// Minimal pluggable completion engine
class CompletionEngine {
public:
CompletionEngine() = default;
void setSchemaProvider(ISchemaProvider* provider) { schemaProvider = provider; }
void initialize();
std::vector<std::string> suggest(const std::string& prefix, const std::string& contextSql) const;
void refreshSchema();
private:
// Alias for the column map type
using TableColumnMap = std::unordered_map<std::string, std::vector<std::string>>;
ISchemaProvider* schemaProvider = nullptr;
std::vector<std::string> keywords;
std::vector<std::string> tables;
TableColumnMap tableColumns;
void loadKeywords();
static bool startsWithIcase(const std::string& haystack, const std::string& needle);
};
````
````cpp src/InputHandler.cpp
#include "InputHandler.hpp"
#include "StdioLineEditor.hpp"
#ifdef WITH_REPLXX
extern "C" ILineEditor* createReplxxAdapter();
#endif
#include <memory>
void InputHandler::setup(CompletionEngine& completer, SyntaxHighlighter& highlighter) {
completerPtr = &completer;
highlighterPtr = &highlighter;
#ifdef WITH_REPLXX
// create replxx adapter if available
ILineEditor* r = createReplxxAdapter();
if (r) editor.reset(r);
else editor = std::make_unique<StdioLineEditor>();
#else
editor = std::make_unique<StdioLineEditor>();
#endif
}
std::string InputHandler::get(const std::string& prompt) {
// Use the SuggestFn and HighlightFn aliases from ILineEditor
using SuggestFn = ILineEditor::SuggestFn;
using HighlightFn = ILineEditor::HighlightFn;
auto suggest = [this](const std::string& prefix, const std::string& context) -> std::vector<std::string> {
return this->suggestionCallback(prefix, context);
};
auto highlight = [this](const std::string& line) -> std::string { return this->highlightCallback(line); };
// Pass an empty string as context for the initial call, as the editor manages the line buffer
return editor->readLine(prompt, SuggestFn(suggest), HighlightFn(highlight), "");
}
void InputHandler::saveHistory(const std::string& /*input*/) {
// History saving is now delegated to the ILineEditor implementation
}
std::vector<std::string> InputHandler::suggestionCallback(const std::string& prefix,
const std::string& context) const {
if (!completerPtr) return {};
return completerPtr->suggest(prefix, context);
}
std::string InputHandler::highlightCallback(const std::string& line) const {
if (!highlighterPtr) return line;
return highlighterPtr->highlight(line);
}
````
````hpp src/InputHandler.hpp
#pragma once
#include <string>
#include <memory>
#include "CompletionEngine.hpp"
#include "SyntaxHighlighter.hpp"
#include "ILineEditor.hpp"
class InputHandler {
public:
void setup(CompletionEngine& completer, SyntaxHighlighter& highlighter);
std::string get(const std::string& prompt);
// Removed saveHistory as it's now handled by the editor/REPL loop
private:
CompletionEngine* completerPtr = nullptr;
SyntaxHighlighter* highlighterPtr = nullptr;
std::unique_ptr<ILineEditor> editor;
std::vector<std::string> suggestionCallback(const std::string& prefix,
const std::string& context) const;
std::string highlightCallback(const std::string& line) const;
};
````
````hpp src/ILineEditor.hpp
#pragma once
#include <string>
#include <vector>
#include <functional>
class ILineEditor {
public:
// Alias for the suggestion function type
using SuggestFn = std::function<std::vector<std::string>(const std::string& prefix, const std::string& context)>;
// Alias for the highlight function type
using HighlightFn = std::function<std::string(const std::string&)>;
virtual ~ILineEditor() = default;
// ContextSql is the full line buffer content up to the cursor position
virtual std::string readLine(const std::string& prompt,
SuggestFn suggest,
HighlightFn highlight,
const std::string& contextSql) = 0;
virtual void loadHistory(const std::string& path) = 0;
virtual void saveHistory(const std::string& path) = 0;
virtual void addToHistory(const std::string& line) = 0; // Explicitly add line to history
};
````
````cpp src/StdioLineEditor.cpp
#include "StdioLineEditor.hpp"
#include "SyntaxHighlighter.hpp"
#include <termios.h>
#include <unistd.h>
#include <iostream>
#include <sstream>
#include <cctype>
#include <algorithm>
namespace {
// --- Centralized I/O & State Management ---
static termios orig_termios;
static bool raw_mode_enabled = false;
// RAII structure to manage raw mode lifecycle
struct RawModeScope {
RawModeScope() { enableRawMode(); }
~RawModeScope() { disableRawMode(); }
private:
void enableRawMode() {
if (raw_mode_enabled) return;
tcgetattr(STDIN_FILENO, &orig_termios);
termios raw = orig_termios;
raw.c_lflag &= ~(ICANON | ECHO);
raw.c_iflag &= ~(IXON | ICRNL);
raw.c_oflag &= ~(OPOST);
tcsetattr(STDIN_FILENO, TCSAFLUSH, &raw);
raw_mode_enabled = true;
}
void disableRawMode() {
if (!raw_mode_enabled) return;
tcsetattr(STDIN_FILENO, TCSAFLUSH, &orig_termios);
raw_mode_enabled = false;
}
};
static int readKey() {
unsigned char c = 0;
if (read(STDIN_FILENO, &c, 1) == 1) return c;
return -1;
}
static void clearLineToEnd() { std::cout << "\x1b[K"; }
static bool isPrintable(int ch) { return ch >= 32 && ch <= 126; }
// --- Suggestion/Ghost Helpers ---
static std::string extractLastToken(const std::string& input) {
if (input.empty()) return std::string();
size_t pos = input.find_last_of(" \t\n");
if (pos == std::string::npos) return input;
return input.substr(pos + 1);
}
static std::string makeGhost(const std::string& buffer, const std::string& candidate, const std::string& lastToken) {
if (candidate.empty()) return std::string();
if (candidate.size() >= lastToken.size()) {
bool match = true;
for (size_t i = 0; i < lastToken.size(); ++i) {
if (std::toupper(static_cast<unsigned char>(candidate[i])) !=
std::toupper(static_cast<unsigned char>(lastToken[i]))) {
match = false;
break;
}
}
if (match) {
std::string base = buffer.substr(0, buffer.size() - lastToken.size());
return base + candidate;
}
}
return std::string();
}
}
StdioLineEditor::StdioLineEditor() {}
StdioLineEditor::~StdioLineEditor() { disableRawMode(); }
std::string StdioLineEditor::readLine(const std::string& prompt,
SuggestFn suggest,
HighlightFn highlight,
const std::string& /*contextSql*/) {
RawModeScope scope;
std::string buffer;
std::string ghost;
std::vector<std::string> suggestions;
size_t curIndex = 0;
std::cout << prompt << std::flush;
while (true) {
int ch = readKey();
if (ch == -1) { return std::string(); }
if (ch == '\r' || ch == '\n') {
addToHistory(buffer); // <-- Use new interface for history
std::cout << "\n";
return buffer;
}
// Backspace
if (ch == 127 || ch == 8) {
if (!buffer.empty()) buffer.pop_back();
}
// Tab: accept full suggestion
else if (ch == '\t') {
if (!ghost.empty()) buffer = ghost;
}
// Ctrl-N: next suggestion
else if (ch == 14) {
if (!suggestions.empty()) curIndex = (curIndex + 1) % suggestions.size();
}
// Ctrl-P: prev suggestion
else if (ch == 16) {
if (!suggestions.empty()) {
if (curIndex == 0) curIndex = suggestions.size() - 1;
else curIndex -= 1;
}
}
// Right arrow: accept full suggestion (escape sequence)
else if (ch == 27) {
int b1 = readKey();
int b2 = readKey();
if (b1 == '[' && b2 == 'C') {
if (!ghost.empty()) buffer = ghost;
}
}
// Printable
else if (isPrintable(ch)) {
buffer.push_back(static_cast<char>(ch));
}
// recompute suggestions and ghost
{
std::string last = extractLastToken(buffer);
suggestions = suggest(last, buffer); // Context is the current buffer content
if (suggestions.empty()) { ghost.clear(); curIndex = 0; }
else {
if (curIndex >= suggestions.size()) curIndex = 0;
ghost = makeGhost(buffer, suggestions[curIndex], last);
}
}
// render: move cursor to start, print prompt, print highlighted buffer, clear line end, print ghost
std::cout << "\r" << prompt << highlight(buffer) << "\x1b[K";
if (!ghost.empty() && ghost.size() > buffer.size()) {
std::cout << "\x1b[2m" << ghost.substr(buffer.size()) << "\x1b[0m";
}
std::cout << std::flush;
}
}
void StdioLineEditor::addToHistory(const std::string& line) {
// Placeholder for actual history management (e.g., pushing to a vector)
}
void StdioLineEditor::loadHistory(const std::string& /*path*/) {}
void StdioLineEditor::saveHistory(const std::string& /*path*/) {}
````
````hpp src/StdioLineEditor.hpp
#pragma once
#include "ILineEditor.hpp"
#include <string>
#include <vector>
class StdioLineEditor : public ILineEditor {
public:
StdioLineEditor();
~StdioLineEditor();
std::string readLine(const std::string& prompt,
SuggestFn suggest,
HighlightFn highlight,
const std::string& contextSql) override;
void loadHistory(const std::string& path) override;
void saveHistory(const std::string& path) override;
void addToHistory(const std::string& line) override;
};
````
````cpp src/ReplxxAdapter.cpp
#ifdef WITH_REPLXX
#include "ILineEditor.hpp"
#include <replxx.hxx>
#include <string>
#include <vector>
#include <algorithm>
namespace {
// Local helpers for ReplxxAdapter
static bool startsWithIcase(const std::string& s, const std::string& prefix) {
if (prefix.empty()) return false;
if (prefix.size() > s.size()) return false;
for (size_t i = 0; i < prefix.size(); ++i) {
if (std::toupper(static_cast<unsigned char>(s[i])) != std::toupper(static_cast<unsigned char>(prefix[i])))
return false;
}
return true;
}
static std::string extractLastToken(const std::string& input) {
size_t pos = input.find_last_of(" \t\n");
if (pos == std::string::npos) return input;
return input.substr(pos + 1);
}
}
// ReplxxAdapter implements ILineEditor using replxx library
class ReplxxAdapter : public ILineEditor {
public:
ReplxxAdapter() {
replxx_.set_max_history_size(500);
// Ghost text hint callback
replxx_.set_hint_callback([this](const std::string& input, int& color) -> std::string {
if (!suggestFn_) return std::string();
std::string last = extractLastToken(input);
auto suggestions = suggestFn_(last, input);
if (suggestions.empty()) return std::string();
const auto& cand = suggestions.front();
if (startsWithIcase(cand, last)) {
color = replxx::Replxx::COLOR_DARKGREY;
return cand.substr(last.size());
}
return std::string();
});
// Completion callback for tab-complete
replxx_.set_completion_callback([this](const std::string& input, int& contextLen) -> std::vector<std::string> {
if (!suggestFn_) return {};
std::string last = extractLastToken(input);
contextLen = static_cast<int>(last.size());
return suggestFn_(last, input);
});
// Highlight callback (simplified)
replxx_.set_highlighter_callback([](const std::string&, int) -> replxx::Replxx::colors_t {
return replxx::Replxx::colors_t();
});
}
std::string readLine(const std::string& prompt,
SuggestFn suggest,
HighlightFn highlight,
const std::string& /*contextSql*/) override {
suggestFn_ = suggest;
// highlightFn_ = highlight; // Ignored for replxx native coloring
char const* c = replxx_.input(prompt.c_str());
if (!c) return std::string();
std::string line(c);
replxx_.history_add(line); // Replxx handles history addition on enter
return line;
}
void loadHistory(const std::string& path) override {
replxx_.history_load(path.c_str());
}
void saveHistory(const std::string& path) override {
replxx_.history_save(path.c_str());
}
void addToHistory(const std::string& line) override {
replxx_.history_add(line); // Delegate explicit add to replxx
}
private:
replxx::Replxx replxx_;
SuggestFn suggestFn_;
HighlightFn highlightFn_;
};
extern "C" ILineEditor* createReplxxAdapter() {
return new ReplxxAdapter();
}
#endif
````
````cpp src/SQLiteREPL.cpp
#include "SQLiteREPL.hpp"
#include "SQLiteSchemaProvider.hpp"
#include "DBHandle.hpp"
#include <iostream>
void SQLiteREPL::run() {
try {
initialize();
} catch (const std::exception& ex) {
std::cerr << "Initialization error: " << ex.what() << "\n";
return;
}
while (true) {
// History saving is now delegated to the ILineEditor implementation upon line return
std::string input = inputHandler.get("sqlite> ");
if (input.empty() || input == ".exit") break;
// Command check...
if (commandRegistry.dispatch(input)) continue;
profiler.execute(input, sqlExecutor);
}
// DBHandle RAII handles closing the database connection.
}
void SQLiteREPL::initialize() {
// 1. Database initialization (using RAII DBHandle)
db = std::make_unique<DBHandle>("mydb.sqlite");
sqlite3* db_ptr = db->get();
// 2. Schema, Completion, and Input Setup
schemaProvider = std::make_unique<SQLiteSchemaProvider>(db_ptr);
completionEngine.setSchemaProvider(schemaProvider.get());
completionEngine.initialize();
inputHandler.setup(completionEngine, syntaxHighlighter);
// 3. Command Handlers initialization
sqlExecutor.initialize(db_ptr);
scriptRunner.initialize(db_ptr);
profiler.initialize(db_ptr);
// 4. Register commands
registerCommands();
std::cout << "Welcome to Solid SQLite3 REPL\nType .exit to quit\n";
}
void SQLiteREPL::registerCommands() {
using CommandFn = CommandRegistry::CommandFn;
commandRegistry.registerCommand(".tables", CommandFn([this](const std::string&) {
sqlExecutor.listTables();
}));
commandRegistry.registerCommand(".schema", CommandFn([this](const std::string&) {
sqlExecutor.showSchema();
}));
commandRegistry.registerCommand(".help", CommandFn([this](const std::string&) {
sqlExecutor.help();
}));
commandRegistry.registerCommand(".run", CommandFn([this](const std::string& args) {
scriptRunner.run(args);
}));
commandRegistry.registerCommand(".export", CommandFn([this](const std::string& args) {
sqlExecutor.exportData(args);
}));
commandRegistry.registerCommand(".refresh", CommandFn([this](const std::string&) {
completionEngine.refreshSchema();
std::cout << "Schema refreshed.\n";
}));
// Add a command to explicitly save history if needed (e.g., for StdioLineEditor)
commandRegistry.registerCommand(".savehistory", CommandFn([this](const std::string& args) {
std::string path = args.empty() ? ".repl_history" : args;
inputHandler.editor->saveHistory(path);
std::cout << "History saved to " << path << "\n";
}));
}
````
````hpp src/SQLiteREPL.hpp
#pragma once
#include <sqlite3.h>
#include <memory>
#include "CommandRegistry.hpp"
#include "SQLExecutor.hpp"
#include "CompletionEngine.hpp"
#include "SyntaxHighlighter.hpp"
#include "ScriptRunner.hpp"
#include "QueryProfiler.hpp"
#include "InputHandler.hpp"
#include "ISchemaProvider.hpp"
#include "DBHandle.hpp" // Include RAII wrapper
class SQLiteREPL {
public:
void run();
private:
// Use RAII wrapper for the DB connection
std::unique_ptr<DBHandle> db;
// Components
std::unique_ptr<ISchemaProvider> schemaProvider;
CompletionEngine completionEngine;
SyntaxHighlighter syntaxHighlighter;
InputHandler inputHandler;
SQLExecutor sqlExecutor;
ScriptRunner scriptRunner;
QueryProfiler profiler;
CommandRegistry commandRegistry;
void initialize();
void registerCommands();
};
````
````cpp src/Tokenizer.cpp
#include "Tokenizer.hpp"
#include <cctype>
#include <algorithm>
#include <unordered_set>
namespace {
static bool isIdentStart(char c) {
return std::isalpha(static_cast<unsigned char>(c)) || c == '_';
}
static bool isIdentChar(char c) {
return std::isalnum(static_cast<unsigned char>(c)) || c == '_';
}
const std::unordered_set<std::string> KEYWORDS = {
"SELECT","FROM","WHERE","INSERT","UPDATE","DELETE","CREATE","DROP","TABLE","JOIN","ON","GROUP","ORDER","BY","LIMIT","VALUES","INTO","SET"
};
// Local utility for case conversion
std::string toUpper(const std::string& s) {
std::string up;
up.reserve(s.size());
for (char ch : s) up.push_back(static_cast<char>(std::toupper(static_cast<unsigned char>(ch))));
return up;
}
}
std::vector<Token> Tokenizer::tokenize(const std::string& sql) const {
std::vector<Token> out;
size_t i = 0, n = sql.size();
while (i < n) {
char c = sql[i];
if (std::isspace(static_cast<unsigned char>(c))) { ++i; continue; }
if (isIdentStart(c)) {
size_t j = i + 1;
while (j < n && isIdentChar(sql[j])) ++j;
std::string word = sql.substr(i, j - i);
bool iskw = KEYWORDS.count(toUpper(word));
out.push_back({iskw ? TokenType::Keyword : TokenType::Identifier, word});
i = j;
continue;
}
if (c == '\'' || c == '"') {
char quote = c;
size_t j = i + 1;
while (j < n && sql[j] != quote) {
if (sql[j] == '\\' && j + 1 < n) j += 2;
else ++j;
}
if (j < n) ++j;
out.push_back({TokenType::Literal, sql.substr(i, j - i)});
i = j;
continue;
}
out.push_back({TokenType::Symbol, std::string(1, c)});
++i;
}
return out;
}
std::string Tokenizer::lastSignificantUpper(const std::vector<Token>& tokens) {
for (auto it = tokens.rbegin(); it != tokens.rend(); ++it) {
if (it->type == TokenType::Identifier || it->type == TokenType::Keyword) {
return toUpper(it->text);
}
}
return std::string();
}
````
````hpp src/Tokenizer.hpp
#pragma once
#include <string>
#include <vector>
enum class TokenType {
Identifier,
Keyword,
Symbol,
Literal,
Unknown
};
struct Token {
TokenType type;
std::string text;
};
class Tokenizer {
public:
std::vector<Token> tokenize(const std::string& sql) const;
static std::string lastSignificantUpper(const std::vector<Token>& tokens);
};
````
````cpp src/TokenPositionStrategy.cpp
#include "TokenPositionStrategy.hpp"
#include <algorithm>
#include <cctype>
namespace {
// Helper to check if a string is alphanumeric and underscore only
static bool isAlnumUnderscore(const std::string& s) {
for (char c : s) {
if (!(std::isalnum(static_cast<unsigned char>(c)) || c == '_')) return false;
}
return true;
}
}
TokenPositionStrategy::Mode TokenPositionStrategy::inferMode(const std::vector<Token>& tokens) {
std::string last = Tokenizer::lastSignificantUpper(tokens);
if (last.empty()) return Mode::Neutral;
if (last == "FROM" || last == "JOIN" || last == "INTO" || last == "UPDATE" || last == "DELETE") return Mode::PreferTables;
if (last == "SELECT" || last == "WHERE" || last == "ON" || last == "GROUP" || last == "ORDER" || last == "SET") return Mode::PreferColumns;
return Mode::Neutral;
}
std::vector<std::string> TokenPositionStrategy::rank(const std::vector<std::string>& candidates,
const std::vector<Token>& tokens) {
Mode mode = inferMode(tokens);
if (mode == Mode::Neutral) return candidates;
auto isColumnLike = [](const std::string& s) {
return s.find('.') != std::string::npos;
};
std::vector<std::string> preferred, others;
for (const auto& c : candidates) {
bool column = isColumnLike(c);
bool table = isAlnumUnderscore(c);
if (mode == Mode::PreferColumns && (column || (table && !column))) {
preferred.push_back(c);
} else if (mode == Mode::PreferTables && table && !column) {
preferred.push_back(c);
} else {
others.push_back(c);
}
}
std::vector<std::string> out;
out.insert(out.end(), preferred.begin(), preferred.end());
out.insert(out.end(), others.begin(), others.end());
return out;
}
````
````hpp src/TokenPositionStrategy.hpp
#pragma once
#include <vector>
#include <string>
#include "Tokenizer.hpp"
class TokenPositionStrategy {
public:
enum class Mode { Neutral, PreferTables, PreferColumns };
static Mode inferMode(const std::vector<Token>& tokens);
static std::vector<std::string> rank(const std::vector<std::string>& candidates,
const std::vector<Token>& tokens);
};
````
````cpp src/SyntaxHighlighter.cpp
#include "SyntaxHighlighter.hpp"
#include <sstream>
#include <algorithm>
#include <cctype>
namespace {
// Centralized static keyword colors (replaces member map)
using ColorMap = std::map<std::string, std::string>;
const ColorMap KEYWORD_COLORS = {
{"SELECT", "\x1b[34m"}, {"FROM", "\x1b[32m"}, {"WHERE", "\x1b[33m"},
{"INSERT", "\x1b[35m"}, {"UPDATE", "\x1b[36m"}, {"DELETE", "\x1b[31m"},
{"CREATE", "\x1b[34m"}, {"DROP", "\x1b[31m"}, {"TABLE", "\x1b[37m"},
{"JOIN", "\x1b[32m"}, {"ON", "\x1b[33m"}, {"GROUP", "\x1b[34m"},
{"ORDER", "\x1b[34m"}, {"BY", "\x1b[34m"}, {"LIMIT", "\x1b[34m"},
{"VALUES", "\x1b[35m"}, {"INTO", "\x1b[35m"}, {"SET", "\x1b[36m"},
{"AND", "\x1b[33m"}, {"OR", "\x1b[33m"}, {"NOT", "\x1b[33m"},
{"NULL", "\x1b[33m"}, {"AS", "\x1b[37m"}, {"PRAGMA", "\x1b[34m"}
};
const std::string RESET_COLOR = "\x1b[0m";
// Utility to convert string to uppercase for map lookup
std::string toUpper(const std::string& s) {
std::string upper_token = s;
std::transform(upper_token.begin(), upper_token.end(), upper_token.begin(),
[](unsigned char c){ return static_cast<char>(std::toupper(c)); });
return upper_token;
}
}
std::string SyntaxHighlighter::highlight(const std::string& input) {
std::istringstream iss(input);
std::ostringstream oss;
std::string token;
bool first = true;
while (iss >> token) {
if (!first) oss << " ";
first = false;
std::string upper_token = toUpper(token);
auto it = KEYWORD_COLORS.find(upper_token);
if (it != KEYWORD_COLORS.end()) {
oss << it->second << token << RESET_COLOR;
} else if ((token.front() == '\'' && token.back() == '\'') ||
(token.front() == '"' && token.back() == '"')) {
oss << "\x1b[36m" << token << RESET_COLOR; // Cyan for literals
} else {
oss << token;
}
}
return oss.str();
}
````
````hpp src/SyntaxHighlighter.hpp
#pragma once
#include <string>
#include <map>
class SyntaxHighlighter {
public:
std::string highlight(const std::string& input);
private:
// Colors are managed statically in the .cpp file for simplicity
};
````
````cpp src/Trie.cpp
#include "Trie.hpp"
#include <cctype>
#include <algorithm>
namespace {
char norm(char c) noexcept {
return static_cast<char>(std::toupper(static_cast<unsigned char>(c)));
}
}
Trie::Trie() : root_(std::make_unique<Node>()) {}
void Trie::clear() {
root_ = std::make_unique<Node>();
}
void Trie::insert(const std::string& word) {
Node* cur = root_.get();
for (char ch : word) {
char k = norm(ch);
auto it = cur->children.find(k);
if (it == cur->children.end()) {
cur->children[k] = std::make_unique<Node>();
cur = cur->children[k].get();
} else {
cur = it->second.get();
}
}
cur->terminal = true;
// Avoid duplicate exact insertion (case-sensitive)
if (std::find(cur->words.begin(), cur->words.end(), word) == cur->words.end()) {
cur->words.push_back(word);
}
}
const Trie::Node* Trie::findNode(const std::string& prefix) const {
const Node* cur = root_.get();
for (char ch : prefix) {
char k = norm(ch);
auto it = cur->children.find(k);
if (it == cur->children.end()) return nullptr;
cur = it->second.get();
}
return cur;
}
void Trie::collect(const Node* node, std::vector<std::string>& out, size_t limit) const {
if (!node) return;
if (node->terminal) {
for (const auto& w : node->words) {
out.push_back(w);
if (limit && out.size() >= limit) return;
}
}
for (const auto& kv : node->children) {
collect(kv.second.get(), out, limit);
if (limit && out.size() >= limit) return;
}
}
std::vector<std::string> Trie::complete(const std::string& prefix, size_t limit) const {
std::vector<std::string> out;
const Node* node = findNode(prefix);
if (!node) return out;
collect(node, out, limit);
return out;
}
````
````hpp src/Trie.hpp
#pragma once
#include <string>
#include <vector>
#include <memory>
#include <unordered_map>
class Trie {
public:
struct Node {
bool terminal = false;
std::vector<std::string> words;
std::unordered_map<char, std::unique_ptr<Node>> children;
};
Trie();
void clear();
void insert(const std::string& word);
std::vector<std::string> complete(const std::string& prefix, size_t limit = 0) const;
private:
std::unique_ptr<Node> root_;
const Node* findNode(const std::string& prefix) const;
void collect(const Node* node, std::vector<std::string>& out, size_t limit) const;
};
````
````cpp src/SQLiteREPL.cpp
#include "SQLiteREPL.hpp"
#include "SQLiteSchemaProvider.hpp"