-
-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
1819 lines (1562 loc) · 62.1 KB
/
Copy pathMainWindow.cpp
File metadata and controls
1819 lines (1562 loc) · 62.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
#include "MainWindow.h"
#include <functional>
#include <QAction>
#include <QColor>
#include <QDateTime>
#include <QFile>
#include <QFileDialog>
#include <QFileInfo>
#include <QPoint>
#include <QFont>
#include <QHBoxLayout>
#include <QHeaderView>
#include <QInputDialog>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QKeySequence>
#include <QLabel>
#include <QLineEdit>
#include <QMenu>
#include <QMenuBar>
#include <QMessageBox>
#include <QPushButton>
#include <QRegularExpression>
#include <QSettings>
#include <QSplitter>
#include <QSqlError>
#include <QSqlQuery>
#include <QSqlRecord>
#include <QTextStream>
#include <QVariantMap>
#include "CreateIndexDialog.h"
#include "CreateTableDialog.h"
#include "ExportDialog.h"
#include "InsertRowDialog.h"
#include "SettingsDialog.h"
namespace {
// Removes and deletes every widget/layout currently inside layout,
// so the query builder panel can be rebuilt each time the focus changes.
void clearLayout(QLayout* layout)
{
while (QLayoutItem* item = layout->takeAt(0)) {
if (QWidget* w = item->widget()) {
w->deleteLater();
}
delete item;
}
}
// QSettings keys for the Settings dialog's preferences, plus their
// defaults - kept together so loadSettings()/saveSettings() can't drift
// out of sync with each other.
const QString kSettingsUiFontSize = "appearance/uiFontSize";
const QString kSettingsEditorFontSize = "appearance/editorFontSize";
const QString kSettingsConfirmDestructive = "behavior/confirmDestructiveActions";
const QString kSettingsDefaultDir = "files/defaultDialogDir";
constexpr int kDefaultUiFontSize = 12;
constexpr int kDefaultEditorFontSize = 11;
constexpr bool kDefaultConfirmDestructive = true;
// Wraps a value in single quotes for use as a SQL literal, unless it
// already looks like a number - keeps the "add condition" flow simple
// without needing a full type-aware value editor.
QString sqlLiteral(const QString& rawValue)
{
bool isNumber = false;
rawValue.toDouble(&isNumber);
if (isNumber || rawValue.startsWith('\'')) {
return rawValue;
}
return "'" + rawValue + "'";
}
// Splits a block of SQL text into individual statements on ';', while
// ignoring semicolons that appear inside single-quoted string literals
// (with '' as the SQL-standard escaped quote). This isn't a full SQL
// parser - it doesn't know about /* block comments */ or multi-statement
// trigger bodies - but it's enough for round-tripping our own exports
// and for typical hand-written import scripts.
QStringList splitSqlStatements(const QString& sql)
{
QStringList statements;
QString current;
bool inString = false;
for (int i = 0; i < sql.size(); ++i) {
const QChar ch = sql[i];
current += ch;
if (ch == '\'') {
if (inString && i + 1 < sql.size() && sql[i + 1] == '\'') {
// Escaped quote ('') inside a string literal - consume
// both characters without toggling string state.
current += sql[i + 1];
++i;
continue;
}
inString = !inString;
continue;
}
if (ch == ';' && !inString) {
const QString trimmed = current.trimmed();
if (!trimmed.isEmpty()) {
statements << trimmed;
}
current.clear();
}
}
const QString trailing = current.trimmed();
if (!trailing.isEmpty()) {
statements << trailing;
}
return statements;
}
// Escapes a single field for CSV/TSV output per RFC 4180: wrapped in
// double quotes (with embedded quotes doubled) whenever it contains the
// delimiter, a quote, or a newline; left alone otherwise.
QString delimitedFieldEscape(const QString& field, QChar delimiter)
{
if (field.contains(delimiter) || field.contains('"') || field.contains('\n') || field.contains('\r')) {
QString escaped = field;
escaped.replace("\"", "\"\"");
return "\"" + escaped + "\"";
}
return field;
}
// Renders one results-grid cell for a SQL INSERT statement: empty means
// NULL, a numeric-looking value goes out unquoted, everything else is
// quoted with '' escaping. Unlike Schema-aware quoteForExport() (used
// for the full-database export), this works purely off the display text
// already sitting in the grid - no QVariant/type info survives once a
// query's results have been converted to strings for display.
QString sqlLiteralForResultsExport(const QString& text)
{
if (text.isEmpty()) {
return "NULL";
}
bool isNumber = false;
text.toDouble(&isNumber);
if (isNumber) {
return text;
}
QString escaped = text;
escaped.replace("'", "''");
return "'" + escaped + "'";
}
} // namespace
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent)
{
setWindowTitle("WinSQLite");
loadSettings();
buildUi();
buildMenus();
applyDarkTheme();
}
MainWindow::~MainWindow()
{
stopQueryThread();
}
void MainWindow::buildUi()
{
resize(1150, 720);
auto* central = new QWidget(this);
auto* rootLayout = new QVBoxLayout(central);
rootLayout->setContentsMargins(0, 0, 0, 0);
rootLayout->setSpacing(0);
// Top bar
auto* topBar = new QWidget(central);
topBar->setObjectName("topBar");
auto* topLayout = new QHBoxLayout(topBar);
topLayout->setContentsMargins(16, 10, 16, 10);
auto* titleLabel = new QLabel("No database open", topBar);
titleLabel->setObjectName("titleLabel");
m_titleLabel = titleLabel;
topLayout->addWidget(titleLabel);
topLayout->addStretch();
m_sqlModeBtn = new QPushButton("SQL mode", topBar);
m_sqlModeBtn->setCheckable(true);
m_sqlModeBtn->setEnabled(false);
m_executeBtn = new QPushButton("Execute", topBar);
m_executeBtn->setObjectName("primaryButton");
m_executeBtn->setEnabled(false);
topLayout->addWidget(m_sqlModeBtn);
topLayout->addWidget(m_executeBtn);
rootLayout->addWidget(topBar);
// Outer horizontal splitter: the table list on the left spans the
// full window height, independent of the results panel below - only
// the right side (diagram + query builder + results) splits vertically.
auto* outerSplitter = new QSplitter(Qt::Horizontal, central);
outerSplitter->setObjectName("outerSplitter");
outerSplitter->setHandleWidth(8);
outerSplitter->setChildrenCollapsible(false);
outerSplitter->setOpaqueResize(true);
// Left panel - table list, full height top to bottom.
auto* leftPanel = new QWidget(outerSplitter);
leftPanel->setObjectName("leftPanel");
leftPanel->setMinimumWidth(140);
auto* leftLayout = new QVBoxLayout(leftPanel);
leftLayout->setContentsMargins(12, 14, 12, 12);
auto* tablesLabel = new QLabel("TABLES", leftPanel);
tablesLabel->setObjectName("sectionLabel");
leftLayout->addWidget(tablesLabel);
m_tableTree = new QTreeWidget(leftPanel);
m_tableTree->setObjectName("tableTree");
m_tableTree->setHeaderHidden(true);
m_tableTree->setColumnCount(1);
m_tableTree->setIndentation(14);
leftLayout->addWidget(m_tableTree);
outerSplitter->addWidget(leftPanel);
// Right side: everything except the table list. Vertical splitter -
// the diagram/query-builder body on top, query results at the bottom.
auto* rightSide = new QWidget(outerSplitter);
auto* rightSideLayout = new QVBoxLayout(rightSide);
rightSideLayout->setContentsMargins(0, 0, 0, 0);
rightSideLayout->setSpacing(0);
auto* mainSplitter = new QSplitter(Qt::Vertical, rightSide);
mainSplitter->setObjectName("mainSplitter");
mainSplitter->setHandleWidth(8);
mainSplitter->setChildrenCollapsible(false);
// Diagram + query builder body.
auto* body = new QSplitter(Qt::Horizontal, mainSplitter);
body->setObjectName("bodySplitter");
body->setHandleWidth(8);
body->setChildrenCollapsible(false);
body->setOpaqueResize(true);
// Center panel - diagram
m_diagramView = new DiagramView(body);
m_diagramView->setMinimumWidth(200);
body->addWidget(m_diagramView);
// Right panel - query builder
auto* rightPanel = new QWidget(body);
rightPanel->setObjectName("rightPanel");
rightPanel->setMinimumWidth(340);
auto* rightLayout = new QVBoxLayout(rightPanel);
rightLayout->setContentsMargins(14, 14, 14, 14);
auto* builderLabel = new QLabel("QUERY BUILDER", rightPanel);
builderLabel->setObjectName("sectionLabel");
rightLayout->addWidget(builderLabel);
m_rightStack = new QStackedWidget(rightPanel);
// Page 0: the step-based builder view.
auto* builderPage = new QWidget(m_rightStack);
auto* builderPageLayout = new QVBoxLayout(builderPage);
builderPageLayout->setContentsMargins(0, 0, 0, 0);
auto* stepsContainer = new QWidget(builderPage);
m_stepsLayout = new QVBoxLayout(stepsContainer);
m_stepsLayout->setContentsMargins(0, 8, 0, 8);
builderPageLayout->addWidget(stepsContainer);
m_addStepBtn = new QPushButton("+ Add step", builderPage);
builderPageLayout->addWidget(m_addStepBtn);
m_sqlPreview = new QPlainTextEdit(builderPage);
m_sqlPreview->setObjectName("sqlPreview");
m_sqlPreview->setReadOnly(true);
builderPageLayout->addWidget(m_sqlPreview, 1);
m_rightStack->addWidget(builderPage);
// Page 1: raw, editable SQL - the "escape hatch". Edits here are not
// parsed back into the QueryModel; leaving SQL mode discards them and
// restores whatever the builder currently represents.
auto* sqlPage = new QWidget(m_rightStack);
auto* sqlPageLayout = new QVBoxLayout(sqlPage);
sqlPageLayout->setContentsMargins(0, 8, 0, 0);
m_sqlEditor = new SqlEditor(sqlPage);
m_sqlEditor->setObjectName("sqlPreview");
sqlPageLayout->addWidget(m_sqlEditor, 1);
m_rightStack->addWidget(sqlPage);
rightLayout->addWidget(m_rightStack, 1);
body->addWidget(rightPanel);
body->setStretchFactor(0, 1);
body->setStretchFactor(1, 1);
body->setSizes({460, 460});
mainSplitter->addWidget(body);
// Results panel
auto* resultsPanel = new QWidget(mainSplitter);
resultsPanel->setObjectName("resultsPanel");
auto* resultsLayout = new QVBoxLayout(resultsPanel);
resultsLayout->setContentsMargins(16, 10, 16, 12);
auto* resultsHeader = new QHBoxLayout();
auto* resultsLabel = new QLabel("RESULTS", resultsPanel);
resultsLabel->setObjectName("sectionLabel");
resultsHeader->addWidget(resultsLabel);
resultsHeader->addStretch();
m_statusLabel = new QLabel(resultsPanel);
m_statusLabel->setObjectName("statusLabel");
resultsHeader->addWidget(m_statusLabel);
m_exportResultsBtn = new QPushButton("Export…", resultsPanel);
m_exportResultsBtn->setEnabled(false); // enabled once a query returns at least one column
resultsHeader->addWidget(m_exportResultsBtn);
resultsLayout->addLayout(resultsHeader);
m_resultsTable = new QTableWidget(resultsPanel);
m_resultsTable->setObjectName("resultsTable");
m_resultsTable->setEditTriggers(QAbstractItemView::NoEditTriggers);
m_resultsTable->setSelectionBehavior(QAbstractItemView::SelectRows);
m_resultsTable->setAlternatingRowColors(true);
m_resultsTable->verticalHeader()->setVisible(false);
m_resultsTable->horizontalHeader()->setStretchLastSection(true);
resultsLayout->addWidget(m_resultsTable, 1);
mainSplitter->addWidget(resultsPanel);
mainSplitter->setStretchFactor(0, 3);
mainSplitter->setStretchFactor(1, 2);
mainSplitter->setSizes({420, 220});
rightSideLayout->addWidget(mainSplitter, 1);
outerSplitter->addWidget(rightSide);
outerSplitter->setStretchFactor(0, 0);
outerSplitter->setStretchFactor(1, 1);
outerSplitter->setSizes({200, 800});
rootLayout->addWidget(outerSplitter, 1);
setCentralWidget(central);
connect(m_tableTree, &QTreeWidget::itemClicked, this, &MainWindow::onTreeItemClicked);
connect(m_diagramView, &DiagramView::tableClicked, this, &MainWindow::onTableActivated);
connect(m_addStepBtn, &QPushButton::clicked, this, &MainWindow::onAddStepClicked);
connect(m_sqlModeBtn, &QPushButton::toggled, this, &MainWindow::onSqlModeToggled);
connect(m_executeBtn, &QPushButton::clicked, this, &MainWindow::onExecuteClicked);
connect(m_sqlEditor, &QPlainTextEdit::textChanged, this, &MainWindow::onSqlTextChanged);
connect(m_resultsTable, &QTableWidget::itemChanged, this, &MainWindow::onResultCellEdited);
connect(m_exportResultsBtn, &QPushButton::clicked, this, &MainWindow::onExportResultsTriggered);
}
void MainWindow::buildMenus()
{
auto* databaseMenu = menuBar()->addMenu("&Database");
QAction* newDbAction = databaseMenu->addAction("&New Database…");
newDbAction->setShortcut(QKeySequence::New);
connect(newDbAction, &QAction::triggered, this, &MainWindow::onNewDatabaseTriggered);
QAction* openDbAction = databaseMenu->addAction("&Open Database…");
openDbAction->setShortcut(QKeySequence::Open);
connect(openDbAction, &QAction::triggered, this, &MainWindow::onOpenDatabaseTriggered);
databaseMenu->addSeparator();
QAction* exportDbAction = databaseMenu->addAction("&Export Database…");
connect(exportDbAction, &QAction::triggered, this, &MainWindow::onExportDatabaseTriggered);
QAction* importDbAction = databaseMenu->addAction("&Import SQL…");
connect(importDbAction, &QAction::triggered, this, &MainWindow::onImportDatabaseTriggered);
databaseMenu->addSeparator();
QAction* exitAction = databaseMenu->addAction("E&xit");
exitAction->setShortcut(QKeySequence::Quit);
connect(exitAction, &QAction::triggered, this, &QWidget::close);
auto* schemaMenu = menuBar()->addMenu("&Schema");
QAction* newTableAction = schemaMenu->addAction("New &Table…");
newTableAction->setShortcut(QKeySequence("Ctrl+T"));
connect(newTableAction, &QAction::triggered, this, &MainWindow::onNewTableTriggered);
QAction* newIndexAction = schemaMenu->addAction("New &Index…");
newIndexAction->setShortcut(QKeySequence("Ctrl+I"));
connect(newIndexAction, &QAction::triggered, this, &MainWindow::onNewIndexTriggered);
schemaMenu->addSeparator();
QAction* dropTableAction = schemaMenu->addAction("Drop Table…");
connect(dropTableAction, &QAction::triggered, this, &MainWindow::onDropTableTriggered);
QAction* dropIndexAction = schemaMenu->addAction("Drop Index…");
connect(dropIndexAction, &QAction::triggered, this, &MainWindow::onDropIndexTriggered);
auto* dataMenu = menuBar()->addMenu("D&ata");
QAction* insertRowAction = dataMenu->addAction("&Insert Row…");
insertRowAction->setShortcut(QKeySequence("Ctrl+Shift+I"));
connect(insertRowAction, &QAction::triggered, this, &MainWindow::onInsertRowTriggered);
QAction* exportResultsAction = dataMenu->addAction("Export &Results…");
exportResultsAction->setShortcut(QKeySequence("Ctrl+Shift+E"));
connect(exportResultsAction, &QAction::triggered, this, &MainWindow::onExportResultsTriggered);
// These all act on the currently open database, so they start
// disabled - openDatabase() enables them once one is loaded.
m_schemaActions = {newTableAction, newIndexAction, dropTableAction, dropIndexAction, insertRowAction,
exportDbAction, exportResultsAction, importDbAction};
setSchemaActionsEnabled(false);
// Settings is independent of whether a database is open, so its
// action is never added to m_schemaActions / disabled above.
auto* settingsMenu = menuBar()->addMenu("&Settings");
QAction* preferencesAction = settingsMenu->addAction("&Preferences…");
preferencesAction->setShortcut(QKeySequence("Ctrl+,"));
connect(preferencesAction, &QAction::triggered, this, &MainWindow::onSettingsTriggered);
}
void MainWindow::applyDarkTheme()
{
// m_uiFontSize/m_editorFontSize come from the Settings dialog (see
// loadSettings()/onSettingsTriggered()); the title bar scales two
// points larger than the base UI size rather than being a separate
// setting of its own.
const int titleFontSize = m_uiFontSize + 2;
setStyleSheet(QString(R"(
QMainWindow, QWidget { background-color: #17171A; color: #D3D1C7; font-size: %1px; }
#topBar { background-color: #201F22; border-bottom: 1px solid #333230; }
#titleLabel { font-size: %2px; font-weight: 600; color: #F1EFE8; }
QSplitter#bodySplitter::handle, QSplitter#outerSplitter::handle, QSplitter#mainSplitter::handle {
background-color: #2C2C2A;
border-left: 1px solid #444441;
border-right: 1px solid #444441;
}
QSplitter#mainSplitter::handle {
border-left: none;
border-right: none;
border-top: 1px solid #444441;
border-bottom: 1px solid #444441;
}
QSplitter#bodySplitter::handle:hover, QSplitter#outerSplitter::handle:hover, QSplitter#mainSplitter::handle:hover { background-color: #378ADD; }
#leftPanel, #rightPanel, #resultsPanel { background-color: #1C1B1E; }
#rightPanel { border-left: 1px solid #333230; }
#leftPanel { border-right: 1px solid #333230; }
#resultsPanel { border-top: 1px solid #333230; }
#sectionLabel { color: #888780; font-size: 10px; letter-spacing: 1px; padding: 4px 0; }
#statusLabel { color: #888780; font-size: 10px; }
QTreeWidget#tableTree { background: transparent; border: none; }
QTreeWidget#tableTree::item { padding: 5px 4px; border-radius: 6px; }
QTreeWidget#tableTree::item:selected { background-color: #0C447C; color: #E6F1FB; }
QTreeWidget#tableTree::branch { background: transparent; }
QPlainTextEdit#sqlPreview {
background-color: #201F22; border: 1px solid #333230; border-radius: 6px;
font-family: Consolas, monospace; font-size: %3px; color: #FAC775; padding: 8px;
}
QTableWidget#resultsTable {
background-color: #201F22; border: 1px solid #333230; border-radius: 6px;
gridline-color: #333230; alternate-background-color: #232226;
}
QTableWidget#resultsTable::item { padding: 4px 8px; }
QTableWidget#resultsTable::item:selected { background-color: #0C447C; color: #E6F1FB; }
QHeaderView::section {
background-color: #201F22; color: #888780; border: none;
border-bottom: 1px solid #333230; padding: 6px 8px; font-size: 10px;
}
QPushButton {
background-color: #201F22; border: 1px solid #444441; border-radius: 6px;
padding: 6px 12px; color: #D3D1C7;
}
QPushButton:hover { background-color: #2C2C2A; }
QPushButton:checked { background-color: #0C447C; border: 1px solid #378ADD; color: #E6F1FB; }
QPushButton#primaryButton { background-color: #185FA5; border: 1px solid #378ADD; color: white; }
QPushButton#primaryButton:hover { background-color: #0C447C; }
QPushButton#removeStepButton {
background-color: transparent; border: none; color: #888780;
font-weight: 600; padding: 0px;
}
QPushButton#removeStepButton:hover { color: #E5484D; }
)").arg(m_uiFontSize).arg(titleFontSize).arg(m_editorFontSize));
}
bool MainWindow::openDatabase(const QString& path)
{
// Tear down whatever's currently loaded (connection, thread, UI
// state) first, so this also works for switching databases mid-
// session via the Database menu, not just the very first load.
if (m_db.isOpen()) {
m_db.close();
}
if (QSqlDatabase::contains(m_db.connectionName())) {
const QString connectionName = m_db.connectionName();
m_db = QSqlDatabase(); // release our handle before removing it
QSqlDatabase::removeDatabase(connectionName);
}
resetUiForNewDatabase();
m_db = QSqlDatabase::addDatabase("QSQLITE", "main_gui_connection");
m_db.setDatabaseName(path);
if (!m_db.open()) {
return false;
}
if (!m_schema.load(m_db)) {
return false;
}
startQueryThread(path);
m_titleLabel->setText(QFileInfo(path).fileName());
setWindowTitle("WinSQLite — " + QFileInfo(path).fileName());
setSchemaActionsEnabled(true);
m_sqlModeBtn->setEnabled(true);
m_executeBtn->setEnabled(true);
syncSchemaUi();
const QString initialFocus = defaultFocusTable();
if (!initialFocus.isEmpty()) {
focusTable(initialFocus);
}
return true;
}
void MainWindow::resetUiForNewDatabase()
{
m_focusTable.clear();
m_queryModel = QueryModel();
m_sqlModeActive = false;
m_sqlModeBtn->setChecked(false);
m_rightStack->setCurrentIndex(0);
m_sqlEditor->clear();
m_diagramView->clear();
clearLayout(m_stepsLayout);
m_sqlPreview->clear();
m_resultsTable->clear();
m_resultsTable->setRowCount(0);
m_resultsTable->setColumnCount(0);
m_exportResultsBtn->setEnabled(false);
m_statusLabel->clear();
m_tableTree->clear();
}
void MainWindow::syncSchemaUi()
{
populateTableTree();
// Feed the raw-SQL autocomplete with every table and column name now
// that the schema is known, on top of the built-in SQL keywords.
QStringList schemaWords;
for (const auto& table : m_schema.tables()) {
schemaWords << table.name;
for (const auto& col : table.columns) {
schemaWords << col.name;
}
}
m_sqlEditor->setSchemaWords(schemaWords);
}
QString MainWindow::defaultFocusTable() const
{
if (m_schema.tables().isEmpty()) {
return QString();
}
// First table that has at least one relation, so the initial diagram
// isn't a lone box - falls back to the first table.
for (const auto& table : m_schema.tables()) {
if (!m_schema.relationsFor(table.name).isEmpty()) {
return table.name;
}
}
return m_schema.tables().first().name;
}
void MainWindow::populateTableTree()
{
m_tableTree->clear();
for (const auto& table : m_schema.tables()) {
auto* tableItem = new QTreeWidgetItem(m_tableTree, {table.name});
QFont boldFont = tableItem->font(0);
boldFont.setBold(true);
tableItem->setFont(0, boldFont);
tableItem->setData(0, Qt::UserRole, table.name);
for (const auto& col : table.columns) {
QString label = col.name + " : " + col.type;
if (col.isPrimaryKey) {
label += " [PK]";
}
auto* colItem = new QTreeWidgetItem(tableItem, {label});
colItem->setData(0, Qt::UserRole, table.name);
colItem->setForeground(0, QColor("#888780"));
}
for (const auto& index : m_schema.indexesFor(table.name)) {
QString label = "⚡ " + index.name + " (" + index.columns.join(", ") + ")";
if (index.isUnique) {
label += " [UNIQUE]";
}
auto* indexItem = new QTreeWidgetItem(tableItem, {label});
indexItem->setData(0, Qt::UserRole, table.name);
indexItem->setForeground(0, QColor("#1D9E75"));
}
}
m_tableTree->collapseAll();
}
void MainWindow::onTreeItemClicked(QTreeWidgetItem* item, int column)
{
Q_UNUSED(column);
if (!item) {
return;
}
// Table rows and their column/index children all carry the owning
// table name in UserRole, so clicking any of them also focuses that
// table.
const QString tableName = item->data(0, Qt::UserRole).toString();
onTableActivated(tableName);
// Clicking a table row toggles its expanded state, revealing columns.
if (item->parent() == nullptr) {
item->setExpanded(!item->isExpanded());
}
}
void MainWindow::onTableActivated(const QString& tableName)
{
if (tableName.isEmpty()) {
return;
}
if (m_sqlModeActive) {
// In SQL mode, clicking a table in the diagram inserts its name
// into the raw SQL at the cursor instead of touching the builder
// - the other half of the "typing affects the diagram" loop.
m_sqlEditor->insertPlainText(tableName);
m_sqlEditor->setFocus();
return;
}
focusTable(tableName);
}
void MainWindow::focusTable(const QString& tableName)
{
if (tableName.isEmpty() || tableName == m_focusTable) {
return;
}
m_focusTable = tableName;
m_diagramView->setFocusTable(m_schema, tableName);
// Rebuild the query model: FROM = focus table, JOIN = first relation
// found, mirroring what a click on a relation line will eventually
// do explicitly (phase 3). Further joins/conditions can be added
// manually with "+ Add step".
m_queryModel = QueryModel();
m_queryModel.setFromTable(tableName);
auto relations = m_schema.relationsFor(tableName);
if (!relations.isEmpty()) {
const auto& fk = relations.first();
const QString joinTable = (fk.fromTable == tableName) ? fk.toTable : fk.fromTable;
m_queryModel.addJoin(joinTable, fk);
}
refreshQueryPanel();
}
void MainWindow::refreshQueryPanel()
{
clearLayout(m_stepsLayout);
// Builds one row in the steps list. onRemove is empty for the FROM
// row, since the base table can't be removed on its own.
auto addStepRow = [this](const QString& keyword, const QString& value,
std::function<void()> onRemove) {
auto* row = new QWidget();
auto* rowLayout = new QHBoxLayout(row);
rowLayout->setContentsMargins(0, 4, 0, 4);
auto* label = new QLabel(QString("<span style='color:#888780'>%1</span> "
"<span style='color:#E6F1FB; font-weight:600'>%2</span>")
.arg(keyword, value));
label->setWordWrap(true);
rowLayout->addWidget(label, 1);
if (onRemove) {
auto* removeBtn = new QPushButton("\u00D7");
removeBtn->setObjectName("removeStepButton");
removeBtn->setFixedSize(20, 20);
removeBtn->setToolTip("Remove step");
connect(removeBtn, &QPushButton::clicked, this, onRemove);
rowLayout->addWidget(removeBtn);
}
m_stepsLayout->addWidget(row);
};
addStepRow("FROM", m_queryModel.fromTable(), nullptr);
for (int i = 0; i < m_queryModel.joins().size(); ++i) {
const auto& join = m_queryModel.joins()[i];
addStepRow("JOIN", join.table, [this, i]() { onRemoveJoinClicked(i); });
}
for (int i = 0; i < m_queryModel.conditions().size(); ++i) {
const auto& cond = m_queryModel.conditions()[i];
addStepRow("WHERE", cond.column + " " + cond.op + " " + cond.value,
[this, i]() { onRemoveConditionClicked(i); });
}
m_sqlPreview->setPlainText(m_queryModel.toSql());
}
void MainWindow::onAddStepClicked()
{
if (m_queryModel.isEmpty()) {
return;
}
QMenu menu(this);
QAction* joinAction = menu.addAction("Join related table (JOIN)…");
QAction* conditionAction = menu.addAction("Add condition (WHERE)…");
QAction* chosen = menu.exec(m_addStepBtn->mapToGlobal(QPoint(0, m_addStepBtn->height())));
if (chosen == joinAction) {
addJoinStep();
} else if (chosen == conditionAction) {
addConditionStep();
}
}
void MainWindow::addJoinStep()
{
// Candidate joins: any relation touching a table already in the
// query, whose "other side" isn't already joined in.
const QVector<QString> involved = m_queryModel.involvedTables();
QVector<ForeignKey> candidateKeys;
QStringList candidateLabels;
for (const auto& table : involved) {
for (const auto& fk : m_schema.relationsFor(table)) {
const QString other = (fk.fromTable == table) ? fk.toTable : fk.fromTable;
if (other == table || involved.contains(other)) {
continue;
}
candidateKeys.push_back(fk);
candidateLabels << QString("%1 (%2.%3 → %4.%5)")
.arg(other, fk.fromTable, fk.fromColumn, fk.toTable, fk.toColumn);
}
}
if (candidateLabels.isEmpty()) {
QMessageBox::information(this, "No available relations",
"All related tables are already included in the query.");
return;
}
bool ok = false;
const QString choice = QInputDialog::getItem(this, "Join table",
"Select a relation for JOIN:",
candidateLabels, 0, false, &ok);
if (!ok) {
return;
}
const int index = candidateLabels.indexOf(choice);
if (index < 0) {
return;
}
const ForeignKey& fk = candidateKeys[index];
// The candidate was built from the "other" side of the relation
// relative to a table already in the query - recompute which side
// that is so we join in the correct table name.
QString otherTable = fk.fromTable;
for (const auto& table : involved) {
if (fk.fromTable == table) {
otherTable = fk.toTable;
break;
}
if (fk.toTable == table) {
otherTable = fk.fromTable;
break;
}
}
m_queryModel.addJoin(otherTable, fk);
refreshQueryPanel();
}
void MainWindow::addConditionStep()
{
const QVector<QString> involved = m_queryModel.involvedTables();
QStringList columnLabels;
for (const auto& tableName : involved) {
const Table* table = m_schema.findTable(tableName);
if (!table) {
continue;
}
for (const auto& col : table->columns) {
columnLabels << (tableName + "." + col.name);
}
}
if (columnLabels.isEmpty()) {
QMessageBox::information(this, "No available columns",
"The query doesn't have any tables with columns yet.");
return;
}
bool ok = false;
const QString column = QInputDialog::getItem(this, "New condition",
"Column:", columnLabels, 0, false, &ok);
if (!ok) {
return;
}
static const QStringList operators = {"=", "!=", ">", "<", ">=", "<=", "LIKE"};
const QString op = QInputDialog::getItem(this, "New condition",
"Operator:", operators, 0, false, &ok);
if (!ok) {
return;
}
const QString rawValue = QInputDialog::getText(this, "New condition",
"Value:", QLineEdit::Normal,
QString(), &ok);
if (!ok || rawValue.isEmpty()) {
return;
}
Condition condition;
condition.column = column;
condition.op = op;
condition.value = sqlLiteral(rawValue);
m_queryModel.addCondition(condition);
refreshQueryPanel();
}
void MainWindow::onRemoveJoinClicked(int index)
{
m_queryModel.removeJoin(index);
refreshQueryPanel();
}
void MainWindow::onRemoveConditionClicked(int index)
{
m_queryModel.removeCondition(index);
refreshQueryPanel();
}
void MainWindow::onSqlModeToggled(bool checked)
{
m_sqlModeActive = checked;
if (checked) {
// Seed the editable box with whatever the builder currently
// represents, then hand control over to free-text SQL.
m_sqlEditor->setPlainText(m_queryModel.toSql());
m_rightStack->setCurrentIndex(1);
m_addStepBtn->setEnabled(false);
} else {
// Leaving SQL mode discards manual edits and restores the
// builder's view of the query, per the "escape hatch" design.
m_rightStack->setCurrentIndex(0);
m_addStepBtn->setEnabled(true);
refreshQueryPanel();
m_diagramView->setFocusTable(m_schema, m_focusTable);
}
}
void MainWindow::onExecuteClicked()
{
const QString sql = m_sqlModeActive ? m_sqlEditor->toPlainText().trimmed()
: m_queryModel.toSql();
if (sql.isEmpty()) {
showError("No query to execute.");
return;
}
runQuery(sql);
}
void MainWindow::onSqlTextChanged()
{
if (!m_sqlModeActive) {
return;
}
const QString sql = m_sqlEditor->toPlainText();
// Crude but effective: pull the table right after FROM and every
// table right after JOIN, so the diagram tracks whatever the person
// is typing without needing a full SQL parser.
static const QRegularExpression fromPattern(R"(\bFROM\s+([A-Za-z_][A-Za-z0-9_]*))",
QRegularExpression::CaseInsensitiveOption);
static const QRegularExpression joinPattern(R"(\bJOIN\s+([A-Za-z_][A-Za-z0-9_]*))",
QRegularExpression::CaseInsensitiveOption);
const auto fromMatch = fromPattern.match(sql);
if (!fromMatch.hasMatch()) {
return;
}
const QString fromTable = resolveTableName(fromMatch.captured(1));
if (fromTable.isEmpty()) {
return;
}
// Tables explicitly typed after JOIN...
QVector<QString> relatedTables;
auto matches = joinPattern.globalMatch(sql);
while (matches.hasNext()) {
const QString joinTable = resolveTableName(matches.next().captured(1));
if (!joinTable.isEmpty() && joinTable != fromTable && !relatedTables.contains(joinTable)) {
relatedTables.push_back(joinTable);
}
}
// ...plus the focus table's own known foreign-key relations, so the
// diagram also shows what it CAN join to, not only what's typed yet.
for (const auto& fk : m_schema.relationsFor(fromTable)) {
const QString other = (fk.fromTable == fromTable) ? fk.toTable : fk.fromTable;
if (other != fromTable && !relatedTables.contains(other)) {
relatedTables.push_back(other);
}
}
m_diagramView->setTablesFromNames(m_schema, fromTable, relatedTables);
}
QString MainWindow::resolveTableName(const QString& rawName) const
{
for (const auto& table : m_schema.tables()) {
if (table.name.compare(rawName, Qt::CaseInsensitive) == 0) {
return table.name;
}
}
return QString();
}
void MainWindow::startQueryThread(const QString& dbPath)
{
// Opening a database is no longer a one-time thing (Database menu
// lets the user switch mid-session), so always tear down any
// previous worker/thread cleanly first.
stopQueryThread();
m_queryThread = new QThread(this);
m_queryWorker = new QueryWorker(dbPath);
m_queryWorker->moveToThread(m_queryThread);
// requestQuery() is emitted on the GUI thread and delivered to
// execute() on m_queryThread; succeeded()/failed() make the return
// trip the same way. Both connections are automatically queued
// because sender and receiver live on different threads.
connect(this, &MainWindow::requestQuery, m_queryWorker, &QueryWorker::execute);
connect(m_queryWorker, &QueryWorker::succeeded, this, &MainWindow::onQuerySucceeded);
connect(m_queryWorker, &QueryWorker::failed, this, &MainWindow::onQueryFailed);
m_queryThread->start();
}
void MainWindow::stopQueryThread()
{
if (!m_queryThread) {
return;
}
m_queryThread->quit();
m_queryThread->wait();
// m_queryWorker was moved onto m_queryThread via moveToThread(), not
// parented to it - QObject parent/child and thread affinity are
// separate, so deleting the thread alone would leak the worker. Now
// that wait() confirms the thread has fully stopped, it's safe to
// delete both directly from the GUI thread.
delete m_queryWorker;
m_queryWorker = nullptr;
delete m_queryThread;
m_queryThread = nullptr;
m_queryRunning = false;
}
void MainWindow::runQuery(const QString& sql)
{
if (!m_queryThread || !m_queryWorker) {