NetworkedApplications: SQLite-backed KV profile

This commit is contained in:
faumaray committed 2026-12-03 20:41:19 +03:00
1 parent 61582ea461
commit c21dbf5c93
4 files changed
+651 -2

No files matched your search

@@ -0,0 +1,104 @@
#include "networked_kv/sqlite_store.hpp"
#include <cassert>
#include <cstdio>
#include <filesystem>
#include <optional>
#include <string>
#include <unistd.h>
namespace
{
using namespace NetworkedKv;
std::filesystem::path temp_database()
{
const auto directory =
std::filesystem::temp_directory_path() /
("void-kv-sqlite-" + std::to_string(::getpid()));
std::filesystem::create_directories(directory);
return directory / "kv.db";
}
} // namespace
int main()
{
const auto path = temp_database();
std::filesystem::remove_all(path.parent_path());
std::filesystem::create_directories(path.parent_path());
{
auto store = SqliteKvStore::open(path);
assert(store.has_value());
auto& kv = **store;
auto created = kv.put("a", "one", Precondition::absent(), {"r1"});
assert(created.has_value());
assert(created->outcome == WriteOutcome::Applied);
assert(created->version == 1);
auto conflict = kv.put("a", "two", Precondition::absent(), {"r2"});
assert(conflict.has_value());
assert(conflict->outcome == WriteOutcome::Conflict);
auto updated = kv.put("a", "two", Precondition::at_version(1), {"r3"});
assert(updated.has_value());
assert(updated->outcome == WriteOutcome::Applied);
assert(updated->version == 2);
// Idempotent replay does not mutate the row.
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
assert(replay.has_value());
assert(replay->version == 2);
auto got = kv.get("a");
assert(got.has_value() && got->has_value());
assert((*got)->value == "two");
assert((*got)->version == 2);
for (int i = 0; i < 5; ++i) {
auto written = kv.put("s" + std::to_string(i), "v",
Precondition::absent(),
{"s" + std::to_string(i)});
assert(written.has_value());
}
std::size_t seen = 0;
std::optional<std::string> cursor;
for (;;) {
auto page = kv.scan(cursor ? std::optional<std::string_view>{*cursor}
: std::nullopt,
2);
assert(page.has_value());
assert(page->items.size() <= 2);
seen += page->items.size();
if (!page->next_cursor) {
break;
}
cursor = page->next_cursor;
}
assert(seen == 6);
}
// Reopen: durable rows and idempotency records survive.
{
auto store = SqliteKvStore::open(path);
assert(store.has_value());
auto& kv = **store;
auto got = kv.get("a");
assert(got.has_value() && got->has_value());
assert((*got)->value == "two");
auto replay = kv.put("a", "ignored", Precondition::at_version(2), {"r3"});
assert(replay.has_value());
assert(replay->version == 2);
auto removed = kv.erase("a", Precondition::at_version(2), {"r4"});
assert(removed.has_value());
assert(removed->outcome == WriteOutcome::Applied);
assert(!kv.get("a")->has_value());
}
std::filesystem::remove_all(path.parent_path());
std::puts("networked-kv sqlite profile ok");
return 0;
}