Add Void::Sqlite — RAII SQLite wrapper with migrations

New SHARED module (separate from Data so Json/Csv/Ini consumers don't link
SQLite). Generic, Result-based:
- Database — open (file or :memory:), exec, prepare, begin, last_insert_rowid,
  changes; enables WAL + busy timeout + foreign_keys for writable modes.
- Statement — move-only prepared statement; 1-based typed bind (int/double/
  text/null/optional), step(), reset, 0-based column accessors.
- Transaction — RAII; rolls back on scope exit unless commit() is called.
- Migration + Database::migrate() — forward, in-order, idempotent schema
  upgrades tracked via PRAGMA user_version.

Dependencies.cmake resolves SQLite::SQLite3 via find_package. Tests exercise
CRUD, null handling, commit/rollback, migrations and errors on :memory:.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
faumarayandClaude Opus 4.8 committed 2026-06-22 16:24:18 +03:00
1 parent c92dff6ff7
commit cb639a713d
5 files changed
+579

No files matched your search

+7
View File
@@ -45,6 +45,13 @@ function(void_fetch_dependency DEP_NAME)
endif()
return()
endif()
if(DEP_NAME STREQUAL "SQLite")
if(NOT TARGET SQLite::SQLite3)
find_package(SQLite3 REQUIRED)
endif()
return()
endif()
# FIXME: Add if needed external
# if(DEP_NAME STREQUAL "glaze")
# if(NOT glaze_POPULATED)
+148
View File
@@ -0,0 +1,148 @@
#pragma once
#include <Void/Functional/Error.hpp>
#include <Void/Functional/Result.hpp>
#include <cstdint>
#include <filesystem>
#include <optional>
#include <span>
#include <string>
#include <string_view>
#include <utility>
struct sqlite3;
struct sqlite3_stmt;
// A thin, RAII, Result-based wrapper over the SQLite C API. Generic — no
// application schema baggage. Open a Database, prepare Statements, bind by
// 1-based index, step over result rows, read columns by 0-based index. Schema
// versioning is handled via PRAGMA user_version (migrate()).
namespace Void::Sqlite
{
using Void::Result::Error;
template <typename T> using Result = Void::Result::Result<T, Error>;
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate };
class Database;
/// A prepared statement. Move-only; finalizes on destruction.
class Statement
{
public:
Statement() = default;
~Statement();
Statement(Statement&&) noexcept;
Statement& operator=(Statement&&) noexcept;
Statement(const Statement&) = delete;
Statement& operator=(const Statement&) = delete;
// Bind parameters (1-based, matching SQLite). Chainable.
Statement& bind(int index, std::int64_t value);
Statement& bind(int index, int value)
{
return bind(index, static_cast<std::int64_t>(value));
}
Statement& bind(int index, double value);
Statement& bind(int index, std::string_view value);
Statement& bind(int index, std::nullptr_t);
Statement& bind(int index, const std::optional<std::string>& value);
/// Advance to the next row. Returns true with a row available,
/// false when the statement is done, or an Error on failure.
[[nodiscard]] Result<bool> step();
/// Reset for re-execution (keeps bindings unless clear_bindings).
void reset() noexcept;
void clear_bindings() noexcept;
// Column accessors (0-based), valid after step() yields a row.
[[nodiscard]] int column_count() const noexcept;
[[nodiscard]] bool is_null(int col) const noexcept;
[[nodiscard]] std::int64_t column_int(int col) const noexcept;
[[nodiscard]] double column_double(int col) const noexcept;
[[nodiscard]] std::string column_text(int col) const;
private:
friend class Database;
explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {}
sqlite3_stmt* m_stmt = nullptr;
};
/// RAII transaction. Rolls back on destruction unless commit() was called.
class Transaction
{
public:
~Transaction();
Transaction(Transaction&&) noexcept;
Transaction& operator=(Transaction&&) noexcept;
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
Result<void> commit();
void rollback() noexcept;
private:
friend class Database;
explicit Transaction(Database* db) : m_db(db) {}
Database* m_db = nullptr;
bool m_done = false;
};
/// A single forward schema migration applied when the database's
/// user_version is below `version`.
struct Migration {
int version; ///< target schema version (1, 2, 3, ...)
std::string_view sql; ///< DDL/DML to reach this version
};
class Database
{
public:
Database() = default;
~Database();
Database(Database&&) noexcept;
Database& operator=(Database&&) noexcept;
Database(const Database&) = delete;
Database& operator=(const Database&) = delete;
/// Open (or create) a database file. Use ":memory:" for an
/// in-memory db. Enables WAL + a busy timeout for ReadWrite modes.
[[nodiscard]] static Result<Database>
open(const std::filesystem::path& path,
OpenMode mode = OpenMode::ReadWriteCreate);
/// Execute one or more semicolon-separated statements (no results).
Result<void> exec(std::string_view sql);
/// Prepare a single statement for binding/stepping.
[[nodiscard]] Result<Statement> prepare(std::string_view sql);
/// Begin a transaction (BEGIN; commit/rollback via the handle).
[[nodiscard]] Result<Transaction> begin();
[[nodiscard]] std::int64_t last_insert_rowid() const noexcept;
[[nodiscard]] int changes() const noexcept;
/// Current schema version (PRAGMA user_version).
[[nodiscard]] Result<int> user_version();
/// Apply, in order, any migrations whose version exceeds the
/// current user_version, each inside a transaction, then bump
/// user_version. Idempotent and safe to call on every startup.
Result<void> migrate(std::span<const Migration> migrations);
[[nodiscard]] sqlite3* handle() const noexcept { return m_db; }
private:
sqlite3* m_db = nullptr;
};
} // namespace Void::Sqlite
+282
View File
@@ -0,0 +1,282 @@
#include <Void/Sqlite/Sqlite.hpp>
#include <sqlite3.h>
#include <format>
#include <utility>
namespace Void::Sqlite
{
namespace
{
[[nodiscard]] Error sqlite_error(sqlite3* db, std::string_view what)
{
const char* msg = db ? sqlite3_errmsg(db) : "no database";
return Error{std::format("Sqlite: {}: {}", what,
msg ? msg : "unknown error")};
}
} // namespace
// ── Statement ───────────────────────────────────────────────────────────
Statement::~Statement()
{
if (m_stmt) sqlite3_finalize(m_stmt);
}
Statement::Statement(Statement&& o) noexcept
: m_stmt(std::exchange(o.m_stmt, nullptr))
{
}
Statement& Statement::operator=(Statement&& o) noexcept
{
if (this != &o) {
if (m_stmt) sqlite3_finalize(m_stmt);
m_stmt = std::exchange(o.m_stmt, nullptr);
}
return *this;
}
Statement& Statement::bind(int index, std::int64_t value)
{
sqlite3_bind_int64(m_stmt, index, value);
return *this;
}
Statement& Statement::bind(int index, double value)
{
sqlite3_bind_double(m_stmt, index, value);
return *this;
}
Statement& Statement::bind(int index, std::string_view value)
{
sqlite3_bind_text(m_stmt, index, value.data(),
static_cast<int>(value.size()), SQLITE_TRANSIENT);
return *this;
}
Statement& Statement::bind(int index, std::nullptr_t)
{
sqlite3_bind_null(m_stmt, index);
return *this;
}
Statement& Statement::bind(int index, const std::optional<std::string>& v)
{
if (v) return bind(index, std::string_view{*v});
return bind(index, nullptr);
}
Result<bool> Statement::step()
{
const int rc = sqlite3_step(m_stmt);
if (rc == SQLITE_ROW) return true;
if (rc == SQLITE_DONE) return false;
return Void::Result::fail(
Error{std::format("Sqlite: step failed (code {})", rc)});
}
void Statement::reset() noexcept { sqlite3_reset(m_stmt); }
void Statement::clear_bindings() noexcept { sqlite3_clear_bindings(m_stmt); }
int Statement::column_count() const noexcept
{
return sqlite3_column_count(m_stmt);
}
bool Statement::is_null(int col) const noexcept
{
return sqlite3_column_type(m_stmt, col) == SQLITE_NULL;
}
std::int64_t Statement::column_int(int col) const noexcept
{
return sqlite3_column_int64(m_stmt, col);
}
double Statement::column_double(int col) const noexcept
{
return sqlite3_column_double(m_stmt, col);
}
std::string Statement::column_text(int col) const
{
const auto* p = sqlite3_column_text(m_stmt, col);
const int n = sqlite3_column_bytes(m_stmt, col);
if (!p || n <= 0) return {};
return std::string{reinterpret_cast<const char*>(p),
static_cast<std::size_t>(n)};
}
// ── Transaction ─────────────────────────────────────────────────────────
Transaction::~Transaction()
{
if (!m_done && m_db && m_db->handle()) {
sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr, nullptr);
}
}
Transaction::Transaction(Transaction&& o) noexcept
: m_db(std::exchange(o.m_db, nullptr)),
m_done(std::exchange(o.m_done, true))
{
}
Transaction& Transaction::operator=(Transaction&& o) noexcept
{
if (this != &o) {
if (!m_done && m_db && m_db->handle()) {
sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr,
nullptr);
}
m_db = std::exchange(o.m_db, nullptr);
m_done = std::exchange(o.m_done, true);
}
return *this;
}
Result<void> Transaction::commit()
{
if (m_done) return {};
m_done = true;
if (sqlite3_exec(m_db->handle(), "COMMIT", nullptr, nullptr, nullptr) !=
SQLITE_OK) {
return Void::Result::fail(sqlite_error(m_db->handle(), "commit"));
}
return {};
}
void Transaction::rollback() noexcept
{
if (m_done) return;
m_done = true;
sqlite3_exec(m_db->handle(), "ROLLBACK", nullptr, nullptr, nullptr);
}
// ── Database ────────────────────────────────────────────────────────────
Database::~Database()
{
if (m_db) sqlite3_close(m_db);
}
Database::Database(Database&& o) noexcept
: m_db(std::exchange(o.m_db, nullptr))
{
}
Database& Database::operator=(Database&& o) noexcept
{
if (this != &o) {
if (m_db) sqlite3_close(m_db);
m_db = std::exchange(o.m_db, nullptr);
}
return *this;
}
Result<Database> Database::open(const std::filesystem::path& path,
OpenMode mode)
{
int flags = 0;
switch (mode) {
case OpenMode::ReadOnly: flags = SQLITE_OPEN_READONLY; break;
case OpenMode::ReadWrite: flags = SQLITE_OPEN_READWRITE; break;
case OpenMode::ReadWriteCreate:
flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
break;
}
sqlite3* db = nullptr;
const int rc =
sqlite3_open_v2(path.string().c_str(), &db, flags, nullptr);
if (rc != SQLITE_OK) {
Error e = sqlite_error(db, "open");
if (db) sqlite3_close(db);
return Void::Result::fail(std::move(e));
}
Database out;
out.m_db = db;
if (mode != OpenMode::ReadOnly) {
sqlite3_busy_timeout(db, 5000);
sqlite3_exec(db, "PRAGMA journal_mode=WAL", nullptr, nullptr,
nullptr);
sqlite3_exec(db, "PRAGMA foreign_keys=ON", nullptr, nullptr,
nullptr);
}
return out;
}
Result<void> Database::exec(std::string_view sql)
{
char* err = nullptr;
const std::string s{sql};
if (sqlite3_exec(m_db, s.c_str(), nullptr, nullptr, &err) != SQLITE_OK) {
std::string msg = err ? err : "unknown error";
if (err) sqlite3_free(err);
return Void::Result::fail(
Error{std::format("Sqlite: exec: {}", msg)});
}
return {};
}
Result<Statement> Database::prepare(std::string_view sql)
{
sqlite3_stmt* stmt = nullptr;
if (sqlite3_prepare_v2(m_db, sql.data(), static_cast<int>(sql.size()),
&stmt, nullptr) != SQLITE_OK) {
return Void::Result::fail(sqlite_error(m_db, "prepare"));
}
return Statement{stmt};
}
Result<Transaction> Database::begin()
{
if (sqlite3_exec(m_db, "BEGIN", nullptr, nullptr, nullptr) !=
SQLITE_OK) {
return Void::Result::fail(sqlite_error(m_db, "begin"));
}
return Transaction{this};
}
std::int64_t Database::last_insert_rowid() const noexcept
{
return sqlite3_last_insert_rowid(m_db);
}
int Database::changes() const noexcept { return sqlite3_changes(m_db); }
Result<int> Database::user_version()
{
auto stmt = prepare("PRAGMA user_version");
if (!stmt) return Void::Result::fail(std::move(stmt).error());
auto row = stmt->step();
if (!row) return Void::Result::fail(std::move(row).error());
return static_cast<int>(stmt->column_int(0));
}
Result<void> Database::migrate(std::span<const Migration> migrations)
{
auto current = user_version();
if (!current) return Void::Result::fail(std::move(current).error());
int version = *current;
for (const auto& m : migrations) {
if (m.version <= version) continue;
auto tx = begin();
if (!tx) return Void::Result::fail(std::move(tx).error());
if (auto r = exec(m.sql); !r) {
tx->rollback();
return r;
}
if (auto r = exec(std::format("PRAGMA user_version={}", m.version));
!r) {
tx->rollback();
return r;
}
if (auto r = tx->commit(); !r) {
return r;
}
version = m.version;
}
return {};
}
} // namespace Void::Sqlite
+4
View File
@@ -0,0 +1,4 @@
void_add_module(Sqlite
INTERNAL_DEPS Functional
EXTERNAL_DEPS SQLite::SQLite3
)
+138
View File
@@ -0,0 +1,138 @@
#include <Void/Sqlite/Sqlite.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Suite.hpp>
#include <array>
#include <string>
namespace
{
using Void::Sqlite::Database;
using Void::Sqlite::Migration;
using Void::Testing::Test;
[[nodiscard]] Database fresh()
{
auto db = Database::open(":memory:");
Void::Testing::expect(db.has_value());
return std::move(*db);
}
struct SqliteTests : Void::Testing::Suite<SqliteTests> {
Test open_in_memory()
{
auto db = Database::open(":memory:");
Void::Testing::expect(db.has_value());
}
Test exec_create_and_insert()
{
auto db = fresh();
Void::Testing::expect(
db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, "
"name TEXT, score REAL)")
.has_value());
Void::Testing::expect(
db.exec("INSERT INTO t(name,score) VALUES('a',1.5)")
.has_value());
Void::Testing::expect_eq(db.last_insert_rowid(),
static_cast<std::int64_t>(1));
}
Test prepared_bind_and_read()
{
auto db = fresh();
(void)db.exec("CREATE TABLE t(id INTEGER, name TEXT, s REAL)");
auto ins = db.prepare(
"INSERT INTO t(id,name,s) VALUES(?,?,?)");
Void::Testing::expect(ins.has_value());
ins->bind(1, 7).bind(2, std::string_view{"hello"}).bind(3, 2.5);
const auto done = ins->step();
Void::Testing::expect(done.has_value() && *done == false);
auto sel = db.prepare("SELECT id,name,s FROM t WHERE id=?");
Void::Testing::expect(sel.has_value());
sel->bind(1, 7);
const auto row = sel->step();
Void::Testing::expect(row.has_value() && *row == true);
Void::Testing::expect_eq(sel->column_int(0),
static_cast<std::int64_t>(7));
Void::Testing::expect_eq(sel->column_text(1),
std::string{"hello"});
Void::Testing::expect(sel->column_double(2) == 2.5);
const auto end = sel->step();
Void::Testing::expect(end.has_value() && *end == false);
}
Test null_handling()
{
auto db = fresh();
(void)db.exec("CREATE TABLE t(v TEXT)");
auto ins = db.prepare("INSERT INTO t(v) VALUES(?)");
ins->bind(1, nullptr);
(void)ins->step();
auto sel = db.prepare("SELECT v FROM t");
(void)sel->step();
Void::Testing::expect(sel->is_null(0));
}
Test transaction_commit_persists()
{
auto db = fresh();
(void)db.exec("CREATE TABLE t(n INTEGER)");
{
auto tx = db.begin();
Void::Testing::expect(tx.has_value());
(void)db.exec("INSERT INTO t VALUES(1)");
(void)db.exec("INSERT INTO t VALUES(2)");
Void::Testing::expect(tx->commit().has_value());
}
auto sel = db.prepare("SELECT COUNT(*) FROM t");
(void)sel->step();
Void::Testing::expect_eq(sel->column_int(0),
static_cast<std::int64_t>(2));
}
Test transaction_rollback_on_scope_exit()
{
auto db = fresh();
(void)db.exec("CREATE TABLE t(n INTEGER)");
{
auto tx = db.begin();
(void)db.exec("INSERT INTO t VALUES(99)");
// no commit -> rolled back on destruction
}
auto sel = db.prepare("SELECT COUNT(*) FROM t");
(void)sel->step();
Void::Testing::expect_eq(sel->column_int(0),
static_cast<std::int64_t>(0));
}
Test migrations_apply_in_order_and_are_idempotent()
{
auto db = fresh();
const std::array<Migration, 2> migs{{
{1, "CREATE TABLE a(id INTEGER)"},
{2, "ALTER TABLE a ADD COLUMN name TEXT"},
}};
Void::Testing::expect(db.migrate(migs).has_value());
Void::Testing::expect_eq(*db.user_version(), 2);
// Second call is a no-op (idempotent) and must not error.
Void::Testing::expect(db.migrate(migs).has_value());
Void::Testing::expect_eq(*db.user_version(), 2);
// The v2 column exists.
Void::Testing::expect(
db.exec("INSERT INTO a(id,name) VALUES(1,'x')")
.has_value());
}
Test prepare_bad_sql_errors()
{
auto db = fresh();
Void::Testing::expect(!db.prepare("SELECT FROM").has_value());
}
};
} // namespace