aboutsummaryrefslogtreecommitdiff
path: root/src/db.cpp
diff options
context:
space:
mode:
authorCara Salter <cara@devcara.com>2023-04-06 17:14:22 -0400
committerCara Salter <cara@devcara.com>2023-04-06 17:14:22 -0400
commit555810bedc0cf9d9d954f56b5a2c8c92522ad27f (patch)
tree0dd37a701fb242fa953c23f2b0a94252fa60762b /src/db.cpp
parent3a3a1e5345ae8e133fa7800d9fcba2dbb779b8b9 (diff)
parent7629de5b888bd3d1cdb94dce3ba51cb1e1c2e625 (diff)
download142bot-555810bedc0cf9d9d954f56b5a2c8c92522ad27f.tar.gz
142bot-555810bedc0cf9d9d954f56b5a2c8c92522ad27f.zip
Merge branch 'database'
Change-Id: I5f6fb3b64db0585955defdec0fe1ee9555ba89ec
Diffstat (limited to 'src/db.cpp')
-rw-r--r--src/db.cpp76
1 files changed, 76 insertions, 0 deletions
diff --git a/src/db.cpp b/src/db.cpp
new file mode 100644
index 0000000..92e3d1d
--- /dev/null
+++ b/src/db.cpp
@@ -0,0 +1,76 @@
+/*
+ * =====================================================================================
+ *
+ * Filename: db.cpp
+ *
+ * Description: Connection to a postgres database
+ *
+ * Version: 1.0
+ * Created: 04/06/2023 11:40:39 AM
+ * Revision: none
+ * Compiler: gcc
+ *
+ * Author: Cara Salter (muirrum), cara@devcara.com
+ * Organization: Worcester Polytechnic Institute
+ *
+ * =====================================================================================
+ */
+#include <fmt/core.h>
+#include <mutex>
+#include <stdlib.h>
+#include <stdio.h>
+#include <iostream>
+#include <142bot/db.hpp>
+#include <pqxx/pqxx>
+#include <fmt/format.h>
+#include <cstdarg>
+
+using namespace std;
+
+namespace db {
+ std::mutex db_mutex;
+ std::string _error;
+
+ /**
+ * Connects to a postgres database, returns false if error
+ **/
+ pqxx::connection connect(const std::string &host, const std::string &user, const std::string &pass, const std::string &db, int port) {
+ std::lock_guard<std::mutex> db_lock(db_mutex);
+
+ std::string cn_s = "postgresql://";
+
+ if (!user.empty()) {
+ cn_s = cn_s + user;
+ }
+ if (!pass.empty() && !user.empty()) {
+ cn_s = cn_s + ":" + pass;
+ }
+
+ if ((!user.empty() || !pass.empty())) {
+ cn_s = cn_s + "@";
+ }
+
+ if (!host.empty()) {
+ cn_s = cn_s + "localhost";
+ }
+ if (port != 0 && !host.empty()) {
+ cn_s = cn_s + ":" + std::to_string(port);
+ }
+ if (!db.empty()) {
+ cn_s = cn_s + "/" + db;
+ }
+
+ try {
+ pqxx::connection c{cn_s};
+ return c;
+ } catch (std::exception const &e) {
+ _error = e.what();
+ throw e;
+ }
+ }
+
+ const std::string& error() {
+ return _error;
+ }
+
+}