feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool
This commit is contained in:
1 parent
9925ea1764
commit
427cc9a843
15 files changed
+4438
-134
No files matched your search
@@ -0,0 +1,179 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Async/Detail/Types.hpp>
|
||||
#include <Void/Async/Executor.hpp>
|
||||
#include <Void/Async/Operation.hpp>
|
||||
#include <Void/Async/Task.hpp>
|
||||
#include <Void/Sqlite/Sqlite.hpp>
|
||||
#include <Void/Sqlite/Types.hpp>
|
||||
#include <Void/Time/Clock.hpp>
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
struct AsyncPoolOptions {
|
||||
std::filesystem::path path{};
|
||||
OpenOptions open_options{};
|
||||
/// Default 4 reader connections alongside 1 dedicated writer lane.
|
||||
std::size_t reader_connections{4};
|
||||
std::size_t max_queued_jobs{1024};
|
||||
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
int progress_handler_steps{64};
|
||||
const Void::Time::MonotonicClock* clock{nullptr};
|
||||
};
|
||||
|
||||
struct AsyncPoolStats {
|
||||
std::size_t reader_connections{0};
|
||||
std::size_t queued_read_jobs{0};
|
||||
std::size_t queued_write_jobs{0};
|
||||
std::size_t active_read_jobs{0};
|
||||
std::size_t active_write_jobs{0};
|
||||
std::size_t pending_input_bytes{0};
|
||||
std::uint64_t completed_jobs{0};
|
||||
std::uint64_t rejected_jobs{0};
|
||||
std::uint64_t cancelled_jobs{0};
|
||||
};
|
||||
|
||||
/// Bounded blocking SQLite connection pool (1 writer lane + N reader lanes).
|
||||
/// Leases one connection exclusively for the entire callback/transaction
|
||||
/// without ever running SQLite calls on an IO event-loop thread or leaking
|
||||
/// interrupts across subsequent borrowers.
|
||||
class AsyncPool
|
||||
{
|
||||
public:
|
||||
~AsyncPool();
|
||||
AsyncPool(AsyncPool&&) noexcept;
|
||||
AsyncPool& operator=(AsyncPool&&) noexcept;
|
||||
AsyncPool(const AsyncPool&) = delete;
|
||||
AsyncPool& operator=(const AsyncPool&) = delete;
|
||||
|
||||
[[nodiscard]] static Result<AsyncPool> open(
|
||||
AsyncPoolOptions options,
|
||||
Void::Async::Executor* completion_executor = nullptr);
|
||||
|
||||
/// Execute a read-only unit of work on a leased reader connection.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_read(
|
||||
std::function<Result<T>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
auto box = std::make_shared<std::optional<Result<T>>>();
|
||||
auto r = co_await submit_erased(
|
||||
false,
|
||||
[box, f = std::move(fn)](Database& db) -> Result<void> {
|
||||
*box = f(db);
|
||||
return {};
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
if (!r) {
|
||||
co_return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
if (!box->has_value()) {
|
||||
co_return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::sqlite_error,
|
||||
"AsyncPool read callback produced no result"));
|
||||
}
|
||||
co_return std::move(**box);
|
||||
}
|
||||
|
||||
/// Execute a write unit of work on the serialized writer lane.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_write(
|
||||
std::function<Result<T>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
auto box = std::make_shared<std::optional<Result<T>>>();
|
||||
auto r = co_await submit_erased(
|
||||
true,
|
||||
[box, f = std::move(fn)](Database& db) -> Result<void> {
|
||||
*box = f(db);
|
||||
return {};
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
if (!r) {
|
||||
co_return Void::Result::fail(std::move(r).error());
|
||||
}
|
||||
if (!box->has_value()) {
|
||||
co_return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::sqlite_error,
|
||||
"AsyncPool write callback produced no result"));
|
||||
}
|
||||
co_return std::move(**box);
|
||||
}
|
||||
|
||||
/// Execute a full transaction on the leased writer connection.
|
||||
/// Commits if `fn` returns ok; rolls back on error. Never releases
|
||||
/// the writer lease mid-transaction.
|
||||
template <typename T>
|
||||
[[nodiscard]] Void::Coro::Task<Result<T>> run_write_transaction(
|
||||
BeginMode mode,
|
||||
std::function<Result<T>(Database&, Transaction&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0)
|
||||
{
|
||||
return run_write<T>(
|
||||
[mode, f = std::move(fn)](Database& db) -> Result<T> {
|
||||
auto tx = db.begin(mode);
|
||||
if (!tx) {
|
||||
return Void::Result::fail(std::move(tx).error());
|
||||
}
|
||||
auto res = f(db, *tx);
|
||||
if (!res) {
|
||||
(void)tx->rollback_checked();
|
||||
return res;
|
||||
}
|
||||
if (tx->is_active()) {
|
||||
auto c = tx->commit();
|
||||
if (!c) {
|
||||
if (tx->is_active()) {
|
||||
(void)tx->rollback_checked();
|
||||
}
|
||||
return Void::Result::fail(std::move(c).error());
|
||||
}
|
||||
}
|
||||
return res;
|
||||
},
|
||||
std::move(op),
|
||||
input_bytes);
|
||||
}
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> run_read_void(
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0);
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> run_write_void(
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op = {},
|
||||
std::size_t input_bytes = 0);
|
||||
|
||||
[[nodiscard]] AsyncPoolStats stats() const noexcept;
|
||||
|
||||
/// Stop new admission, drain all admitted jobs, join worker threads,
|
||||
/// and close all pooled SQLite connections.
|
||||
[[nodiscard]] Result<void> close_and_join();
|
||||
|
||||
private:
|
||||
struct Impl;
|
||||
explicit AsyncPool(std::shared_ptr<Impl> impl) noexcept;
|
||||
|
||||
[[nodiscard]] Void::Coro::Task<Result<void>> submit_erased(
|
||||
bool is_write,
|
||||
std::function<Result<void>(Database&)> fn,
|
||||
Void::Async::OperationOptions op,
|
||||
std::size_t input_bytes);
|
||||
|
||||
std::shared_ptr<Impl> m_impl{};
|
||||
};
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
+253
-33
@@ -2,36 +2,79 @@
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
#include <Void/Sqlite/Types.hpp>
|
||||
|
||||
#include <cstdint>
|
||||
#include <filesystem>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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()).
|
||||
// A hardened RAII, Result-based wrapper over the SQLite C API. Generic — no
|
||||
// application schema baggage. Open a Database (or open_database with explicit
|
||||
// OpenOptions), prepare Statements, bind by 1-based index or parameter name,
|
||||
// step over result rows, and read typed columns by 0-based index.
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class OpenMode { ReadOnly, ReadWrite, ReadWriteCreate };
|
||||
namespace detail
|
||||
{
|
||||
struct ConnectionState;
|
||||
} // namespace detail
|
||||
|
||||
class Database;
|
||||
class Statement;
|
||||
class Transaction;
|
||||
class Savepoint;
|
||||
|
||||
/// A prepared statement. Move-only; finalizes on destruction.
|
||||
/// Non-owning view of the current row of a Statement. Expires on the next
|
||||
/// step(), reset(), reset_checked(), finalize_checked(), or destruction.
|
||||
/// Must never cross an await or outlive the Statement step that produced it.
|
||||
class RowView
|
||||
{
|
||||
public:
|
||||
RowView() noexcept = default;
|
||||
|
||||
[[nodiscard]] bool is_valid() const noexcept;
|
||||
[[nodiscard]] int column_count() const noexcept;
|
||||
[[nodiscard]] Result<ColumnType> column_type(int col) const;
|
||||
[[nodiscard]] Result<bool> is_null(int col) const;
|
||||
[[nodiscard]] Result<std::int64_t> get_int(int col) const;
|
||||
[[nodiscard]] Result<double> get_double(int col) const;
|
||||
[[nodiscard]] Result<std::string_view> get_text_view(int col) const;
|
||||
[[nodiscard]] Result<std::string> get_text(int col) const;
|
||||
[[nodiscard]] Result<std::span<const std::byte>> get_blob_view(int col) const;
|
||||
[[nodiscard]] Result<std::vector<std::byte>> get_blob(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::int64_t>> get_optional_int(int col) const;
|
||||
[[nodiscard]] Result<std::optional<double>> get_optional_double(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::string>> get_optional_text(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> get_optional_blob(int col) const;
|
||||
[[nodiscard]] Result<OwnedValue> get_value(int col) const;
|
||||
[[nodiscard]] Result<OwnedRow> copy() const;
|
||||
|
||||
private:
|
||||
friend class Statement;
|
||||
RowView(const Statement* stmt, std::uint64_t generation) noexcept
|
||||
: m_stmt(stmt), m_generation(generation)
|
||||
{
|
||||
}
|
||||
|
||||
const Statement* m_stmt{nullptr};
|
||||
std::uint64_t m_generation{0};
|
||||
};
|
||||
|
||||
/// A prepared statement. Move-only; retains shared ConnectionState so moving
|
||||
/// or destroying Database cannot dangle this statement.
|
||||
class Statement
|
||||
{
|
||||
public:
|
||||
|
||||
Statement() = default;
|
||||
~Statement();
|
||||
Statement(Statement&&) noexcept;
|
||||
@@ -39,7 +82,7 @@ namespace Void::Sqlite
|
||||
Statement(const Statement&) = delete;
|
||||
Statement& operator=(const Statement&) = delete;
|
||||
|
||||
// Bind parameters (1-based, matching SQLite). Chainable.
|
||||
// ── Legacy 1.x chainable bind methods (1-based) ──────────────────
|
||||
Statement& bind(int index, std::int64_t value);
|
||||
Statement& bind(int index, int value)
|
||||
{
|
||||
@@ -56,48 +99,143 @@ namespace Void::Sqlite
|
||||
Statement& bind(int index, std::nullptr_t);
|
||||
Statement& bind(int index, const std::optional<std::string>& value);
|
||||
|
||||
/// Error captured by the most recent legacy unchecked bind() call, if any.
|
||||
[[nodiscard]] const std::optional<Error>& last_bind_error() const noexcept
|
||||
{
|
||||
return m_last_bind_error;
|
||||
}
|
||||
|
||||
// ── Checked bind / parameter metadata ────────────────────────────
|
||||
[[nodiscard]] int bind_parameter_count() const noexcept;
|
||||
[[nodiscard]] Result<int> bind_parameter_index(std::string_view name) const;
|
||||
|
||||
[[nodiscard]] Result<void> bind_checked(int index, ValueView value);
|
||||
[[nodiscard]] Result<void> bind_checked(std::string_view name, ValueView value);
|
||||
|
||||
/// Zero-copy borrowed text/blob binding keeping `owner` alive until
|
||||
/// reset(), clear_bindings(), rebind, finalize, or destruction.
|
||||
[[nodiscard]] Result<void> bind_borrowed_text(
|
||||
int index, std::string_view value, std::shared_ptr<const void> owner);
|
||||
[[nodiscard]] Result<void> bind_borrowed_blob(
|
||||
int index, std::span<const std::byte> value, std::shared_ptr<const void> owner);
|
||||
|
||||
/// 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;
|
||||
[[nodiscard]] Result<void> reset_checked();
|
||||
|
||||
// Column accessors (0-based), valid after step() yields a row.
|
||||
void clear_bindings() noexcept;
|
||||
[[nodiscard]] Result<void> clear_bindings_checked();
|
||||
|
||||
/// Explicitly finalize the statement and report any native error.
|
||||
[[nodiscard]] Result<void> finalize_checked();
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept { return m_stmt != nullptr; }
|
||||
[[nodiscard]] bool has_row() const noexcept { return m_has_row; }
|
||||
[[nodiscard]] std::uint64_t row_generation() const noexcept
|
||||
{
|
||||
return m_row_generation;
|
||||
}
|
||||
|
||||
// ── Legacy 1.x column accessors (0-based) ────────────────────────
|
||||
[[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:
|
||||
// ── Strict typed column accessors & row views ────────────────────
|
||||
[[nodiscard]] Result<RowView> current_row() const;
|
||||
[[nodiscard]] Result<OwnedRow> copy_row() const;
|
||||
[[nodiscard]] Result<ColumnType> column_type(int col) const;
|
||||
[[nodiscard]] Result<std::int64_t> try_column_int(int col) const;
|
||||
[[nodiscard]] Result<double> try_column_double(int col) const;
|
||||
[[nodiscard]] Result<std::string_view> try_column_text_view(int col) const;
|
||||
[[nodiscard]] Result<std::string> try_column_text(int col) const;
|
||||
[[nodiscard]] Result<std::span<const std::byte>> try_column_blob_view(int col) const;
|
||||
[[nodiscard]] Result<std::vector<std::byte>> try_column_blob(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::int64_t>> try_column_optional_int(int col) const;
|
||||
[[nodiscard]] Result<std::optional<double>> try_column_optional_double(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::string>> try_column_optional_text(int col) const;
|
||||
[[nodiscard]] Result<std::optional<std::vector<std::byte>>> try_column_optional_blob(int col) const;
|
||||
[[nodiscard]] Result<OwnedValue> try_column_value(int col) const;
|
||||
|
||||
private:
|
||||
friend class Database;
|
||||
explicit Statement(sqlite3_stmt* stmt) : m_stmt(stmt) {}
|
||||
sqlite3_stmt* m_stmt = nullptr;
|
||||
friend class RowView;
|
||||
|
||||
Statement(std::shared_ptr<detail::ConnectionState> conn,
|
||||
sqlite3_stmt* stmt) noexcept;
|
||||
void release_handle() noexcept;
|
||||
[[nodiscard]] Result<void> validate_column_access(int col) const;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
sqlite3_stmt* m_stmt{nullptr};
|
||||
bool m_has_row{false};
|
||||
std::uint64_t m_row_generation{0};
|
||||
std::vector<std::shared_ptr<const void>> m_borrowed_owners{};
|
||||
std::optional<Error> m_last_bind_error{};
|
||||
};
|
||||
|
||||
/// RAII transaction. Rolls back on destruction unless commit() was called.
|
||||
/// RAII transaction retaining shared ConnectionState. Never marks Committed
|
||||
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error.
|
||||
class Transaction
|
||||
{
|
||||
public:
|
||||
|
||||
Transaction() noexcept = default;
|
||||
~Transaction();
|
||||
Transaction(Transaction&&) noexcept;
|
||||
Transaction& operator=(Transaction&&) noexcept;
|
||||
Transaction(const Transaction&) = delete;
|
||||
Transaction& operator=(const Transaction&) = delete;
|
||||
|
||||
[[nodiscard]] TransactionState state() const noexcept { return m_state; }
|
||||
[[nodiscard]] bool is_active() const noexcept
|
||||
{
|
||||
return m_state == TransactionState::Active;
|
||||
}
|
||||
|
||||
Result<void> commit();
|
||||
[[nodiscard]] Result<void> rollback_checked();
|
||||
void rollback() noexcept;
|
||||
|
||||
private:
|
||||
|
||||
friend class Database;
|
||||
explicit Transaction(Database* db) : m_db(db) {}
|
||||
Database* m_db = nullptr;
|
||||
bool m_done = false;
|
||||
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn) noexcept;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
TransactionState m_state{TransactionState::RolledBack};
|
||||
};
|
||||
|
||||
/// Separately owned nested savepoint scope.
|
||||
class Savepoint
|
||||
{
|
||||
public:
|
||||
Savepoint() noexcept = default;
|
||||
~Savepoint();
|
||||
Savepoint(Savepoint&&) noexcept;
|
||||
Savepoint& operator=(Savepoint&&) noexcept;
|
||||
Savepoint(const Savepoint&) = delete;
|
||||
Savepoint& operator=(const Savepoint&) = delete;
|
||||
|
||||
[[nodiscard]] bool is_active() const noexcept { return m_active; }
|
||||
[[nodiscard]] std::string_view name() const noexcept { return m_name; }
|
||||
|
||||
[[nodiscard]] Result<void> release();
|
||||
[[nodiscard]] Result<void> rollback_to();
|
||||
[[nodiscard]] Result<void> rollback_and_release();
|
||||
|
||||
private:
|
||||
friend class Database;
|
||||
Savepoint(std::shared_ptr<detail::ConnectionState> conn,
|
||||
std::string name) noexcept;
|
||||
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
std::string m_name{};
|
||||
bool m_active{false};
|
||||
};
|
||||
|
||||
/// A single forward schema migration applied when the database's
|
||||
@@ -107,10 +245,18 @@ namespace Void::Sqlite
|
||||
std::string_view sql; ///< DDL/DML to reach this version
|
||||
};
|
||||
|
||||
using ScalarFunction =
|
||||
std::function<Result<OwnedValue>(std::span<const ValueView>)>;
|
||||
using AuthorizerCallback = std::function<AuthorizerDecision(
|
||||
int action_code,
|
||||
std::string_view arg1,
|
||||
std::string_view arg2,
|
||||
std::string_view db_name,
|
||||
std::string_view trigger_or_view)>;
|
||||
|
||||
class Database
|
||||
{
|
||||
public:
|
||||
|
||||
Database() = default;
|
||||
~Database();
|
||||
Database(Database&&) noexcept;
|
||||
@@ -119,19 +265,46 @@ namespace Void::Sqlite
|
||||
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.
|
||||
/// in-memory db. Enables checked WAL + FULL + foreign_keys for
|
||||
/// writable file databases.
|
||||
[[nodiscard]] static Result<Database>
|
||||
open(const std::filesystem::path& path,
|
||||
OpenMode mode = OpenMode::ReadWriteCreate);
|
||||
|
||||
/// Open with explicit checked options, limits, and diagnostics.
|
||||
[[nodiscard]] static Result<Database>
|
||||
open_with_options(const std::filesystem::path& path,
|
||||
OpenOptions options);
|
||||
|
||||
/// Execute one or more semicolon-separated statements (no results).
|
||||
Result<void> exec(std::string_view sql);
|
||||
|
||||
/// Prepare a single statement for binding/stepping.
|
||||
/// Prepare a single statement for binding/stepping. Rejects
|
||||
/// non-whitespace trailing SQL and enforces statement/SQL limits.
|
||||
[[nodiscard]] Result<Statement> prepare(std::string_view sql);
|
||||
|
||||
/// Begin a transaction (BEGIN; commit/rollback via the handle).
|
||||
[[nodiscard]] Result<Transaction> begin();
|
||||
/// Begin a transaction. Rejects nested begin() while a transaction
|
||||
/// is already active (use savepoint() for nesting).
|
||||
[[nodiscard]] Result<Transaction> begin(BeginMode mode = BeginMode::Deferred);
|
||||
|
||||
/// Create a named nested savepoint (ASCII identifier only).
|
||||
[[nodiscard]] Result<Savepoint> savepoint(std::string_view name);
|
||||
|
||||
/// Stream all rows from a prepared statement with row & byte caps.
|
||||
[[nodiscard]] Result<std::vector<OwnedRow>> query_all(
|
||||
Statement& stmt,
|
||||
std::size_t max_rows = 0,
|
||||
std::size_t max_bytes = 0);
|
||||
|
||||
/// Explicitly close the connection. Stops admission and returns
|
||||
/// SqliteErrorCode::busy while live statements/transactions/savepoints
|
||||
/// remain open.
|
||||
[[nodiscard]] Result<void> close();
|
||||
|
||||
[[nodiscard]] bool is_open() const noexcept;
|
||||
[[nodiscard]] EffectiveCapabilities capabilities() const;
|
||||
[[nodiscard]] ConnectionHealth health() const;
|
||||
[[nodiscard]] const SqliteLimits& limits() const noexcept;
|
||||
|
||||
[[nodiscard]] std::int64_t last_insert_rowid() const noexcept;
|
||||
[[nodiscard]] int changes() const noexcept;
|
||||
@@ -139,16 +312,63 @@ namespace Void::Sqlite
|
||||
/// 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.
|
||||
/// Validate strictly increasing unique versions before mutation,
|
||||
/// reject unexpected newer schemas, and apply pending migrations.
|
||||
Result<void> migrate(std::span<const Migration> migrations);
|
||||
|
||||
[[nodiscard]] sqlite3* handle() const noexcept { return m_db; }
|
||||
/// Validate migrations, record immutable id & checksum in
|
||||
/// `_void_schema_migrations` in the same transaction as user_version,
|
||||
/// and reject checksum drift or unexpected newer schemas.
|
||||
[[nodiscard]] Result<void>
|
||||
migrate_checked(std::span<const CheckedMigration> migrations);
|
||||
|
||||
/// Run a WAL checkpoint and report completed/remaining frames and busy state.
|
||||
[[nodiscard]] Result<CheckpointReport>
|
||||
checkpoint(CheckpointMode mode = CheckpointMode::Passive);
|
||||
|
||||
/// Copy this database consistently to `destination` via SQLite's backup API.
|
||||
[[nodiscard]] Result<BackupReport>
|
||||
backup_to(const std::filesystem::path& destination,
|
||||
BackupOptions options = {});
|
||||
|
||||
/// Restore this database consistently from `source` via SQLite's backup API.
|
||||
[[nodiscard]] Result<BackupReport>
|
||||
restore_from(const std::filesystem::path& source,
|
||||
BackupOptions options = {});
|
||||
|
||||
/// Register an exception-safe custom scalar SQL function owned by
|
||||
/// this connection's ConnectionState.
|
||||
[[nodiscard]] Result<void> create_scalar_function(
|
||||
std::string name,
|
||||
int num_args,
|
||||
ScalarFunction fn,
|
||||
bool deterministic = true);
|
||||
|
||||
/// Register (or clear when empty) an exception-safe SQLite authorizer.
|
||||
[[nodiscard]] Result<void> set_authorizer(AuthorizerCallback cb);
|
||||
|
||||
/// Expert native handle borrow under caller's execution lease.
|
||||
[[nodiscard]] sqlite3* handle() const noexcept;
|
||||
|
||||
/// Operation-scoped interrupt/progress hooks for leased async execution
|
||||
/// (serialized with end_operation so interrupts never leak across queries).
|
||||
void begin_leased_operation(std::uint64_t generation,
|
||||
int progress_steps,
|
||||
std::function<bool()> should_interrupt);
|
||||
void interrupt_leased_operation(std::uint64_t generation) noexcept;
|
||||
void end_leased_operation(std::uint64_t generation) noexcept;
|
||||
|
||||
private:
|
||||
|
||||
sqlite3* m_db = nullptr;
|
||||
explicit Database(std::shared_ptr<detail::ConnectionState> conn) noexcept;
|
||||
std::shared_ptr<detail::ConnectionState> m_conn{};
|
||||
};
|
||||
|
||||
/// Free-function helper matching roadmap `open_database(path, OpenOptions)`.
|
||||
[[nodiscard]] inline Result<Database> open_database(
|
||||
const std::filesystem::path& path,
|
||||
OpenOptions options = {})
|
||||
{
|
||||
return Database::open_with_options(path, std::move(options));
|
||||
}
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
@@ -0,0 +1,405 @@
|
||||
#pragma once
|
||||
|
||||
#include <Void/Functional/Error.hpp>
|
||||
#include <Void/Functional/Result.hpp>
|
||||
|
||||
#include <chrono>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
#include <functional>
|
||||
#include <optional>
|
||||
#include <span>
|
||||
#include <string>
|
||||
#include <string_view>
|
||||
#include <variant>
|
||||
#include <vector>
|
||||
|
||||
namespace Void::Sqlite
|
||||
{
|
||||
using Void::Result::Error;
|
||||
template <typename T> using Result = Void::Result::Result<T, Error>;
|
||||
|
||||
enum class OpenMode : std::uint8_t {
|
||||
ReadOnly,
|
||||
ReadWrite,
|
||||
ReadWriteCreate
|
||||
};
|
||||
|
||||
enum class JournalMode : std::uint8_t {
|
||||
Wal,
|
||||
Rollback
|
||||
};
|
||||
|
||||
enum class SyncMode : std::uint8_t {
|
||||
Full,
|
||||
Normal
|
||||
};
|
||||
|
||||
enum class BeginMode : std::uint8_t {
|
||||
Deferred,
|
||||
Immediate,
|
||||
Exclusive
|
||||
};
|
||||
|
||||
enum class CheckpointMode : std::uint8_t {
|
||||
Passive,
|
||||
Full,
|
||||
Restart,
|
||||
Truncate
|
||||
};
|
||||
|
||||
enum class TransactionState : std::uint8_t {
|
||||
Active,
|
||||
Committed,
|
||||
RolledBack,
|
||||
RecoveryRequired
|
||||
};
|
||||
|
||||
enum class ColumnType : std::uint8_t {
|
||||
Null = 0,
|
||||
Integer = 1,
|
||||
Real = 2,
|
||||
Text = 3,
|
||||
Blob = 4
|
||||
};
|
||||
|
||||
enum class SqliteErrorCode : std::int32_t {
|
||||
none = 0,
|
||||
invalid_argument = 1,
|
||||
busy = 2,
|
||||
locked = 3,
|
||||
constraint = 4,
|
||||
corrupt = 5,
|
||||
io = 6,
|
||||
readonly = 7,
|
||||
full = 8,
|
||||
misuse = 9,
|
||||
not_found = 10,
|
||||
range = 11,
|
||||
type_mismatch = 12,
|
||||
trailing_sql = 13,
|
||||
statement_limit = 14,
|
||||
size_limit = 15,
|
||||
unsupported_pragma = 16,
|
||||
recovery_required = 17,
|
||||
closed = 18,
|
||||
cancelled = 19,
|
||||
timeout = 20,
|
||||
overloaded = 21,
|
||||
migration_error = 22,
|
||||
backup_error = 23,
|
||||
sqlite_error = 24
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Error make_sqlite_error(
|
||||
SqliteErrorCode code,
|
||||
std::string message,
|
||||
int primary_code = 0,
|
||||
int extended_code = 0)
|
||||
{
|
||||
using Void::Result::ErrorCode;
|
||||
using Void::Result::ErrorKind;
|
||||
|
||||
ErrorKind kind = ErrorKind::internal;
|
||||
switch (code) {
|
||||
case SqliteErrorCode::none:
|
||||
case SqliteErrorCode::sqlite_error:
|
||||
kind = ErrorKind::internal;
|
||||
break;
|
||||
case SqliteErrorCode::invalid_argument:
|
||||
case SqliteErrorCode::misuse:
|
||||
case SqliteErrorCode::range:
|
||||
case SqliteErrorCode::type_mismatch:
|
||||
case SqliteErrorCode::trailing_sql:
|
||||
kind = ErrorKind::invalid_argument;
|
||||
break;
|
||||
case SqliteErrorCode::busy:
|
||||
case SqliteErrorCode::locked:
|
||||
case SqliteErrorCode::constraint:
|
||||
case SqliteErrorCode::recovery_required:
|
||||
case SqliteErrorCode::migration_error:
|
||||
kind = ErrorKind::conflict;
|
||||
break;
|
||||
case SqliteErrorCode::corrupt:
|
||||
kind = ErrorKind::corrupt;
|
||||
break;
|
||||
case SqliteErrorCode::io:
|
||||
case SqliteErrorCode::readonly:
|
||||
case SqliteErrorCode::backup_error:
|
||||
kind = ErrorKind::io;
|
||||
break;
|
||||
case SqliteErrorCode::full:
|
||||
case SqliteErrorCode::statement_limit:
|
||||
case SqliteErrorCode::size_limit:
|
||||
kind = ErrorKind::exhausted;
|
||||
break;
|
||||
case SqliteErrorCode::not_found:
|
||||
kind = ErrorKind::not_found;
|
||||
break;
|
||||
case SqliteErrorCode::unsupported_pragma:
|
||||
kind = ErrorKind::unsupported;
|
||||
break;
|
||||
case SqliteErrorCode::closed:
|
||||
case SqliteErrorCode::cancelled:
|
||||
kind = ErrorKind::cancelled;
|
||||
break;
|
||||
case SqliteErrorCode::timeout:
|
||||
kind = ErrorKind::timeout;
|
||||
break;
|
||||
case SqliteErrorCode::overloaded:
|
||||
kind = ErrorKind::overloaded;
|
||||
break;
|
||||
}
|
||||
|
||||
if (primary_code != 0 || extended_code != 0) {
|
||||
message += " (sqlite rc=";
|
||||
message += std::to_string(primary_code);
|
||||
if (extended_code != 0 && extended_code != primary_code) {
|
||||
message += ", extended=";
|
||||
message += std::to_string(extended_code);
|
||||
}
|
||||
message += ")";
|
||||
}
|
||||
|
||||
return Error{
|
||||
kind,
|
||||
std::move(message),
|
||||
ErrorCode{Void::Result::kSqliteErrorDomain,
|
||||
static_cast<std::int32_t>(code)}};
|
||||
}
|
||||
|
||||
struct SqliteLimits {
|
||||
std::size_t max_live_statements{128};
|
||||
std::size_t max_sql_bytes{1024ULL * 1024ULL};
|
||||
std::size_t max_value_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_query_all_rows{10000};
|
||||
std::size_t max_query_all_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_cached_statements{64};
|
||||
std::size_t max_cache_bytes{8ULL * 1024ULL * 1024ULL};
|
||||
std::chrono::milliseconds busy_timeout{5000};
|
||||
std::uint64_t wal_checkpoint_threshold_bytes{16ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t wal_warn_threshold_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
std::uint64_t wal_stop_writes_threshold_bytes{256ULL * 1024ULL * 1024ULL};
|
||||
std::size_t max_queued_jobs{1024};
|
||||
std::size_t max_pending_input_bytes{64ULL * 1024ULL * 1024ULL};
|
||||
};
|
||||
|
||||
[[nodiscard]] inline Result<void> validate_limits(const SqliteLimits& limits)
|
||||
{
|
||||
if (limits.max_live_statements == 0 ||
|
||||
limits.max_sql_bytes == 0 ||
|
||||
limits.max_value_bytes == 0 ||
|
||||
limits.max_query_all_rows == 0 ||
|
||||
limits.max_query_all_bytes == 0 ||
|
||||
limits.max_cached_statements == 0 ||
|
||||
limits.max_cache_bytes == 0 ||
|
||||
limits.busy_timeout.count() < 0 ||
|
||||
limits.wal_checkpoint_threshold_bytes == 0 ||
|
||||
limits.wal_warn_threshold_bytes == 0 ||
|
||||
limits.wal_stop_writes_threshold_bytes == 0 ||
|
||||
limits.max_queued_jobs == 0 ||
|
||||
limits.max_pending_input_bytes == 0) {
|
||||
return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::invalid_argument,
|
||||
"SqliteLimits must specify positive finite bounds"));
|
||||
}
|
||||
if (limits.wal_checkpoint_threshold_bytes > limits.wal_warn_threshold_bytes ||
|
||||
limits.wal_warn_threshold_bytes > limits.wal_stop_writes_threshold_bytes) {
|
||||
return Void::Result::fail(make_sqlite_error(
|
||||
SqliteErrorCode::invalid_argument,
|
||||
"SqliteLimits WAL thresholds must be non-decreasing"));
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
struct OpenOptions {
|
||||
OpenMode mode{OpenMode::ReadWriteCreate};
|
||||
JournalMode journal_mode{JournalMode::Wal};
|
||||
SyncMode sync_mode{SyncMode::Full};
|
||||
bool foreign_keys{true};
|
||||
bool allow_extension_loading{false};
|
||||
SqliteLimits limits{};
|
||||
std::function<void(std::string_view)> diagnostic_hook{};
|
||||
};
|
||||
|
||||
struct EffectiveCapabilities {
|
||||
std::string sqlite_version{};
|
||||
int sqlite_version_number{0};
|
||||
int threadsafe_mode{0};
|
||||
bool in_memory{false};
|
||||
bool read_only{false};
|
||||
std::string journal_mode{};
|
||||
int synchronous_mode{0};
|
||||
bool foreign_keys{false};
|
||||
bool extension_loading_enabled{false};
|
||||
};
|
||||
|
||||
struct ValueView {
|
||||
using Storage = std::variant<
|
||||
std::nullptr_t,
|
||||
std::int64_t,
|
||||
double,
|
||||
std::string_view,
|
||||
std::span<const std::byte>>;
|
||||
|
||||
Storage value{nullptr};
|
||||
|
||||
constexpr ValueView() noexcept = default;
|
||||
constexpr ValueView(std::nullptr_t) noexcept : value(nullptr) {}
|
||||
constexpr ValueView(std::int64_t v) noexcept : value(v) {}
|
||||
constexpr ValueView(int v) noexcept : value(static_cast<std::int64_t>(v)) {}
|
||||
constexpr ValueView(double v) noexcept : value(v) {}
|
||||
constexpr ValueView(std::string_view v) noexcept : value(v) {}
|
||||
ValueView(const std::string& v) noexcept : value(std::string_view{v}) {}
|
||||
constexpr ValueView(const char* v) noexcept
|
||||
: value(v ? Storage{std::string_view{v}} : Storage{nullptr}) {}
|
||||
constexpr ValueView(std::span<const std::byte> v) noexcept : value(v) {}
|
||||
|
||||
[[nodiscard]] constexpr ColumnType type() const noexcept
|
||||
{
|
||||
switch (value.index()) {
|
||||
case 0: return ColumnType::Null;
|
||||
case 1: return ColumnType::Integer;
|
||||
case 2: return ColumnType::Real;
|
||||
case 3: return ColumnType::Text;
|
||||
case 4: return ColumnType::Blob;
|
||||
default: return ColumnType::Null;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] constexpr bool is_null() const noexcept
|
||||
{
|
||||
return std::holds_alternative<std::nullptr_t>(value);
|
||||
}
|
||||
};
|
||||
|
||||
struct OwnedValue {
|
||||
using Storage = std::variant<
|
||||
std::nullptr_t,
|
||||
std::int64_t,
|
||||
double,
|
||||
std::string,
|
||||
std::vector<std::byte>>;
|
||||
|
||||
Storage value{nullptr};
|
||||
|
||||
OwnedValue() noexcept = default;
|
||||
OwnedValue(std::nullptr_t) noexcept : value(nullptr) {}
|
||||
OwnedValue(std::int64_t v) noexcept : value(v) {}
|
||||
OwnedValue(double v) noexcept : value(v) {}
|
||||
OwnedValue(std::string v) noexcept : value(std::move(v)) {}
|
||||
OwnedValue(std::vector<std::byte> v) noexcept : value(std::move(v)) {}
|
||||
|
||||
[[nodiscard]] ColumnType type() const noexcept
|
||||
{
|
||||
switch (value.index()) {
|
||||
case 0: return ColumnType::Null;
|
||||
case 1: return ColumnType::Integer;
|
||||
case 2: return ColumnType::Real;
|
||||
case 3: return ColumnType::Text;
|
||||
case 4: return ColumnType::Blob;
|
||||
default: return ColumnType::Null;
|
||||
}
|
||||
}
|
||||
|
||||
[[nodiscard]] bool is_null() const noexcept
|
||||
{
|
||||
return std::holds_alternative<std::nullptr_t>(value);
|
||||
}
|
||||
|
||||
[[nodiscard]] ValueView as_view() const noexcept
|
||||
{
|
||||
if (const auto* i = std::get_if<std::int64_t>(&value)) return ValueView{*i};
|
||||
if (const auto* d = std::get_if<double>(&value)) return ValueView{*d};
|
||||
if (const auto* s = std::get_if<std::string>(&value)) return ValueView{std::string_view{*s}};
|
||||
if (const auto* b = std::get_if<std::vector<std::byte>>(&value)) {
|
||||
return ValueView{std::span<const std::byte>{b->data(), b->size()}};
|
||||
}
|
||||
return ValueView{nullptr};
|
||||
}
|
||||
|
||||
[[nodiscard]] bool operator==(const OwnedValue&) const = default;
|
||||
};
|
||||
|
||||
struct OwnedRow {
|
||||
std::vector<OwnedValue> columns{};
|
||||
|
||||
[[nodiscard]] std::size_t size() const noexcept { return columns.size(); }
|
||||
[[nodiscard]] bool empty() const noexcept { return columns.empty(); }
|
||||
[[nodiscard]] const OwnedValue& operator[](std::size_t idx) const noexcept
|
||||
{
|
||||
return columns[idx];
|
||||
}
|
||||
};
|
||||
|
||||
struct CheckpointReport {
|
||||
int log_frames{0};
|
||||
int checkpointed_frames{0};
|
||||
bool busy{false};
|
||||
std::uint64_t wal_size_bytes{0};
|
||||
};
|
||||
|
||||
struct BackupOptions {
|
||||
int pages_per_step{64};
|
||||
int max_steps{1000000};
|
||||
std::chrono::milliseconds step_sleep{0};
|
||||
};
|
||||
|
||||
struct BackupReport {
|
||||
int total_pages{0};
|
||||
int remaining_pages{0};
|
||||
int steps{0};
|
||||
};
|
||||
|
||||
/// Immutable schema migration with explicit identity & checksum verification.
|
||||
struct CheckedMigration {
|
||||
int version{0};
|
||||
std::string_view id{};
|
||||
std::string_view checksum{};
|
||||
std::string_view sql{};
|
||||
};
|
||||
|
||||
struct ConnectionHealth {
|
||||
std::size_t live_statements{0};
|
||||
bool active_transaction{false};
|
||||
std::size_t open_savepoints{0};
|
||||
std::uint64_t wal_size_bytes{0};
|
||||
bool wal_checkpoint_recommended{false};
|
||||
bool wal_warn_exceeded{false};
|
||||
bool wal_write_admission_blocked{false};
|
||||
};
|
||||
|
||||
enum class AuthorizerDecision : std::uint8_t {
|
||||
Allow,
|
||||
Deny,
|
||||
Ignore
|
||||
};
|
||||
|
||||
struct FaultConfig {
|
||||
/// If non-zero, next COMMIT returns this SQLite error code without
|
||||
/// calling SQLite COMMIT (leaving transaction active so autocommit==0).
|
||||
int fail_next_commit_rc{0};
|
||||
/// If true along with fail_next_commit_rc, simulates SQLite
|
||||
/// auto-rollback before returning the error.
|
||||
bool auto_rollback_on_faulted_commit{false};
|
||||
/// If non-zero, next explicit close() returns this SQLite error code.
|
||||
int fail_next_close_rc{0};
|
||||
};
|
||||
|
||||
/// Process-local RAII guard for deterministic fault injection in tests.
|
||||
class ScopedFaultGuard
|
||||
{
|
||||
public:
|
||||
explicit ScopedFaultGuard(FaultConfig cfg) noexcept;
|
||||
~ScopedFaultGuard();
|
||||
|
||||
ScopedFaultGuard(const ScopedFaultGuard&) = delete;
|
||||
ScopedFaultGuard& operator=(const ScopedFaultGuard&) = delete;
|
||||
|
||||
[[nodiscard]] static FaultConfig current() noexcept;
|
||||
|
||||
private:
|
||||
FaultConfig prev_{};
|
||||
};
|
||||
|
||||
} // namespace Void::Sqlite
|
||||
Reference in new issue
Block a user