Files

809 lines
33 KiB
C++

#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 <format>
#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
Void::Testing::Test sqlite_wal_admission_counts_uncheckpointed_frames()
{
TempSqliteDir dir;
const auto db_path = dir.path / "wal-frames.db";
const auto wal_path = std::filesystem::path{db_path.string() + "-wal"};
OpenOptions opts;
opts.limits.busy_timeout = std::chrono::milliseconds{20};
opts.limits.wal_checkpoint_threshold_bytes = 4096;
opts.limits.wal_warn_threshold_bytes = 8192;
opts.limits.wal_stop_writes_threshold_bytes = 16384;
auto writer_r = open_database(db_path, opts);
Void::Testing::require(writer_r.has_value());
auto& writer = *writer_r;
Void::Testing::require(
writer.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB)").has_value());
// Grow the WAL past the stop threshold.
{
auto tx = writer.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
auto ins = writer.prepare("INSERT INTO t(payload) VALUES(?)");
Void::Testing::require(ins.has_value());
const std::string blob(4096, 'W');
for (int i = 0; i < 8; ++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());
}
Void::Testing::require(std::filesystem::exists(wal_path));
Void::Testing::expect(std::filesystem::file_size(wal_path) >= 16384);
// Pin a reader at the current snapshot.
OpenOptions ropts;
ropts.mode = OpenMode::ReadOnly;
auto reader_r = open_database(db_path, ropts);
Void::Testing::require(reader_r.has_value());
auto& reader = *reader_r;
auto rtx = reader.begin(BeginMode::Deferred);
Void::Testing::require(rtx.has_value());
{
auto sel = reader.prepare("SELECT COUNT(*) FROM t");
Void::Testing::require(sel.has_value() && *sel->step());
}
// A passive checkpoint can backfill every frame the reader has already seen.
// The WAL file itself stays large (passive checkpoints never truncate).
auto ckpt = writer.checkpoint(CheckpointMode::Passive);
Void::Testing::require(ckpt.has_value());
Void::Testing::expect(ckpt->uncheckpointed_frames == 0);
Void::Testing::expect(std::filesystem::file_size(wal_path) >= 16384);
const auto h = writer.health();
Void::Testing::expect(h.wal_size_bytes >= 16384);
Void::Testing::expect(h.wal_frames_known);
Void::Testing::expect(h.wal_uncheckpointed_frames == 0);
Void::Testing::expect(!h.wal_checkpoint_recommended);
Void::Testing::expect(!h.wal_write_admission_blocked);
// Admission uses un-checkpointed frames, not the large but checkpointed file.
auto admitted = writer.begin(BeginMode::Immediate);
Void::Testing::require(admitted.has_value());
{
auto ins = writer.prepare("INSERT INTO t(payload) VALUES(?)");
Void::Testing::require(ins.has_value());
const std::string blob(4096, 'N');
for (int i = 0; i < 8; ++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(admitted->commit().has_value());
// New frames cannot be checkpointed while the reader pins its snapshot.
const auto h2 = writer.health();
Void::Testing::expect(h2.wal_frames_known);
Void::Testing::expect(h2.wal_uncheckpointed_frames > 0);
Void::Testing::expect(h2.wal_write_admission_blocked);
auto rejected = writer.begin(BeginMode::Immediate);
Void::Testing::expect(!rejected.has_value());
Void::Testing::expect(rejected.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::overloaded));
// Releasing the reader allows a truncating checkpoint to restore 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);
}
Void::Testing::Test sqlite_transaction_reports_automatic_rollback()
{
TempSqliteDir dir;
const auto db_path = dir.path / "auto-rollback.db";
auto db_r = open_database(db_path);
Void::Testing::require(db_r.has_value());
auto& db = *db_r;
Void::Testing::require(
db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, payload BLOB)").has_value());
// sqlite3_interrupt during an INSERT inside an explicit transaction makes
// SQLite roll the whole transaction back.
{
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(
db.exec("INSERT INTO t(payload) VALUES(randomblob(1024))").has_value());
int progress_calls = 0;
db.begin_leased_operation(
7, 1, [&progress_calls] { return ++progress_calls > 20; });
auto stmt = db.prepare(
"INSERT INTO t(payload) SELECT randomblob(512) FROM ("
"WITH RECURSIVE c(x) AS (VALUES(1) UNION ALL "
"SELECT x + 1 FROM c WHERE x < 10000000) SELECT x FROM c)");
Void::Testing::require(stmt.has_value());
auto interrupted = stmt->step();
db.end_leased_operation(7);
Void::Testing::expect(!interrupted.has_value());
Void::Testing::expect(interrupted.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::cancelled));
Void::Testing::expect(sqlite3_get_autocommit(db.handle()) != 0);
Void::Testing::expect(tx->state() == TransactionState::RolledBack);
Void::Testing::expect(!tx->is_active());
// The wrapper must not let the stale handle commit a later transaction.
auto stale_commit = tx->commit();
Void::Testing::expect(!stale_commit.has_value());
Void::Testing::expect(stale_commit.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::misuse));
Void::Testing::require(tx->rollback_checked().has_value());
}
// SQLITE_FULL during a statement is another automatic-rollback path.
{
auto page_count_stmt = db.prepare("PRAGMA page_count");
Void::Testing::require(page_count_stmt.has_value() && *page_count_stmt->step());
const auto page_count = *page_count_stmt->try_column_int(0);
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(
db.exec(std::format("PRAGMA max_page_count={}", page_count)).has_value());
auto ins = db.prepare("INSERT INTO t(payload) VALUES(?)");
Void::Testing::require(ins.has_value());
std::vector<std::byte> huge(4U * 1024U * 1024U, std::byte{0x5A});
Void::Testing::require(
ins->bind_checked(1, ValueView{std::span<const std::byte>{huge}}).has_value());
auto full = ins->step();
Void::Testing::expect(!full.has_value());
Void::Testing::expect(full.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::full));
Void::Testing::expect(sqlite3_get_autocommit(db.handle()) != 0);
Void::Testing::expect(tx->state() == TransactionState::RolledBack);
Void::Testing::expect(!tx->is_active());
// Restore a growth-friendly page limit for the remaining tests.
Void::Testing::require(db.exec("PRAGMA max_page_count=1073741823").has_value());
}
}
Void::Testing::Test sqlite_native_result_codes_are_structural()
{
TempSqliteDir dir;
const auto db_path = dir.path / "native.db";
auto db_res = open_database(db_path);
Void::Testing::require(db_res.has_value());
auto db = std::move(*db_res);
Void::Testing::require(
db.exec("CREATE TABLE u(id INTEGER PRIMARY KEY, email TEXT UNIQUE NOT NULL)")
.has_value());
Void::Testing::require(
db.exec("INSERT INTO u(id, email) VALUES(1, 'a@example.com')").has_value());
// A UNIQUE violation exposes the fine-grained extended code structurally.
auto duplicate = db.exec("INSERT INTO u(id, email) VALUES(2, 'a@example.com')");
Void::Testing::require(!duplicate.has_value());
auto native = sqlite_native_code(duplicate.error());
Void::Testing::require(native.has_value());
Void::Testing::expect_eq(native->primary, SQLITE_CONSTRAINT);
Void::Testing::expect_eq(native->extended, SQLITE_CONSTRAINT_UNIQUE);
// Same primary code, different extended reason.
auto null_email = db.exec("INSERT INTO u(id, email) VALUES(3, NULL)");
Void::Testing::require(!null_email.has_value());
auto null_native = sqlite_native_code(null_email.error());
Void::Testing::require(null_native.has_value());
Void::Testing::expect_eq(null_native->primary, SQLITE_CONSTRAINT);
Void::Testing::expect_eq(null_native->extended, SQLITE_CONSTRAINT_NOTNULL);
Void::Testing::expect(null_native->extended != native->extended);
// Validation errors carry no native SQLite code.
auto invalid = db.prepare("SELECT 1; SELECT 2");
Void::Testing::require(!invalid.has_value());
Void::Testing::expect(!sqlite_native_code(invalid.error()).has_value());
}
Void::Testing::Test sqlite_busy_timeout_override_is_scoped()
{
using namespace std::chrono_literals;
TempSqliteDir dir;
auto db_res = open_database(dir.path / "busy.db");
Void::Testing::require(db_res.has_value());
auto db = std::move(*db_res);
// Nested overrides restore the exact previous value, not the default.
{
auto outer = db.override_busy_timeout(200ms);
Void::Testing::require(outer.has_value());
Void::Testing::expect(outer->is_active());
Void::Testing::expect_eq(outer->previous(), 5000ms);
{
auto inner = db.override_busy_timeout(10ms);
Void::Testing::require(inner.has_value());
Void::Testing::expect_eq(inner->previous(), 200ms);
}
auto after_inner = db.override_busy_timeout(1ms);
Void::Testing::require(after_inner.has_value());
Void::Testing::expect_eq(after_inner->previous(), 200ms);
after_inner->restore();
Void::Testing::expect(!after_inner->is_active());
after_inner->restore(); // idempotent
}
auto restored = db.override_busy_timeout(2ms);
Void::Testing::require(restored.has_value());
Void::Testing::expect_eq(restored->previous(), 5000ms);
// A negative timeout is rejected without changing the connection.
auto negative = db.override_busy_timeout(-1ms);
Void::Testing::require(!negative.has_value());
Void::Testing::expect_eq(
negative.error().code().value,
static_cast<std::int32_t>(SqliteErrorCode::invalid_argument));
}
Void::Testing::Test sqlite_failed_commit_outcome_is_unknown_not_rolled_back()
{
TempSqliteDir dir;
const auto db_path = dir.path / "unknown-commit.db";
auto db_r = open_database(db_path);
Void::Testing::require(db_r.has_value());
auto& db = *db_r;
Void::Testing::expect_eq(db.capabilities().journal_mode, std::string{"wal"});
Void::Testing::require(
db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT)").has_value());
// A WAL I/O error can be reported after the commit record became durable.
// The wrapper must not claim the transaction was definitely rolled back.
{
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(
db.exec("INSERT INTO t VALUES(1, 'maybe committed')").has_value());
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_IOERR,
.commit_applied_before_error = true}};
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::io));
}
Void::Testing::expect(tx->state() == TransactionState::Unknown);
Void::Testing::expect(!tx->is_active());
// The row is visible: reporting RolledBack would have been a lie.
auto count = db.prepare("SELECT COUNT(*) FROM t WHERE id = 1");
Void::Testing::require(count.has_value() && *count->step());
Void::Testing::expect_eq(*count->try_column_int(0), static_cast<std::int64_t>(1));
// The ambiguous transaction cannot be committed or rolled back again;
// the caller must inspect the database.
auto stale_commit = tx->commit();
Void::Testing::expect(!stale_commit.has_value());
Void::Testing::expect(stale_commit.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::misuse));
auto stale_rollback = tx->rollback_checked();
Void::Testing::expect(!stale_rollback.has_value());
Void::Testing::expect(stale_rollback.error().code().value ==
static_cast<std::int32_t>(SqliteErrorCode::recovery_required));
}
// A WAL I/O error that leaves the transaction open keeps it Active so the
// caller can retry or roll back explicitly.
{
auto tx = db.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(db.exec("INSERT INTO t VALUES(2, 'retry')").has_value());
{
ScopedFaultGuard guard{FaultConfig{.fail_next_commit_rc = SQLITE_IOERR}};
auto failed_commit = tx->commit();
Void::Testing::expect(!failed_commit.has_value());
Void::Testing::expect(tx->state() == TransactionState::Active);
Void::Testing::expect(sqlite3_get_autocommit(db.handle()) == 0);
}
Void::Testing::require(tx->rollback_checked().has_value());
}
// The same error in rollback-journal mode is a known rollback: SQLite has
// crash recovery for a hot journal, so the wrapper reports RolledBack.
{
OpenOptions rollback_opts;
rollback_opts.journal_mode = JournalMode::Rollback;
const auto rollback_path = dir.path / "rollback.db";
auto rdb_r = open_database(rollback_path, rollback_opts);
Void::Testing::require(rdb_r.has_value());
auto& rdb = *rdb_r;
Void::Testing::require(
rdb.exec("CREATE TABLE t(id INTEGER PRIMARY KEY)").has_value());
auto tx = rdb.begin(BeginMode::Immediate);
Void::Testing::require(tx.has_value());
Void::Testing::require(rdb.exec("INSERT INTO t VALUES(1)").has_value());
{
ScopedFaultGuard guard{FaultConfig{
.fail_next_commit_rc = SQLITE_IOERR,
.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);
}
}