48 lines
1.7 KiB
C++
48 lines
1.7 KiB
C++
#pragma once
|
|
|
|
#include <algorithm>
|
|
#include <cctype>
|
|
#include <optional>
|
|
#include <regex>
|
|
#include <string>
|
|
|
|
// Непрозрачный для клиента курсор keyset-пагинации: "<created_at в мкс от epoch>|<uuid>".
|
|
// Микросекунды сохраняют точный created_at строки, даже если в JSON время округлено до секунд.
|
|
struct Cursor {
|
|
std::string created_us;
|
|
std::string id;
|
|
};
|
|
|
|
// Выражение SQL, восстанавливающее timestamptz из created_us без потери точности.
|
|
constexpr const char* kCursorTimestampSql =
|
|
"(timestamptz 'epoch' + $3::bigint * interval '1 microsecond')";
|
|
|
|
constexpr const char* kCreatedUsSql =
|
|
"(EXTRACT(EPOCH FROM created_at) * 1000000)::bigint AS created_us";
|
|
|
|
inline bool is_uuid(const std::string& s) {
|
|
static const std::regex re(
|
|
"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-"
|
|
"[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
|
|
return std::regex_match(s, re);
|
|
}
|
|
|
|
inline std::optional<Cursor> parse_cursor(const std::string& raw) {
|
|
const auto bar = raw.find('|');
|
|
if (bar == std::string::npos) {
|
|
return std::nullopt;
|
|
}
|
|
Cursor c{raw.substr(0, bar), raw.substr(bar + 1)};
|
|
const bool digits = !c.created_us.empty() && c.created_us.size() <= 18 &&
|
|
std::all_of(c.created_us.begin(), c.created_us.end(),
|
|
[](unsigned char ch) { return std::isdigit(ch); });
|
|
if (!digits || !is_uuid(c.id)) {
|
|
return std::nullopt;
|
|
}
|
|
return c;
|
|
}
|
|
|
|
inline std::string make_cursor(const std::string& created_us, const std::string& id) {
|
|
return created_us + "|" + id;
|
|
}
|