diff --git a/native/cpp/CommonCpp/DatabaseManagers/SQLiteQueryExecutor.cpp b/native/cpp/CommonCpp/DatabaseManagers/SQLiteQueryExecutor.cpp --- a/native/cpp/CommonCpp/DatabaseManagers/SQLiteQueryExecutor.cpp +++ b/native/cpp/CommonCpp/DatabaseManagers/SQLiteQueryExecutor.cpp @@ -554,29 +554,42 @@ Logger::log(version_msg.str()); for (const auto &[idx, migration] : migrations) { - if (idx <= db_version) { - continue; - } - const auto &[applyMigration, shouldBeInTransaction] = migration; - std::stringstream migration_msg; + const auto &[applyMigration, shouldBeInTransaction] = migration; if (shouldBeInTransaction) { sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, nullptr); } + auto db_version = get_database_version(db); + if (idx <= db_version) { + if (shouldBeInTransaction) { + sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr); + } + continue; + } auto rc = applyMigration(db); if (!rc) { + if (shouldBeInTransaction) { + sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr); + } migration_msg << "migration " << idx << " failed." << std::endl; Logger::log(migration_msg.str()); break; } + if (!shouldBeInTransaction) { + sqlite3_exec(db, "BEGIN TRANSACTION;", nullptr, nullptr, nullptr); + auto inner_db_version = get_database_version(db); + if (idx <= inner_db_version) { + sqlite3_exec(db, "ROLLBACK;", nullptr, nullptr, nullptr); + continue; + } + } + set_database_version(db, idx); - if (shouldBeInTransaction) { - sqlite3_exec(db, "END TRANSACTION;", nullptr, nullptr, nullptr); - } + sqlite3_exec(db, "END TRANSACTION;", nullptr, nullptr, nullptr); migration_msg << "migration " << idx << " succeeded." << std::endl; Logger::log(migration_msg.str()); }