#include "user_repo.hpp" #include #include #include #include #include #include #include namespace { std::string make_uuid() { static std::mt19937_64 rng{std::random_device{}()}; std::uniform_int_distribution d16(0, 0xffff); std::uniform_int_distribution d32(0, 0xffffffffu); std::ostringstream out; out << std::hex << std::setfill('0'); out << std::setw(8) << d32(rng); out << '-' << std::setw(4) << d16(rng); out << '-' << std::setw(4) << ((d16(rng) & 0x0fff) | 0x4000); out << '-' << std::setw(4) << ((d16(rng) & 0x3fff) | 0x8000); out << '-' << std::setw(4) << d16(rng) << std::setw(8) << d32(rng); return out.str(); } std::string epoch_to_rfc3339(long long epoch) { const std::time_t t = static_cast(epoch); std::tm tm{}; gmtime_r(&t, &tm); std::ostringstream out; out << std::put_time(&tm, "%Y-%m-%dT%H:%M:%SZ"); return out.str(); } std::string now_epoch_str() { const auto now = std::chrono::system_clock::now(); const auto secs = std::chrono::duration_cast( now.time_since_epoch()).count(); return std::to_string(secs); } User row_to_user(const pqxx::row& r) { User u; u.id = r["id"].as(); u.username = r["username"].as(); u.display_name = r["display_name"].as(); u.password_hash = r["password_hash"].as(); u.created_at = epoch_to_rfc3339(r["created_at_epoch"].as()); return u; } constexpr const char* kUserColumns = "id, username, display_name, password_hash, " "EXTRACT(EPOCH FROM created_at)::bigint AS created_at_epoch"; } std::optional UserRepo::create(const std::string& username, const std::string& display_name, const std::string& password_hash) { auto lease = pool_.acquire(); pqxx::work tx(*lease); try { const std::string id = make_uuid(); auto r = tx.exec( "INSERT INTO users (id, username, display_name, password_hash, created_at) " "VALUES ($1, $2, $3, $4, to_timestamp($5::bigint)) " "RETURNING " + std::string(kUserColumns), pqxx::params{id, username, display_name, password_hash, now_epoch_str()}); tx.commit(); return row_to_user(r[0]); } catch (const pqxx::unique_violation&) { tx.abort(); return std::nullopt; } } std::optional UserRepo::find_by_id(const std::string& id) { auto lease = pool_.acquire(); pqxx::work tx(*lease); auto r = tx.exec( "SELECT " + std::string(kUserColumns) + " FROM users WHERE id = $1", pqxx::params{id}); tx.commit(); if (r.empty()) return std::nullopt; return row_to_user(r[0]); } std::optional UserRepo::find_by_username(const std::string& username) { auto lease = pool_.acquire(); pqxx::work tx(*lease); auto r = tx.exec( "SELECT " + std::string(kUserColumns) + " FROM users WHERE username = $1", pqxx::params{username}); tx.commit(); if (r.empty()) return std::nullopt; return row_to_user(r[0]); }