feat(sqlite): harden Sqlite lifecycle/transactions/migrations/ops and add SqliteAsync pool

This commit is contained in:
faumaray committed 2026-11-26 15:17:59 +03:00
1 parent 9925ea1764
commit 427cc9a843
15 files changed
+4438 -134

No files matched your search

+179
View File
@@ -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
View File
@@ -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
+405
View File
@@ -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
+2329 -100
View File
File diff suppressed because it is too large. Load diff
+2 -1
View File
@@ -1,4 +1,5 @@
void_add_module(Sqlite
INTERNAL_DEPS Functional
INTERNAL_DEPS Functional Time
EXTERNAL_DEPS SQLite3::SQLite3
EXCLUDE_HEADERS Void/Sqlite/AsyncPool.hpp
)
+461
View File
@@ -0,0 +1,461 @@
#include <Void/Sqlite/AsyncPool.hpp>
#include <atomic>
#include <condition_variable>
#include <deque>
#include <memory>
#include <mutex>
#include <stop_token>
#include <thread>
#include <utility>
#include <vector>
namespace Void::Sqlite
{
struct AsyncPool::Impl : public std::enable_shared_from_this<Impl> {
struct Job {
std::shared_ptr<Void::Async::OperationState<void>> op_state{};
std::function<Result<void>(Database&)> fn{};
std::size_t input_bytes{0};
std::uint64_t generation{0};
};
explicit Impl(AsyncPoolOptions opts, Void::Async::Executor* exec)
: options(std::move(opts)),
clock(options.clock ? options.clock
: &Void::Time::SystemMonotonicClock::instance()),
completion_executor(exec)
{
}
~Impl()
{
(void)close_and_join();
}
Result<void> start()
{
if (options.path.empty()) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: database path must not be empty"));
}
if (options.reader_connections > 0 &&
(options.path == ":memory:" ||
options.path.string().starts_with("file::memory:"))) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: multi-connection pool does not support private :memory: paths"));
}
if (options.max_queued_jobs == 0 || options.max_pending_input_bytes == 0) {
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: max_queued_jobs and max_pending_input_bytes must be positive"));
}
if (auto v = validate_limits(options.open_options.limits); !v) {
return v;
}
// Open writer first so the file and WAL mode are initialized before
// read-only connections open.
OpenOptions writer_opts = options.open_options;
if (writer_opts.mode == OpenMode::ReadOnly) {
writer_opts.mode = OpenMode::ReadWriteCreate;
}
auto wdb = Database::open_with_options(options.path, std::move(writer_opts));
if (!wdb) {
return Void::Result::fail(std::move(wdb).error());
}
writer_db = std::move(*wdb);
readers.reserve(options.reader_connections);
for (std::size_t i = 0; i < options.reader_connections; ++i) {
OpenOptions ropts = options.open_options;
ropts.mode = OpenMode::ReadOnly;
auto rdb = Database::open_with_options(options.path, std::move(ropts));
if (!rdb) {
(void)writer_db.close();
for (auto& existing : readers) {
(void)existing.close();
}
readers.clear();
return Void::Result::fail(std::move(rdb).error());
}
readers.push_back(std::move(*rdb));
}
writer_thread = std::thread([this]() { run_writer_loop(); });
reader_threads.reserve(readers.size());
for (std::size_t i = 0; i < readers.size(); ++i) {
reader_threads.emplace_back([this, i]() { run_reader_loop(i); });
}
return {};
}
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)
{
if (!fn) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::invalid_argument,
"AsyncPool: null work callback"));
}
if (is_write == false && readers.empty()) {
// Route read to writer lane when configured with 0 readers.
is_write = true;
}
if (op.stop.stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before admission"));
}
if (op.deadline.has_value() && clock->now() >= *op.deadline) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before admission"));
}
auto state = Void::Async::OperationState<void>::create(
op, completion_executor, Void::Async::StopBehavior::notify_only);
Job job;
job.op_state = state;
job.fn = std::move(fn);
job.input_bytes = input_bytes;
{
std::lock_guard lk{mu};
if (closing || closed) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed,
"AsyncPool: pool is closing"));
}
const std::size_t total_queued = write_queue.size() + read_queue.size();
if (total_queued >= options.max_queued_jobs ||
input_bytes > options.max_pending_input_bytes ||
pending_input_bytes > options.max_pending_input_bytes - input_bytes) {
rejected_jobs.fetch_add(1, std::memory_order_relaxed);
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::overloaded,
"AsyncPool: queue depth or pending input byte budget exceeded"));
}
job.generation = ++next_generation;
pending_input_bytes += input_bytes;
state->acquire_backend_ref();
if (is_write) {
write_queue.push_back(std::move(job));
} else {
read_queue.push_back(std::move(job));
}
}
if (is_write) {
write_cv.notify_one();
} else {
read_cv.notify_one();
}
auto res = co_await state->awaitable(completion_executor);
co_return res;
}
void execute_job(Database& db, Job& job)
{
auto& state = job.op_state;
if (state->stop_requested()) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::cancelled,
"AsyncPool: operation cancelled before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
if (state->is_deadline_expired(*clock)) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
if (auto t = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation deadline expired before execution"));
t) {
t->dispatch();
}
state->release_backend_ref_and_dispatch();
return;
}
const auto gen = job.generation;
const int steps = std::max(1, options.progress_handler_steps);
db.begin_leased_operation(
gen,
steps,
[state, clk = this->clock]() {
return state->stop_requested() || state->is_deadline_expired(*clk);
});
struct StopInterrupter {
Database* target_db{nullptr};
std::uint64_t target_gen{0};
void operator()() const noexcept
{
if (target_db != nullptr) {
target_db->interrupt_leased_operation(target_gen);
}
}
};
// Registered before job.fn runs and destroyed BEFORE end_leased_operation,
// so stop callbacks never race with subsequent borrowers.
Result<void> exec_result;
{
std::optional<std::stop_callback<StopInterrupter>> stop_cb;
const auto st = state->stop_token();
if (st.stop_possible()) {
stop_cb.emplace(st, StopInterrupter{&db, gen});
}
exec_result = job.fn(db);
}
db.end_leased_operation(gen);
std::optional<Void::Async::ResumeTicket> ticket;
if (exec_result) {
completed_jobs.fetch_add(1, std::memory_order_relaxed);
ticket = state->try_commit_value();
} else {
const auto kind = exec_result.error().kind();
if (kind == Void::Result::ErrorKind::cancelled ||
kind == Void::Result::ErrorKind::timeout) {
cancelled_jobs.fetch_add(1, std::memory_order_relaxed);
}
// Reclassify SQLITE_INTERRUPT when caused by deadline expiry.
if (kind == Void::Result::ErrorKind::cancelled &&
!state->stop_requested() &&
state->is_deadline_expired(*clock)) {
ticket = state->try_commit_error(make_sqlite_error(
SqliteErrorCode::timeout,
"AsyncPool: operation interrupted due to deadline expiry"));
} else {
ticket = state->try_commit_error(std::move(exec_result).error());
}
}
if (ticket) {
ticket->dispatch();
}
state->release_backend_ref_and_dispatch();
}
void run_writer_loop()
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
write_cv.wait(lk, [this]() {
return !write_queue.empty() || closing;
});
if (write_queue.empty() && closing) {
return;
}
job = std::move(write_queue.front());
write_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_write_jobs;
}
execute_job(writer_db, job);
{
std::lock_guard lk{mu};
--active_write_jobs;
}
}
}
void run_reader_loop(std::size_t idx)
{
for (;;) {
Job job;
{
std::unique_lock lk{mu};
read_cv.wait(lk, [this]() {
return !read_queue.empty() || closing;
});
if (read_queue.empty() && closing) {
return;
}
job = std::move(read_queue.front());
read_queue.pop_front();
pending_input_bytes -= job.input_bytes;
++active_read_jobs;
}
execute_job(readers[idx], job);
{
std::lock_guard lk{mu};
--active_read_jobs;
}
}
}
Result<void> close_and_join()
{
{
std::lock_guard lk{mu};
if (closed) {
return {};
}
closing = true;
}
write_cv.notify_all();
read_cv.notify_all();
if (writer_thread.joinable()) {
writer_thread.join();
}
for (auto& t : reader_threads) {
if (t.joinable()) {
t.join();
}
}
reader_threads.clear();
std::optional<Error> first_err;
if (writer_db.is_open()) {
if (auto r = writer_db.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
for (auto& rdb : readers) {
if (rdb.is_open()) {
if (auto r = rdb.close(); !r && !first_err) {
first_err = std::move(r).error();
}
}
}
readers.clear();
{
std::lock_guard lk{mu};
closed = true;
}
if (first_err) {
return Void::Result::fail(std::move(*first_err));
}
return {};
}
AsyncPoolOptions options;
const Void::Time::MonotonicClock* clock;
Void::Async::Executor* completion_executor{nullptr};
Database writer_db{};
std::vector<Database> readers{};
mutable std::mutex mu{};
std::condition_variable write_cv{};
std::condition_variable read_cv{};
std::deque<Job> write_queue{};
std::deque<Job> read_queue{};
std::size_t pending_input_bytes{0};
std::size_t active_read_jobs{0};
std::size_t active_write_jobs{0};
std::uint64_t next_generation{0};
bool closing{false};
bool closed{false};
std::atomic<std::uint64_t> completed_jobs{0};
std::atomic<std::uint64_t> rejected_jobs{0};
std::atomic<std::uint64_t> cancelled_jobs{0};
std::thread writer_thread{};
std::vector<std::thread> reader_threads{};
};
AsyncPool::AsyncPool(std::shared_ptr<Impl> impl) noexcept
: m_impl(std::move(impl))
{
}
AsyncPool::~AsyncPool()
{
if (m_impl) {
(void)m_impl->close_and_join();
}
}
AsyncPool::AsyncPool(AsyncPool&&) noexcept = default;
AsyncPool& AsyncPool::operator=(AsyncPool&&) noexcept = default;
Result<AsyncPool> AsyncPool::open(
AsyncPoolOptions options,
Void::Async::Executor* completion_executor)
{
auto impl = std::make_shared<Impl>(std::move(options), completion_executor);
if (auto r = impl->start(); !r) {
return Void::Result::fail(std::move(r).error());
}
return AsyncPool{std::move(impl)};
}
Void::Coro::Task<Result<void>> AsyncPool::submit_erased(
bool is_write,
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
if (!m_impl) {
co_return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::closed, "AsyncPool: moved-from pool"));
}
co_return co_await m_impl->submit_erased(
is_write, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_read_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(false, std::move(fn), std::move(op), input_bytes);
}
Void::Coro::Task<Result<void>> AsyncPool::run_write_void(
std::function<Result<void>(Database&)> fn,
Void::Async::OperationOptions op,
std::size_t input_bytes)
{
co_return co_await submit_erased(true, std::move(fn), std::move(op), input_bytes);
}
AsyncPoolStats AsyncPool::stats() const noexcept
{
AsyncPoolStats out;
if (!m_impl) return out;
std::lock_guard lk{m_impl->mu};
out.reader_connections = m_impl->readers.size();
out.queued_read_jobs = m_impl->read_queue.size();
out.queued_write_jobs = m_impl->write_queue.size();
out.active_read_jobs = m_impl->active_read_jobs;
out.active_write_jobs = m_impl->active_write_jobs;
out.pending_input_bytes = m_impl->pending_input_bytes;
out.completed_jobs = m_impl->completed_jobs.load(std::memory_order_relaxed);
out.rejected_jobs = m_impl->rejected_jobs.load(std::memory_order_relaxed);
out.cancelled_jobs = m_impl->cancelled_jobs.load(std::memory_order_relaxed);
return out;
}
Result<void> AsyncPool::close_and_join()
{
if (!m_impl) return {};
return m_impl->close_and_join();
}
} // namespace Void::Sqlite
+4
View File
@@ -0,0 +1,4 @@
void_add_module(SqliteAsync
INTERNAL_DEPS Sqlite Async Time Functional
EXTRA_HEADERS Void/Sqlite/AsyncPool.hpp
)
+3
View File
@@ -133,6 +133,9 @@ if(_all_generated)
if(TARGET OpenSSL::Crypto)
target_link_libraries(VoidTests PRIVATE OpenSSL::Crypto)
endif()
if(TARGET SQLite3::SQLite3)
target_link_libraries(VoidTests PRIVATE SQLite3::SQLite3)
endif()
add_test(NAME VoidTests COMMAND VoidTests)
+18
View File
@@ -214,6 +214,24 @@ if(_has_update)
-DCMAKE_DISABLE_FIND_PACKAGE_SQLite3=TRUE)
endif()
has_modules(_has_sqlite Sqlite Functional Time)
if(_has_sqlite)
run_consumer(SqliteOnly "${install_prefix}" "SqliteOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE)
endif()
has_modules(_has_sqlite_async SqliteAsync Sqlite Async Time Functional LogState)
if(_has_sqlite_async)
run_consumer(SqliteAsyncOnly "${install_prefix}" "SqliteAsyncOnly"
-DCMAKE_DISABLE_FIND_PACKAGE_Boost=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_LibArchive=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_OpenSSL=TRUE
-DCMAKE_DISABLE_FIND_PACKAGE_PkgConfig=TRUE)
endif()
# Foundation consumer with Core-formatting bridge and zero external packages.
has_modules(_has_foundation Math Text Time Functional Binary FunctionalCoreFormatting Memory Core)
if(_has_foundation)
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidSqliteAsyncOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS SqliteAsync)
add_executable(void_sqlite_async_only_consumer main.cpp)
target_link_libraries(void_sqlite_async_only_consumer PRIVATE Void::SqliteAsync)
target_compile_features(void_sqlite_async_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME SqliteAsyncOnlyConsumer COMMAND void_sqlite_async_only_consumer)
+24
View File
@@ -0,0 +1,24 @@
#include <Void/Sqlite/AsyncPool.hpp>
#include <atomic>
#include <filesystem>
#include <string>
#include <unistd.h>
int main()
{
const auto dir = std::filesystem::temp_directory_path() /
("void-sqlite-async-pkg-" + std::to_string(::getpid()));
std::error_code ec;
std::filesystem::remove_all(dir, ec);
std::filesystem::create_directories(dir, ec);
Void::Sqlite::AsyncPoolOptions opts;
opts.path = dir / "pkg.db";
opts.reader_connections = 2;
auto pool = Void::Sqlite::AsyncPool::open(opts);
const bool ok = pool.has_value() && pool->stats().reader_connections == 2 &&
pool->close_and_join().has_value();
std::filesystem::remove_all(dir, ec);
return ok ? 0 : 1;
}
+11
View File
@@ -0,0 +1,11 @@
cmake_minimum_required(VERSION 4.0)
project(VoidSqliteOnlyConsumer LANGUAGES CXX)
find_package(Void CONFIG REQUIRED COMPONENTS Sqlite)
add_executable(void_sqlite_only_consumer main.cpp)
target_link_libraries(void_sqlite_only_consumer PRIVATE Void::Sqlite)
target_compile_features(void_sqlite_only_consumer PRIVATE cxx_std_26)
enable_testing()
add_test(NAME SqliteOnlyConsumer COMMAND void_sqlite_only_consumer)
+19
View File
@@ -0,0 +1,19 @@
#include <Void/Sqlite/Sqlite.hpp>
int main()
{
Void::Sqlite::OpenOptions opts;
auto db = Void::Sqlite::open_database(":memory:", opts);
if (!db) return 1;
if (!db->exec("CREATE TABLE t(id INTEGER PRIMARY KEY)").has_value()) return 2;
auto tx = db->begin(Void::Sqlite::BeginMode::Immediate);
if (!tx) return 3;
auto st = db->prepare("INSERT INTO t(id) VALUES(?)");
if (!st) return 4;
if (!st->bind_checked(1, Void::Sqlite::ValueView{7}).has_value()) return 5;
if (!st->step().has_value()) return 6;
if (!st->finalize_checked().has_value()) return 7;
if (!tx->commit().has_value()) return 8;
if (!db->close().has_value()) return 9;
return 0;
}
+469
View File
@@ -0,0 +1,469 @@
#include <Void/Sqlite/Sqlite.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <sqlite3.h>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <limits>
#include <memory>
#include <stdexcept>
#include <string>
#include <thread>
#include <unistd.h>
#include <vector>
namespace
{
using namespace Void::Sqlite;
struct TempSqliteDir {
std::filesystem::path path;
TempSqliteDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-sqlite-test-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempSqliteDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Testing::Test sqlite_connection_state_lifetime_close_and_statement_limits()
{
TempSqliteDir dir;
const auto db_path = dir.path / "state.db";
std::vector<std::string> diagnostics;
OpenOptions opts;
opts.journal_mode = JournalMode::Wal;
opts.sync_mode = SyncMode::Full;
opts.foreign_keys = true;
opts.limits.max_live_statements = 2;
opts.limits.max_sql_bytes = 256;
opts.limits.max_value_bytes = 64;
opts.diagnostic_hook = [&](std::string_view msg) { diagnostics.emplace_back(msg); };
auto db_res = open_database(db_path, opts);
Void::Testing::require(db_res.has_value());
auto db = std::move(*db_res);
const auto caps = db.capabilities();
Void::Testing::expect(!caps.in_memory);
Void::Testing::expect(!caps.read_only);
Void::Testing::expect_eq(caps.journal_mode, std::string{"wal"});
Void::Testing::expect_eq(caps.synchronous_mode, 2);
Void::Testing::expect(caps.foreign_keys);
Void::Testing::expect(!caps.extension_loading_enabled);
// load_extension is disabled by default.
Void::Testing::expect(!db.exec("SELECT load_extension('nonexistent')").has_value());
Void::Testing::require(db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, val TEXT)").has_value());
// Prepare rejects trailing SQL and SQL exceeding max_sql_bytes.
auto trailing = db.prepare("SELECT 1; SELECT 2");
Void::Testing::expect(!trailing.has_value());
Void::Testing::expect(trailing.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::trailing_sql));
const std::string too_long_sql(300, ' ');
auto oversized = db.prepare("SELECT 1" + too_long_sql);
Void::Testing::expect(!oversized.has_value());
Void::Testing::expect(oversized.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
// Move Database and destroy original while Transaction + Statement remain alive!
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
auto s1 = db.prepare("INSERT INTO t(id, val) VALUES(?, ?)");
Void::Testing::require(s1.has_value());
// Statement limit enforcement.
auto s2 = db.prepare("SELECT COUNT(*) FROM t");
Void::Testing::require(s2.has_value());
auto s3 = db.prepare("SELECT 1");
Void::Testing::expect(!s3.has_value());
Void::Testing::expect(s3.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::statement_limit));
Database moved_db{std::move(db)};
// Old moved-from handle has no connection; new handle owns it, and close()
// refuses while s1, s2, tx are live!
auto busy_close = moved_db.close();
Void::Testing::expect(!busy_close.has_value());
Void::Testing::expect(busy_close.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::require(s1->bind_checked(1, ValueView{42}).has_value());
Void::Testing::require(s1->bind_checked(2, ValueView{"survived_move"}).has_value());
Void::Testing::require(s1->step().has_value());
Void::Testing::require(s1->finalize_checked().has_value());
Void::Testing::require(s2->finalize_checked().has_value());
Void::Testing::require(tx->commit().has_value());
Void::Testing::expect(tx->state() == TransactionState::Committed);
// Injected close error test, followed by real clean close.
{
ScopedFaultGuard guard{FaultConfig{.fail_next_close_rc = SQLITE_IOERR}};
auto fail_close = moved_db.close();
Void::Testing::expect(!fail_close.has_value());
Void::Testing::expect(fail_close.error().kind() == Void::Result::ErrorKind::io);
}
Void::Testing::require(moved_db.close().has_value());
Void::Testing::expect(!moved_db.is_open());
// Reopen to confirm persistence on disk after move + commit.
auto reopened = open_database(db_path, opts);
Void::Testing::require(reopened.has_value());
auto sel = reopened->prepare("SELECT val FROM t WHERE id=42");
Void::Testing::require(sel.has_value());
auto has = sel->step();
Void::Testing::require(has.has_value() && *has);
Void::Testing::expect_eq(*sel->try_column_text(0), std::string{"survived_move"});
}
Void::Testing::Test sqlite_checked_binds_borrowed_owners_typed_rows_and_query_all()
{
OpenOptions opts;
opts.limits.max_value_bytes = 32;
opts.limits.max_query_all_rows = 3;
auto db_res = open_database(":memory:", opts);
Void::Testing::require(db_res.has_value());
auto& db = *db_res;
Void::Testing::require(
db.exec("CREATE TABLE items(id INTEGER, r REAL, txt TEXT, bin BLOB)").has_value());
auto ins = db.prepare(
"INSERT INTO items(id, r, txt, bin) VALUES(:id, :r, :txt, :bin)");
Void::Testing::require(ins.has_value());
Void::Testing::expect_eq(ins->bind_parameter_count(), 4);
// Out of range & missing named param
auto bad_idx = ins->bind_checked(5, ValueView{1});
Void::Testing::expect(!bad_idx.has_value());
Void::Testing::expect(bad_idx.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::range));
auto bad_name = ins->bind_checked(":missing", ValueView{1});
Void::Testing::expect(!bad_name.has_value());
Void::Testing::expect(bad_name.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::not_found));
// Oversized value fails before bind
const std::string huge(100, 'x');
auto too_big = ins->bind_checked(":txt", ValueView{huge});
Void::Testing::expect(!too_big.has_value());
Void::Testing::expect(too_big.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
// Row 1: INT64_MIN, double, embedded NUL text via borrowed owner, empty blob
auto borrowed_str = std::make_shared<std::string>(std::string_view{"ab\0cd", 5});
const std::string_view borrowed_view{borrowed_str->data(), borrowed_str->size()};
const std::vector<std::byte> empty_blob{};
Void::Testing::require(ins->bind_checked(":id", ValueView{std::numeric_limits<std::int64_t>::min()}).has_value());
Void::Testing::require(ins->bind_checked(":r", ValueView{3.25}).has_value());
Void::Testing::require(ins->bind_borrowed_text(3, borrowed_view, borrowed_str).has_value());
Void::Testing::require(ins->bind_checked(":bin", ValueView{std::span<const std::byte>{empty_blob}}).has_value());
// Drop caller's shared_ptr — Statement retains borrowed_str safely until clear/finalize!
const std::weak_ptr<const std::string> weak_owner = borrowed_str;
borrowed_str.reset();
Void::Testing::expect(!weak_owner.expired());
auto step1 = ins->step();
Void::Testing::require(step1.has_value() && !*step1);
Void::Testing::require(ins->reset_checked().has_value());
// Still alive after reset because SQLite retains SQLITE_STATIC until clear_bindings/finalize!
Void::Testing::expect(!weak_owner.expired());
Void::Testing::require(ins->clear_bindings_checked().has_value());
Void::Testing::expect(weak_owner.expired());
// Row 2: numeric string "123", INT64_MAX, NULL blob
Void::Testing::require(ins->bind_checked(1, ValueView{std::numeric_limits<std::int64_t>::max()}).has_value());
Void::Testing::require(ins->bind_checked(2, ValueView{nullptr}).has_value());
Void::Testing::require(ins->bind_checked(3, ValueView{"123"}).has_value());
Void::Testing::require(ins->bind_checked(4, ValueView{nullptr}).has_value());
Void::Testing::require(ins->step().has_value());
auto sel = db.prepare("SELECT id, r, txt, bin FROM items ORDER BY id ASC");
Void::Testing::require(sel.has_value());
auto has1 = sel->step();
Void::Testing::require(has1.has_value() && *has1);
auto rv1 = sel->current_row();
Void::Testing::require(rv1.has_value() && rv1->is_valid());
Void::Testing::expect_eq(*rv1->get_int(0), std::numeric_limits<std::int64_t>::min());
Void::Testing::expect(*rv1->get_double(1) == 3.25);
const std::string got_nul_txt = *rv1->get_text(2);
Void::Testing::expect_eq(got_nul_txt.size(), static_cast<std::size_t>(5));
Void::Testing::expect_eq(got_nul_txt[2], '\0');
auto ct_blob = rv1->column_type(3);
Void::Testing::require(ct_blob.has_value() && *ct_blob == ColumnType::Blob);
Void::Testing::expect(rv1->get_blob(3)->empty());
auto has2 = sel->step();
Void::Testing::require(has2.has_value() && *has2);
// rv1 expired at next step!
Void::Testing::expect(!rv1->is_valid());
Void::Testing::expect(!rv1->get_int(0).has_value());
// Typed reads reject coercion ("123" is TEXT, not INTEGER!).
Void::Testing::expect_eq(*sel->try_column_int(0), std::numeric_limits<std::int64_t>::max());
Void::Testing::expect(!sel->try_column_optional_double(1)->has_value());
auto bad_coercion = sel->try_column_int(2);
Void::Testing::expect(!bad_coercion.has_value());
Void::Testing::expect(bad_coercion.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::type_mismatch));
Void::Testing::expect(!sel->try_column_optional_blob(3)->has_value());
// query_all row cap
for (int i = 0; i < 4; ++i) {
Void::Testing::require(db.exec("INSERT INTO items(id, txt) VALUES(1, 'z')").has_value());
}
auto all_q = db.prepare("SELECT id, txt FROM items");
Void::Testing::require(all_q.has_value());
auto over_rows = db.query_all(*all_q, 3, 4096);
Void::Testing::expect(!over_rows.has_value());
Void::Testing::expect(over_rows.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::size_limit));
}
Void::Testing::Test sqlite_transactions_busy_commit_savepoints_and_checked_migrations()
{
TempSqliteDir dir;
const auto db_path = dir.path / "tx.db";
OpenOptions opts;
opts.limits.busy_timeout = std::chrono::milliseconds{20};
auto db1_r = open_database(db_path, opts);
Void::Testing::require(db1_r.has_value());
auto& db1 = *db1_r;
Void::Testing::require(db1.exec("CREATE TABLE t(k INTEGER PRIMARY KEY, v TEXT)").has_value());
// Real two-connection BUSY test
auto db2_r = open_database(db_path, opts);
Void::Testing::require(db2_r.has_value());
auto& db2 = *db2_r;
{
auto tx1 = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx1.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(1, 'holder')").has_value());
auto tx2_busy = db2.begin(BeginMode::Immediate);
Void::Testing::expect(!tx2_busy.has_value());
Void::Testing::expect(tx2_busy.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::require(tx1->commit().has_value());
}
// Faulted COMMIT leaving autocommit==0 keeps Transaction active for retry/rollback!
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(2, 'retried')").has_value());
// Nested begin is rejected.
auto nested = db1.begin();
Void::Testing::expect(!nested.has_value());
Void::Testing::expect(nested.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::misuse));
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_BUSY,
.auto_rollback_on_faulted_commit = false}};
auto failed_commit = tx->commit();
Void::Testing::expect(!failed_commit.has_value());
Void::Testing::expect(failed_commit.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::busy));
Void::Testing::expect(tx->state() == TransactionState::Active);
Void::Testing::expect(sqlite3_get_autocommit(db1.handle()) == 0);
}
// Now retry commit succeeds!
Void::Testing::require(tx->commit().has_value());
Void::Testing::expect(tx->state() == TransactionState::Committed);
}
// Faulted COMMIT with auto-rollback transitions to RolledBack properly!
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(3, 'rolled')").has_value());
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_FULL,
.auto_rollback_on_faulted_commit = true}};
auto failed_commit = tx->commit();
Void::Testing::expect(!failed_commit.has_value());
Void::Testing::expect(tx->state() == TransactionState::RolledBack);
}
}
// Savepoint rollback_to + release
{
auto tx = db1.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(10, 'kept')").has_value());
{
auto sp = db1.savepoint("inner_sp");
Void::Testing::require(sp.has_value());
Void::Testing::require(db1.exec("INSERT INTO t VALUES(11, 'undone')").has_value());
Void::Testing::require(sp->rollback_and_release().has_value());
}
Void::Testing::require(tx->commit().has_value());
}
auto cnt = db1.prepare("SELECT COUNT(*) FROM t WHERE k IN (1, 2, 10, 11)");
Void::Testing::require(cnt.has_value() && *cnt->step());
Void::Testing::expect_eq(*cnt->try_column_int(0), static_cast<std::int64_t>(3));
// Checked migrations: invalid order rejected before mutation, checksum drift rejected!
const auto mig_db_path = dir.path / "mig.db";
auto mdb_r = open_database(mig_db_path);
Void::Testing::require(mdb_r.has_value());
auto& mdb = *mdb_r;
const std::array<CheckedMigration, 2> bad_order{{
{2, "v2", "sum2", "CREATE TABLE x(id INTEGER)"},
{2, "v2b", "sum2b", "CREATE TABLE y(id INTEGER)"},
}};
Void::Testing::expect(!mdb.migrate_checked(bad_order).has_value());
Void::Testing::expect_eq(*mdb.user_version(), 0);
const std::array<CheckedMigration, 2> good_migs{{
{1, "init_x", "sha256:aaa", "CREATE TABLE x(id INTEGER PRIMARY KEY)"},
{2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"},
}};
Void::Testing::require(mdb.migrate_checked(good_migs).has_value());
Void::Testing::expect_eq(*mdb.user_version(), 2);
// Checksum drift must fail without mutating.
const std::array<CheckedMigration, 2> drifted{{
{1, "init_x", "sha256:TAMPERED", "CREATE TABLE x(id INTEGER PRIMARY KEY)"},
{2, "add_name", "sha256:bbb", "ALTER TABLE x ADD COLUMN name TEXT"},
}};
auto drift_res = mdb.migrate_checked(drifted);
Void::Testing::expect(!drift_res.has_value());
Void::Testing::expect(drift_res.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::migration_error));
// Unexpected newer schema (only supplying v1 when DB is at v2) rejected.
const std::array<CheckedMigration, 1> older_plan{{good_migs[0]}};
Void::Testing::expect(!mdb.migrate_checked(older_plan).has_value());
}
Void::Testing::Test sqlite_checkpoint_wal_admission_backup_restore_and_safe_callbacks()
{
TempSqliteDir dir;
const auto db_path = dir.path / "ops.db";
const auto backup_path = dir.path / "backup.db";
OpenOptions wopts;
wopts.limits.busy_timeout = std::chrono::milliseconds{20};
wopts.limits.wal_checkpoint_threshold_bytes = 4096;
wopts.limits.wal_warn_threshold_bytes = 8192;
wopts.limits.wal_stop_writes_threshold_bytes = 16384;
auto writer_r = open_database(db_path, wopts);
Void::Testing::require(writer_r.has_value());
auto& writer = *writer_r;
Void::Testing::require(writer.exec("CREATE TABLE logs(id INTEGER PRIMARY KEY, payload TEXT)").has_value());
Void::Testing::require(writer.exec("INSERT INTO logs VALUES(1, 'seed')").has_value());
// Open a long-lived reader transaction that pins the old snapshot so WAL
// cannot truncate past it!
OpenOptions ropts;
ropts.mode = OpenMode::ReadOnly;
auto reader_r = open_database(db_path, ropts);
Void::Testing::require(reader_r.has_value());
auto rtx = reader_r->begin(BeginMode::Deferred);
Void::Testing::require(rtx.has_value());
{
auto rsel = reader_r->prepare("SELECT COUNT(*) FROM logs");
Void::Testing::require(rsel.has_value() && *rsel->step());
}
// Write > 16 KiB across commits to push WAL past wal_stop_writes_threshold_bytes.
{
auto tx = writer.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
auto ins = writer.prepare("INSERT INTO logs(payload) VALUES(?)");
Void::Testing::require(ins.has_value());
const std::string blob(1024, 'W');
for (int i = 0; i < 40; ++i) {
Void::Testing::require(ins->bind_checked(1, ValueView{blob}).has_value());
Void::Testing::require(ins->step().has_value());
Void::Testing::require(ins->reset_checked().has_value());
}
Void::Testing::require(tx->commit().has_value());
}
// While reader holds snapshot, FULL/TRUNCATE checkpoint reports busy!
auto blocked_ckpt = writer.checkpoint(CheckpointMode::Truncate);
Void::Testing::require(blocked_ckpt.has_value());
Void::Testing::expect(blocked_ckpt->busy);
const auto h1 = writer.health();
Void::Testing::expect(h1.wal_write_admission_blocked);
auto rejected_begin = writer.begin(BeginMode::Immediate);
Void::Testing::expect(!rejected_begin.has_value());
Void::Testing::expect(rejected_begin.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::overloaded));
// Backup while reader+writer active still copies consistent committed state.
auto bkup = writer.backup_to(backup_path);
Void::Testing::require(bkup.has_value());
Void::Testing::expect_eq(bkup->remaining_pages, 0);
// Release reader snapshot and truncate checkpoint -> unblocks write admission!
Void::Testing::require(rtx->commit().has_value());
auto ok_ckpt = writer.checkpoint(CheckpointMode::Truncate);
Void::Testing::require(ok_ckpt.has_value());
Void::Testing::expect(!writer.health().wal_write_admission_blocked);
auto unblocked_tx = writer.begin(BeginMode::Immediate);
Void::Testing::require(unblocked_tx.has_value());
Void::Testing::require(writer.exec("INSERT INTO logs(payload) VALUES('after_ckpt')").has_value());
Void::Testing::require(unblocked_tx->commit().has_value());
// Restore from earlier backup into another DB and verify count matches 41!
const auto restored_path = dir.path / "restored.db";
auto restored_r = open_database(restored_path);
Void::Testing::require(restored_r.has_value());
Void::Testing::require(restored_r->restore_from(backup_path).has_value());
auto rcnt = restored_r->prepare("SELECT COUNT(*) FROM logs");
Void::Testing::require(rcnt.has_value() && *rcnt->step());
Void::Testing::expect_eq(*rcnt->try_column_int(0), static_cast<std::int64_t>(41));
// Throwing scalar function & authorizer never unwind across SQLite C frames.
Void::Testing::require(writer.create_scalar_function(
"boom_fn", 0,
[](std::span<const ValueView>) -> Result<OwnedValue> {
throw std::runtime_error{"boom"};
}).has_value());
auto boom = writer.prepare("SELECT boom_fn()");
Void::Testing::require(boom.has_value());
auto boom_step = boom->step();
Void::Testing::expect(!boom_step.has_value());
Void::Testing::require(writer.set_authorizer(
[](int action, std::string_view arg1, std::string_view, std::string_view, std::string_view) {
if (action == SQLITE_DROP_TABLE || arg1 == "blocked_tbl") {
throw std::runtime_error{"auth boom converts to deny"};
}
return AuthorizerDecision::Allow;
}).has_value());
Void::Testing::expect(!writer.exec("DROP TABLE logs").has_value());
}
} // namespace
@@ -0,0 +1,250 @@
#include <Void/Async/Executor.hpp>
#include <Void/Async/Task.hpp>
#include <Void/Sqlite/AsyncPool.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <atomic>
#include <chrono>
#include <cstdint>
#include <filesystem>
#include <stop_token>
#include <string>
#include <thread>
#include <unistd.h>
namespace
{
using namespace Void::Sqlite;
struct TempPoolDir {
std::filesystem::path path;
TempPoolDir()
{
static std::atomic<std::uint64_t> seq{0};
const auto id = seq.fetch_add(1, std::memory_order_relaxed);
path = std::filesystem::temp_directory_path() /
("void-sqlite-async-" + std::to_string(::getpid()) + "-" + std::to_string(id));
std::error_code ec;
std::filesystem::remove_all(path, ec);
std::filesystem::create_directories(path, ec);
}
~TempPoolDir()
{
std::error_code ec;
std::filesystem::remove_all(path, ec);
}
};
Void::Coro::Task<void> run_pool_crud_and_backpressure(
AsyncPool& pool,
Void::Async::ManualExecutor& exec)
{
(void)exec;
auto init = co_await pool.run_write_void([](Database& db) {
return db.exec("CREATE TABLE kv(k INTEGER PRIMARY KEY, v TEXT)");
});
Void::Testing::require(init.has_value());
// Write transaction commit
auto tx_ok = co_await pool.run_write_transaction<int>(
BeginMode::Immediate,
[](Database& db, Transaction&) -> Result<int> {
auto r1 = db.exec("INSERT INTO kv VALUES(1, 'one')");
if (!r1) return Void::Result::fail(std::move(r1).error());
auto r2 = db.exec("INSERT INTO kv VALUES(2, 'two')");
if (!r2) return Void::Result::fail(std::move(r2).error());
return 2;
});
Void::Testing::require(tx_ok.has_value() && *tx_ok == 2);
// Write transaction error rolls back cleanly inside same lease
auto tx_err = co_await pool.run_write_transaction<int>(
BeginMode::Immediate,
[](Database& db, Transaction&) -> Result<int> {
auto r1 = db.exec("INSERT INTO kv VALUES(3, 'rolled')");
if (!r1) return Void::Result::fail(std::move(r1).error());
return Void::Result::fail(make_sqlite_error(
SqliteErrorCode::constraint, "intentional rollback"));
});
Void::Testing::expect(!tx_err.has_value());
// 4 concurrent reads via coroutine calls
for (int i = 0; i < 4; ++i) {
auto count = co_await pool.run_read<std::int64_t>([](Database& db) -> Result<std::int64_t> {
auto st = db.prepare("SELECT COUNT(*) FROM kv");
if (!st) return Void::Result::fail(std::move(st).error());
auto s = st->step();
if (!s) return Void::Result::fail(std::move(s).error());
return st->try_column_int(0);
});
Void::Testing::require(count.has_value());
Void::Testing::expect_eq(*count, static_cast<std::int64_t>(2));
}
// Oversized input bytes rejected before queueing
auto over_bytes = co_await pool.run_read_void(
[](Database&) -> Result<void> { return {}; },
{},
4096);
Void::Testing::expect(!over_bytes.has_value());
Void::Testing::expect(over_bytes.error().kind() == Void::Result::ErrorKind::overloaded);
}
Void::Coro::Task<void> run_heavy_query(
AsyncPool& pool,
std::stop_token st,
Result<std::int64_t>* out)
{
Void::Async::OperationOptions op;
op.stop = st;
*out = co_await pool.run_read<std::int64_t>(
[](Database& db) -> Result<std::int64_t> {
auto stmt = db.prepare(
"WITH RECURSIVE cnt(x) AS (SELECT 1 UNION ALL SELECT x+1 FROM cnt WHERE x < 20000000) "
"SELECT MAX(x) FROM cnt");
if (!stmt) return Void::Result::fail(std::move(stmt).error());
auto s = stmt->step();
if (!s) return Void::Result::fail(std::move(s).error());
return stmt->try_column_int(0);
},
op);
}
Void::Coro::Task<void> verify_follow_up_reads(AsyncPool& pool)
{
for (int i = 0; i < 10; ++i) {
auto r = co_await pool.run_read<std::int64_t>(
[](Database& db) -> Result<std::int64_t> {
auto st = db.prepare("SELECT 42");
if (!st) return Void::Result::fail(std::move(st).error());
auto has = st->step();
if (!has) return Void::Result::fail(std::move(has).error());
return st->try_column_int(0);
});
Void::Testing::require(r.has_value());
Void::Testing::expect_eq(*r, static_cast<std::int64_t>(42));
}
}
Void::Coro::Task<void> drive_pool_crud(
AsyncPool& pool,
Void::Async::ManualExecutor& exec,
bool* done)
{
co_await run_pool_crud_and_backpressure(pool, exec);
*done = true;
}
Void::Coro::Task<void> drive_warmup(AsyncPool& pool, bool* done)
{
auto r = co_await pool.run_write_void([](Database& db) {
return db.exec("CREATE TABLE dummy(id INTEGER)");
});
Void::Testing::require(r.has_value());
*done = true;
}
Void::Coro::Task<void> drive_heavy_query(
AsyncPool& pool,
std::stop_token st,
Result<std::int64_t>* out,
bool* done)
{
co_await run_heavy_query(pool, st, out);
*done = true;
}
Void::Coro::Task<void> drive_followups(AsyncPool& pool, bool* done)
{
co_await verify_follow_up_reads(pool);
*done = true;
}
Void::Testing::Test sqlite_async_pool_readers_writer_transactions_and_backpressure()
{
TempPoolDir dir;
Void::Async::ManualExecutor exec;
AsyncPoolOptions opts;
opts.path = dir.path / "pool.db";
opts.reader_connections = 4;
opts.max_queued_jobs = 8;
opts.max_pending_input_bytes = 1024;
auto pool_r = AsyncPool::open(opts, &exec);
Void::Testing::require(pool_r.has_value());
auto pool = std::move(*pool_r);
bool done = false;
auto t = drive_pool_crud(pool, exec, &done);
t.handle().resume();
while (!done) {
if (exec.drain() == 0) {
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
const auto st = pool.stats();
Void::Testing::expect_eq(st.reader_connections, static_cast<std::size_t>(4));
Void::Testing::expect(st.completed_jobs >= 7);
Void::Testing::expect(st.rejected_jobs >= 1);
Void::Testing::require(pool.close_and_join().has_value());
}
Void::Testing::Test sqlite_async_pool_cancellation_no_cross_query_interrupt_leak()
{
TempPoolDir dir;
Void::Async::ManualExecutor exec;
AsyncPoolOptions opts;
opts.path = dir.path / "cancel.db";
opts.reader_connections = 1; // force all follow-up reads onto the exact same connection
opts.progress_handler_steps = 32;
auto pool_r = AsyncPool::open(opts, &exec);
Void::Testing::require(pool_r.has_value());
auto pool = std::move(*pool_r);
// Warm up DB with initial table/checkpoint
{
bool warmup_done = false;
auto wt = drive_warmup(pool, &warmup_done);
wt.handle().resume();
while (!warmup_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
}
std::stop_source ss;
Result<std::int64_t> cancel_res = Void::Result::fail("uninitialized");
bool cancel_done = false;
auto rt = drive_heavy_query(pool, ss.get_token(), &cancel_res, &cancel_done);
rt.handle().resume();
// Wait until reader is actively running, then interrupt it.
for (int i = 0; i < 100 && pool.stats().active_read_jobs == 0 && !cancel_done; ++i) {
exec.drain();
std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
ss.request_stop();
while (!cancel_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
Void::Testing::expect(!cancel_res.has_value());
Void::Testing::expect(cancel_res.error().kind() == Void::Result::ErrorKind::cancelled);
// Immediately run 10 follow-up queries on the same single reader connection;
// zero interrupts may leak to subsequent borrowers!
bool followup_done = false;
auto ft = drive_followups(pool, &followup_done);
ft.handle().resume();
while (!followup_done) {
if (exec.drain() == 0) std::this_thread::sleep_for(std::chrono::milliseconds{1});
}
Void::Testing::require(pool.close_and_join().has_value());
}
} // namespace