diff --git a/cmake/Dependencies.cmake b/cmake/Dependencies.cmake index abe7b8d..7e502fb 100644 --- a/cmake/Dependencies.cmake +++ b/cmake/Dependencies.cmake @@ -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) diff --git a/include/Void/Sqlite/Sqlite.hpp b/include/Void/Sqlite/Sqlite.hpp new file mode 100644 index 0000000..6eceb8a --- /dev/null +++ b/include/Void/Sqlite/Sqlite.hpp @@ -0,0 +1,148 @@ +#pragma once + +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +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 using Result = Void::Result::Result; + + 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(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& 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 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 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 + open(const std::filesystem::path& path, + OpenMode mode = OpenMode::ReadWriteCreate); + + /// Execute one or more semicolon-separated statements (no results). + Result exec(std::string_view sql); + + /// Prepare a single statement for binding/stepping. + [[nodiscard]] Result prepare(std::string_view sql); + + /// Begin a transaction (BEGIN; commit/rollback via the handle). + [[nodiscard]] Result begin(); + + [[nodiscard]] std::int64_t last_insert_rowid() const noexcept; + [[nodiscard]] int changes() const noexcept; + + /// Current schema version (PRAGMA user_version). + [[nodiscard]] Result 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 migrate(std::span migrations); + + [[nodiscard]] sqlite3* handle() const noexcept { return m_db; } + + private: + + sqlite3* m_db = nullptr; + }; + +} // namespace Void::Sqlite diff --git a/src/Sqlite/Sqlite.cpp b/src/Sqlite/Sqlite.cpp new file mode 100644 index 0000000..4047d98 --- /dev/null +++ b/src/Sqlite/Sqlite.cpp @@ -0,0 +1,282 @@ +#include + +#include + +#include +#include + +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(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& v) + { + if (v) return bind(index, std::string_view{*v}); + return bind(index, nullptr); + } + + Result 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(p), + static_cast(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 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::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 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 Database::prepare(std::string_view sql) + { + sqlite3_stmt* stmt = nullptr; + if (sqlite3_prepare_v2(m_db, sql.data(), static_cast(sql.size()), + &stmt, nullptr) != SQLITE_OK) { + return Void::Result::fail(sqlite_error(m_db, "prepare")); + } + return Statement{stmt}; + } + + Result 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 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(stmt->column_int(0)); + } + + Result Database::migrate(std::span 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 diff --git a/src/Sqlite/module.cmake b/src/Sqlite/module.cmake new file mode 100644 index 0000000..e969f82 --- /dev/null +++ b/src/Sqlite/module.cmake @@ -0,0 +1,4 @@ +void_add_module(Sqlite + INTERNAL_DEPS Functional + EXTERNAL_DEPS SQLite::SQLite3 +) diff --git a/tests/standalone/Sqlite/Sqlite.cpp b/tests/standalone/Sqlite/Sqlite.cpp new file mode 100644 index 0000000..cddf5d7 --- /dev/null +++ b/tests/standalone/Sqlite/Sqlite.cpp @@ -0,0 +1,138 @@ +#include +#include +#include + +#include +#include + +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 { + 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(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(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(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(0)); + } + + Test migrations_apply_in_order_and_are_idempotent() + { + auto db = fresh(); + const std::array 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