Complete M7.2 PostgreSQL adapter and migration bootstrap
This commit is contained in:
@@ -0,0 +1,181 @@
|
||||
#include "evo/persistence/postgres.hpp"
|
||||
#include <algorithm>
|
||||
#include <arpa/inet.h>
|
||||
#include <cerrno>
|
||||
#include <climits>
|
||||
#include <cstdlib>
|
||||
#include <libpq-fe.h>
|
||||
#include <poll.h>
|
||||
|
||||
namespace evo::persistence {
|
||||
namespace {
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Finish {
|
||||
void operator()(PGconn* p) const {
|
||||
PQfinish(p);
|
||||
}
|
||||
};
|
||||
struct Clear {
|
||||
void operator()(PGresult* p) const {
|
||||
PQclear(p);
|
||||
}
|
||||
};
|
||||
using Connection = std::unique_ptr<PGconn, Finish>;
|
||||
using Result = std::unique_ptr<PGresult, Clear>;
|
||||
bool wait(PGconn* c, short events, Clock::time_point deadline) {
|
||||
for (;;) {
|
||||
const auto left =
|
||||
std::chrono::duration_cast<std::chrono::milliseconds>(deadline - Clock::now());
|
||||
if (left.count() <= 0 || PQsocket(c) < 0)
|
||||
return false;
|
||||
pollfd descriptor{PQsocket(c), events, 0};
|
||||
const auto ready = ::poll(
|
||||
&descriptor, 1, static_cast<int>(std::min(left.count(), static_cast<long>(INT_MAX))));
|
||||
if (ready > 0)
|
||||
return (descriptor.revents & events) != 0;
|
||||
if (ready == 0 || errno != EINTR)
|
||||
return false;
|
||||
}
|
||||
}
|
||||
bool bounded(const std::string& s) {
|
||||
return s.size() <= 4096 && s.find('\0') == std::string::npos;
|
||||
}
|
||||
bool duration(std::chrono::milliseconds t) {
|
||||
return t.count() > 0 && t.count() <= 30000;
|
||||
}
|
||||
PgFailure fail(PgError e) {
|
||||
return {e, {}};
|
||||
}
|
||||
} // namespace
|
||||
struct Postgres::Impl {
|
||||
Connection connection;
|
||||
};
|
||||
Postgres::Postgres(std::unique_ptr<Impl> impl) : impl_(std::move(impl)) {}
|
||||
Postgres::~Postgres() = default;
|
||||
std::expected<std::unique_ptr<Postgres>, PgFailure>
|
||||
Postgres::connect(const PgOptions& o, std::chrono::milliseconds timeout) {
|
||||
if (!duration(timeout) || o.host.empty() || o.database.empty() || o.user.empty() ||
|
||||
o.port.empty())
|
||||
return std::unexpected{fail(PgError::config)};
|
||||
for (const auto* value :
|
||||
{&o.host, &o.hostaddr, &o.port, &o.database, &o.user, &o.password_file, &o.ca_file})
|
||||
if (!bounded(*value))
|
||||
return std::unexpected{fail(PgError::config)};
|
||||
const bool local = o.host.front() == '/';
|
||||
if (o.host.find(',') != std::string::npos ||
|
||||
(local && (std::getenv("PGHOSTADDR") || std::getenv("PGSERVICE"))))
|
||||
return std::unexpected{fail(PgError::config)};
|
||||
std::array<unsigned char, 16> address{};
|
||||
if ((!local &&
|
||||
(o.ca_file.empty() || (inet_pton(AF_INET, o.hostaddr.c_str(), address.data()) != 1 &&
|
||||
inet_pton(AF_INET6, o.hostaddr.c_str(), address.data()) != 1))) ||
|
||||
(local && !o.hostaddr.empty()))
|
||||
return std::unexpected{fail(PgError::config)};
|
||||
const char* keys[] = {"host", "hostaddr", "port", "dbname", "user", "passfile",
|
||||
"sslrootcert", "sslmode", "gssencmode", "options", nullptr};
|
||||
const char* values[] = {o.host.c_str(),
|
||||
o.hostaddr.c_str(),
|
||||
o.port.c_str(),
|
||||
o.database.c_str(),
|
||||
o.user.c_str(),
|
||||
o.password_file.c_str(),
|
||||
o.ca_file.c_str(),
|
||||
local ? "disable" : "verify-full",
|
||||
"disable",
|
||||
"-csearch_path= -cstatement_timeout=10000 -clock_timeout=5000",
|
||||
nullptr};
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
Connection c{PQconnectStartParams(keys, values, 0)};
|
||||
if (!c)
|
||||
return std::unexpected{fail(PgError::connect)};
|
||||
auto status = PGRES_POLLING_WRITING;
|
||||
while (status != PGRES_POLLING_OK) {
|
||||
if (status == PGRES_POLLING_FAILED ||
|
||||
!wait(c.get(), status == PGRES_POLLING_READING ? POLLIN : POLLOUT, deadline))
|
||||
return std::unexpected{fail(PgError::connect)};
|
||||
status = PQconnectPoll(c.get());
|
||||
}
|
||||
if (PQlibVersion() != 180006 || PQserverVersion(c.get()) != 180006)
|
||||
return std::unexpected{fail(PgError::version)};
|
||||
if (PQsetnonblocking(c.get(), 1) != 0)
|
||||
return std::unexpected{fail(PgError::connect)};
|
||||
auto impl = std::make_unique<Impl>();
|
||||
impl->connection = std::move(c);
|
||||
return std::unique_ptr<Postgres>(new Postgres(std::move(impl)));
|
||||
}
|
||||
std::expected<PgRows, PgFailure> Postgres::query(const std::string& sql,
|
||||
std::span<const std::string> parameters,
|
||||
std::chrono::milliseconds timeout) {
|
||||
auto& owned = impl_->connection;
|
||||
if (!owned)
|
||||
return std::unexpected{fail(PgError::closed)};
|
||||
if (!duration(timeout) || sql.size() > 16384 || sql.find('\0') != std::string::npos ||
|
||||
parameters.size() > 16)
|
||||
return std::unexpected{fail(PgError::config)};
|
||||
std::array<const char*, 16> values{};
|
||||
for (std::size_t i = 0; i < parameters.size(); ++i) {
|
||||
if (!bounded(parameters[i]))
|
||||
return std::unexpected{fail(PgError::bounds)};
|
||||
values[i] = parameters[i].c_str();
|
||||
}
|
||||
auto* c = owned.get();
|
||||
const auto deadline = Clock::now() + timeout;
|
||||
const auto unknown = [&]() -> std::expected<PgRows, PgFailure> {
|
||||
owned.reset();
|
||||
return std::unexpected{fail(PgError::unknown)};
|
||||
};
|
||||
if (PQsendQueryParams(c, sql.c_str(), static_cast<int>(parameters.size()), nullptr,
|
||||
values.data(), nullptr, nullptr, 0) != 1 ||
|
||||
PQsetSingleRowMode(c) != 1)
|
||||
return unknown();
|
||||
int flush{};
|
||||
while ((flush = PQflush(c)) == 1)
|
||||
if (!wait(c, POLLOUT, deadline))
|
||||
return unknown();
|
||||
if (flush < 0)
|
||||
return unknown();
|
||||
PgRows rows;
|
||||
std::size_t bytes{};
|
||||
std::optional<PgFailure> error;
|
||||
for (;;) {
|
||||
if (Clock::now() >= deadline)
|
||||
return unknown();
|
||||
while (PQisBusy(c))
|
||||
if (!wait(c, POLLIN, deadline) || PQconsumeInput(c) != 1)
|
||||
return unknown();
|
||||
Result r{PQgetResult(c)};
|
||||
if (!r)
|
||||
break;
|
||||
const auto status = PQresultStatus(r.get());
|
||||
if (status == PGRES_SINGLE_TUPLE) {
|
||||
if (rows.size() == 128 || PQnfields(r.get()) > 16)
|
||||
return unknown();
|
||||
std::vector<std::optional<std::string>> row;
|
||||
for (int j = 0; j < PQnfields(r.get()); ++j) {
|
||||
const auto length = static_cast<std::size_t>(PQgetlength(r.get(), 0, j));
|
||||
if (length > 65536 - bytes)
|
||||
return unknown();
|
||||
bytes += length;
|
||||
if (PQgetisnull(r.get(), 0, j))
|
||||
row.emplace_back(std::nullopt);
|
||||
else
|
||||
row.emplace_back(std::string(PQgetvalue(r.get(), 0, j), length));
|
||||
}
|
||||
rows.push_back(std::move(row));
|
||||
} else if (status != PGRES_COMMAND_OK && status != PGRES_TUPLES_OK) {
|
||||
if (status != PGRES_FATAL_ERROR)
|
||||
return unknown();
|
||||
PgFailure f = fail(PgError::sql);
|
||||
const auto* state = PQresultErrorField(r.get(), PG_DIAG_SQLSTATE);
|
||||
if (state)
|
||||
std::copy_n(state, 5, f.sqlstate.begin());
|
||||
error = f;
|
||||
}
|
||||
}
|
||||
if (PQstatus(c) != CONNECTION_OK)
|
||||
return unknown();
|
||||
if (error)
|
||||
return std::unexpected{*error};
|
||||
return rows;
|
||||
}
|
||||
} // namespace evo::persistence
|
||||
Reference in New Issue
Block a user