forked from sqlitebrowser/sqlitebrowser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.cpp
More file actions
2356 lines (2023 loc) · 89.4 KB
/
MainWindow.cpp
File metadata and controls
2356 lines (2023 loc) · 89.4 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 "ui_MainWindow.h"
#include "EditIndexDialog.h"
#include "AboutDialog.h"
#include "EditTableDialog.h"
#include "ImportCsvDialog.h"
#include "ExportDataDialog.h"
#include "Settings.h"
#include "PreferencesDialog.h"
#include "EditDialog.h"
#include "sqlitetablemodel.h"
#include "SqlExecutionArea.h"
#include "VacuumDialog.h"
#include "DbStructureModel.h"
#include "version.h"
#include "sqlite.h"
#include "CipherDialog.h"
#include "ExportSqlDialog.h"
#include "SqlUiLexer.h"
#include "FileDialog.h"
#include "ColumnDisplayFormatDialog.h"
#include "FilterTableHeader.h"
#include "RemoteDock.h"
#include "RemoteDatabase.h"
#include <QFile>
#include <QApplication>
#include <QTextStream>
#include <QWhatsThis>
#include <QMessageBox>
#include <QStandardItemModel>
#include <QPersistentModelIndex>
#include <QDragEnterEvent>
#include <QScrollBar>
#include <QSortFilterProxyModel>
#include <QElapsedTimer>
#include <QSettings>
#include <QMimeData>
#include <QColorDialog>
#include <QDesktopServices>
#include <QXmlStreamReader>
#include <QXmlStreamWriter>
#include <QInputDialog>
#include <QProgressDialog>
#include <QTextEdit>
#include <QClipboard>
#include <QShortcut>
#include <QTextCodec>
MainWindow::MainWindow(QWidget* parent)
: QMainWindow(parent),
ui(new Ui::MainWindow),
m_browseTableModel(new SqliteTableModel(db, this, Settings::getValue("db", "prefetchsize").toInt())),
m_currentTabTableModel(m_browseTableModel),
m_remoteDb(new RemoteDatabase),
editDock(new EditDialog(this)),
plotDock(new PlotDock(this)),
remoteDock(new RemoteDock(this)),
gotoValidator(new QIntValidator(0, 0, this))
{
ui->setupUi(this);
init();
activateFields(false);
updateRecentFileActions();
}
MainWindow::~MainWindow()
{
delete m_remoteDb;
delete gotoValidator;
delete ui;
}
void MainWindow::init()
{
// Load window settings
tabifyDockWidget(ui->dockLog, ui->dockPlot);
tabifyDockWidget(ui->dockLog, ui->dockSchema);
tabifyDockWidget(ui->dockLog, ui->dockRemote);
// Connect SQL logging and database state setting to main window
connect(&db, SIGNAL(dbChanged(bool)), this, SLOT(dbState(bool)));
connect(&db, SIGNAL(sqlExecuted(QString, int)), this, SLOT(logSql(QString,int)));
connect(&db, SIGNAL(structureUpdated()), this, SLOT(populateStructure()));
// Set the validator for the goto line edit
ui->editGoto->setValidator(gotoValidator);
// Set up filters
connect(ui->dataTable->filterHeader(), SIGNAL(filterChanged(int,QString)), this, SLOT(updateFilter(int,QString)));
connect(m_browseTableModel, SIGNAL(dataChanged(QModelIndex,QModelIndex)), this, SLOT(dataTableSelectionChanged(QModelIndex)));
// Set up DB structure tab
dbStructureModel = new DbStructureModel(db, this);
ui->dbTreeWidget->setModel(dbStructureModel);
ui->dbTreeWidget->setColumnHidden(1, true);
ui->dbTreeWidget->setColumnWidth(0, 300);
// Set up DB schema dock
ui->treeSchemaDock->setModel(dbStructureModel);
ui->treeSchemaDock->setColumnHidden(1, true);
ui->treeSchemaDock->setColumnWidth(0, 300);
// Set up the table combo box in the Browse Data tab
ui->comboBrowseTable->setModel(dbStructureModel);
// Create docks
ui->dockEdit->setWidget(editDock);
ui->dockPlot->setWidget(plotDock);
ui->dockRemote->setWidget(remoteDock);
// Restore window geometry
restoreGeometry(Settings::getValue("MainWindow", "geometry").toByteArray());
restoreState(Settings::getValue("MainWindow", "windowState").toByteArray());
// Restore dock state settings
ui->comboLogSubmittedBy->setCurrentIndex(ui->comboLogSubmittedBy->findText(Settings::getValue("SQLLogDock", "Log").toString()));
// Add keyboard shortcuts
QList<QKeySequence> shortcuts = ui->actionExecuteSql->shortcuts();
shortcuts.push_back(QKeySequence(tr("Ctrl+Return")));
ui->actionExecuteSql->setShortcuts(shortcuts);
QShortcut* shortcutBrowseRefreshF5 = new QShortcut(QKeySequence("F5"), this);
connect(shortcutBrowseRefreshF5, SIGNAL(activated()), this, SLOT(refresh()));
QShortcut* shortcutBrowseRefreshCtrlR = new QShortcut(QKeySequence("Ctrl+R"), this);
connect(shortcutBrowseRefreshCtrlR, SIGNAL(activated()), this, SLOT(refresh()));
// Create the actions for the recently opened dbs list
for(int i = 0; i < MaxRecentFiles; ++i) {
recentFileActs[i] = new QAction(this);
recentFileActs[i]->setVisible(false);
connect(recentFileActs[i], SIGNAL(triggered()), this, SLOT(openRecentFile()));
}
for(int i = 0; i < MaxRecentFiles; ++i)
ui->fileMenu->insertAction(ui->fileExitAction, recentFileActs[i]);
recentSeparatorAct = ui->fileMenu->insertSeparator(ui->fileExitAction);
// Create popup menus
popupTableMenu = new QMenu(this);
popupTableMenu->addAction(ui->actionEditBrowseTable);
popupTableMenu->addAction(ui->editModifyObjectAction);
popupTableMenu->addAction(ui->editDeleteObjectAction);
popupTableMenu->addSeparator();
popupTableMenu->addAction(ui->actionEditCopyCreateStatement);
popupTableMenu->addAction(ui->actionExportCsvPopup);
popupSaveSqlFileMenu = new QMenu(this);
popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFile);
popupSaveSqlFileMenu->addAction(ui->actionSqlSaveFileAs);
ui->actionSqlSaveFilePopup->setMenu(popupSaveSqlFileMenu);
popupBrowseDataHeaderMenu = new QMenu(this);
popupBrowseDataHeaderMenu->addAction(ui->actionShowRowidColumn);
popupBrowseDataHeaderMenu->addAction(ui->actionBrowseTableEditDisplayFormat);
popupBrowseDataHeaderMenu->addAction(ui->actionSetTableEncoding);
popupBrowseDataHeaderMenu->addSeparator();
popupBrowseDataHeaderMenu->addAction(ui->actionSetAllTablesEncoding);
QShortcut* dittoRecordShortcut = new QShortcut(QKeySequence("Ctrl+\""), this);
connect(dittoRecordShortcut, &QShortcut::activated, [this]() {
int currentRow = ui->dataTable->currentIndex().row();
auto row = m_browseTableModel->dittoRecord(currentRow);
ui->dataTable->setCurrentIndex(row);
});
// Add menu item for log dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockLog->toggleViewAction());
ui->viewMenu->actions().at(0)->setShortcut(QKeySequence(tr("Ctrl+L")));
ui->viewMenu->actions().at(0)->setIcon(QIcon(":/icons/log_dock"));
ui->viewDBToolbarAction->setChecked(!ui->toolbarDB->isHidden());
// Add menu item for plot dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockPlot->toggleViewAction());
QList<QKeySequence> plotkeyseqlist;
plotkeyseqlist << QKeySequence(tr("Ctrl+P")) << QKeySequence(tr("Ctrl+D"));
ui->viewMenu->actions().at(1)->setShortcuts(plotkeyseqlist);
ui->viewMenu->actions().at(1)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for schema dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockSchema->toggleViewAction());
ui->viewMenu->actions().at(2)->setShortcut(QKeySequence(tr("Ctrl+I")));
ui->viewMenu->actions().at(2)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for edit dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockEdit->toggleViewAction());
ui->viewMenu->actions().at(3)->setShortcut(QKeySequence(tr("Ctrl+E")));
ui->viewMenu->actions().at(3)->setIcon(QIcon(":/icons/log_dock"));
// Add menu item for plot dock
ui->viewMenu->insertAction(ui->viewDBToolbarAction, ui->dockRemote->toggleViewAction());
ui->viewMenu->actions().at(4)->setIcon(QIcon(":/icons/log_dock"));
// If we're not compiling in SQLCipher, hide its FAQ link in the help menu
#ifndef ENABLE_SQLCIPHER
ui->actionSqlCipherFaq->setVisible(false);
#endif
// Set statusbar fields
statusEncryptionLabel = new QLabel(ui->statusbar);
statusEncryptionLabel->setEnabled(false);
statusEncryptionLabel->setVisible(false);
statusEncryptionLabel->setText(tr("Encrypted"));
statusEncryptionLabel->setToolTip(tr("Database is encrypted using SQLCipher"));
ui->statusbar->addPermanentWidget(statusEncryptionLabel);
statusReadOnlyLabel = new QLabel(ui->statusbar);
statusReadOnlyLabel->setEnabled(false);
statusReadOnlyLabel->setVisible(false);
statusReadOnlyLabel->setText(tr("Read only"));
statusReadOnlyLabel->setToolTip(tr("Database file is read only. Editing the database is disabled."));
ui->statusbar->addPermanentWidget(statusReadOnlyLabel);
statusEncodingLabel = new QLabel(ui->statusbar);
statusEncodingLabel->setEnabled(false);
statusEncodingLabel->setText("UTF-8");
statusEncodingLabel->setToolTip(tr("Database encoding"));
ui->statusbar->addPermanentWidget(statusEncodingLabel);
// Connect some more signals and slots
connect(ui->dataTable->filterHeader(), SIGNAL(sectionClicked(int)), this, SLOT(browseTableHeaderClicked(int)));
connect(ui->dataTable->verticalScrollBar(), SIGNAL(valueChanged(int)), this, SLOT(setRecordsetLabel()));
connect(ui->dataTable->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(updateBrowseDataColumnWidth(int,int,int)));
connect(editDock, SIGNAL(recordTextUpdated(QPersistentModelIndex, QByteArray, bool)), this, SLOT(updateRecordText(QPersistentModelIndex, QByteArray, bool)));
connect(ui->dbTreeWidget->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(changeTreeSelection()));
connect(ui->dataTable->horizontalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showDataColumnPopupMenu(QPoint)));
connect(ui->dataTable->verticalHeader(), SIGNAL(customContextMenuRequested(QPoint)), this, SLOT(showRecordPopupMenu(QPoint)));
connect(ui->dockEdit, SIGNAL(visibilityChanged(bool)), this, SLOT(toggleEditDock(bool)));
connect(m_remoteDb, SIGNAL(openFile(QString)), this, SLOT(fileOpen(QString)));
connect(m_remoteDb, &RemoteDatabase::gotCurrentVersion, this, &MainWindow::checkNewVersion);
// Lambda function for keyboard shortcuts for selecting next/previous table in Browse Data tab
connect(ui->dataTable, &ExtendedTableWidget::switchTable, [this](bool next) {
int index = ui->comboBrowseTable->currentIndex();
int num_items = ui->comboBrowseTable->count();
if(next)
{
if(++index >= num_items)
index = 0;
} else {
if(--index < 0)
index = num_items - 1;
}
ui->comboBrowseTable->setCurrentIndex(index);
populateTable();
});
// Set other window settings
setAcceptDrops(true);
setWindowTitle(QApplication::applicationName());
// Load all settings
reloadSettings();
#ifdef CHECKNEWVERSION
// Check for a new version if automatic update check aren't disabled in the settings dialog
if(Settings::getValue("checkversion", "enabled").toBool())
{
m_remoteDb->fetch("https://raw.githubusercontent.com/sqlitebrowser/sqlitebrowser/master/currentrelease",
RemoteDatabase::RequestTypeNewVersionCheck);
}
#endif
#ifndef ENABLE_SQLCIPHER
// Only show encryption menu action when SQLCipher support is enabled
ui->actionEncryption->setVisible(false);
#endif
/* Remove all the '&' signs from the dock titles. On at least Windows and
* OSX, Qt doesn't seem to support them properly, so they end up being
* visible instead of creating a keyboard shortcut
*/
ui->dockEdit->setWindowTitle(ui->dockEdit->windowTitle().remove('&'));
ui->dockLog->setWindowTitle(ui->dockLog->windowTitle().remove('&'));
ui->dockPlot->setWindowTitle(ui->dockPlot->windowTitle().remove('&'));
ui->dockSchema->setWindowTitle(ui->dockSchema->windowTitle().remove('&'));
ui->dockRemote->setWindowTitle(ui->dockRemote->windowTitle().remove('&'));
}
bool MainWindow::fileOpen(const QString& fileName, bool dontAddToRecentFiles, bool readOnly)
{
bool retval = false;
QString wFile = fileName;
if (!QFile::exists(wFile))
{
wFile = FileDialog::getOpenFileName(
this,
tr("Choose a database file")
#ifndef Q_OS_MAC // Filters on OS X are buggy
, FileDialog::getSqlDatabaseFileFilter()
#endif
);
}
if(QFile::exists(wFile) )
{
// Close the database. If the user didn't want to close it, though, stop here
if (db.isOpen())
if(!fileClose())
return false;
// Try opening it as a project file first
if(loadProject(wFile, readOnly))
{
retval = true;
} else {
// No project file; so it should be a database file
if(db.open(wFile, readOnly))
{
statusEncodingLabel->setText(db.getPragma("encoding"));
statusEncryptionLabel->setVisible(db.encrypted());
statusReadOnlyLabel->setVisible(db.readOnly());
setCurrentFile(wFile);
if(!dontAddToRecentFiles)
addToRecentFilesMenu(wFile);
openSqlTab(true);
loadExtensionsFromSettings();
if(ui->mainTab->currentIndex() == BrowseTab)
populateTable();
else if(ui->mainTab->currentIndex() == PragmaTab)
loadPragmas();
retval = true;
} else {
QMessageBox::warning(this, qApp->applicationName(), tr("Could not open database file.\nReason: %1").arg(db.lastError()));
return false;
}
}
}
return retval;
}
void MainWindow::fileNew()
{
QString fileName = FileDialog::getSaveFileName(this,
tr("Choose a filename to save under"),
FileDialog::getSqlDatabaseFileFilter());
if(!fileName.isEmpty())
{
if(QFile::exists(fileName))
QFile::remove(fileName);
db.create(fileName);
setCurrentFile(fileName);
addToRecentFilesMenu(fileName);
statusEncodingLabel->setText(db.getPragma("encoding"));
statusEncryptionLabel->setVisible(false);
statusReadOnlyLabel->setVisible(false);
loadExtensionsFromSettings();
populateTable();
openSqlTab(true);
createTable();
}
}
void MainWindow::populateStructure()
{
QString old_table = ui->comboBrowseTable->currentText();
// Refresh the structure tab
dbStructureModel->reloadData();
ui->dbTreeWidget->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure
ui->dbTreeWidget->expandToDepth(0);
ui->treeSchemaDock->setRootIndex(dbStructureModel->index(1, 0)); // Show the 'All' part of the db structure
ui->treeSchemaDock->expandToDepth(0);
// Refresh the browse data tab
ui->comboBrowseTable->setRootModelIndex(dbStructureModel->index(0, 0)); // Show the 'browsable' section of the db structure tree
int old_table_index = ui->comboBrowseTable->findText(old_table);
if(old_table_index == -1 && ui->comboBrowseTable->count()) // If the old table couldn't be found anymore but there is another table, select that
ui->comboBrowseTable->setCurrentIndex(0);
else if(old_table_index == -1) // If there aren't any tables to be selected anymore, clear the table view
clearTableBrowser();
else // Under normal circumstances just select the old table again
ui->comboBrowseTable->setCurrentIndex(old_table_index);
// Cancel here if no database is opened
if(!db.isOpen())
return;
// Update table and column names for syntax highlighting
objectMap tab = db.getBrowsableObjects();
SqlUiLexer::TablesAndColumnsMap tablesToColumnsMap;
for(auto it=tab.constBegin();it!=tab.constEnd();++it)
{
QString objectname = (*it)->name();
sqlb::FieldInfoList fi = (*it)->fieldInformation();
foreach(const sqlb::FieldInfo& f, fi)
tablesToColumnsMap[objectname].append(f.name);
}
SqlTextEdit::sqlLexer->setTableNames(tablesToColumnsMap);
ui->editLogApplication->reloadKeywords();
ui->editLogUser->reloadKeywords();
for(int i=0;i<ui->tabSqlAreas->count();i++)
qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->widget(i))->getEditor()->reloadKeywords();
// Resize SQL column to fit contents
ui->dbTreeWidget->resizeColumnToContents(3);
}
void MainWindow::clearTableBrowser()
{
if (!ui->dataTable->model())
return;
ui->dataTable->setModel(0);
if(qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader()))
qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader())->generateFilters(0);
}
void MainWindow::populateTable()
{
// Early exit if the Browse Data tab isn't visible as there is no need to update it in this case
if(ui->mainTab->currentIndex() != BrowseTab)
return;
// Remove the model-view link if the table name is empty in order to remove any data from the view
if(ui->comboBrowseTable->model()->rowCount(ui->comboBrowseTable->rootModelIndex()) == 0)
{
clearTableBrowser();
return;
}
QApplication::setOverrideCursor(Qt::WaitCursor);
// Get current table name
QString tablename = ui->comboBrowseTable->currentText();
// Set model
bool reconnectSelectionSignals = false;
if(ui->dataTable->model() == 0)
reconnectSelectionSignals = true;
ui->dataTable->setModel(m_browseTableModel);
if(reconnectSelectionSignals)
connect(ui->dataTable->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)), this, SLOT(dataTableSelectionChanged(QModelIndex)));
// Search stored table settings for this table
auto tableIt = browseTableSettings.constFind(tablename);
bool storedDataFound = tableIt != browseTableSettings.constEnd();
// Set new table
if(!storedDataFound)
{
m_browseTableModel->setTable(tablename);
} else {
QVector<QString> v;
bool only_defaults = true;
const sqlb::FieldInfoList& tablefields = db.getObjectByName(tablename)->fieldInformation();
for(int i=0; i<tablefields.size(); ++i)
{
QString format = tableIt.value().displayFormats[i+1];
if(format.size())
{
v.push_back(format);
only_defaults = false;
} else {
v.push_back(sqlb::escapeIdentifier(tablefields.at(i).name));
}
}
if(only_defaults)
m_browseTableModel->setTable(tablename);
else
m_browseTableModel->setTable(tablename, v);
}
// Restore table settings
if(storedDataFound)
{
// There is information stored for this table, so extract it and apply it
// Show rowid column. Needs to be done before the column widths setting because of the workaround in there and before the filter setting
// because of the filter row generation.
showRowidColumn(tableIt.value().showRowid);
// Column widths
for(auto widthIt=tableIt.value().columnWidths.constBegin();widthIt!=tableIt.value().columnWidths.constEnd();++widthIt)
ui->dataTable->setColumnWidth(widthIt.key(), widthIt.value());
// Sorting
m_browseTableModel->sort(tableIt.value().sortOrderIndex, tableIt.value().sortOrderMode);
ui->dataTable->filterHeader()->setSortIndicator(tableIt.value().sortOrderIndex, tableIt.value().sortOrderMode);
// Filters
FilterTableHeader* filterHeader = qobject_cast<FilterTableHeader*>(ui->dataTable->horizontalHeader());
for(auto filterIt=tableIt.value().filterValues.constBegin();filterIt!=tableIt.value().filterValues.constEnd();++filterIt)
filterHeader->setFilter(filterIt.key(), filterIt.value());
// Encoding
m_browseTableModel->setEncoding(tableIt.value().encoding);
// Plot
plotDock->updatePlot(m_browseTableModel, &browseTableSettings[ui->comboBrowseTable->currentText()], true, false);
} else {
// There aren't any information stored for this table yet, so use some default values
// Hide rowid column. Needs to be done before the column widths setting because of the workaround in there
showRowidColumn(false);
// Column widths
for(int i=1;i<m_browseTableModel->columnCount();i++)
ui->dataTable->setColumnWidth(i, ui->dataTable->horizontalHeader()->defaultSectionSize());
// Sorting
m_browseTableModel->sort(0, Qt::AscendingOrder);
ui->dataTable->filterHeader()->setSortIndicator(0, Qt::AscendingOrder);
// Encoding
m_browseTableModel->setEncoding(defaultBrowseTableEncoding);
// Plot
plotDock->updatePlot(m_browseTableModel, &browseTableSettings[ui->comboBrowseTable->currentText()]);
// The filters can be left empty as they are
}
// Activate the add and delete record buttons and editing only if a table has been selected
bool editable = db.getObjectByName(tablename)->type() == sqlb::Object::Types::Table && !db.readOnly();
ui->buttonNewRecord->setEnabled(editable);
ui->buttonDeleteRecord->setEnabled(editable);
ui->dataTable->setEditTriggers(editable ? QAbstractItemView::SelectedClicked | QAbstractItemView::AnyKeyPressed | QAbstractItemView::EditKeyPressed : QAbstractItemView::NoEditTriggers);
// Set the recordset label
setRecordsetLabel();
QApplication::restoreOverrideCursor();
}
bool MainWindow::fileClose()
{
// Close the database but stop the closing process here if the user pressed the cancel button in there
if(!db.close())
return false;
setWindowTitle(QApplication::applicationName());
loadPragmas();
statusEncryptionLabel->setVisible(false);
statusReadOnlyLabel->setVisible(false);
// Reset the model for the Browse tab
m_browseTableModel->reset();
// Remove all stored table information browse data tab
browseTableSettings.clear();
defaultBrowseTableEncoding = QString();
// Clear edit dock
editDock->setCurrentIndex(QModelIndex());
// Reset the recordset label inside the Browse tab now
setRecordsetLabel();
// Reset the plot dock model
plotDock->updatePlot(0);
activateFields(false);
// Clear the SQL Log
ui->editLogApplication->clear();
ui->editLogUser->clear();
for(int i=ui->tabSqlAreas->count()-1;i>=0;i--)
closeSqlTab(i, true);
return true;
}
void MainWindow::closeEvent( QCloseEvent* event )
{
if(db.close())
{
Settings::setValue("MainWindow", "geometry", saveGeometry());
Settings::setValue("MainWindow", "windowState", saveState());
Settings::setValue("SQLLogDock", "Log", ui->comboLogSubmittedBy->currentText());
QMainWindow::closeEvent(event);
} else {
event->ignore();
}
}
void MainWindow::addRecord()
{
int row = m_browseTableModel->rowCount();
if(m_browseTableModel->insertRow(row))
{
selectTableLine(row);
} else {
QMessageBox::warning(this, QApplication::applicationName(), tr("Error adding record:\n") + db.lastError());
}
}
void MainWindow::deleteRecord()
{
if(ui->dataTable->selectionModel()->hasSelection())
{
// If only filter header is selected
if(ui->dataTable->selectionModel()->selectedIndexes().isEmpty())
return;
int old_row = ui->dataTable->currentIndex().row();
while(ui->dataTable->selectionModel()->hasSelection())
{
int first_selected_row = ui->dataTable->selectionModel()->selectedIndexes().first().row();
int last_selected_row = ui->dataTable->selectionModel()->selectedIndexes().last().row();
int selected_rows_count = last_selected_row - first_selected_row + 1;
if(!m_browseTableModel->removeRows(first_selected_row, selected_rows_count))
{
QMessageBox::warning(this, QApplication::applicationName(), tr("Error deleting record:\n%1").arg(db.lastError()));
break;
}
}
if(old_row > m_browseTableModel->totalRowCount())
old_row = m_browseTableModel->totalRowCount();
selectTableLine(old_row);
} else {
QMessageBox::information( this, QApplication::applicationName(), tr("Please select a record first"));
}
}
void MainWindow::selectTableLine(int lineToSelect)
{
// Are there even that many lines?
if(lineToSelect >= m_browseTableModel->totalRowCount())
return;
QApplication::setOverrideCursor( Qt::WaitCursor );
// Make sure this line has already been fetched
while(lineToSelect >= m_browseTableModel->rowCount() && m_browseTableModel->canFetchMore())
m_browseTableModel->fetchMore();
// Select it
ui->dataTable->clearSelection();
ui->dataTable->selectRow(lineToSelect);
ui->dataTable->scrollTo(ui->dataTable->currentIndex());
QApplication::restoreOverrideCursor();
}
void MainWindow::navigatePrevious()
{
int curRow = ui->dataTable->currentIndex().row();
curRow -= 100;
if(curRow < 0)
curRow = 0;
selectTableLine(curRow);
}
void MainWindow::navigateNext()
{
int curRow = ui->dataTable->currentIndex().row();
curRow += 100;
if(curRow >= m_browseTableModel->totalRowCount())
curRow = m_browseTableModel->totalRowCount() - 1;
selectTableLine(curRow);
}
void MainWindow::navigateBegin()
{
selectTableLine(0);
}
void MainWindow::navigateEnd()
{
selectTableLine(m_browseTableModel->totalRowCount()-1);
}
void MainWindow::navigateGoto()
{
int row = ui->editGoto->text().toInt();
if(row <= 0)
row = 1;
if(row > m_browseTableModel->totalRowCount())
row = m_browseTableModel->totalRowCount();
selectTableLine(row - 1);
ui->editGoto->setText(QString::number(row));
}
void MainWindow::setRecordsetLabel()
{
// Get all the numbers, i.e. the number of the first row and the last row as well as the total number of rows
int from = ui->dataTable->verticalHeader()->visualIndexAt(0) + 1;
int total = m_browseTableModel->totalRowCount();
int to = ui->dataTable->verticalHeader()->visualIndexAt(ui->dataTable->height()) - 1;
if (to == -2)
to = total;
// Update the validator of the goto row field
gotoValidator->setRange(0, total);
// Update the label showing the current position
ui->labelRecordset->setText(tr("%1 - %2 of %3").arg(from).arg(to).arg(total));
}
void MainWindow::refresh()
{
// What the Refresh function does depends on the currently active tab. This way the keyboard shortcuts (F5 and Ctrl+R)
// always perform some meaningful task; they just happen to be context dependent in the function they trigger.
switch(ui->mainTab->currentIndex())
{
case StructureTab:
// Refresh the schema
db.updateSchema();
break;
case BrowseTab:
// Refresh the schema and reload the current table
db.updateSchema();
populateTable();
break;
case PragmaTab:
// Reload pragma values
loadPragmas();
break;
case ExecuteTab:
// (Re-)Run the current SQL query
executeQuery();
break;
}
}
void MainWindow::createTable()
{
if (!db.isOpen()){
QMessageBox::information( this, QApplication::applicationName(), tr("There is no database opened. Please open or create a new database file."));
return;
}
EditTableDialog dialog(db, "", true, this);
if(dialog.exec())
{
populateTable();
}
}
void MainWindow::createIndex()
{
if (!db.isOpen()){
QMessageBox::information( this, QApplication::applicationName(), tr("There is no database opened. Please open or create a new database file."));
return;
}
EditIndexDialog dialog(db, "", true, this);
if(dialog.exec())
populateTable();
}
void MainWindow::compact()
{
VacuumDialog dialog(&db, this);
dialog.exec();
}
void MainWindow::deleteObject()
{
// Get name and type of object to delete
QString table = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), 0), Qt::EditRole).toString();
QString type = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), 1), Qt::EditRole).toString();
// Ask user if he really wants to delete that table
if(QMessageBox::warning(this, QApplication::applicationName(), tr("Are you sure you want to delete the %1 '%2'?\nAll data associated with the %1 will be lost.").arg(type).arg(table),
QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes)
{
// Delete the table
QString statement = QString("DROP %1 %2;").arg(type.toUpper()).arg(sqlb::escapeIdentifier(table));
if(!db.executeSQL( statement))
{
QString error = tr("Error: could not delete the %1. Message from database engine:\n%2").arg(type).arg(db.lastError());
QMessageBox::warning(this, QApplication::applicationName(), error);
} else {
populateTable();
changeTreeSelection();
}
}
}
void MainWindow::editObject()
{
if(!ui->dbTreeWidget->selectionModel()->hasSelection())
return;
// Get name and type of the object to edit
QString name = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), 0), Qt::EditRole).toString();
QString type = ui->dbTreeWidget->model()->data(ui->dbTreeWidget->currentIndex().sibling(ui->dbTreeWidget->currentIndex().row(), 1), Qt::EditRole).toString();
if(type == "table")
{
EditTableDialog dialog(db, name, false, this);
if(dialog.exec())
populateTable();
} else if(type == "index") {
EditIndexDialog dialog(db, name, false, this);
if(dialog.exec())
populateTable();
}
}
void MainWindow::helpWhatsThis()
{
QWhatsThis::enterWhatsThisMode ();
}
void MainWindow::helpAbout()
{
AboutDialog dialog(this);
dialog.exec();
}
void MainWindow::updateRecordText(const QPersistentModelIndex& idx, const QByteArray& text, bool isBlob)
{
m_currentTabTableModel->setTypedData(idx, isBlob, text);
}
void MainWindow::toggleEditDock(bool visible)
{
if (!visible) {
// Update main window
activateWindow();
ui->dataTable->setFocus();
} else {
// fill edit dock with actual data
editDock->setCurrentIndex(ui->dataTable->currentIndex());
}
}
void MainWindow::doubleClickTable(const QModelIndex& index)
{
// Cancel on invalid index
if (!index.isValid()) {
return;
}
// * Don't allow editing of other objects than tables (on the browse table) *
bool isEditingAllowed = (m_currentTabTableModel == m_browseTableModel) &&
(db.getObjectByName(ui->comboBrowseTable->currentText())->type() == sqlb::Object::Types::Table);
// Enable or disable the Apply, Null, & Import buttons in the Edit Cell
// dock depending on the value of the "isEditingAllowed" bool above
editDock->setReadOnly(!isEditingAllowed);
editDock->setCurrentIndex(index);
// Show the edit dock
ui->dockEdit->setVisible(true);
// Set focus on the edit dock
editDock->setFocus();
}
void MainWindow::dataTableSelectionChanged(const QModelIndex& index)
{
// Cancel on invalid index
if(!index.isValid()) {
editDock->setCurrentIndex(QModelIndex());
return;
}
bool editingAllowed = (m_currentTabTableModel == m_browseTableModel) &&
(db.getObjectByName(ui->comboBrowseTable->currentText())->type() == sqlb::Object::Types::Table);
// Don't allow editing of other objects than tables
editDock->setReadOnly(!editingAllowed);
// If the Edit Cell dock is visible, load the new value into it
if (editDock->isVisible()) {
editDock->setCurrentIndex(index);
}
}
/*
* I'm still not happy how the results are represented to the user
* right now you only see the result of the last executed statement.
* A better experience would be tabs on the bottom with query results
* for all the executed statements.
* Or at least a some way the use could see results/status message
* per executed statement.
*/
void MainWindow::executeQuery()
{
SqlExecutionArea* sqlWidget = qobject_cast<SqlExecutionArea*>(ui->tabSqlAreas->currentWidget());
// Get SQL code to execute. This depends on the button that's been pressed
QString query;
int execution_start_line = 0;
int execution_start_index = 0;
if(sender()->objectName() == "actionSqlExecuteLine")
{
int cursor_line, cursor_index;
SqlTextEdit *editor = sqlWidget->getEditor();
editor->getCursorPosition(&cursor_line, &cursor_index);
execution_start_line = cursor_line;
int lineStartCursorPosition = editor->positionFromLineIndex(cursor_line, 0);
QString entireSQL = editor->text();
QString firstPartEntireSQL = entireSQL.left(lineStartCursorPosition);
QString secondPartEntireSQL = entireSQL.right(entireSQL.length() - lineStartCursorPosition);
QString firstPartSQL = firstPartEntireSQL.split(";").last();
QString lastPartSQL = secondPartEntireSQL.split(";").first();
query = firstPartSQL + lastPartSQL;
} else {
// if a part of the query is selected, we will only execute this part
query = sqlWidget->getSelectedSql();
int dummy;
if(query.isEmpty())
query = sqlWidget->getSql();
else
sqlWidget->getEditor()->getSelection(&execution_start_line, &execution_start_index, &dummy, &dummy);
}
if (query.trimmed().isEmpty() || query.trimmed() == ";")
return;
query = query.remove(QRegExp("^\\s*BEGIN TRANSACTION;|COMMIT;\\s*$")).trimmed();
//log the query
db.logSQL(query, kLogMsg_User);
sqlite3_stmt *vm;
QByteArray utf8Query = query.toUtf8();
const char *tail = utf8Query.data();
int sql3status = SQLITE_OK;
int tail_length = utf8Query.length();
QString statusMessage;
bool modified = false;
bool wasdirty = db.getDirty();
bool structure_updated = false;
// there is no choice, we have to start a transaction before
// we create the prepared statement, otherwise every executed
// statement will get committed after the prepared statement
// gets finalized, see http://www.sqlite.org/lang_transaction.html
db.setSavepoint();
// Remove any error indicators
sqlWidget->getEditor()->clearErrorIndicators();
//Accept multi-line queries, by looping until the tail is empty
QElapsedTimer timer;
timer.start();
while( tail && *tail != 0 && (sql3status == SQLITE_OK || sql3status == SQLITE_DONE))
{
// Check whether the DB structure is changed by this statement
QString qtail = QString(tail);
if(!structure_updated && (qtail.startsWith("ALTER", Qt::CaseInsensitive) ||
qtail.startsWith("CREATE", Qt::CaseInsensitive) ||
qtail.startsWith("DROP", Qt::CaseInsensitive) ||
qtail.startsWith("ROLLBACK", Qt::CaseInsensitive)))
structure_updated = true;
// Execute next statement
int tail_length_before = tail_length;
const char* qbegin = tail;
sql3status = sqlite3_prepare_v2(db._db,tail, tail_length, &vm, &tail);
QString queryPart = QString::fromUtf8(qbegin, tail - qbegin);
tail_length -= (tail - qbegin);
int execution_end_index = execution_start_index + tail_length_before - tail_length;
if (sql3status == SQLITE_OK)
{
sql3status = sqlite3_step(vm);
sqlite3_finalize(vm);
// SQLite returns SQLITE_DONE when a valid SELECT statement was executed but returned no results. To run into the branch that updates
// the status message and the table view anyway manipulate the status value here. This is also done for PRAGMA statements as they (sometimes)
// return rows just like SELECT statements, too.
if((queryPart.trimmed().startsWith("SELECT", Qt::CaseInsensitive) ||
queryPart.trimmed().startsWith("PRAGMA", Qt::CaseInsensitive)) && sql3status == SQLITE_DONE)
sql3status = SQLITE_ROW;
switch(sql3status)
{
case SQLITE_ROW:
{
sqlWidget->getModel()->setQuery(queryPart);
if(sqlWidget->getModel()->valid())
{
// The query takes the last placeholder as it may itself contain the sequence '%' + number
statusMessage = tr("%1 rows returned in %2ms from: %3").arg(
sqlWidget->getModel()->totalRowCount()).arg(timer.elapsed()).arg(queryPart.trimmed());
sqlWidget->enableSaveButton(true);
sql3status = SQLITE_OK;
}
else
{
statusMessage = tr("Error executing query: %1").arg(queryPart);
sql3status = SQLITE_ERROR;
}
}
case SQLITE_DONE:
case SQLITE_OK:
{
if( !queryPart.trimmed().startsWith("SELECT", Qt::CaseInsensitive) )
{
modified = true;