Files
hydra/src/libhydra/db.hh

51 lines
1.1 KiB
C++
Raw Normal View History

2015-07-07 10:17:21 +02:00
#pragma once
#include <pqxx/pqxx>
2025-04-07 11:36:59 -04:00
#include <nix/util/environment-variables.hh>
#include <nix/util/util.hh>
2015-07-07 10:17:21 +02:00
struct Connection : pqxx::connection
{
Connection() : pqxx::connection(getFlags()) { };
2015-07-07 10:29:43 +02:00
std::string getFlags()
2015-07-07 10:17:21 +02:00
{
2015-07-07 10:29:43 +02:00
using namespace nix;
auto s = getEnv("HYDRA_DBI").value_or("dbi:Pg:dbname=hydra;");
std::string lower_prefix = "dbi:Pg:";
std::string upper_prefix = "DBI:Pg:";
if (hasPrefix(s, lower_prefix) || hasPrefix(s, upper_prefix)) {
return concatStringsSep(" ", tokenizeString<Strings>(std::string(s, lower_prefix.size()), ";"));
}
throw Error("$HYDRA_DBI does not denote a PostgreSQL database");
2015-07-07 10:17:21 +02:00
}
};
class receiver
2015-07-07 10:17:21 +02:00
{
std::optional<std::string> status;
pqxx::connection & conn;
public:
2015-07-07 10:17:21 +02:00
receiver(pqxx::connection_base & c, const std::string & channel)
: conn(static_cast<pqxx::connection &>(c))
2015-07-07 10:17:21 +02:00
{
conn.listen(channel, [this](pqxx::notification n) {
status = std::string(n.payload);
});
}
std::optional<std::string> get() {
auto s = status;
status = std::nullopt;
return s;
2015-07-07 10:17:21 +02:00
}
};