implemented db migration system

This commit is contained in:
Kamil 2020-12-18 18:12:57 +01:00 committed by Gent S
parent 140227406c
commit 002bfffb62

View File

@ -13,6 +13,10 @@
#include <string> #include <string>
#include <sqlite3.h> #include <sqlite3.h>
#include <iostream>
#include <fstream>
#include <sstream>
#if defined(__MINGW32__) && !defined(_GLIBCXX_HAS_GTHREADS) #if defined(__MINGW32__) && !defined(_GLIBCXX_HAS_GTHREADS)
#include "mingw/mingw.mutex.h" #include "mingw/mingw.mutex.h"
#else #else
@ -127,30 +131,35 @@ void Database::checkMetaTable() {
int dbVersion = sqlite3_column_int(stmt, 0); int dbVersion = sqlite3_column_int(stmt, 0);
sqlite3_finalize(stmt); sqlite3_finalize(stmt);
if (dbVersion != DATABASE_VERSION) { if (dbVersion > DATABASE_VERSION) {
// migrations std::cout << "[FATAL] Server Build is incompatible with DB Version" << std::endl;
if (dbVersion == 1) { exit(1);
// Version 1 - > 2 }
sqlite3_exec(db, "BEGIN TRANSACTION;", NULL, NULL, NULL);
int rc = sqlite3_exec(db, "ALTER TABLE Accounts ADD BanReason TEXT", NULL, NULL, NULL); while (dbVersion != DATABASE_VERSION){
if (rc != SQLITE_OK) { // db migrations
std::cout << "[FATAL] Failed to apply Database migration" << std::endl; std::cout << "[INFO] Migrating Database to Version " << dbVersion + 1 << std::endl;
exit(1);
}
rc = sqlite3_exec(db, "UPDATE Meta SET Value = 2 WHERE Key = 'DatabaseVersion';", NULL, NULL, NULL);
if (rc != SQLITE_OK) {
std::cout << "[FATAL] Failed to apply Database migration" << std::endl;
exit(1);
}
sqlite3_exec(db, "COMMIT;", NULL, NULL, NULL); std::string path = "sql/migrations/" + std::to_string(dbVersion) + ".sql";
} std::ifstream file(path);
else { if (!file.is_open()) {
std::cout << "[FATAL] Invalid DB Version" << std::endl; std::cout << "[FATAL] Failed to migrate database: Couldn't open migration file" << std::endl;
exit(1); exit(1);
} }
}
std::ostringstream stream;
stream << file.rdbuf();
std::string sql = stream.str();
int rc = sqlite3_exec(db, sql.c_str(), NULL, NULL, NULL);
if (rc != SQLITE_OK) {
std::cout << "[FATAL] Failed to migrate database" << std::endl;
exit(1);
}
dbVersion++;
std::cout << "[INFO] Successfull Database Migration to Version " << dbVersion << std::endl;
}
} }
void Database::createMetaTable() { void Database::createMetaTable() {