Debian Codegraph @

src/librssguard/database/sqlitedriver.cpp

raw symbols SCIP
1 // For license of this file, see <project-root-folder>/LICENSE.md.
2
3 #include "database/sqlitedriver.h"
4
5 #include "exceptions/applicationexception.h"
6 #include "miscellaneous/application.h"
7
8 #include <QDir>
9 #include <QSqlDriver>
10 #include <QSqlError>
11 #include <QSqlQuery>
12
13 SqliteDriver::SqliteDriver(bool in_memory, QObject* parent)
14 : DatabaseDriver(parent), m_inMemoryDatabase(in_memory),
15 m_databaseFilePath(qApp->userDataFolder() + QDir::separator() + QSL(APP_DB_SQLITE_PATH)),
16 m_fileBasedDatabaseInitialized(false), m_inMemoryDatabaseInitialized(false) {}
17
18 QString SqliteDriver::location() const {
19 return QDir::toNativeSeparators(m_databaseFilePath);
20 }
21
22 DatabaseDriver::DriverType SqliteDriver::driverType() const {
23 return DriverType::SQLite;
24 }
25
26 bool SqliteDriver::vacuumDatabase() {
27 QSqlDatabase database;
28
29 saveDatabase();
30 database = connection(objectName(), DatabaseDriver::DesiredStorageType::StrictlyFileBased);
31
32 QSqlQuery query_vacuum(database);
33
34 return query_vacuum.exec(QSL("VACUUM"));
35 }
36
37 QString SqliteDriver::ddlFilePrefix() const {
38 return QSL("sqlite");
39 }
40
41 int SqliteDriver::loadOrSaveDbInMemoryDb(sqlite3* in_memory_db, const char* db_filename, bool save) {
42 int rc; /* Function return code */
43 sqlite3* p_file; /* Database connection opened on zFilename */
44 sqlite3_backup* p_backup; /* Backup object used to copy data */
45 sqlite3* p_to; /* Database to copy to (pFile or pInMemory) */
46 sqlite3* p_from; /* Database to copy from (pFile or pInMemory) */
47
48 /* Open the database file identified by zFilename. Exit early if this fails
49 ** for any reason. */
50 rc = sqlite3_open(db_filename, &p_file);
51
52 if (rc == SQLITE_OK) {
53 /* If this is a 'load' operation (isSave==0), then data is copied
54 ** from the database file just opened to database pInMemory.
55 ** Otherwise, if this is a 'save' operation (isSave==1), then data
56 ** is copied from pInMemory to pFile. Set the variables pFrom and
57 ** pTo accordingly. */
58 p_from = (save ? in_memory_db : p_file);
59 p_to = (save ? p_file : in_memory_db);
60
61 /* Set up the backup procedure to copy from the "main" database of
62 ** connection pFile to the main database of connection pInMemory.
63 ** If something goes wrong, pBackup will be set to NULL and an error
64 ** code and message left in connection pTo.
65 **
66 ** If the backup object is successfully created, call backup_step()
67 ** to copy data from pFile to pInMemory. Then call backup_finish()
68 ** to release resources associated with the pBackup object. If an
69 ** error occurred, then an error code and message will be left in
70 ** connection pTo. If no error occurred, then the error code belonging
71 ** to pTo is set to SQLITE_OK.
72 */
73 p_backup = sqlite3_backup_init(p_to, "main", p_from, "main");
74 if (p_backup) {
75 (void)sqlite3_backup_step(p_backup, -1);
76 (void)sqlite3_backup_finish(p_backup);
77 }
78 rc = sqlite3_errcode(p_to);
79 }
80
81 sqlite3_db_cacheflush(p_file);
82
83 /* Close the database connection opened on database file zFilename
84 ** and return the result of this function. */
85 (void)sqlite3_close(p_file);
86 return rc;
87 }
88
89 bool SqliteDriver::saveDatabase() {
90 if (!m_inMemoryDatabase) {
91 return true;
92 }
93 else {
94 qDebugNN << LOGSEC_DB << "Saving in-memory working database back to persistent file-based storage.";
95
96 QSqlDatabase database = connection(QSL("SaveFromMemory"), DatabaseDriver::DesiredStorageType::StrictlyInMemory);
97 const QDir db_path(m_databaseFilePath);
98 QFile db_file(db_path.absoluteFilePath(QSL(APP_DB_SQLITE_FILE)));
99 QVariant v = database.driver()->handle();
100
101 if (v.isValid() && (qstrcmp(v.typeName(), "sqlite3*") == 0)) {
102 // v.data() returns a pointer to the handle
103 sqlite3* handle = *static_cast<sqlite3**>(v.data());
104
105 if (handle != nullptr) {
106 loadOrSaveDbInMemoryDb(handle, QDir::toNativeSeparators(db_file.fileName()).toStdString().c_str(), 1);
107 }
108 else {
109 throw ApplicationException(tr("cannot get native 'sqlite3' DB handle"));
110 }
111 }
112
113 return true;
114 }
115 }
116
117 QSqlDatabase SqliteDriver::connection(const QString& connection_name, DesiredStorageType desired_type) {
118 bool want_in_memory = desired_type == DatabaseDriver::DesiredStorageType::StrictlyInMemory ||
119 (desired_type == DatabaseDriver::DesiredStorageType::FromSettings && m_inMemoryDatabase);
120
121 if ((want_in_memory && !m_inMemoryDatabaseInitialized) || (!want_in_memory && !m_fileBasedDatabaseInitialized)) {
122 return initializeDatabase(connection_name, want_in_memory);
123 }
124 else {
125 // No need to initialize.
126 QSqlDatabase database;
127
128 if (QSqlDatabase::contains(connection_name)) {
129 qDebugNN << LOGSEC_DB << "SQLite connection" << QUOTE_W_SPACE(connection_name) << "is already active.";
130
131 // This database connection was added previously, no need to
132 // setup its properties.
133 database = QSqlDatabase::database(connection_name);
134 }
135 else {
136 database = QSqlDatabase::addDatabase(QSL(APP_DB_SQLITE_DRIVER), connection_name);
137
138 if (want_in_memory) {
139 database.setConnectOptions(QSL("QSQLITE_OPEN_URI;QSQLITE_ENABLE_SHARED_CACHE;QSQLITE_ENABLE_REGEXP"));
140 database.setDatabaseName(QSL("file::memory:"));
141 }
142 else {
143 const QDir db_path(m_databaseFilePath);
144 QFile db_file(db_path.absoluteFilePath(QSL(APP_DB_SQLITE_FILE)));
145
146 database.setConnectOptions(QSL("QSQLITE_ENABLE_SHARED_CACHE;QSQLITE_ENABLE_REGEXP"));
147 database.setDatabaseName(db_file.fileName());
148 }
149 }
150
151 if (!database.isOpen() && !database.open()) {
152 qFatal("SQLite database was NOT opened. Delivered error message: '%s'.", qPrintable(database.lastError().text()));
153 }
154 else {
155 qDebugNN << LOGSEC_DB << "SQLite database connection" << QUOTE_W_SPACE(connection_name) << "to file"
156 << QUOTE_W_SPACE(database.databaseName()) << "seems to be established.";
157 }
158
159 QSqlQuery query_db(database);
160
161 query_db.setForwardOnly(true);
162 setPragmas(query_db);
163
164 return database;
165 }
166 }
167
168 bool SqliteDriver::initiateRestoration(const QString& database_package_file) {
169 return IOFactory::copyFile(database_package_file,
170 m_databaseFilePath + QDir::separator() + BACKUP_NAME_DATABASE + BACKUP_SUFFIX_DATABASE);
171 }
172
173 bool SqliteDriver::finishRestoration() {
174 const QString backup_database_file =
175 m_databaseFilePath + QDir::separator() + BACKUP_NAME_DATABASE + BACKUP_SUFFIX_DATABASE;
176
177 if (QFile::exists(backup_database_file)) {
178 qDebugNN << LOGSEC_DB << "Backup database file '" << QDir::toNativeSeparators(backup_database_file)
179 << "' was detected. Restoring it.";
180
181 if (IOFactory::copyFile(backup_database_file, m_databaseFilePath + QDir::separator() + APP_DB_SQLITE_FILE)) {
182 QFile::remove(backup_database_file);
183 qDebugNN << LOGSEC_DB << "Database file was restored successully.";
184 }
185 else {
186 qCriticalNN << LOGSEC_DB << "Database file was NOT restored due to error when copying the file.";
187 return false;
188 }
189 }
190
191 return true;
192 }
193
194 QSqlDatabase SqliteDriver::initializeDatabase(const QString& connection_name, bool in_memory) {
195 finishRestoration();
196
197 QString db_file_name;
198
199 if (!in_memory) {
200 // Prepare file paths.
201 const QDir db_path(m_databaseFilePath);
202 QFile db_file(db_path.absoluteFilePath(QSL(APP_DB_SQLITE_FILE)));
203
204 // Check if database directory exists.
205 if (!db_path.exists()) {
206 if (!db_path.mkpath(db_path.absolutePath())) {
207 // Failure when create database file path.
208 qFatal("Directory '%s' for SQLite database file '%s' was NOT created."
209 "This is HUGE problem.",
210 qPrintable(db_path.absolutePath()),
211 qPrintable(db_file.symLinkTarget()));
212 }
213 }
214
215 db_file_name = db_file.fileName();
216 }
217 else {
218 db_file_name = QSL("file::memory:");
219 }
220
221 // Folders are created. Create new QSQLDatabase object.
222 QSqlDatabase database;
223
224 database = QSqlDatabase::addDatabase(QSL(APP_DB_SQLITE_DRIVER), connection_name);
225
226 if (in_memory) {
227 database.setConnectOptions(QSL("QSQLITE_OPEN_URI;QSQLITE_ENABLE_SHARED_CACHE;QSQLITE_ENABLE_REGEXP"));
228 }
229 else {
230 database.setConnectOptions(QSL("QSQLITE_ENABLE_SHARED_CACHE;QSQLITE_ENABLE_REGEXP"));
231 }
232
233 database.setDatabaseName(db_file_name);
234
235 if (!database.open()) {
236 qFatal("SQLite database was NOT opened. Delivered error message: '%s'", qPrintable(database.lastError().text()));
237 }
238 else {
239 QSqlQuery query_db(database);
240
241 query_db.setForwardOnly(true);
242 setPragmas(query_db);
243
244 // Sample query which checks for existence of tables.
245 if (!query_db.exec(QSL("SELECT inf_value FROM Information WHERE inf_key = 'schema_version'"))) {
246 qWarningNN << LOGSEC_DB << "SQLite database is not initialized. Initializing now.";
247
248 try {
249 const QStringList statements = prepareScript(APP_SQL_PATH, QSL(APP_DB_SQLITE_INIT));
250
251 for (const QString& statement : statements) {
252 query_db.exec(statement);
253
254 if (query_db.lastError().isValid()) {
255 throw ApplicationException(query_db.lastError().text());
256 }
257 }
258
259 setSchemaVersion(query_db, QSL(APP_DB_SCHEMA_VERSION).toInt(), true);
260 }
261 catch (const ApplicationException& ex) {
262 qFatal("Error when running SQL scripts: %s.", qPrintable(ex.message()));
263 }
264
265 qDebugNN << LOGSEC_DB << "SQLite database backend should be ready now.";
266 }
267 else if (!in_memory) {
268 query_db.next();
269 const int installed_db_schema = query_db.value(0).toString().toInt();
270
271 if (installed_db_schema < QSL(APP_DB_SCHEMA_VERSION).toInt()) {
272 // Now, it would be good to create backup of SQLite DB file.
273 if (IOFactory::copyFile(databaseFilePath(), databaseFilePath() + QSL("-v%1.bak").arg(installed_db_schema))) {
274 qDebugNN << LOGSEC_DB << "Creating backup of SQLite DB file.";
275 }
276 else {
277 qFatal("Creation of backup SQLite DB file failed.");
278 }
279
280 try {
281 updateDatabaseSchema(query_db, installed_db_schema);
282 qDebugNN << LOGSEC_DB << "Database schema was updated from" << QUOTE_W_SPACE(installed_db_schema) << "to"
283 << QUOTE_W_SPACE(APP_DB_SCHEMA_VERSION) << "successully.";
284 }
285 catch (const ApplicationException& ex) {
286 qFatal("Error when updating DB schema from %d: %s.", installed_db_schema, qPrintable(ex.message()));
287 }
288 }
289
290 qDebugNN << LOGSEC_DB << "File-based SQLite database connection '" << connection_name << "' to file '"
291 << QDir::toNativeSeparators(database.databaseName()) << "' seems to be established.";
292 qDebugNN << LOGSEC_DB << "File-based SQLite database has version '" << installed_db_schema << "'.";
293 }
294 else {
295 query_db.next();
296 qDebugNN << LOGSEC_DB << "SQLite database has version" << QUOTE_W_SPACE_DOT(query_db.value(0).toString());
297 }
298 }
299
300 if (in_memory) {
301 // Loading messages from file-based database.
302 QSqlDatabase file_database = connection(objectName(), DatabaseDriver::DesiredStorageType::StrictlyFileBased);
303 QSqlQuery copy_contents(database);
304
305 // Attach database.
306 copy_contents.exec(QSL("ATTACH DATABASE '%1' AS 'storage';").arg(file_database.databaseName()));
307
308 // Copy all stuff.
309 QStringList tables;
310
311 if (copy_contents.exec(QSL("SELECT name FROM storage.sqlite_master WHERE type = 'table';"))) {
312 while (copy_contents.next()) {
313 tables.append(copy_contents.value(0).toString());
314 }
315 }
316 else {
317 qFatal("Cannot obtain list of table names from file-based SQLite database.");
318 }
319
320 for (const QString& table : tables) {
321 copy_contents.exec(QSL("INSERT INTO main.%1 SELECT * FROM storage.%1;").arg(table));
322 }
323
324 qDebugNN << LOGSEC_DB << "Copying data from file-based database into working in-memory database.";
325
326 // Detach database and finish.
327 copy_contents.exec(QSL("DETACH 'storage'"));
328
329 file_database.close();
330 QSqlDatabase::removeDatabase(file_database.connectionName());
331 }
332
333 // Everything is initialized now.
334 if (in_memory) {
335 m_inMemoryDatabaseInitialized = true;
336 }
337 else {
338 m_fileBasedDatabaseInitialized = true;
339 }
340
341 return database;
342 }
343
344 QString SqliteDriver::databaseFilePath() const {
345 return m_databaseFilePath + QDir::separator() + APP_DB_SQLITE_FILE;
346 }
347
348 void SqliteDriver::setPragmas(QSqlQuery& query) {
349 query.exec(QSL("PRAGMA encoding = \"UTF-8\""));
350 query.exec(QSL("PRAGMA page_size = 32768"));
351 query.exec(QSL("PRAGMA cache_size = 32768"));
352 query.exec(QSL("PRAGMA mmap_size = 100000000"));
353 query.exec(QSL("PRAGMA count_changes = OFF"));
354 query.exec(QSL("PRAGMA temp_store = MEMORY"));
355 query.exec(QSL("PRAGMA synchronous = OFF"));
356 query.exec(QSL("PRAGMA journal_mode = MEMORY"));
357 }
358
359 qint64 SqliteDriver::databaseDataSize() {
360 QSqlDatabase database = connection(metaObject()->className(), DatabaseDriver::DesiredStorageType::FromSettings);
361 qint64 result = 1;
362 QSqlQuery query(database);
363
364 if (query.exec(QSL("PRAGMA page_count;"))) {
365 query.next();
366 result *= query.value(0).value<qint64>();
367 }
368 else {
369 return 0;
370 }
371
372 if (query.exec(QSL("PRAGMA page_size;"))) {
373 query.next();
374 result *= query.value(0).value<qint64>();
375 }
376 else {
377 return 0;
378 }
379
380 return result;
381 }
382
383 QString SqliteDriver::humanDriverType() const {
384 return tr("SQLite (embedded database)");
385 }
386
387 QString SqliteDriver::qtDriverCode() const {
388 return QSL(APP_DB_SQLITE_DRIVER);
389 }
390
391 void SqliteDriver::backupDatabase(const QString& backup_folder, const QString& backup_name) {
392 qDebugNN << LOGSEC_DB << "Creating SQLite DB backup.";
393
394 saveDatabase();
395
396 if (!IOFactory::copyFile(databaseFilePath(),
397 backup_folder + QDir::separator() + backup_name + BACKUP_SUFFIX_DATABASE)) {
398 throw ApplicationException(tr("Database file not copied to output directory successfully."));
399 }
400 }
401
402 QString SqliteDriver::autoIncrementPrimaryKey() const {
403 return QSL("INTEGER PRIMARY KEY");
404 }
405
406 QString SqliteDriver::blob() const {
407 return QSL("BLOB");
408 }
409
410 QString SqliteDriver::text() const {
411 return QSL("TEXT");
412 }