2022-07-10 19:40:26 +00:00
# include "MigrationRunner.h"
# include "GeneralUtils.h"
# include <fstream>
# include <algorithm>
# include <thread>
void MigrationRunner : : RunMigrations ( ) {
auto stmt = Database : : CreatePreppedStmt ( " CREATE TABLE IF NOT EXISTS migration_history (name TEXT NOT NULL, date TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP()); " ) ;
stmt - > executeQuery ( ) ;
delete stmt ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
sql : : SQLString finalSQL = " " ;
Migration checkMigration { } ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
for ( const auto & entry : GeneralUtils : : GetFileNamesFromFolder ( " ./migrations/ " ) ) {
auto migration = LoadMigration ( entry ) ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
if ( migration . data . empty ( ) ) {
continue ;
}
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
checkMigration = migration ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
stmt = Database : : CreatePreppedStmt ( " SELECT name FROM migration_history WHERE name = ?; " ) ;
stmt - > setString ( 1 , migration . name ) ;
auto res = stmt - > executeQuery ( ) ;
bool doExit = res - > next ( ) ;
delete res ;
delete stmt ;
if ( doExit ) continue ;
2022-07-28 13:39:57 +00:00
2022-07-27 06:52:53 +00:00
Game : : logger - > Log ( " MigrationRunner " , " Running migration: %s " , migration . name . c_str ( ) ) ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
finalSQL . append ( migration . data ) ;
finalSQL . append ( ' \n ' ) ;
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
stmt = Database : : CreatePreppedStmt ( " INSERT INTO migration_history (name) VALUES (?); " ) ;
stmt - > setString ( 1 , entry ) ;
stmt - > execute ( ) ;
delete stmt ;
}
2022-07-28 13:39:57 +00:00
2022-07-10 19:40:26 +00:00
if ( ! finalSQL . empty ( ) ) {
try {
auto simpleStatement = Database : : CreateStmt ( ) ;
simpleStatement - > execute ( finalSQL ) ;
delete simpleStatement ;
} catch ( sql : : SQLException e ) {
2022-07-27 06:52:53 +00:00
Game : : logger - > Log ( " MigrationRunner " , " Encountered error running migration: %s " , e . what ( ) ) ;
2022-07-10 19:40:26 +00:00
}
}
}
Migration MigrationRunner : : LoadMigration ( std : : string path ) {
Migration migration { } ;
std : : ifstream file ( " ./migrations/ " + path ) ;
if ( file . is_open ( ) ) {
std : : hash < std : : string > hash ;
2022-07-25 02:26:51 +00:00
2022-07-10 19:40:26 +00:00
std : : string line ;
std : : string total = " " ;
while ( std : : getline ( file , line ) ) {
total + = line ;
}
file . close ( ) ;
migration . name = path ;
migration . data = total ;
}
2022-07-25 02:26:51 +00:00
2022-07-10 19:40:26 +00:00
return migration ;
}