just some thoughts

This commit is contained in:
Blue 2023-12-11 20:29:55 -03:00
parent 03d7614673
commit f0d205dee7
Signed by: blue
GPG key ID: 9B203B252A63EE38
15 changed files with 172 additions and 34 deletions

View file

@ -10,6 +10,6 @@ set(SOURCES
find_package(MariaDB REQUIRED)
target_sources(pica PRIVATE ${SOURCES})
target_sources(${PROJECT_NAME} PRIVATE ${SOURCES})
target_link_libraries(pica PRIVATE MariaDB::client)
target_link_libraries(${PROJECT_NAME} PRIVATE MariaDB::client)

View file

@ -116,6 +116,14 @@ void MySQL::executeFile(const std::filesystem::path& relativePath) {
std::ifstream inputFile(path);
std::string query;
while (std::getline(inputFile, query, ';')) {
std::optional<std::string> comment = getComment(query);
while (comment) {
std::cout << '\t' << comment.value() << std::endl;
comment = getComment(query);
}
if (query.empty())
continue;
int result = mysql_query(con, query.c_str());
if (result != 0) {
int errcode = mysql_errno(con);
@ -162,15 +170,49 @@ void MySQL::migrate(uint8_t targetVersion) {
uint8_t currentVersion = getVersion();
while (currentVersion < targetVersion) {
if (currentVersion == 255)
throw std::runtime_error("Maximum possible database version reached");
uint8_t nextVersion = currentVersion + 1;
std::string fileName = "migrations/m" + std::to_string(currentVersion) + ".sql";
std::cout << "Performing migration "
<< std::to_string(currentVersion)
<< " -> "
<< std::to_string(++currentVersion)
<< std::to_string(nextVersion)
<< std::endl;
executeFile(fileName);
setVersion(currentVersion);
setVersion(nextVersion);
currentVersion = nextVersion;
}
std::cout << "Database is now on actual version " << std::to_string(targetVersion) << std::endl;
}
std::optional<std::string> MySQL::getComment(std::string& string) {
ltrim(string);
if (string.length() < 2)
return std::nullopt;
if (string[0] == '-') {
if (string[1] == '-') {
string.erase(0, 2);
std::string::size_type eol = string.find('\n');
return extract(string, 0, eol);
}
} else if (string[0] == '/') {
if (string[1] == '*') {
string.erase(0, 2);
std::string::size_type end = 0;
do {
end = string.find(end, '*');
} while (end != std::string::npos && end < string.size() - 1 && string[end + 1] == '/');
if (end < string.size() - 1)
end = std::string::npos;
return extract(string, 0, end);
}
}
return std::nullopt;
}

View file

@ -5,6 +5,7 @@
#include <stdexcept>
#include <filesystem>
#include <optional>
#include <mysql.h>
@ -28,6 +29,7 @@ public:
private:
void executeFile(const std::filesystem::path& relativePath);
static std::optional<std::string> getComment(std::string& string);
protected:
MYSQL connection;