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
+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
|
||||
Reference in new issue
Block a user