Track SQL migrations
This commit is contained in:
@@ -6,6 +6,7 @@
|
|||||||
#include <cctype>
|
#include <cctype>
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
|
#include <optional>
|
||||||
#include <sstream>
|
#include <sstream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <vector>
|
#include <vector>
|
||||||
@@ -63,6 +64,13 @@ std::vector<std::string> splitStatements(const std::string &sql)
|
|||||||
}
|
}
|
||||||
return statements;
|
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
|
} // namespace
|
||||||
|
|
||||||
void MigrationRunner::run(const std::string &directory)
|
void MigrationRunner::run(const std::string &directory)
|
||||||
@@ -86,8 +94,20 @@ void MigrationRunner::run(const std::string &directory)
|
|||||||
std::sort(files.begin(), files.end());
|
std::sort(files.begin(), files.end());
|
||||||
|
|
||||||
auto db = drogon::app().getDbClient();
|
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)
|
for (const auto &file : files)
|
||||||
{
|
{
|
||||||
|
const auto name = file.filename().string();
|
||||||
|
if (hasMigration(db, name))
|
||||||
|
{
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
std::ifstream input(file);
|
std::ifstream input(file);
|
||||||
std::stringstream buffer;
|
std::stringstream buffer;
|
||||||
buffer << input.rdbuf();
|
buffer << input.rdbuf();
|
||||||
@@ -96,8 +116,8 @@ void MigrationRunner::run(const std::string &directory)
|
|||||||
{
|
{
|
||||||
db->execSqlSync(statement);
|
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
|
} // namespace visione::repositories
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user