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

+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