diff options
author | Cara Salter <cara@devcara.com> | 2023-04-06 17:14:22 -0400 |
---|---|---|
committer | Cara Salter <cara@devcara.com> | 2023-04-06 17:14:22 -0400 |
commit | 555810bedc0cf9d9d954f56b5a2c8c92522ad27f (patch) | |
tree | 0dd37a701fb242fa953c23f2b0a94252fa60762b /src/bot.cpp | |
parent | 3a3a1e5345ae8e133fa7800d9fcba2dbb779b8b9 (diff) | |
parent | 7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625 (diff) | |
download | 142bot-555810bedc0cf9d9d954f56b5a2c8c92522ad27f.tar.gz 142bot-555810bedc0cf9d9d954f56b5a2c8c92522ad27f.zip |
Merge branch 'database'
Change-Id: I5f6fb3b64db0585955defdec0fe1ee9555ba89ec
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; } |