Files
vdm/daemon/src/store/sqlite.cpp
T
samiandClaude Sonnet 5 4b279e8271 daemon: store/ — SQLite WAL schema + forward-only migrator (build step 3)
The daemon's persistent state. SQLite in WAL mode, foreign keys on,
5 s busy timeout so a writer waits rather than SQLITE_BUSY under the
RPC loop.

- store/sqlite — RAII Db/Stmt over the C API; errors returned as
  DbResult<T> (std::expected), never thrown — the RPC loop must not
  unwind. transaction() helper: BEGIN / fn / COMMIT, ROLLBACK on error.
- store/migrations/0001_initial.sql — the eight tables from the brief:
  settings, categories, queues, tasks, segments, rules, history,
  pairings. Notable choices:
    * tasks columns project onto proto TaskSummary with no computation;
      requested vs effective segments/buffer split per ADR 0010/0012;
      pause_reason column per ADR 0013.
    * segments end_byte is NOT constrained >= 0 so a whole-file
      zero-length download is one row with end_byte = -1 (ADR 0010 B3a).
    * pairings stores only token_sha256 — the plaintext token is
      returned once from session.pair and never persisted (CLAUDE.md §4).
    * indices on tasks(state), (category_id), (queue_id, queue_position),
      (created_at), (completed_at) for the "1000 tasks, download.list
      under 50 ms" DoD.
    * six built-in categories + a Main queue seeded.
- store/migrations — runs every embedded migration past PRAGMA
  user_version, each in its own transaction, forward-only. SQL files
  are embedded at build time by cmake/embed_migrations.cmake.

Test veloxd.store_migrations (ASan+UBSan and TSan clean): fresh DB ->
head, all tables present, seed rows, FK cascade (segment orphan
rejected, task delete cascades), the end_byte=-1 zero-length case,
idempotent re-run, and forward-only from every released user_version.

Also: daemon/docs/proto-requests-m1.md — P1 marked landed on lane/proto
as 1.4.0 (HandlerError/HandlerResult), to be adopted in rpc/ once that
merges to main; P2 resolved.

Not linked into the running daemon yet — the store is wired to the
dispatcher when download.add/list/get get real bodies, next.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Upd9WhG9oppieig5nRDLig
2026-09-10 15:27:20 +04:00

147 lines
4.5 KiB
C++

#include "store/sqlite.hpp"
#include <sqlite3.h>
#include <utility>
namespace velox::daemon::store {
// --- Db ------------------------------------------------------------------------------
Db::~Db() {
if (db_ != nullptr) sqlite3_close(db_);
}
Db::Db(Db&& o) noexcept : db_(std::exchange(o.db_, nullptr)) {}
Db& Db::operator=(Db&& o) noexcept {
if (this != &o) {
if (db_ != nullptr) sqlite3_close(db_);
db_ = std::exchange(o.db_, nullptr);
}
return *this;
}
DbError Db::last_error() const {
return DbError{sqlite3_extended_errcode(db_), sqlite3_errmsg(db_)};
}
DbResult<Db> Db::open(const std::string& path) {
sqlite3* handle = nullptr;
const int rc = sqlite3_open_v2(
path.c_str(), &handle, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_NOMUTEX,
nullptr);
if (rc != SQLITE_OK) {
DbError e{rc, handle != nullptr ? sqlite3_errmsg(handle) : "sqlite3_open_v2 failed"};
if (handle != nullptr) sqlite3_close(handle);
return std::unexpected(std::move(e));
}
Db db(handle);
// WAL for crash-safe concurrent readers (docs/01 §1). busy_timeout so a writer waits
// rather than returning SQLITE_BUSY under the RPC loop. foreign_keys is per-connection.
for (const char* pragma : {"PRAGMA journal_mode=WAL", "PRAGMA synchronous=NORMAL",
"PRAGMA foreign_keys=ON", "PRAGMA busy_timeout=5000"}) {
if (auto r = db.exec(pragma); !r) return std::unexpected(r.error());
}
return db;
}
DbResult<void> Db::exec(std::string_view sql) {
char* err = nullptr;
const int rc = sqlite3_exec(db_, std::string(sql).c_str(), nullptr, nullptr, &err);
if (rc != SQLITE_OK) {
DbError e{rc, err != nullptr ? err : sqlite3_errmsg(db_)};
sqlite3_free(err);
return std::unexpected(std::move(e));
}
return {};
}
DbResult<Stmt> Db::prepare(std::string_view sql) {
sqlite3_stmt* s = nullptr;
const int rc =
sqlite3_prepare_v2(db_, sql.data(), static_cast<int>(sql.size()), &s, nullptr);
if (rc != SQLITE_OK) return std::unexpected(last_error());
return Stmt(db_, s);
}
std::int64_t Db::user_version() {
auto st = prepare("PRAGMA user_version");
if (!st) return -1;
auto row = st->step();
if (!row || !*row) return -1;
return st->column_int(0);
}
DbResult<void> Db::set_user_version(std::int64_t v) {
// PRAGMA does not accept a bound parameter; the value is our own integer.
return exec("PRAGMA user_version=" + std::to_string(v));
}
// --- Stmt ----------------------------------------------------------------------------
Stmt::~Stmt() {
if (stmt_ != nullptr) sqlite3_finalize(stmt_);
}
Stmt::Stmt(Stmt&& o) noexcept
: db_(std::exchange(o.db_, nullptr)), stmt_(std::exchange(o.stmt_, nullptr)) {}
Stmt& Stmt::operator=(Stmt&& o) noexcept {
if (this != &o) {
if (stmt_ != nullptr) sqlite3_finalize(stmt_);
db_ = std::exchange(o.db_, nullptr);
stmt_ = std::exchange(o.stmt_, nullptr);
}
return *this;
}
DbError Stmt::last_error() const {
return DbError{sqlite3_extended_errcode(db_), sqlite3_errmsg(db_)};
}
DbResult<void> Stmt::bind(int i, std::int64_t v) {
if (sqlite3_bind_int64(stmt_, i, v) != SQLITE_OK) return std::unexpected(last_error());
return {};
}
DbResult<void> Stmt::bind(int i, std::string_view v) {
if (sqlite3_bind_text(stmt_, i, v.data(), static_cast<int>(v.size()), SQLITE_TRANSIENT) !=
SQLITE_OK)
return std::unexpected(last_error());
return {};
}
DbResult<void> Stmt::bind_null(int i) {
if (sqlite3_bind_null(stmt_, i) != SQLITE_OK) return std::unexpected(last_error());
return {};
}
DbResult<bool> Stmt::step() {
const int rc = sqlite3_step(stmt_);
if (rc == SQLITE_ROW) return true;
if (rc == SQLITE_DONE) return false;
return std::unexpected(last_error());
}
DbResult<void> Stmt::reset() {
if (sqlite3_reset(stmt_) != SQLITE_OK) return std::unexpected(last_error());
return {};
}
std::int64_t Stmt::column_int(int i) const { return sqlite3_column_int64(stmt_, i); }
std::string Stmt::column_text(int i) const {
const auto* p = sqlite3_column_text(stmt_, i);
if (p == nullptr) return {};
return std::string(reinterpret_cast<const char*>(p),
static_cast<std::size_t>(sqlite3_column_bytes(stmt_, i)));
}
bool Stmt::column_is_null(int i) const {
return sqlite3_column_type(stmt_, i) == SQLITE_NULL;
}
} // namespace velox::daemon::store