{{ message }}
Repository navigation
Expand file tree
/
Copy pathsqlitedb.cpp
More file actions
2383 lines (2035 loc) · 92.7 KB
/
Copy pathsqlitedb.cpp
File metadata and controls
2383 lines (2035 loc) · 92.7 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 "sqlitedb.h"
#include "sqlite.h"
#include "sqlitetablemodel.h"
#include "CipherDialog.h"
#include "CipherSettings.h"
#include "Settings.h"
#include "Data.h"
#include <QFile>
#include <QMessageBox>
#include <QProgressDialog>
#include <QApplication>
#include <QInputDialog>
#include <QFileInfo>
#include <QDir>
#include <QDebug>
#include <QThread>
#include <QRegularExpression>
#include <QSettings>
#include <algorithm>
#include <array>
#include <atomic>
#include <cctype>
#include <chrono>
#include <cstring>
#include <functional>
namespace {
bool equalsIgnoreCase(const std::string& lhs, const std::string& rhs)
{
if(lhs.size() != rhs.size())
return false;
return std::equal(lhs.begin(), lhs.end(), rhs.begin(), rhs.end(), [](unsigned char a, unsigned char b) {
return std::tolower(a) == std::tolower(b);
});
}
template<typename MapType>
typename MapType::const_iterator findCaseInsensitive(const MapType& map, const std::string& key)
{
auto it = map.find(key);
if(it != map.end())
return it;
return std::find_if(map.begin(), map.end(), [&key](const auto& entry) {
return equalsIgnoreCase(entry.first, key);
});
}
}
const QStringList DBBrowserDB::journalModeValues = {"DELETE", "TRUNCATE", "PERSIST", "MEMORY", "WAL", "OFF"};
const QStringList DBBrowserDB::lockingModeValues = {"NORMAL", "EXCLUSIVE"};
QStringList DBBrowserDB::Datatypes = {"INTEGER", "TEXT", "BLOB", "REAL", "NUMERIC"};
QStringList DBBrowserDB::DatatypesStrict = {"INT", "INTEGER", "TEXT", "BLOB", "REAL", "ANY"};
// Helper template to allow turning member functions into a C-style function pointer
// See https://stackoverflow.com/questions/19808054/convert-c-function-pointer-to-c-function-pointer/19809787
template <typename T>
struct Callback;
template <typename Ret, typename... Params>
struct Callback<Ret(Params...)> {
template <typename... Args>
static Ret callback(Args... args) { return func(args...); }
static std::function<Ret(Params...)> func;
};
template <typename Ret, typename... Params>
std::function<Ret(Params...)> Callback<Ret(Params...)>::func;
namespace sqlb {
QString escapeIdentifier(const QString& id)
{
return QString::fromStdString(escapeIdentifier(id.toStdString()));
}
QString escapeString(const QString& literal)
{
return QString::fromStdString(escapeString(literal.toStdString()));
}
QString escapeByteArray(const QByteArray& literal)
{
if(isTextOnly(literal))
return sqlb::escapeString(literal);
else
return QString("X'%1'").arg(QString(literal.toHex()));
}}
// collation callbacks
int collCompare(void* /*pArg*/, int sizeA, const void* sA, int sizeB, const void* sB)
{
if(sizeA == sizeB)
return memcmp(sA, sB, static_cast<size_t>(sizeA));
return sizeA - sizeB;
}
static int sqlite_compare_utf16( void* /*arg*/,int size1, const void *str1, int size2, const void* str2)
{
const QString string1 = QString::fromRawData(reinterpret_cast<const QChar*>(str1), static_cast<int>(static_cast<size_t>(size1) / sizeof(QChar)));
const QString string2 = QString::fromRawData(reinterpret_cast<const QChar*>(str2), static_cast<int>(static_cast<size_t>(size2) / sizeof(QChar)));
return QString::compare(string1, string2, Qt::CaseSensitive);
}
static int sqlite_compare_utf16ci( void* /*arg*/,int size1, const void *str1, int size2, const void* str2)
{
const QString string1 = QString::fromRawData(reinterpret_cast<const QChar*>(str1), static_cast<int>(static_cast<size_t>(size1) / sizeof(QChar)));
const QString string2 = QString::fromRawData(reinterpret_cast<const QChar*>(str2), static_cast<int>(static_cast<size_t>(size2) / sizeof(QChar)));
return QString::compare(string1, string2, Qt::CaseInsensitive);
}
static void sqlite_make_single_value(sqlite3_context* ctx, int num_arguments, sqlite3_value* arguments[])
{
QByteArray output;
for(int i=0;i<num_arguments;i++)
output += QByteArray::number(sqlite3_value_bytes(arguments[i])) + ":" + reinterpret_cast<const char*>(sqlite3_value_text(arguments[i]));
char* output_str = new char[static_cast<size_t>(output.size()) + 1];
std::strcpy(output_str, output);
sqlite3_result_text(ctx, output_str, output.size(), [](void* ptr) {
char* cptr = static_cast<char*>(ptr);
delete cptr;
});
}
DBBrowserDB::DBBrowserDB() :
_db(nullptr),
db_used(false),
isEncrypted(false),
isReadOnly(false),
disableStructureUpdateChecks(false)
{
// Register error log callback. This needs to be done before SQLite is first used
Callback<void(void*, int, const char*)>::func = std::bind(&DBBrowserDB::errorLogCallback, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3);
void (*log_callback)(void*, int, const char*) = static_cast<decltype(log_callback)>(Callback<void(void*, int, const char*)>::callback);
sqlite3_config(SQLITE_CONFIG_LOG, log_callback, nullptr);
// Enable URI filenames
sqlite3_config(SQLITE_CONFIG_URI, 1);
}
void DBBrowserDB::collationNeeded(void* /*pData*/, sqlite3* /*db*/, int eTextRep, const char* sCollationName)
{
QString name(sCollationName);
// Don't request built-in collations. SQLite requests these collations even though they are built into
// the library. Since we have no need for overriding them, we just silently ignore these requests.
if(name.compare("BINARY", Qt::CaseInsensitive) &&
name.compare("NOCASE", Qt::CaseInsensitive) &&
name.compare("RTRIM", Qt::CaseInsensitive))
{
emit requestCollation(name, eTextRep);
}
}
void DBBrowserDB::errorLogCallback(void* /*user_data*/, int error_code, const char* message)
{
QString msg = QString("(%1) %2").arg(error_code).arg(message);
logSQL(msg, kLogMsg_ErrorLog);
}
static void regexp(sqlite3_context* ctx, int /*argc*/, sqlite3_value* argv[])
{
// This is a cache for the last 50 regular expressions. Compiling them takes some time, so we want to cache the compiled
// regular expressions for performance purposes.
static std::array<std::pair<QString, QRegularExpression>, 50> regex_cache;
// Check if pattern is in cache
QString pattern{reinterpret_cast<const char*>(sqlite3_value_text(argv[0]))};
QRegularExpression regex;
const auto it = std::find_if(regex_cache.begin(), regex_cache.end(), [pattern](const std::pair<QString, QRegularExpression>& val) {
return val.first == pattern;
});
if(it == regex_cache.end())
{
// Pattern is not in cache. Create a new regular expressions object, compile it, and insert it into the cache
regex.setPattern(pattern);
regex.setPatternOptions(QRegularExpression::UseUnicodePropertiesOption);
if(!regex.isValid())
return sqlite3_result_error(ctx, "invalid operand", -1);
regex.optimize();
static size_t regex_cache_size;
regex_cache_size = (regex_cache_size + 1) % regex_cache.size();
regex_cache[regex_cache_size] = {pattern, regex};
} else {
// Pattern is in the cache. Just retrieve it
regex = it->second;
}
// Get arguments and check their values
QString arg2{reinterpret_cast<const char*>(sqlite3_value_text(argv[1]))};
// Perform the actual matching and return the result.
// SQLite expects a 0 for not found and a 1 for found.
sqlite3_result_int(ctx, regex.match(arg2).hasMatch());
}
bool DBBrowserDB::isOpen ( ) const
{
return _db != nullptr;
}
bool DBBrowserDB::getDirty() const
{
return !savepointList.empty();
}
bool DBBrowserDB::open(const QString& db, bool readOnly)
{
if (isOpen()) close();
isEncrypted = false;
disableStructureUpdateChecks = false;
// Get encryption settings for database file
CipherSettings cipherSettings;
if(tryEncryptionSettings(db, &isEncrypted, &cipherSettings) == false)
return false;
// Open database file
if(sqlite3_open_v2(db.toUtf8(), &_db, readOnly ? SQLITE_OPEN_READONLY : SQLITE_OPEN_READWRITE, nullptr) != SQLITE_OK)
{
lastErrorMessage = QString::fromUtf8(sqlite3_errmsg(_db));
return false;
}
// Set encryption details if database is encrypted
#ifdef ENABLE_SQLCIPHER
if(isEncrypted)
{
executeSQL("PRAGMA key = " + cipherSettings.getPassword(), false, false);
executeSQL("PRAGMA cipher_page_size = " + std::to_string(cipherSettings.getPageSize()), false, false);
executeSQL("PRAGMA kdf_iter = " + std::to_string(cipherSettings.getKdfIterations()), false, false);
executeSQL("PRAGMA cipher_hmac_algorithm = " + cipherSettings.getHmacAlgorithm(), false, false);
executeSQL("PRAGMA cipher_kdf_algorithm = " + cipherSettings.getKdfAlgorithm(), false, false);
executeSQL("PRAGMA cipher_plaintext_header_size = " + std::to_string(cipherSettings.getPlaintextHeaderSize()), false, false);
}
#endif
if (_db)
{
// add UTF16 collation (comparison is performed by QString functions)
sqlite3_create_collation(_db, "UTF16", SQLITE_UTF16, nullptr, sqlite_compare_utf16);
// add UTF16CI (case insensitive) collation (comparison is performed by QString functions)
sqlite3_create_collation(_db, "UTF16CI", SQLITE_UTF16, nullptr, sqlite_compare_utf16ci);
// register collation callback
Callback<void(void*, sqlite3*, int, const char*)>::func = std::bind(&DBBrowserDB::collationNeeded, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3, std::placeholders::_4);
void (*c_callback)(void*, sqlite3*, int, const char*) = static_cast<decltype(c_callback)>(Callback<void(void*, sqlite3*, int, const char*)>::callback);
sqlite3_collation_needed(_db, nullptr, c_callback);
// Set foreign key settings as requested in the preferences
bool foreignkeys = Settings::getValue("db", "foreignkeys").toBool();
setPragma("foreign_keys", foreignkeys ? "1" : "0");
// Register REGEXP function
if(Settings::getValue("extensions", "disableregex").toBool() == false)
sqlite3_create_function(_db, "REGEXP", 2, SQLITE_UTF8, nullptr, regexp, nullptr, nullptr);
// Register our internal helper function for putting multiple values into a single column
sqlite3_create_function_v2(
_db,
"sqlb_make_single_value",
-1,
SQLITE_UTF8 | SQLITE_DETERMINISTIC,
nullptr,
sqlite_make_single_value,
nullptr,
nullptr,
nullptr
);
// Check if file is read only. In-memory databases are never read only
if(db == ":memory:")
{
isReadOnly = false;
} else {
QFileInfo fi(db);
QFileInfo fid(fi.absoluteDir().absolutePath());
isReadOnly = readOnly || !fi.isWritable() || !fid.isWritable();
}
// Load extensions
loadExtensionsFromSettings();
// Execute default SQL
if(!isReadOnly)
{
QByteArray default_sql = Settings::getValue("db", "defaultsqltext").toByteArray();
if(!default_sql.isEmpty())
executeMultiSQL(default_sql, false, true);
}
curDBFilename = db;
updateSchema();
return true;
} else {
return false;
}
}
/**
detaches a previously attached database identified with its alias-name
**/
bool DBBrowserDB::detach(const std::string& attached_as)
{
if(!_db)
{
return false;
}
waitForDbRelease();
// detach database
if(!executeSQL("DETACH " + sqlb::escapeIdentifier(attached_as) + ";", false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
// Update schema to load database schema of the newly attached database
updateSchema();
return true;
}
bool DBBrowserDB::attach(const QString& filePath, QString attach_as)
{
if(!_db)
return false;
waitForDbRelease();
// In shared cache mode, attempting to attach the same database file more than once results in an error.
// So no need for a check if this file has already been attached and abort if this is the case
// Ask for name to be given to the attached database if none was provided
if(attach_as.isEmpty())
{
attach_as = QInputDialog::getText(nullptr,
qApp->applicationName(),
tr("Please specify the database name under which you want to access the attached database"),
QLineEdit::Normal,
QFileInfo(filePath).baseName()
).trimmed();
}
if(attach_as.isNull())
return false;
#ifdef ENABLE_SQLCIPHER
// Try encryption settings
CipherSettings cipherSettings;
bool is_encrypted;
if(tryEncryptionSettings(filePath, &is_encrypted, &cipherSettings) == false)
return false;
// Attach database
std::string key;
if(is_encrypted)
key = "KEY " + cipherSettings.getPassword();
else
key = "KEY ''";
// Only apply cipher settings if the database is encrypted
if(is_encrypted)
{
if(!executeSQL("PRAGMA cipher_default_page_size = " + std::to_string(cipherSettings.getPageSize()), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
if(!executeSQL("PRAGMA cipher_default_kdf_iter = " + std::to_string(cipherSettings.getKdfIterations()), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
if(!executeSQL("PRAGMA cipher_hmac_algorithm = " + cipherSettings.getHmacAlgorithm(), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
if(!executeSQL("PRAGMA cipher_kdf_algorithm = " + cipherSettings.getKdfAlgorithm(), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
if(!executeSQL("PRAGMA cipher_plaintext_header_size = " + std::to_string(cipherSettings.getPlaintextHeaderSize()), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
}
if(!executeSQL("ATTACH " + sqlb::escapeString(filePath.toStdString()) + " AS " + sqlb::escapeIdentifier(attach_as.toStdString()) + " " + key, false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
// Clean up cipher settings
#else
// Attach database
if(!executeSQL("ATTACH " + sqlb::escapeString(filePath.toStdString()) + " AS " + sqlb::escapeIdentifier(attach_as.toStdString()), false))
{
QMessageBox::warning(nullptr, qApp->applicationName(), lastErrorMessage);
return false;
}
#endif
// Update schema to load database schema of the newly attached database
updateSchema();
return true;
}
bool DBBrowserDB::tryEncryptionSettings(const QString& filePath, bool* encrypted, CipherSettings* cipherSettings) const
{
lastErrorMessage = tr("Invalid file format");
// Open database file
sqlite3* dbHandle;
if(sqlite3_open_v2(filePath.toUtf8(), &dbHandle, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK)
return false;
// Try reading from database
#ifdef ENABLE_SQLCIPHER
bool isDotenvChecked = false;
// Determine default encryption settings depending on the SQLCipher version we use
QString sqlite_version, sqlcipher_version;
getSqliteVersion(sqlite_version, sqlcipher_version);
int enc_default_page_size, enc_default_kdf_iter;
int enc_default_plaintext_header_size = 0;
std::string enc_default_hmac_algorithm, enc_default_kdf_algorithm;
if(sqlcipher_version.startsWith('4'))
{
enc_default_page_size = 4096;
enc_default_kdf_iter = 256000;
enc_default_hmac_algorithm = "SHA512";
enc_default_kdf_algorithm = "SHA512";
} else {
enc_default_page_size = 1024;
enc_default_kdf_iter = 64000;
enc_default_hmac_algorithm = "SHA1";
enc_default_kdf_algorithm = "SHA1";
}
#endif
*encrypted = false;
while(true)
{
const std::string statement = "SELECT COUNT(*) FROM sqlite_master;";
sqlite3_stmt* vm;
const char* tail;
int err = sqlite3_prepare_v2(dbHandle, statement.c_str(), static_cast<int>(statement.size()), &vm, &tail);
if(err == SQLITE_BUSY || err == SQLITE_PERM || err == SQLITE_NOMEM || err == SQLITE_IOERR || err == SQLITE_CORRUPT || err == SQLITE_CANTOPEN)
{
lastErrorMessage = QString::fromUtf8(sqlite3_errmsg(dbHandle));
sqlite3_close_v2(dbHandle);
return false;
}
if(sqlite3_step(vm) != SQLITE_ROW)
{
sqlite3_finalize(vm);
#ifdef ENABLE_SQLCIPHER
bool foundDotenvPassword = false;
// Being in a while loop, we don't want to check the same file multiple times
if (!isDotenvChecked) {
const QFileInfo databaseFileInfo(filePath);
const QDir databaseDirectory(databaseFileInfo.absoluteDir());
const QString databaseFileName(databaseFileInfo.fileName());
auto tryLoadDotenv = [&](const QString& dotenvFilePath) -> bool {
if (!QFile::exists(dotenvFilePath))
return false;
const QSettings dotenv(dotenvFilePath, QSettings::IniFormat);
const QVariant passwordValue = dotenv.value(databaseFileName);
if (passwordValue.isNull())
return false;
const std::string password = passwordValue.toString().toStdString();
const QVariant keyFormatValue = dotenv.value(databaseFileName + "_keyFormat", QVariant(CipherSettings::KeyFormats::Passphrase));
const CipherSettings::KeyFormats keyFormat = CipherSettings::getKeyFormat(keyFormatValue.toInt());
const int pageSize = dotenv.value(databaseFileName + "_pageSize", enc_default_page_size).toInt();
const int kdfIterations = dotenv.value(databaseFileName + "_kdfIter", enc_default_kdf_iter).toInt();
const int plaintextHeaderSize = dotenv.value(databaseFileName + "_plaintextHeaderSize", enc_default_plaintext_header_size).toInt();
const std::string hmacAlgorithm = dotenv.value(databaseFileName + "_hmacAlgorithm", QString::fromStdString(enc_default_hmac_algorithm)).toString().toStdString();
const std::string kdfAlgorithm = dotenv.value(databaseFileName + "_kdfAlgorithm", QString::fromStdString(enc_default_kdf_algorithm)).toString().toStdString();
cipherSettings->setKeyFormat(keyFormat);
cipherSettings->setPassword(password);
cipherSettings->setPageSize(pageSize);
cipherSettings->setKdfIterations(kdfIterations);
cipherSettings->setHmacAlgorithm("HMAC_" + hmacAlgorithm);
cipherSettings->setKdfAlgorithm("PBKDF2_HMAC_" + kdfAlgorithm);
cipherSettings->setPlaintextHeaderSize(plaintextHeaderSize);
return true;
};
const QString db4sEnvPath = databaseDirectory.filePath(".db4s.env");
const bool hasDB4SEnv = QFile::exists(db4sEnvPath);
if (hasDB4SEnv)
{
foundDotenvPassword = tryLoadDotenv(db4sEnvPath);
} else {
// Deprecated: legacy .env in the database directory only. Remove once .db4s.env is adopted.
foundDotenvPassword = tryLoadDotenv(databaseDirectory.filePath(".env"));
// Parent folder search is opt-in because it can slow down opening encrypted databases.
if (!foundDotenvPassword && Settings::getValue("db", "sqlcipherparentdotenvlookup").toBool())
{
QDir searchDirectory(databaseDirectory);
while (searchDirectory.cdUp())
{
if (tryLoadDotenv(searchDirectory.filePath(".db4s.env")))
{
foundDotenvPassword = true;
break;
}
}
}
}
isDotenvChecked = true;
}
if(foundDotenvPassword)
{
// Skip the CipherDialog prompt for now to test if the dotenv settings are correct
} else {
CipherDialog *cipherDialog = new CipherDialog(nullptr, false);
if(cipherDialog->exec())
{
*cipherSettings = cipherDialog->getCipherSettings();
} else {
sqlite3_close_v2(dbHandle);
*encrypted = false;
return false;
}
}
// Close and reopen database first to be in a clean state after the failed read attempt from above
sqlite3_close_v2(dbHandle);
if(sqlite3_open_v2(filePath.toUtf8(), &dbHandle, SQLITE_OPEN_READONLY, nullptr) != SQLITE_OK)
return false;
// Set the key
sqlite3_exec(dbHandle, ("PRAGMA key = " + cipherSettings->getPassword()).c_str(), nullptr, nullptr, nullptr);
// Set the settings if they differ from the default values
if(cipherSettings->getPageSize() != enc_default_page_size)
sqlite3_exec(dbHandle, ("PRAGMA cipher_page_size = " + std::to_string(cipherSettings->getPageSize())).c_str(), nullptr, nullptr, nullptr);
if(cipherSettings->getKdfIterations() != enc_default_kdf_iter)
sqlite3_exec(dbHandle, ("PRAGMA kdf_iter = " + std::to_string(cipherSettings->getKdfIterations())).c_str(), nullptr, nullptr, nullptr);
if(cipherSettings->getHmacAlgorithm() != enc_default_hmac_algorithm)
sqlite3_exec(dbHandle, ("PRAGMA cipher_hmac_algorithm = " + cipherSettings->getHmacAlgorithm()).c_str(), nullptr, nullptr, nullptr);
if(cipherSettings->getKdfAlgorithm() != enc_default_kdf_algorithm)
sqlite3_exec(dbHandle, ("PRAGMA cipher_kdf_algorithm = " + cipherSettings->getKdfAlgorithm()).c_str(), nullptr, nullptr, nullptr);
if(cipherSettings->getPlaintextHeaderSize() != enc_default_plaintext_header_size)
sqlite3_exec(dbHandle, ("PRAGMA cipher_plaintext_header_size = " + std::to_string(cipherSettings->getPlaintextHeaderSize())).c_str(), nullptr, nullptr, nullptr);
*encrypted = true;
#else
lastErrorMessage = QString::fromUtf8(sqlite3_errmsg(dbHandle));
sqlite3_close_v2(dbHandle);
return false;
#endif
} else {
sqlite3_finalize(vm);
sqlite3_close_v2(dbHandle);
return true;
}
}
}
void DBBrowserDB::getSqliteVersion(QString& sqlite, QString& sqlcipher)
{
sqlite = QString(SQLITE_VERSION);
// The SQLCipher version must be queried via a pragma and for a pragma we need a database connection.
// Because we want to be able to query the SQLCipher version without opening a database file first, we
// open a separate connection to an in-memory database here.
sqlcipher = QString();
#ifdef ENABLE_SQLCIPHER
sqlite3* dummy;
if(sqlite3_open(":memory:", &dummy) == SQLITE_OK)
{
sqlite3_stmt* stmt;
if(sqlite3_prepare_v2(dummy, "PRAGMA cipher_version", -1, &stmt, nullptr) == SQLITE_OK)
{
if(sqlite3_step(stmt) == SQLITE_ROW)
sqlcipher = QByteArray(static_cast<const char*>(sqlite3_column_blob(stmt, 0)), sqlite3_column_bytes(stmt, 0));
sqlite3_finalize(stmt);
}
sqlite3_close_v2(dummy);
}
#endif
}
bool DBBrowserDB::setSavepoint(const std::string& pointname, bool unique)
{
if(!isOpen())
return false;
if(isReadOnly) {
qWarning() << "setSavepoint: not done. DB is read-only";
return false;
}
if(unique && contains(savepointList, pointname))
return true;
executeSQL("SAVEPOINT " + sqlb::escapeIdentifier(pointname) + ";", false, true);
savepointList.push_back(pointname);
emit dbChanged(getDirty());
return true;
}
bool DBBrowserDB::releaseSavepoint(const std::string& pointname)
{
if(!isOpen())
return false;
if(contains(savepointList, pointname) == false)
// If there is no such savepoint in the list,
// we have already released it, so in this case
// the operation should be successfull
return true;
if(!executeSQL("RELEASE " + sqlb::escapeIdentifier(pointname) + ";", false, true))
return false;
// SQLite releases all savepoints that were created between
// creation of given savepoint and releasing of it,
// so we should too
auto it = std::find(savepointList.rbegin(), savepointList.rend(), pointname).base() - 1;
savepointList.erase(it, savepointList.end());
emit dbChanged(getDirty());
return true;
}
bool DBBrowserDB::revertToSavepoint(const std::string& pointname)
{
if(!isOpen() || contains(savepointList, pointname) == false)
return false;
executeSQL("ROLLBACK TO SAVEPOINT " + sqlb::escapeIdentifier(pointname) + ";", false, true);
executeSQL("RELEASE " + sqlb::escapeIdentifier(pointname) + ";", false, true);
// SQLite releases all savepoints that were created between
// creation of given savepoint and releasing of it,
// so we should too
auto it = std::find(savepointList.rbegin(), savepointList.rend(), pointname).base() - 1;
savepointList.erase(it, savepointList.end());
emit dbChanged(getDirty());
return true;
}
bool DBBrowserDB::releaseAllSavepoints()
{
if(!_db)
return false;
waitForDbRelease();
while(!savepointList.empty())
{
if(!releaseSavepoint(savepointList.front()))
return false;
}
// When still in a transaction, commit that too
if(sqlite3_get_autocommit(_db) == 0)
executeSQL("COMMIT;", false, true);
return true;
}
bool DBBrowserDB::revertAll()
{
while(!savepointList.empty())
{
if(!revertToSavepoint(savepointList.front()))
return false;
}
return true;
}
bool DBBrowserDB::create ( const QString & db)
{
if (isOpen())
close();
// read encoding from settings and open with sqlite3_open for utf8 and sqlite3_open16 for utf16
QString sEncoding = Settings::getValue("db", "defaultencoding").toString();
int openresult = SQLITE_OK;
if(sEncoding == "UTF-8" || sEncoding == "UTF8" || sEncoding == "Latin1")
openresult = sqlite3_open(db.toUtf8(), &_db);
else
openresult = sqlite3_open16(db.utf16(), &_db);
if( openresult != SQLITE_OK ){
lastErrorMessage = QString::fromUtf8(sqlite3_errmsg(_db));
sqlite3_close_v2(_db);
_db = nullptr;
return false;
}
if (_db)
{
// force sqlite3 do write proper file header
// if we don't create and drop the table we might end up
// with a 0 byte file, if the user cancels the create table dialog
{
NoStructureUpdateChecks nup(*this);
executeSQL("CREATE TABLE notempty (id integer primary key);", false, false);
executeSQL("DROP TABLE notempty;", false, false);
}
// Close database and open it through the code for opening existing database files. This is slightly less efficient but saves us some duplicate
// code.
sqlite3_close_v2(_db);
return open(db);
} else {
return false;
}
}
bool DBBrowserDB::close()
{
// Do nothing if no file is opened
if(!_db)
return true;
waitForDbRelease();
if (getDirty())
{
// In-memory databases can't be saved to disk. So the need another text than regular databases.
// Note that the QMessageBox::Yes option in the :memory: case and the QMessageBox::No option in the regular case are
// doing the same job: proceeding but not saving anything.
QMessageBox::StandardButton reply;
if(curDBFilename == ":memory:")
{
reply = QMessageBox::question(nullptr,
QApplication::applicationName(),
tr("Do you really want to close this temporary database? All data will be lost."),
QMessageBox::Yes | QMessageBox::Cancel);
} else {
reply = QMessageBox::question(nullptr,
QApplication::applicationName(),
tr("Do you want to save the changes made to the database file %1?").arg(curDBFilename),
QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
}
// If the user clicked the cancel button stop here and return false
if(reply == QMessageBox::Cancel)
return false;
// If he didn't it was either yes or no
if(reply == QMessageBox::Save)
releaseAllSavepoints();
else
revertAll(); //not really necessary, I think... but will not hurt.
}
if(sqlite3_close_v2(_db) != SQLITE_OK)
qWarning() << tr("Database didn't close correctly, probably still busy");
_db = nullptr;
curDBFilename.clear();
schemata.clear();
savepointList.clear();
emit dbChanged(getDirty());
emit structureUpdated();
// Return true to tell the calling function that the closing wasn't cancelled by the user
return true;
}
bool DBBrowserDB::saveAs(const std::string& filename) {
if(!_db)
return false;
waitForDbRelease();
// Open the database file identified by filename. Exit early if this fails
// for any reason.
sqlite3* pTo;
int rc = sqlite3_open(filename.c_str(), &pTo);
if(rc!=SQLITE_OK) {
qWarning() << tr("Cannot open destination file: '%1'").arg(filename.c_str());
return false;
} else {
// Set up the backup procedure to copy from the "main" database of
// connection _db to the main database of connection pTo.
// If something goes wrong, pBackup will be set to nullptr and an error
// code and message left in connection pTo.
//
// If the backup object is successfully created, call backup_step()
// to copy data from _db to pTo. Then call backup_finish()
// to release resources associated with the pBackup object. If an
// error occurred, then an error code and message will be left in
// connection pTo. If no error occurred, then the error code belonging
// to pTo is set to SQLITE_OK.
//
sqlite3_backup* pBackup = sqlite3_backup_init(pTo, "main", _db, "main");
if(pBackup == nullptr) {
qWarning() << tr("Cannot backup to file: '%1'. Message: %2").arg(filename.c_str(), sqlite3_errmsg(pTo));
sqlite3_close_v2(pTo);
return false;
} else {
sqlite3_backup_step(pBackup, -1);
sqlite3_backup_finish(pBackup);
}
rc = sqlite3_errcode(pTo);
}
if(rc == SQLITE_OK) {
// Close current database and set backup as current
sqlite3_close_v2(_db);
_db = pTo;
curDBFilename = QString::fromStdString(filename);
return true;
} else {
qWarning() << tr("Cannot backup to file: '%1'. Message: %2").arg(filename.c_str(), sqlite3_errmsg(pTo));
// Close failed database connection.
sqlite3_close_v2(pTo);
return false;
}
}
DBBrowserDB::db_pointer_type DBBrowserDB::get(const QString& user, bool force_wait)
{
if(!_db)
return nullptr;
waitForDbRelease(force_wait ? Wait : Ask);
db_user = user;
db_used = true;
emit databaseInUseChanged(true, user);
return db_pointer_type(_db, DatabaseReleaser(this));
}
void DBBrowserDB::waitForDbRelease(ChoiceOnUse choice) const
{
if(!_db)
return;
// We can't show a message box from another thread than the main thread. So instead of crashing we
// just decide that we don't interrupt any running query in this case.
if(choice == Ask && QThread::currentThread() != QApplication::instance()->thread())
choice = Wait;
std::unique_lock<std::mutex> lk(m);
while(db_used) {
// notify user, give him the opportunity to cancel that
auto str = db_user;
lk.unlock();
bool cancel = choice == CancelOther;
if(choice == Ask) {
QMessageBox msgBox;
msgBox.setText(tr("The database is currently busy: ") + str);
msgBox.setInformativeText(tr("Do you want to abort that other operation?"));
msgBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
msgBox.setDefaultButton(QMessageBox::No);
int ret = msgBox.exec();
cancel = ret == QMessageBox::Yes;
}
if(cancel)
sqlite3_interrupt(_db);
lk.lock();
cv.wait(lk, [this](){ return !db_used; });
}
}
bool DBBrowserDB::dump(const QString& filePath,
const std::vector<std::string>& tablesToDump,
bool insertColNames,
bool insertNewSyntx,
bool keepOriginal,
bool exportSchema,
bool exportData,
bool keepOldSchema) const
{
waitForDbRelease();
// Open file
QFile file(filePath);
if(file.open(QIODevice::WriteOnly|QIODevice::Text))
{
QApplication::setOverrideCursor(Qt::WaitCursor);
// Count the total number of all records in all tables for the progress dialog
size_t numRecordsTotal = 0;
objectMap objMap = schemata.at("main"); // We only always export the main database, not the attached databases
std::vector<sqlb::TablePtr> tables;
for(const auto& it : objMap.tables)
{
QString tableName = QString::fromStdString(it.first);
// Never export the sqlite internal tables. Also only export any tables which are selected for export.
if(!it.second->isView()
&& !tableName.startsWith("sqlite_", Qt::CaseInsensitive)
&& contains(tablesToDump, it.first))
{
// Get the number of records in this table and remember to export it
tables.push_back(it.second);
numRecordsTotal += querySingleValueFromDb("SELECT COUNT(*) FROM " + sqlb::ObjectIdentifier("main", it.first).toString()).toUInt();
}
}
QProgressDialog progress(tr("Exporting database to SQL file..."),
tr("Cancel"), 0, static_cast<int>(numRecordsTotal));
// Disable context help button on Windows
progress.setWindowFlags(progress.windowFlags()
& ~Qt::WindowContextHelpButtonHint);
progress.setWindowModality(Qt::ApplicationModal);
progress.show();
qApp->processEvents();
// Open text stream to the file
QTextStream stream(&file);
// Put the SQL commands in a transaction block
stream << "BEGIN TRANSACTION;\n";
// First export the schema of all selected tables. We need to export the schema of all tables before we export the first INSERT statement to
// make sure foreign keys are working properly.
if(exportSchema)
{
for(const auto& it : tables)
{
// Write the SQL string used to create this table to the output file
if(!keepOldSchema)
stream << QString("DROP TABLE IF EXISTS %1;\n").arg(QString::fromStdString(sqlb::escapeIdentifier(it->name())));
if(it->fullyParsed() && !keepOriginal)
stream << QString::fromStdString(it->sql("main", keepOldSchema)) << "\n";
else {
QString statement = QString::fromStdString(it->originalSql());
if(keepOldSchema) {
if (statement.startsWith("CREATE VIRTUAL TABLE", Qt::CaseInsensitive)) {
const int createTableLength = 20;
statement.replace(0, createTableLength, "CREATE VIRTUAL TABLE IF NOT EXISTS");
} else {
// The statement is guaranteed by SQLite to start with "CREATE TABLE"
const int createTableLength = 12;
statement.replace(0, createTableLength, "CREATE TABLE IF NOT EXISTS");
}
}
stream << statement << ";\n";
}
}
}
// Now export the data as well
if(exportData)
{
for(const auto& it : tables)
{
// get columns
sqlb::StringVector cols = it->fieldNames();
// Generated columns cannot be inserted into, so leave them out of both the SELECT and the
// INSERT statements, like the sqlite3 shell's .dump does
std::string sQuery = "SELECT * FROM " + sqlb::escapeIdentifier(it->name());
if(std::any_of(it->fields.begin(), it->fields.end(), [](const sqlb::Field& f) { return f.generated() != nullptr; }))
{
cols.clear();
for(const sqlb::Field& f : it->fields)
{
You can’t perform that action at this time.
