#pragma once #include #include #include #include #include #include #include #include #include #include #include #include #include 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 column_type(int col) const; [[nodiscard]] Result is_null(int col) const; [[nodiscard]] Result get_int(int col) const; [[nodiscard]] Result get_double(int col) const; [[nodiscard]] Result get_text_view(int col) const; [[nodiscard]] Result get_text(int col) const; [[nodiscard]] Result> get_blob_view(int col) const; [[nodiscard]] Result> get_blob(int col) const; [[nodiscard]] Result> get_optional_int(int col) const; [[nodiscard]] Result> get_optional_double(int col) const; [[nodiscard]] Result> get_optional_text(int col) const; [[nodiscard]] Result>> get_optional_blob(int col) const; [[nodiscard]] Result get_value(int col) const; [[nodiscard]] Result 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(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). 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& value); /// Error captured by the most recent legacy unchecked bind() call, if any. [[nodiscard]] const std::optional& last_bind_error() const noexcept { return m_last_bind_error; } // ── Checked bind / parameter metadata ──────────────────────────── [[nodiscard]] int bind_parameter_count() const noexcept; [[nodiscard]] Result bind_parameter_index(std::string_view name) const; [[nodiscard]] Result bind_checked(int index, ValueView value); [[nodiscard]] Result 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 bind_borrowed_text( int index, std::string_view value, std::shared_ptr owner); [[nodiscard]] Result bind_borrowed_blob( int index, std::span value, std::shared_ptr 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 step(); /// Reset for re-execution (keeps bindings unless clear_bindings). void reset() noexcept; [[nodiscard]] Result reset_checked(); void clear_bindings() noexcept; [[nodiscard]] Result clear_bindings_checked(); /// Explicitly finalize the statement and report any native error. [[nodiscard]] Result 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 current_row() const; [[nodiscard]] Result copy_row() const; [[nodiscard]] Result column_type(int col) const; [[nodiscard]] Result try_column_int(int col) const; [[nodiscard]] Result try_column_double(int col) const; [[nodiscard]] Result try_column_text_view(int col) const; [[nodiscard]] Result try_column_text(int col) const; [[nodiscard]] Result> try_column_blob_view(int col) const; [[nodiscard]] Result> try_column_blob(int col) const; [[nodiscard]] Result> try_column_optional_int(int col) const; [[nodiscard]] Result> try_column_optional_double(int col) const; [[nodiscard]] Result> try_column_optional_text(int col) const; [[nodiscard]] Result>> try_column_optional_blob(int col) const; [[nodiscard]] Result try_column_value(int col) const; private: friend class Database; friend class RowView; Statement(std::shared_ptr conn, sqlite3_stmt* stmt) noexcept; void release_handle() noexcept; [[nodiscard]] Result validate_column_access(int col) const; std::shared_ptr m_conn{}; sqlite3_stmt* m_stmt{nullptr}; bool m_has_row{false}; std::uint64_t m_row_generation{0}; std::vector> m_borrowed_owners{}; std::optional 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. 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; Result commit(); [[nodiscard]] Result rollback_checked(); void rollback() noexcept; private: friend class Database; explicit Transaction(std::shared_ptr conn, std::uint64_t id) noexcept; void refresh_state() const noexcept; std::shared_ptr 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 release(); [[nodiscard]] Result rollback_to(); [[nodiscard]] Result rollback_and_release(); private: friend class Database; Savepoint(std::shared_ptr conn, std::string name) noexcept; std::shared_ptr m_conn{}; std::string m_name{}; 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(std::span)>; using AuthorizerCallback = std::function; 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 open(const std::filesystem::path& path, OpenMode mode = OpenMode::ReadWriteCreate); /// Open with explicit checked options, limits, and diagnostics. [[nodiscard]] static Result open_with_options(const std::filesystem::path& path, OpenOptions options); /// Execute one or more semicolon-separated statements (no results). Result exec(std::string_view sql); /// Prepare a single statement for binding/stepping. Rejects /// non-whitespace trailing SQL and enforces statement/SQL limits. [[nodiscard]] Result prepare(std::string_view sql); /// Begin a transaction. Rejects nested begin() while a transaction /// is already active (use savepoint() for nesting). [[nodiscard]] Result begin(BeginMode mode = BeginMode::Deferred); /// Create a named nested savepoint (ASCII identifier only). [[nodiscard]] Result savepoint(std::string_view name); /// Stream all rows from a prepared statement with row & byte caps. [[nodiscard]] Result> 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 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 user_version(); /// Validate strictly increasing unique versions before mutation, /// reject unexpected newer schemas, and apply pending migrations. Result migrate(std::span 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 migrate_checked(std::span migrations); /// Run a WAL checkpoint and report completed/remaining frames and busy state. [[nodiscard]] Result checkpoint(CheckpointMode mode = CheckpointMode::Passive); /// Copy this database consistently to `destination` via SQLite's backup API. [[nodiscard]] Result backup_to(const std::filesystem::path& destination, BackupOptions options = {}); /// Restore this database consistently from `source` via SQLite's backup API. [[nodiscard]] Result 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 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 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 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 conn) noexcept; std::shared_ptr m_conn{}; }; /// Free-function helper matching roadmap `open_database(path, OpenOptions)`. [[nodiscard]] inline Result open_database( const std::filesystem::path& path, OpenOptions options = {}) { return Database::open_with_options(path, std::move(options)); } } // namespace Void::Sqlite