From 7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625 Mon Sep 17 00:00:00 2001 From: Cara Salter Date: Thu, 6 Apr 2023 15:45:39 -0400 Subject: pg: Add postgres support Supports migrations Change-Id: Ifca8358d4f57a4b417f1d972e400e98767e01bb5 --- src/bot.cpp | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) (limited to 'src/bot.cpp') 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 #include +#include #include <142bot/bot.hpp> #include #include <142bot/modules.hpp> #include <142bot/util.hpp> #include #include +#include +#include <142bot/db.hpp> +#include + +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; } -- cgit v1.2.3