Files
Library/include/Void/Sqlite/Sqlite.hpp
T

425 lines
16 KiB
C++

#pragma once
#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 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
{
namespace detail
{
struct ConnectionState;
} // namespace detail
class Database;
class Statement;
class Transaction;
class Savepoint;
/// 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;
Statement& operator=(Statement&&) noexcept;
Statement(const Statement&) = delete;
Statement& operator=(const Statement&) = delete;
// ── Legacy 1.x chainable bind methods (1-based) ──────────────────
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);
// Disambiguates std::string args (which otherwise match both
// string_view and optional<string>).
Statement& bind(int index, const std::string& value)
{
return bind(index, std::string_view{value});
}
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;
[[nodiscard]] Result<void> reset_checked();
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;
// ── 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;
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 retaining shared ConnectionState. Never marks Committed
/// before COMMIT succeeds; inspects sqlite3_get_autocommit on error and after
/// statements so an automatic rollback is reported as RolledBack. A failed
/// COMMIT whose outcome cannot be proven (WAL I/O error) is reported as
/// Unknown, never as RolledBack.
class Transaction
{
public:
Transaction() noexcept = default;
~Transaction();
Transaction(Transaction&&) noexcept;
Transaction& operator=(Transaction&&) noexcept;
Transaction(const Transaction&) = delete;
Transaction& operator=(const Transaction&) = delete;
/// Observes the native autocommit state; returns RolledBack when SQLite
/// already ended this transaction (for example SQLITE_FULL or an
/// interrupt inside the transaction).
[[nodiscard]] TransactionState state() const noexcept;
[[nodiscard]] bool is_active() const noexcept;
/// Commits the transaction. On failure state() is Active (SQLite kept
/// the transaction open; retry or roll back), RolledBack (SQLite ended
/// it and it was not committed), or Unknown (SQLite ended it but a WAL
/// I/O error means the commit may have taken effect).
Result<void> commit();
[[nodiscard]] Result<void> rollback_checked();
void rollback() noexcept;
private:
friend class Database;
explicit Transaction(std::shared_ptr<detail::ConnectionState> conn,
std::uint64_t id) noexcept;
void refresh_state() const noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
std::uint64_t m_id{0};
mutable 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};
};
/// Scoped per-call override of the connection busy timeout.
///
/// The previous timeout is restored when this object is destroyed (or
/// explicitly via restore()), so a single statement or transaction can use
/// a tighter or looser bound without permanently changing the connection.
class BusyTimeoutOverride
{
public:
BusyTimeoutOverride() noexcept = default;
~BusyTimeoutOverride();
BusyTimeoutOverride(BusyTimeoutOverride&&) noexcept;
BusyTimeoutOverride& operator=(BusyTimeoutOverride&&) noexcept;
BusyTimeoutOverride(const BusyTimeoutOverride&) = delete;
BusyTimeoutOverride& operator=(const BusyTimeoutOverride&) = delete;
[[nodiscard]] bool is_active() const noexcept { return m_active; }
[[nodiscard]] std::chrono::milliseconds previous() const noexcept
{
return m_previous;
}
/// Restore the previous timeout early. Idempotent.
void restore() noexcept;
private:
friend class Database;
BusyTimeoutOverride(std::shared_ptr<detail::ConnectionState> conn,
std::chrono::milliseconds previous) noexcept;
std::shared_ptr<detail::ConnectionState> m_conn{};
std::chrono::milliseconds m_previous{0};
bool m_active{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
};
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;
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 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. Rejects
/// non-whitespace trailing SQL and enforces statement/SQL limits.
[[nodiscard]] Result<Statement> prepare(std::string_view sql);
/// 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);
/// Temporarily override the connection busy timeout for the next
/// calls. The previous value is restored when the returned scope is
/// destroyed. A negative timeout is rejected.
[[nodiscard]] Result<BusyTimeoutOverride>
override_busy_timeout(std::chrono::milliseconds timeout);
/// 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;
/// Current schema version (PRAGMA user_version).
[[nodiscard]] Result<int> user_version();
/// Validate strictly increasing unique versions before mutation,
/// reject unexpected newer schemas, and apply pending migrations.
Result<void> migrate(std::span<const Migration> migrations);
/// 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:
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