common: Use DBMigrator to init and update database

Cette révision appartient à :
Albert S. 2022-02-27 23:39:55 +01:00
Parent 3d8b086f53
révision d43c35819d

Voir le fichier

@ -9,13 +9,16 @@
#include <QDebug> #include <QDebug>
#include "looqsgeneralexception.h" #include "looqsgeneralexception.h"
#include "common.h" #include "common.h"
#include "dbmigrator.h"
#include "databasefactory.h"
#include "logger.h"
#define SETTINGS_KEY_DBPATH "dbpath" #define SETTINGS_KEY_DBPATH "dbpath"
#define SETTINGS_KEY_FIRSTRUN "firstrun" #define SETTINGS_KEY_FIRSTRUN "firstrun"
inline void initResources() inline void initResources()
{ {
Q_INIT_RESOURCE(create); Q_INIT_RESOURCE(migrations);
} }
bool Common::initSqliteDatabase(QString path) bool Common::initSqliteDatabase(QString path)
@ -28,28 +31,9 @@ bool Common::initSqliteDatabase(QString path)
return false; return false;
} }
initResources(); initResources();
QFile file(":./create.sql"); DBMigrator migrator{db};
if(!file.open(QIODevice::ReadOnly)) migrator.performMigrations();
{
qDebug() << "Failed to load SQL creation script from embedded resource";
return false;
}
QTextStream stream(&file);
db.transaction();
while(!stream.atEnd())
{
QString sql = stream.readLine();
QSqlQuery sqlQuery;
if(!sqlQuery.exec(sql))
{
qDebug() << "Failed to execute sql statement while initializing database: " << sqlQuery.lastError();
db.rollback();
return false;
}
}
db.commit();
db.close(); db.close();
file.close();
return true; return true;
} }
@ -84,6 +68,21 @@ void Common::ensureConfigured()
{ {
throw LooqsGeneralException("Database " + dbpath + " was not found"); throw LooqsGeneralException("Database " + dbpath + " was not found");
} }
DatabaseFactory factory{dbpath};
auto db = factory.forCurrentThread();
DBMigrator migrator{db};
if(migrator.migrationNeeded())
{
QFile out;
out.open(stderr, QIODevice::WriteOnly);
Logger migrationLogger{&out};
migrationLogger << "Database is being upgraded, please be patient..." << Qt::endl;
QObject::connect(&migrator, &DBMigrator::migrationDone,
[&migrationLogger](uint32_t migration)
{ migrationLogger << "Progress: Successfully migrated to: " << migration << Qt::endl; });
migrator.performMigrations();
migrationLogger << "Database upgraded successfully" << Qt::endl;
}
} }
} }