diff options
author | Cara Salter <cara@devcara.com> | 2023-04-06 15:45:39 -0400 |
---|---|---|
committer | Cara Salter <cara@devcara.com> | 2023-04-06 17:11:52 -0400 |
commit | 7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625 (patch) | |
tree | 0dd37a701fb242fa953c23f2b0a94252fa60762b /src/bot.cpp | |
parent | b66bf922cc2d8eb3a623d1f776ab6a144832f587 (diff) | |
download | 142bot-7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625.tar.gz 142bot-7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625.zip |
pg: Add postgres support
Supports migrations
Change-Id: Ifca8358d4f57a4b417f1d972e400e98767e01bb5
Diffstat (limited to 'src/bot.cpp')
-rw-r--r-- | src/bot.cpp | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/src/bot.cpp b/src/bot.cpp index 03bea02..ad818a0 100644 --- a/src/bot.cpp +++ b/src/bot.cpp @@ -1,21 +1,72 @@ #include <dpp/snowflake.h> #include <stdlib.h> +#include <string> #include <142bot/bot.hpp> #include <dpp/dpp.h> #include <142bot/modules.hpp> #include <142bot/util.hpp> #include <fmt/format.h> #include <fmt/format-inl.h> +#include <pqxx/pqxx> +#include <142bot/db.hpp> +#include <filesystem> + +namespace fs = std::filesystem; Bot::Bot(bool devel, dpp::cluster* cluster) { dev = devel; this->core = cluster; + + std::ifstream f("config.json"); + json cfg = json::parse(f); + std::string token = cfg.value("token", "bad-token"); + + this->conn = db::connect(cfg["postgres"]["host"], cfg["postgres"]["user"], cfg["postgres"]["pass"], cfg["postgres"]["database"], cfg["postgres"]["port"]); + + run_database_migrations(); + this->loader = new ModuleLoader(this); this->loader->load_all(); // this->loader->LoadAll(); } +/** + * Attempts to run migrations stored in a directory local to CWD. + * + * Returns false on any error +*/ +bool Bot::run_database_migrations() { + + // Start a transaction + this->core->log(dpp::ll_info, "Attempting database migrations..."); + pqxx::work w(this->conn); + // Get all files in ./migrations + std::string path = "./migrations"; + for (const auto &entry : fs::directory_iterator(path)) { + std::ifstream f(entry.path()); + std::ostringstream sstr; + sstr << f.rdbuf(); + std::string stmt = sstr.str(); + + this->core->log(dpp::ll_debug, fmt::format("Attempting to migrate database with statement {}", stmt)); + + try { + w.exec0(stmt); + } catch (std::exception &e) { + w.abort(); + this->core->log(dpp::ll_error, e.what()); + return false; + } + + } + + w.commit(); + this->core->log(dpp::ll_info, "Done."); + + return true; +} + bool Bot::isDevMode() { return dev; } |