Track SQL migrations
This commit is contained in:
@@ -6,6 +6,7 @@
|
||||
#include <cctype>
|
||||
#include <filesystem>
|
||||
#include <fstream>
|
||||
#include <optional>
|
||||
#include <sstream>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
@@ -63,6 +64,13 @@ std::vector<std::string> splitStatements(const std::string &sql)
|
||||
}
|
||||
return statements;
|
||||
}
|
||||
|
||||
bool hasMigration(const drogon::orm::DbClientPtr &db, const std::string &name)
|
||||
{
|
||||
const auto result = db->execSqlSync(
|
||||
"SELECT name FROM schema_migrations WHERE name = ? LIMIT 1", name);
|
||||
return !result.empty();
|
||||
}
|
||||
} // namespace
|
||||
|
||||
void MigrationRunner::run(const std::string &directory)
|
||||
@@ -86,8 +94,20 @@ void MigrationRunner::run(const std::string &directory)
|
||||
std::sort(files.begin(), files.end());
|
||||
|
||||
auto db = drogon::app().getDbClient();
|
||||
db->execSqlSync(
|
||||
"CREATE TABLE IF NOT EXISTS schema_migrations ("
|
||||
"name VARCHAR(255) NOT NULL PRIMARY KEY, "
|
||||
"applied_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP"
|
||||
")");
|
||||
|
||||
for (const auto &file : files)
|
||||
{
|
||||
const auto name = file.filename().string();
|
||||
if (hasMigration(db, name))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
std::ifstream input(file);
|
||||
std::stringstream buffer;
|
||||
buffer << input.rdbuf();
|
||||
@@ -96,8 +116,8 @@ void MigrationRunner::run(const std::string &directory)
|
||||
{
|
||||
db->execSqlSync(statement);
|
||||
}
|
||||
LOG_INFO << "Applied migration " << file.string();
|
||||
db->execSqlSync("INSERT INTO schema_migrations (name) VALUES (?)", name);
|
||||
LOG_INFO << "Applied migration " << name;
|
||||
}
|
||||
}
|
||||
} // namespace visione::repositories
|
||||
|
||||
|
||||
Reference in New Issue
Block a user