2666 lines
83 KiB
C++
2666 lines
83 KiB
C++
#include <Void/Sqlite/Sqlite.hpp>
|
|
#include <Void/Time/Clock.hpp>
|
|
|
|
#include <sqlite3.h>
|
|
|
|
#include <algorithm>
|
|
#include <atomic>
|
|
#include <cctype>
|
|
#include <climits>
|
|
#include <cstring>
|
|
#include <filesystem>
|
|
#include <format>
|
|
#include <mutex>
|
|
#include <stop_token>
|
|
#include <string>
|
|
#include <string_view>
|
|
#include <thread>
|
|
#include <utility>
|
|
#include <vector>
|
|
|
|
namespace Void::Sqlite
|
|
{
|
|
namespace
|
|
{
|
|
std::mutex g_fault_mutex;
|
|
FaultConfig g_fault_config{};
|
|
|
|
[[nodiscard]] FaultConfig consume_fault_commit() noexcept
|
|
{
|
|
std::lock_guard lk{g_fault_mutex};
|
|
FaultConfig out{};
|
|
if (g_fault_config.fail_next_commit_rc != 0) {
|
|
out.fail_next_commit_rc = std::exchange(g_fault_config.fail_next_commit_rc, 0);
|
|
out.auto_rollback_on_faulted_commit =
|
|
std::exchange(g_fault_config.auto_rollback_on_faulted_commit, false);
|
|
}
|
|
return out;
|
|
}
|
|
|
|
[[nodiscard]] int consume_fault_close() noexcept
|
|
{
|
|
std::lock_guard lk{g_fault_mutex};
|
|
return std::exchange(g_fault_config.fail_next_close_rc, 0);
|
|
}
|
|
|
|
[[nodiscard]] SqliteErrorCode map_sqlite_rc(int rc) noexcept
|
|
{
|
|
const int primary = rc & 0xFF;
|
|
switch (primary) {
|
|
case SQLITE_OK:
|
|
case SQLITE_ROW:
|
|
case SQLITE_DONE:
|
|
return SqliteErrorCode::none;
|
|
case SQLITE_BUSY:
|
|
return SqliteErrorCode::busy;
|
|
case SQLITE_LOCKED:
|
|
return SqliteErrorCode::locked;
|
|
case SQLITE_CONSTRAINT:
|
|
return SqliteErrorCode::constraint;
|
|
case SQLITE_CORRUPT:
|
|
case SQLITE_NOTADB:
|
|
return SqliteErrorCode::corrupt;
|
|
case SQLITE_IOERR:
|
|
return SqliteErrorCode::io;
|
|
case SQLITE_READONLY:
|
|
return SqliteErrorCode::readonly;
|
|
case SQLITE_FULL:
|
|
case SQLITE_TOOBIG:
|
|
case SQLITE_NOMEM:
|
|
return SqliteErrorCode::full;
|
|
case SQLITE_MISUSE:
|
|
return SqliteErrorCode::misuse;
|
|
case SQLITE_RANGE:
|
|
return SqliteErrorCode::range;
|
|
case SQLITE_CANTOPEN:
|
|
case SQLITE_NOTFOUND:
|
|
return SqliteErrorCode::not_found;
|
|
case SQLITE_INTERRUPT:
|
|
return SqliteErrorCode::cancelled;
|
|
default:
|
|
return SqliteErrorCode::sqlite_error;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] Error sqlite_error_from_db(
|
|
sqlite3* db,
|
|
int primary_rc,
|
|
std::string_view what)
|
|
{
|
|
const int ext = db ? sqlite3_extended_errcode(db) : primary_rc;
|
|
const char* msg = db ? sqlite3_errmsg(db) : sqlite3_errstr(primary_rc);
|
|
return make_sqlite_error(
|
|
map_sqlite_rc(primary_rc),
|
|
std::format("Sqlite: {}: {}", what, msg ? msg : "unknown error"),
|
|
primary_rc,
|
|
ext);
|
|
}
|
|
|
|
[[nodiscard]] std::string ascii_lower(std::string_view s)
|
|
{
|
|
std::string out;
|
|
out.reserve(s.size());
|
|
for (const unsigned char c : s) {
|
|
out.push_back(static_cast<char>(std::tolower(c)));
|
|
}
|
|
return out;
|
|
}
|
|
|
|
[[nodiscard]] bool is_ascii_whitespace(char c) noexcept
|
|
{
|
|
return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f' || c == '\v';
|
|
}
|
|
|
|
[[nodiscard]] bool is_valid_savepoint_name(std::string_view name) noexcept
|
|
{
|
|
if (name.empty() || name.size() > 64) {
|
|
return false;
|
|
}
|
|
const auto is_start = [](unsigned char c) {
|
|
return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_';
|
|
};
|
|
if (!is_start(static_cast<unsigned char>(name.front()))) {
|
|
return false;
|
|
}
|
|
for (const unsigned char c : name) {
|
|
if (!is_start(c) && !(c >= '0' && c <= '9')) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
[[nodiscard]] bool is_memory_path(const std::filesystem::path& path)
|
|
{
|
|
const std::string s = path.string();
|
|
return s.empty() || s == ":memory:" || s.starts_with("file::memory:");
|
|
}
|
|
|
|
[[nodiscard]] int clamp_to_int(std::size_t v) noexcept
|
|
{
|
|
if (v >= static_cast<std::size_t>(INT_MAX)) {
|
|
return INT_MAX;
|
|
}
|
|
return static_cast<int>(v);
|
|
}
|
|
|
|
[[nodiscard]] ColumnType map_column_type(int sqlite_type) noexcept
|
|
{
|
|
switch (sqlite_type) {
|
|
case SQLITE_INTEGER: return ColumnType::Integer;
|
|
case SQLITE_FLOAT: return ColumnType::Real;
|
|
case SQLITE_TEXT: return ColumnType::Text;
|
|
case SQLITE_BLOB: return ColumnType::Blob;
|
|
case SQLITE_NULL:
|
|
default:
|
|
return ColumnType::Null;
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] Result<void> query_single_text_pragma(
|
|
sqlite3* db,
|
|
std::string_view sql,
|
|
std::string& out_value)
|
|
{
|
|
sqlite3_stmt* raw = nullptr;
|
|
const int prep_rc = sqlite3_prepare_v2(
|
|
db, sql.data(), static_cast<int>(sql.size()), &raw, nullptr);
|
|
if (prep_rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(db, prep_rc, sql));
|
|
}
|
|
struct StmtGuard {
|
|
sqlite3_stmt* s;
|
|
~StmtGuard() { if (s) sqlite3_finalize(s); }
|
|
} guard{raw};
|
|
const int step_rc = sqlite3_step(raw);
|
|
if (step_rc != SQLITE_ROW) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
std::format("Sqlite: pragma '{}' returned no result", sql),
|
|
step_rc,
|
|
db ? sqlite3_extended_errcode(db) : step_rc));
|
|
}
|
|
const auto* p = sqlite3_column_text(raw, 0);
|
|
const int n = sqlite3_column_bytes(raw, 0);
|
|
out_value = (p && n > 0)
|
|
? std::string{reinterpret_cast<const char*>(p),
|
|
static_cast<std::size_t>(n)}
|
|
: std::string{};
|
|
return {};
|
|
}
|
|
|
|
[[nodiscard]] Result<int> query_single_int_pragma(
|
|
sqlite3* db,
|
|
std::string_view sql)
|
|
{
|
|
sqlite3_stmt* raw = nullptr;
|
|
const int prep_rc = sqlite3_prepare_v2(
|
|
db, sql.data(), static_cast<int>(sql.size()), &raw, nullptr);
|
|
if (prep_rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(db, prep_rc, sql));
|
|
}
|
|
struct StmtGuard {
|
|
sqlite3_stmt* s;
|
|
~StmtGuard() { if (s) sqlite3_finalize(s); }
|
|
} guard{raw};
|
|
const int step_rc = sqlite3_step(raw);
|
|
if (step_rc != SQLITE_ROW) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
std::format("Sqlite: pragma '{}' returned no result", sql),
|
|
step_rc,
|
|
db ? sqlite3_extended_errcode(db) : step_rc));
|
|
}
|
|
return static_cast<int>(sqlite3_column_int(raw, 0));
|
|
}
|
|
|
|
[[nodiscard]] Result<void> exec_raw_sql(
|
|
sqlite3* db,
|
|
const std::string& sql,
|
|
std::string_view what)
|
|
{
|
|
char* err = nullptr;
|
|
const int rc = sqlite3_exec(db, sql.c_str(), nullptr, nullptr, &err);
|
|
if (rc != SQLITE_OK) {
|
|
std::string msg = err ? err : (db ? sqlite3_errmsg(db) : sqlite3_errstr(rc));
|
|
if (err) sqlite3_free(err);
|
|
const int ext = db ? sqlite3_extended_errcode(db) : rc;
|
|
return Void::Result::fail(make_sqlite_error(
|
|
map_sqlite_rc(rc),
|
|
std::format("Sqlite: {}: {}", what, msg),
|
|
rc,
|
|
ext));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
struct ScalarFunctionBox {
|
|
ScalarFunction fn{};
|
|
};
|
|
|
|
struct AuthorizerBox {
|
|
AuthorizerCallback cb{};
|
|
};
|
|
|
|
void scalar_function_trampoline(
|
|
sqlite3_context* ctx,
|
|
int argc,
|
|
sqlite3_value** argv) noexcept
|
|
{
|
|
const auto* box = static_cast<const ScalarFunctionBox*>(sqlite3_user_data(ctx));
|
|
if (!box || !box->fn) {
|
|
sqlite3_result_error(ctx, "Sqlite: scalar function missing target", -1);
|
|
return;
|
|
}
|
|
try {
|
|
std::vector<ValueView> args;
|
|
args.reserve(static_cast<std::size_t>(std::max(0, argc)));
|
|
for (int i = 0; i < argc; ++i) {
|
|
sqlite3_value* v = argv[i];
|
|
switch (sqlite3_value_type(v)) {
|
|
case SQLITE_NULL:
|
|
args.emplace_back(nullptr);
|
|
break;
|
|
case SQLITE_INTEGER:
|
|
args.emplace_back(static_cast<std::int64_t>(sqlite3_value_int64(v)));
|
|
break;
|
|
case SQLITE_FLOAT:
|
|
args.emplace_back(sqlite3_value_double(v));
|
|
break;
|
|
case SQLITE_TEXT: {
|
|
const auto* p = sqlite3_value_text(v);
|
|
const int n = sqlite3_value_bytes(v);
|
|
args.emplace_back(std::string_view{
|
|
p && n > 0 ? reinterpret_cast<const char*>(p) : "",
|
|
n > 0 ? static_cast<std::size_t>(n) : 0ULL});
|
|
break;
|
|
}
|
|
case SQLITE_BLOB: {
|
|
const auto* p = sqlite3_value_blob(v);
|
|
const int n = sqlite3_value_bytes(v);
|
|
args.emplace_back(std::span<const std::byte>{
|
|
p && n > 0 ? static_cast<const std::byte*>(p) : nullptr,
|
|
n > 0 ? static_cast<std::size_t>(n) : 0ULL});
|
|
break;
|
|
}
|
|
default:
|
|
args.emplace_back(nullptr);
|
|
break;
|
|
}
|
|
}
|
|
auto res = box->fn(args);
|
|
if (!res) {
|
|
const std::string& msg = res.error().message();
|
|
sqlite3_result_error(
|
|
ctx,
|
|
msg.empty() ? "Sqlite scalar function failed" : msg.c_str(),
|
|
clamp_to_int(msg.size()));
|
|
return;
|
|
}
|
|
const OwnedValue& out = *res;
|
|
if (out.is_null()) {
|
|
sqlite3_result_null(ctx);
|
|
} else if (const auto* iv = std::get_if<std::int64_t>(&out.value)) {
|
|
sqlite3_result_int64(ctx, *iv);
|
|
} else if (const auto* dv = std::get_if<double>(&out.value)) {
|
|
sqlite3_result_double(ctx, *dv);
|
|
} else if (const auto* sv = std::get_if<std::string>(&out.value)) {
|
|
sqlite3_result_text(
|
|
ctx,
|
|
sv->empty() ? "" : sv->data(),
|
|
clamp_to_int(sv->size()),
|
|
SQLITE_TRANSIENT);
|
|
} else if (const auto* bv = std::get_if<std::vector<std::byte>>(&out.value)) {
|
|
sqlite3_result_blob(
|
|
ctx,
|
|
bv->empty() ? static_cast<const void*>("") : bv->data(),
|
|
clamp_to_int(bv->size()),
|
|
SQLITE_TRANSIENT);
|
|
}
|
|
} catch (const std::exception& ex) {
|
|
sqlite3_result_error(ctx, ex.what(), -1);
|
|
} catch (...) {
|
|
sqlite3_result_error(ctx, "Sqlite: scalar function threw unknown exception", -1);
|
|
}
|
|
}
|
|
|
|
int authorizer_trampoline(
|
|
void* user_data,
|
|
int action_code,
|
|
const char* arg1,
|
|
const char* arg2,
|
|
const char* db_name,
|
|
const char* trigger_or_view) noexcept
|
|
{
|
|
const auto* box = static_cast<const AuthorizerBox*>(user_data);
|
|
if (!box || !box->cb) {
|
|
return SQLITE_OK;
|
|
}
|
|
try {
|
|
const auto decision = box->cb(
|
|
action_code,
|
|
arg1 ? std::string_view{arg1} : std::string_view{},
|
|
arg2 ? std::string_view{arg2} : std::string_view{},
|
|
db_name ? std::string_view{db_name} : std::string_view{},
|
|
trigger_or_view ? std::string_view{trigger_or_view} : std::string_view{});
|
|
switch (decision) {
|
|
case AuthorizerDecision::Allow: return SQLITE_OK;
|
|
case AuthorizerDecision::Ignore: return SQLITE_IGNORE;
|
|
case AuthorizerDecision::Deny: return SQLITE_DENY;
|
|
}
|
|
return SQLITE_DENY;
|
|
} catch (...) {
|
|
return SQLITE_DENY;
|
|
}
|
|
}
|
|
|
|
inline constexpr char kStaticEmptySentinel = '\0';
|
|
} // namespace
|
|
|
|
// ── ScopedFaultGuard ─────────────────────────────────────────────────────
|
|
|
|
ScopedFaultGuard::ScopedFaultGuard(FaultConfig cfg) noexcept
|
|
{
|
|
std::lock_guard lk{g_fault_mutex};
|
|
prev_ = g_fault_config;
|
|
g_fault_config = cfg;
|
|
}
|
|
|
|
ScopedFaultGuard::~ScopedFaultGuard()
|
|
{
|
|
std::lock_guard lk{g_fault_mutex};
|
|
g_fault_config = prev_;
|
|
}
|
|
|
|
FaultConfig ScopedFaultGuard::current() noexcept
|
|
{
|
|
std::lock_guard lk{g_fault_mutex};
|
|
return g_fault_config;
|
|
}
|
|
|
|
// ── detail::ConnectionState ──────────────────────────────────────────────
|
|
|
|
namespace detail
|
|
{
|
|
struct ConnectionState {
|
|
struct WalUsage {
|
|
std::uint64_t size_bytes{0};
|
|
std::uint64_t uncheckpointed_bytes{0};
|
|
int log_frames{-1};
|
|
int checkpointed_frames{-1};
|
|
bool frames_known{false};
|
|
};
|
|
|
|
sqlite3* db{nullptr};
|
|
std::filesystem::path path{};
|
|
OpenOptions options{};
|
|
EffectiveCapabilities caps{};
|
|
int page_size{0};
|
|
bool closing{false};
|
|
bool closed{false};
|
|
std::size_t live_statements{0};
|
|
bool active_transaction{false};
|
|
std::uint64_t active_transaction_id{0};
|
|
std::uint64_t next_transaction_id{0};
|
|
std::size_t open_savepoints{0};
|
|
|
|
std::vector<std::unique_ptr<ScalarFunctionBox>> scalar_functions{};
|
|
std::unique_ptr<AuthorizerBox> authorizer{};
|
|
|
|
std::mutex interrupt_mu{};
|
|
std::uint64_t active_op_gen{0};
|
|
std::atomic<bool> cancel_requested{false};
|
|
std::shared_ptr<const std::function<bool()>> progress_predicate{};
|
|
|
|
void emit_diagnostic(std::string_view msg) const noexcept
|
|
{
|
|
if (options.diagnostic_hook) {
|
|
try {
|
|
options.diagnostic_hook(msg);
|
|
} catch (...) {
|
|
}
|
|
}
|
|
}
|
|
|
|
[[nodiscard]] std::uint64_t current_wal_size_bytes() const noexcept
|
|
{
|
|
if (caps.in_memory || path.empty()) {
|
|
return 0;
|
|
}
|
|
std::error_code ec;
|
|
const std::filesystem::path wal_path{path.string() + "-wal"};
|
|
const auto sz = std::filesystem::file_size(wal_path, ec);
|
|
return ec ? 0ULL : static_cast<std::uint64_t>(sz);
|
|
}
|
|
|
|
/// Measures WAL usage with an un-checkpointed-frame count. A passive
|
|
/// checkpoint is only attempted once the on-disk WAL reaches
|
|
/// `probe_threshold`; below that the file size is already a safe upper
|
|
/// bound and no native checkpoint work is done. Passive checkpoints never
|
|
/// block writers and never truncate, so this only advances nBackfill when
|
|
/// no reader pins the frames. If frame information is unavailable the
|
|
/// on-disk size is returned as a conservative fallback.
|
|
[[nodiscard]] WalUsage wal_usage(std::uint64_t probe_threshold) noexcept
|
|
{
|
|
WalUsage usage;
|
|
usage.size_bytes = current_wal_size_bytes();
|
|
if (usage.size_bytes == 0) {
|
|
return usage;
|
|
}
|
|
if (db == nullptr || usage.size_bytes < probe_threshold) {
|
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
|
return usage;
|
|
}
|
|
|
|
int log_frames = -1;
|
|
int checkpointed_frames = -1;
|
|
const int rc = sqlite3_wal_checkpoint_v2(
|
|
db, "main", SQLITE_CHECKPOINT_PASSIVE, &log_frames, &checkpointed_frames);
|
|
if ((rc == SQLITE_OK || rc == SQLITE_BUSY) && log_frames >= 0 &&
|
|
checkpointed_frames >= 0) {
|
|
usage.log_frames = log_frames;
|
|
usage.checkpointed_frames = checkpointed_frames;
|
|
usage.frames_known = true;
|
|
const auto remaining = static_cast<std::uint64_t>(
|
|
std::max(0, log_frames - checkpointed_frames));
|
|
if (page_size > 0) {
|
|
usage.uncheckpointed_bytes =
|
|
std::min(usage.size_bytes,
|
|
remaining * static_cast<std::uint64_t>(page_size));
|
|
} else {
|
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
|
}
|
|
return usage;
|
|
}
|
|
|
|
usage.uncheckpointed_bytes = usage.size_bytes;
|
|
return usage;
|
|
}
|
|
|
|
/// Clears wrapper transaction bookkeeping when SQLite ended the
|
|
/// transaction on its own (autocommit is back on). The original SQLite
|
|
/// error is never replaced by this observation.
|
|
void observe_autocommit_transition() noexcept
|
|
{
|
|
if (db != nullptr && active_transaction &&
|
|
sqlite3_get_autocommit(db) != 0) {
|
|
active_transaction = false;
|
|
active_transaction_id = 0;
|
|
}
|
|
}
|
|
|
|
~ConnectionState()
|
|
{
|
|
if (db != nullptr) {
|
|
// Unregister SQLite hooks outside interrupt_mu so db->mutex never
|
|
// nests inside interrupt_mu (lock order is strictly interrupt_mu -> db->mutex).
|
|
sqlite3_progress_handler(db, 0, nullptr, nullptr);
|
|
sqlite3_set_authorizer(db, nullptr, nullptr);
|
|
sqlite3* const db_to_close = db;
|
|
{
|
|
std::lock_guard lk{interrupt_mu};
|
|
active_op_gen = 0;
|
|
cancel_requested.store(false, std::memory_order_release);
|
|
db = nullptr;
|
|
}
|
|
progress_predicate.reset();
|
|
const int rc = sqlite3_close(db_to_close);
|
|
if (rc != SQLITE_OK) {
|
|
emit_diagnostic(std::format(
|
|
"Sqlite: deferred close failed (rc={}, msg={})",
|
|
rc,
|
|
sqlite3_errmsg(db_to_close) ? sqlite3_errmsg(db_to_close) : "unknown"));
|
|
(void)sqlite3_close_v2(db_to_close);
|
|
}
|
|
}
|
|
scalar_functions.clear();
|
|
authorizer.reset();
|
|
}
|
|
};
|
|
|
|
int progress_handler_trampoline(void* ctx) noexcept
|
|
{
|
|
auto* conn = static_cast<ConnectionState*>(ctx);
|
|
if (conn == nullptr) {
|
|
return 0;
|
|
}
|
|
// Invoked synchronously on the connection's worker thread while SQLite
|
|
// holds db->mutex; never acquire interrupt_mu here to avoid lock inversion.
|
|
if (conn->cancel_requested.load(std::memory_order_acquire)) {
|
|
return 1;
|
|
}
|
|
const auto pred = conn->progress_predicate;
|
|
if (!pred || !(*pred)) {
|
|
return 0;
|
|
}
|
|
try {
|
|
if ((*pred)()) {
|
|
conn->cancel_requested.store(true, std::memory_order_release);
|
|
return 1;
|
|
}
|
|
} catch (...) {
|
|
conn->cancel_requested.store(true, std::memory_order_release);
|
|
return 1;
|
|
}
|
|
return 0;
|
|
}
|
|
} // namespace detail
|
|
|
|
// ── RowView ──────────────────────────────────────────────────────────────
|
|
|
|
bool RowView::is_valid() const noexcept
|
|
{
|
|
return m_stmt != nullptr &&
|
|
m_stmt->is_open() &&
|
|
m_stmt->has_row() &&
|
|
m_stmt->row_generation() == m_generation;
|
|
}
|
|
|
|
int RowView::column_count() const noexcept
|
|
{
|
|
return is_valid() ? m_stmt->column_count() : 0;
|
|
}
|
|
|
|
Result<ColumnType> RowView::column_type(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse,
|
|
"Sqlite: RowView has expired or belongs to an invalid statement"));
|
|
}
|
|
return m_stmt->column_type(col);
|
|
}
|
|
|
|
Result<bool> RowView::is_null(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
return *ct == ColumnType::Null;
|
|
}
|
|
|
|
Result<std::int64_t> RowView::get_int(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_int"));
|
|
}
|
|
return m_stmt->try_column_int(col);
|
|
}
|
|
|
|
Result<double> RowView::get_double(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_double"));
|
|
}
|
|
return m_stmt->try_column_double(col);
|
|
}
|
|
|
|
Result<std::string_view> RowView::get_text_view(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_text_view"));
|
|
}
|
|
return m_stmt->try_column_text_view(col);
|
|
}
|
|
|
|
Result<std::string> RowView::get_text(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_text"));
|
|
}
|
|
return m_stmt->try_column_text(col);
|
|
}
|
|
|
|
Result<std::span<const std::byte>> RowView::get_blob_view(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_blob_view"));
|
|
}
|
|
return m_stmt->try_column_blob_view(col);
|
|
}
|
|
|
|
Result<std::vector<std::byte>> RowView::get_blob(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_blob"));
|
|
}
|
|
return m_stmt->try_column_blob(col);
|
|
}
|
|
|
|
Result<std::optional<std::int64_t>> RowView::get_optional_int(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_int"));
|
|
}
|
|
return m_stmt->try_column_optional_int(col);
|
|
}
|
|
|
|
Result<std::optional<double>> RowView::get_optional_double(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_double"));
|
|
}
|
|
return m_stmt->try_column_optional_double(col);
|
|
}
|
|
|
|
Result<std::optional<std::string>> RowView::get_optional_text(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_text"));
|
|
}
|
|
return m_stmt->try_column_optional_text(col);
|
|
}
|
|
|
|
Result<std::optional<std::vector<std::byte>>> RowView::get_optional_blob(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_optional_blob"));
|
|
}
|
|
return m_stmt->try_column_optional_blob(col);
|
|
}
|
|
|
|
Result<OwnedValue> RowView::get_value(int col) const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before get_value"));
|
|
}
|
|
return m_stmt->try_column_value(col);
|
|
}
|
|
|
|
Result<OwnedRow> RowView::copy() const
|
|
{
|
|
if (!is_valid()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: RowView expired before copy"));
|
|
}
|
|
return m_stmt->copy_row();
|
|
}
|
|
|
|
// ── Statement ────────────────────────────────────────────────────────────
|
|
|
|
Statement::Statement(
|
|
std::shared_ptr<detail::ConnectionState> conn,
|
|
sqlite3_stmt* stmt) noexcept
|
|
: m_conn(std::move(conn)), m_stmt(stmt)
|
|
{
|
|
}
|
|
|
|
void Statement::release_handle() noexcept
|
|
{
|
|
++m_row_generation;
|
|
m_has_row = false;
|
|
if (m_stmt != nullptr) {
|
|
sqlite3_finalize(m_stmt);
|
|
m_stmt = nullptr;
|
|
if (m_conn && m_conn->live_statements > 0) {
|
|
--m_conn->live_statements;
|
|
}
|
|
}
|
|
m_borrowed_owners.clear();
|
|
m_conn.reset();
|
|
}
|
|
|
|
Statement::~Statement()
|
|
{
|
|
release_handle();
|
|
}
|
|
|
|
Statement::Statement(Statement&& o) noexcept
|
|
: m_conn(std::move(o.m_conn)),
|
|
m_stmt(std::exchange(o.m_stmt, nullptr)),
|
|
m_has_row(std::exchange(o.m_has_row, false)),
|
|
m_row_generation(o.m_row_generation),
|
|
m_borrowed_owners(std::move(o.m_borrowed_owners)),
|
|
m_last_bind_error(std::move(o.m_last_bind_error))
|
|
{
|
|
}
|
|
|
|
Statement& Statement::operator=(Statement&& o) noexcept
|
|
{
|
|
if (this != &o) {
|
|
release_handle();
|
|
m_conn = std::move(o.m_conn);
|
|
m_stmt = std::exchange(o.m_stmt, nullptr);
|
|
m_has_row = std::exchange(o.m_has_row, false);
|
|
m_row_generation = o.m_row_generation;
|
|
m_borrowed_owners = std::move(o.m_borrowed_owners);
|
|
m_last_bind_error = std::move(o.m_last_bind_error);
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
Statement& Statement::bind(int index, std::int64_t value)
|
|
{
|
|
auto r = bind_checked(index, ValueView{value});
|
|
m_last_bind_error = r ? std::nullopt : std::optional<Error>{std::move(r).error()};
|
|
return *this;
|
|
}
|
|
|
|
Statement& Statement::bind(int index, double value)
|
|
{
|
|
auto r = bind_checked(index, ValueView{value});
|
|
m_last_bind_error = r ? std::nullopt : std::optional<Error>{std::move(r).error()};
|
|
return *this;
|
|
}
|
|
|
|
Statement& Statement::bind(int index, std::string_view value)
|
|
{
|
|
auto r = bind_checked(index, ValueView{value});
|
|
m_last_bind_error = r ? std::nullopt : std::optional<Error>{std::move(r).error()};
|
|
return *this;
|
|
}
|
|
|
|
Statement& Statement::bind(int index, std::nullptr_t)
|
|
{
|
|
auto r = bind_checked(index, ValueView{nullptr});
|
|
m_last_bind_error = r ? std::nullopt : std::optional<Error>{std::move(r).error()};
|
|
return *this;
|
|
}
|
|
|
|
Statement& Statement::bind(int index, const std::optional<std::string>& v)
|
|
{
|
|
if (v) return bind(index, std::string_view{*v});
|
|
return bind(index, nullptr);
|
|
}
|
|
|
|
int Statement::bind_parameter_count() const noexcept
|
|
{
|
|
return m_stmt ? sqlite3_bind_parameter_count(m_stmt) : 0;
|
|
}
|
|
|
|
Result<int> Statement::bind_parameter_index(std::string_view name) const
|
|
{
|
|
if (!m_stmt) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: bind_parameter_index on closed statement"));
|
|
}
|
|
if (name.empty() || name.find('\0') != std::string_view::npos) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: invalid bind parameter name"));
|
|
}
|
|
const std::string zname{name};
|
|
const int idx = sqlite3_bind_parameter_index(m_stmt, zname.c_str());
|
|
if (idx <= 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::not_found,
|
|
std::format("Sqlite: bind parameter '{}' not found", name)));
|
|
}
|
|
return idx;
|
|
}
|
|
|
|
Result<void> Statement::bind_checked(int index, ValueView value)
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: bind_checked on finalized statement"));
|
|
}
|
|
const int param_count = sqlite3_bind_parameter_count(m_stmt);
|
|
if (index < 1 || index > param_count) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::range,
|
|
std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count),
|
|
SQLITE_RANGE,
|
|
SQLITE_RANGE));
|
|
}
|
|
|
|
const std::size_t max_val = m_conn->options.limits.max_value_bytes;
|
|
int rc = SQLITE_OK;
|
|
if (value.is_null()) {
|
|
rc = sqlite3_bind_null(m_stmt, index);
|
|
} else if (const auto* iv = std::get_if<std::int64_t>(&value.value)) {
|
|
rc = sqlite3_bind_int64(m_stmt, index, *iv);
|
|
} else if (const auto* dv = std::get_if<double>(&value.value)) {
|
|
rc = sqlite3_bind_double(m_stmt, index, *dv);
|
|
} else if (const auto* sv = std::get_if<std::string_view>(&value.value)) {
|
|
if (sv->size() > max_val) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: bound text length {} exceeds max_value_bytes {}",
|
|
sv->size(), max_val)));
|
|
}
|
|
const char* ptr = sv->empty() ? &kStaticEmptySentinel : sv->data();
|
|
rc = sqlite3_bind_text64(
|
|
m_stmt, index, ptr, static_cast<sqlite3_uint64>(sv->size()),
|
|
SQLITE_TRANSIENT, SQLITE_UTF8);
|
|
} else if (const auto* bv = std::get_if<std::span<const std::byte>>(&value.value)) {
|
|
if (bv->size() > max_val) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: bound blob length {} exceeds max_value_bytes {}",
|
|
bv->size(), max_val)));
|
|
}
|
|
const void* ptr = bv->empty()
|
|
? static_cast<const void*>(&kStaticEmptySentinel)
|
|
: bv->data();
|
|
rc = sqlite3_bind_blob64(
|
|
m_stmt, index, ptr, static_cast<sqlite3_uint64>(bv->size()),
|
|
SQLITE_TRANSIENT);
|
|
}
|
|
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind"));
|
|
}
|
|
|
|
const auto slot = static_cast<std::size_t>(index);
|
|
if (slot < m_borrowed_owners.size()) {
|
|
m_borrowed_owners[slot].reset();
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> Statement::bind_checked(std::string_view name, ValueView value)
|
|
{
|
|
auto idx = bind_parameter_index(name);
|
|
if (!idx) return Void::Result::fail(std::move(idx).error());
|
|
return bind_checked(*idx, value);
|
|
}
|
|
|
|
Result<void> Statement::bind_borrowed_text(
|
|
int index, std::string_view value, std::shared_ptr<const void> owner)
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: bind_borrowed_text on finalized statement"));
|
|
}
|
|
if (!owner) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: bind_borrowed_text requires a non-null lifetime owner"));
|
|
}
|
|
const int param_count = sqlite3_bind_parameter_count(m_stmt);
|
|
if (index < 1 || index > param_count) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::range,
|
|
std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count),
|
|
SQLITE_RANGE,
|
|
SQLITE_RANGE));
|
|
}
|
|
if (value.size() > m_conn->options.limits.max_value_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
"Sqlite: borrowed text exceeds max_value_bytes"));
|
|
}
|
|
const char* ptr = value.empty() ? &kStaticEmptySentinel : value.data();
|
|
const int rc = sqlite3_bind_text64(
|
|
m_stmt, index, ptr, static_cast<sqlite3_uint64>(value.size()),
|
|
SQLITE_STATIC, SQLITE_UTF8);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind_borrowed_text"));
|
|
}
|
|
const auto slot = static_cast<std::size_t>(index);
|
|
if (m_borrowed_owners.size() <= slot) {
|
|
m_borrowed_owners.resize(slot + 1);
|
|
}
|
|
m_borrowed_owners[slot] = std::move(owner);
|
|
return {};
|
|
}
|
|
|
|
Result<void> Statement::bind_borrowed_blob(
|
|
int index, std::span<const std::byte> value, std::shared_ptr<const void> owner)
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: bind_borrowed_blob on finalized statement"));
|
|
}
|
|
if (!owner) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: bind_borrowed_blob requires a non-null lifetime owner"));
|
|
}
|
|
const int param_count = sqlite3_bind_parameter_count(m_stmt);
|
|
if (index < 1 || index > param_count) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::range,
|
|
std::format("Sqlite: bind index {} out of range [1, {}]", index, param_count),
|
|
SQLITE_RANGE,
|
|
SQLITE_RANGE));
|
|
}
|
|
if (value.size() > m_conn->options.limits.max_value_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
"Sqlite: borrowed blob exceeds max_value_bytes"));
|
|
}
|
|
const void* ptr = value.empty()
|
|
? static_cast<const void*>(&kStaticEmptySentinel)
|
|
: value.data();
|
|
const int rc = sqlite3_bind_blob64(
|
|
m_stmt, index, ptr, static_cast<sqlite3_uint64>(value.size()),
|
|
SQLITE_STATIC);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "bind_borrowed_blob"));
|
|
}
|
|
const auto slot = static_cast<std::size_t>(index);
|
|
if (m_borrowed_owners.size() <= slot) {
|
|
m_borrowed_owners.resize(slot + 1);
|
|
}
|
|
m_borrowed_owners[slot] = std::move(owner);
|
|
return {};
|
|
}
|
|
|
|
Result<bool> Statement::step()
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: step on finalized statement"));
|
|
}
|
|
++m_row_generation;
|
|
m_has_row = false;
|
|
|
|
if (!m_conn->active_transaction && sqlite3_stmt_readonly(m_stmt) == 0) {
|
|
const auto wal = m_conn->wal_usage(
|
|
m_conn->options.limits.wal_stop_writes_threshold_bytes);
|
|
if (wal.uncheckpointed_bytes >=
|
|
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::overloaded,
|
|
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
|
|
"threshold; checkpoint required"));
|
|
}
|
|
}
|
|
|
|
const int rc = sqlite3_step(m_stmt);
|
|
m_conn->observe_autocommit_transition();
|
|
if (rc == SQLITE_ROW) {
|
|
m_has_row = true;
|
|
return true;
|
|
}
|
|
if (rc == SQLITE_DONE) {
|
|
return false;
|
|
}
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "step"));
|
|
}
|
|
|
|
void Statement::reset() noexcept
|
|
{
|
|
++m_row_generation;
|
|
m_has_row = false;
|
|
if (m_stmt) {
|
|
sqlite3_reset(m_stmt);
|
|
}
|
|
}
|
|
|
|
Result<void> Statement::reset_checked()
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: reset_checked on finalized statement"));
|
|
}
|
|
++m_row_generation;
|
|
m_has_row = false;
|
|
const int rc = sqlite3_reset(m_stmt);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "reset"));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
void Statement::clear_bindings() noexcept
|
|
{
|
|
if (m_stmt) {
|
|
sqlite3_clear_bindings(m_stmt);
|
|
}
|
|
m_borrowed_owners.clear();
|
|
m_last_bind_error.reset();
|
|
}
|
|
|
|
Result<void> Statement::clear_bindings_checked()
|
|
{
|
|
if (!m_stmt || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: clear_bindings_checked on finalized statement"));
|
|
}
|
|
const int rc = sqlite3_clear_bindings(m_stmt);
|
|
m_borrowed_owners.clear();
|
|
m_last_bind_error.reset();
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "clear_bindings"));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> Statement::finalize_checked()
|
|
{
|
|
++m_row_generation;
|
|
m_has_row = false;
|
|
if (!m_stmt) {
|
|
return {};
|
|
}
|
|
sqlite3* db = m_conn ? m_conn->db : nullptr;
|
|
const int rc = sqlite3_finalize(m_stmt);
|
|
m_stmt = nullptr;
|
|
if (m_conn && m_conn->live_statements > 0) {
|
|
--m_conn->live_statements;
|
|
}
|
|
m_borrowed_owners.clear();
|
|
auto conn_keep = std::move(m_conn);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(db, rc, "finalize"));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
int Statement::column_count() const noexcept
|
|
{
|
|
return m_stmt ? sqlite3_column_count(m_stmt) : 0;
|
|
}
|
|
|
|
bool Statement::is_null(int col) const noexcept
|
|
{
|
|
if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) {
|
|
return true;
|
|
}
|
|
return sqlite3_column_type(m_stmt, col) == SQLITE_NULL;
|
|
}
|
|
|
|
std::int64_t Statement::column_int(int col) const noexcept
|
|
{
|
|
if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) {
|
|
return 0;
|
|
}
|
|
return sqlite3_column_int64(m_stmt, col);
|
|
}
|
|
|
|
double Statement::column_double(int col) const noexcept
|
|
{
|
|
if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) {
|
|
return 0.0;
|
|
}
|
|
return sqlite3_column_double(m_stmt, col);
|
|
}
|
|
|
|
std::string Statement::column_text(int col) const
|
|
{
|
|
if (!m_stmt || !m_has_row || col < 0 || col >= column_count()) {
|
|
return {};
|
|
}
|
|
const auto* p = sqlite3_column_text(m_stmt, col);
|
|
const int n = sqlite3_column_bytes(m_stmt, col);
|
|
if (!p || n <= 0) return {};
|
|
return std::string{reinterpret_cast<const char*>(p),
|
|
static_cast<std::size_t>(n)};
|
|
}
|
|
|
|
Result<void> Statement::validate_column_access(int col) const
|
|
{
|
|
if (!m_stmt || !m_conn) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: column access on finalized statement"));
|
|
}
|
|
if (!m_has_row) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: column access without an active row"));
|
|
}
|
|
const int cols = sqlite3_column_count(m_stmt);
|
|
if (col < 0 || col >= cols) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::range,
|
|
std::format("Sqlite: column index {} out of range [0, {})", col, cols),
|
|
SQLITE_RANGE,
|
|
SQLITE_RANGE));
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<RowView> Statement::current_row() const
|
|
{
|
|
if (!m_stmt || !m_has_row) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse,
|
|
"Sqlite: current_row() requested with no active row"));
|
|
}
|
|
return RowView{this, m_row_generation};
|
|
}
|
|
|
|
Result<ColumnType> Statement::column_type(int col) const
|
|
{
|
|
if (auto v = validate_column_access(col); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
return map_column_type(sqlite3_column_type(m_stmt, col));
|
|
}
|
|
|
|
Result<std::int64_t> Statement::try_column_int(int col) const
|
|
{
|
|
if (auto v = validate_column_access(col); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
const int t = sqlite3_column_type(m_stmt, col);
|
|
if (t != SQLITE_INTEGER) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::type_mismatch,
|
|
std::format("Sqlite: column {} expected INTEGER, got type {}", col, t)));
|
|
}
|
|
return static_cast<std::int64_t>(sqlite3_column_int64(m_stmt, col));
|
|
}
|
|
|
|
Result<double> Statement::try_column_double(int col) const
|
|
{
|
|
if (auto v = validate_column_access(col); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
const int t = sqlite3_column_type(m_stmt, col);
|
|
if (t != SQLITE_FLOAT) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::type_mismatch,
|
|
std::format("Sqlite: column {} expected REAL, got type {}", col, t)));
|
|
}
|
|
return sqlite3_column_double(m_stmt, col);
|
|
}
|
|
|
|
Result<std::string_view> Statement::try_column_text_view(int col) const
|
|
{
|
|
if (auto v = validate_column_access(col); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
const int t = sqlite3_column_type(m_stmt, col);
|
|
if (t != SQLITE_TEXT) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::type_mismatch,
|
|
std::format("Sqlite: column {} expected TEXT, got type {}", col, t)));
|
|
}
|
|
const auto* p = sqlite3_column_text(m_stmt, col);
|
|
const int n = sqlite3_column_bytes(m_stmt, col);
|
|
if (n < 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::sqlite_error, "Sqlite: negative column byte length"));
|
|
}
|
|
const auto sz = static_cast<std::size_t>(n);
|
|
if (sz > m_conn->options.limits.max_value_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: column {} text size {} exceeds max_value_bytes {}",
|
|
col, sz, m_conn->options.limits.max_value_bytes)));
|
|
}
|
|
if (sz == 0 || p == nullptr) {
|
|
return std::string_view{};
|
|
}
|
|
return std::string_view{reinterpret_cast<const char*>(p), sz};
|
|
}
|
|
|
|
Result<std::string> Statement::try_column_text(int col) const
|
|
{
|
|
auto sv = try_column_text_view(col);
|
|
if (!sv) return Void::Result::fail(std::move(sv).error());
|
|
return std::string{*sv};
|
|
}
|
|
|
|
Result<std::span<const std::byte>> Statement::try_column_blob_view(int col) const
|
|
{
|
|
if (auto v = validate_column_access(col); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
const int t = sqlite3_column_type(m_stmt, col);
|
|
if (t != SQLITE_BLOB) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::type_mismatch,
|
|
std::format("Sqlite: column {} expected BLOB, got type {}", col, t)));
|
|
}
|
|
const auto* p = sqlite3_column_blob(m_stmt, col);
|
|
const int n = sqlite3_column_bytes(m_stmt, col);
|
|
if (n < 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::sqlite_error, "Sqlite: negative blob length"));
|
|
}
|
|
const auto sz = static_cast<std::size_t>(n);
|
|
if (sz > m_conn->options.limits.max_value_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: column {} blob size {} exceeds max_value_bytes {}",
|
|
col, sz, m_conn->options.limits.max_value_bytes)));
|
|
}
|
|
if (sz == 0 || p == nullptr) {
|
|
return std::span<const std::byte>{};
|
|
}
|
|
return std::span<const std::byte>{static_cast<const std::byte*>(p), sz};
|
|
}
|
|
|
|
Result<std::vector<std::byte>> Statement::try_column_blob(int col) const
|
|
{
|
|
auto bv = try_column_blob_view(col);
|
|
if (!bv) return Void::Result::fail(std::move(bv).error());
|
|
return std::vector<std::byte>{bv->begin(), bv->end()};
|
|
}
|
|
|
|
Result<std::optional<std::int64_t>> Statement::try_column_optional_int(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
if (*ct == ColumnType::Null) return std::optional<std::int64_t>{std::nullopt};
|
|
auto v = try_column_int(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return std::optional<std::int64_t>{*v};
|
|
}
|
|
|
|
Result<std::optional<double>> Statement::try_column_optional_double(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
if (*ct == ColumnType::Null) return std::optional<double>{std::nullopt};
|
|
auto v = try_column_double(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return std::optional<double>{*v};
|
|
}
|
|
|
|
Result<std::optional<std::string>> Statement::try_column_optional_text(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
if (*ct == ColumnType::Null) return std::optional<std::string>{std::nullopt};
|
|
auto v = try_column_text(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return std::optional<std::string>{std::move(*v)};
|
|
}
|
|
|
|
Result<std::optional<std::vector<std::byte>>> Statement::try_column_optional_blob(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
if (*ct == ColumnType::Null) return std::optional<std::vector<std::byte>>{std::nullopt};
|
|
auto v = try_column_blob(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return std::optional<std::vector<std::byte>>{std::move(*v)};
|
|
}
|
|
|
|
Result<OwnedValue> Statement::try_column_value(int col) const
|
|
{
|
|
auto ct = column_type(col);
|
|
if (!ct) return Void::Result::fail(std::move(ct).error());
|
|
switch (*ct) {
|
|
case ColumnType::Null:
|
|
return OwnedValue{nullptr};
|
|
case ColumnType::Integer: {
|
|
auto v = try_column_int(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return OwnedValue{*v};
|
|
}
|
|
case ColumnType::Real: {
|
|
auto v = try_column_double(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return OwnedValue{*v};
|
|
}
|
|
case ColumnType::Text: {
|
|
auto v = try_column_text(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return OwnedValue{std::move(*v)};
|
|
}
|
|
case ColumnType::Blob: {
|
|
auto v = try_column_blob(col);
|
|
if (!v) return Void::Result::fail(std::move(v).error());
|
|
return OwnedValue{std::move(*v)};
|
|
}
|
|
}
|
|
return OwnedValue{nullptr};
|
|
}
|
|
|
|
Result<OwnedRow> Statement::copy_row() const
|
|
{
|
|
if (!m_stmt || !m_has_row) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: copy_row with no active row"));
|
|
}
|
|
const int cols = sqlite3_column_count(m_stmt);
|
|
OwnedRow row;
|
|
row.columns.reserve(static_cast<std::size_t>(std::max(0, cols)));
|
|
for (int c = 0; c < cols; ++c) {
|
|
auto val = try_column_value(c);
|
|
if (!val) return Void::Result::fail(std::move(val).error());
|
|
row.columns.push_back(std::move(*val));
|
|
}
|
|
return row;
|
|
}
|
|
|
|
// ── Transaction ──────────────────────────────────────────────────────────
|
|
|
|
Transaction::Transaction(
|
|
std::shared_ptr<detail::ConnectionState> conn,
|
|
std::uint64_t id) noexcept
|
|
: m_conn(std::move(conn)), m_id(id), m_state(TransactionState::Active)
|
|
{
|
|
}
|
|
|
|
void Transaction::refresh_state() const noexcept
|
|
{
|
|
if (m_state != TransactionState::Active || !m_conn || m_conn->db == nullptr) {
|
|
return;
|
|
}
|
|
const bool owns_connection_transaction =
|
|
m_conn->active_transaction && m_conn->active_transaction_id == m_id;
|
|
if (!owns_connection_transaction ||
|
|
sqlite3_get_autocommit(m_conn->db) != 0) {
|
|
m_state = TransactionState::RolledBack;
|
|
if (m_conn->active_transaction_id == m_id) {
|
|
m_conn->active_transaction = false;
|
|
m_conn->active_transaction_id = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
TransactionState Transaction::state() const noexcept
|
|
{
|
|
refresh_state();
|
|
return m_state;
|
|
}
|
|
|
|
bool Transaction::is_active() const noexcept
|
|
{
|
|
return state() == TransactionState::Active;
|
|
}
|
|
|
|
Transaction::~Transaction()
|
|
{
|
|
refresh_state();
|
|
if (m_state == TransactionState::Active) {
|
|
auto r = rollback_checked();
|
|
if (!r && m_conn) {
|
|
m_conn->emit_diagnostic(r.error().message());
|
|
}
|
|
}
|
|
}
|
|
|
|
Transaction::Transaction(Transaction&& o) noexcept
|
|
: m_conn(std::move(o.m_conn)),
|
|
m_id(std::exchange(o.m_id, 0)),
|
|
m_state(std::exchange(o.m_state, TransactionState::RolledBack))
|
|
{
|
|
}
|
|
|
|
Transaction& Transaction::operator=(Transaction&& o) noexcept
|
|
{
|
|
if (this != &o) {
|
|
refresh_state();
|
|
if (m_state == TransactionState::Active) {
|
|
auto r = rollback_checked();
|
|
if (!r && m_conn) {
|
|
m_conn->emit_diagnostic(r.error().message());
|
|
}
|
|
}
|
|
m_conn = std::move(o.m_conn);
|
|
m_id = std::exchange(o.m_id, 0);
|
|
m_state = std::exchange(o.m_state, TransactionState::RolledBack);
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
Result<void> Transaction::commit()
|
|
{
|
|
refresh_state();
|
|
if (m_state != TransactionState::Active) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse,
|
|
m_state == TransactionState::RolledBack
|
|
? "Sqlite: commit() called on a transaction that was already rolled back"
|
|
: "Sqlite: commit() called on non-active transaction"));
|
|
}
|
|
if (!m_conn || m_conn->db == nullptr) {
|
|
m_state = TransactionState::RecoveryRequired;
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::recovery_required,
|
|
"Sqlite: transaction lost its underlying connection before commit"));
|
|
}
|
|
|
|
const auto fault = consume_fault_commit();
|
|
if (fault.fail_next_commit_rc != 0) {
|
|
if (fault.auto_rollback_on_faulted_commit) {
|
|
(void)sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, nullptr);
|
|
}
|
|
if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
|
m_state = TransactionState::Active;
|
|
m_conn->active_transaction = true;
|
|
m_conn->active_transaction_id = m_id;
|
|
} else {
|
|
m_state = TransactionState::RolledBack;
|
|
m_conn->active_transaction = false;
|
|
m_conn->active_transaction_id = 0;
|
|
}
|
|
return Void::Result::fail(make_sqlite_error(
|
|
map_sqlite_rc(fault.fail_next_commit_rc),
|
|
"Sqlite: injected commit failure",
|
|
fault.fail_next_commit_rc,
|
|
fault.fail_next_commit_rc));
|
|
}
|
|
|
|
char* err = nullptr;
|
|
const int rc = sqlite3_exec(m_conn->db, "COMMIT", nullptr, nullptr, &err);
|
|
if (rc == SQLITE_OK) {
|
|
m_state = TransactionState::Committed;
|
|
m_conn->active_transaction = false;
|
|
m_conn->active_transaction_id = 0;
|
|
return {};
|
|
}
|
|
|
|
std::string msg = err ? err : sqlite3_errmsg(m_conn->db);
|
|
if (err) sqlite3_free(err);
|
|
const int ext = sqlite3_extended_errcode(m_conn->db);
|
|
|
|
// SQLite may leave the transaction active after errors like SQLITE_BUSY
|
|
// or auto-roll it back on constraints/IO/full. Query autocommit before
|
|
// updating wrapper state!
|
|
if (sqlite3_get_autocommit(m_conn->db) == 0) {
|
|
m_state = TransactionState::Active;
|
|
m_conn->active_transaction = true;
|
|
m_conn->active_transaction_id = m_id;
|
|
} else {
|
|
m_state = TransactionState::RolledBack;
|
|
m_conn->active_transaction = false;
|
|
m_conn->active_transaction_id = 0;
|
|
}
|
|
|
|
return Void::Result::fail(make_sqlite_error(
|
|
map_sqlite_rc(rc),
|
|
std::format("Sqlite: commit: {}", msg),
|
|
rc,
|
|
ext));
|
|
}
|
|
|
|
Result<void> Transaction::rollback_checked()
|
|
{
|
|
refresh_state();
|
|
if (m_state == TransactionState::RolledBack) {
|
|
return {};
|
|
}
|
|
if (m_state != TransactionState::Active) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse,
|
|
"Sqlite: rollback() called on finalized transaction"));
|
|
}
|
|
if (!m_conn || m_conn->db == nullptr) {
|
|
m_state = TransactionState::RecoveryRequired;
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::recovery_required,
|
|
"Sqlite: transaction missing connection during rollback"));
|
|
}
|
|
|
|
char* err = nullptr;
|
|
const int rc = sqlite3_exec(m_conn->db, "ROLLBACK", nullptr, nullptr, &err);
|
|
std::string msg = err ? err : (rc == SQLITE_OK ? "" : sqlite3_errmsg(m_conn->db));
|
|
if (err) sqlite3_free(err);
|
|
|
|
if (rc == SQLITE_OK || sqlite3_get_autocommit(m_conn->db) != 0) {
|
|
m_state = TransactionState::RolledBack;
|
|
m_conn->active_transaction = false;
|
|
m_conn->active_transaction_id = 0;
|
|
return {};
|
|
}
|
|
|
|
m_state = TransactionState::RecoveryRequired;
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::recovery_required,
|
|
std::format("Sqlite: rollback failed while autocommit remains 0: {}", msg),
|
|
rc,
|
|
sqlite3_extended_errcode(m_conn->db)));
|
|
}
|
|
|
|
void Transaction::rollback() noexcept
|
|
{
|
|
(void)rollback_checked();
|
|
}
|
|
|
|
// ── Savepoint ────────────────────────────────────────────────────────────
|
|
|
|
Savepoint::Savepoint(
|
|
std::shared_ptr<detail::ConnectionState> conn,
|
|
std::string name) noexcept
|
|
: m_conn(std::move(conn)), m_name(std::move(name)), m_active(true)
|
|
{
|
|
}
|
|
|
|
Savepoint::~Savepoint()
|
|
{
|
|
if (m_active) {
|
|
auto r = rollback_and_release();
|
|
if (!r && m_conn) {
|
|
m_conn->emit_diagnostic(r.error().message());
|
|
}
|
|
}
|
|
}
|
|
|
|
Savepoint::Savepoint(Savepoint&& o) noexcept
|
|
: m_conn(std::move(o.m_conn)),
|
|
m_name(std::move(o.m_name)),
|
|
m_active(std::exchange(o.m_active, false))
|
|
{
|
|
}
|
|
|
|
Savepoint& Savepoint::operator=(Savepoint&& o) noexcept
|
|
{
|
|
if (this != &o) {
|
|
if (m_active) {
|
|
auto r = rollback_and_release();
|
|
if (!r && m_conn) {
|
|
m_conn->emit_diagnostic(r.error().message());
|
|
}
|
|
}
|
|
m_conn = std::move(o.m_conn);
|
|
m_name = std::move(o.m_name);
|
|
m_active = std::exchange(o.m_active, false);
|
|
}
|
|
return *this;
|
|
}
|
|
|
|
Result<void> Savepoint::release()
|
|
{
|
|
if (!m_active || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: savepoint is not active"));
|
|
}
|
|
auto r = exec_raw_sql(m_conn->db, std::format("RELEASE SAVEPOINT {}", m_name), "release savepoint");
|
|
if (r) {
|
|
m_active = false;
|
|
if (m_conn->open_savepoints > 0) {
|
|
--m_conn->open_savepoints;
|
|
}
|
|
}
|
|
return r;
|
|
}
|
|
|
|
Result<void> Savepoint::rollback_to()
|
|
{
|
|
if (!m_active || !m_conn || m_conn->db == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: savepoint is not active"));
|
|
}
|
|
return exec_raw_sql(m_conn->db, std::format("ROLLBACK TO SAVEPOINT {}", m_name), "rollback savepoint");
|
|
}
|
|
|
|
Result<void> Savepoint::rollback_and_release()
|
|
{
|
|
if (!m_active) {
|
|
return {};
|
|
}
|
|
if (!m_conn || m_conn->db == nullptr) {
|
|
m_active = false;
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: savepoint connection missing"));
|
|
}
|
|
auto r1 = exec_raw_sql(m_conn->db, std::format("ROLLBACK TO SAVEPOINT {}", m_name), "rollback savepoint");
|
|
auto r2 = exec_raw_sql(m_conn->db, std::format("RELEASE SAVEPOINT {}", m_name), "release savepoint");
|
|
if (r2) {
|
|
m_active = false;
|
|
if (m_conn->open_savepoints > 0) {
|
|
--m_conn->open_savepoints;
|
|
}
|
|
}
|
|
if (!r1) return r1;
|
|
return r2;
|
|
}
|
|
|
|
// ── Database ─────────────────────────────────────────────────────────────
|
|
|
|
Database::Database(std::shared_ptr<detail::ConnectionState> conn) noexcept
|
|
: m_conn(std::move(conn))
|
|
{
|
|
}
|
|
|
|
Database::~Database() = default;
|
|
Database::Database(Database&&) noexcept = default;
|
|
Database& Database::operator=(Database&&) noexcept = default;
|
|
|
|
Result<Database> Database::open(const std::filesystem::path& path, OpenMode mode)
|
|
{
|
|
OpenOptions opts;
|
|
opts.mode = mode;
|
|
return open_with_options(path, std::move(opts));
|
|
}
|
|
|
|
Result<Database> Database::open_with_options(
|
|
const std::filesystem::path& path,
|
|
OpenOptions options)
|
|
{
|
|
if (auto v = validate_limits(options.limits); !v) {
|
|
return Void::Result::fail(std::move(v).error());
|
|
}
|
|
|
|
int flags = SQLITE_OPEN_FULLMUTEX;
|
|
switch (options.mode) {
|
|
case OpenMode::ReadOnly:
|
|
flags |= SQLITE_OPEN_READONLY;
|
|
break;
|
|
case OpenMode::ReadWrite:
|
|
flags |= SQLITE_OPEN_READWRITE;
|
|
break;
|
|
case OpenMode::ReadWriteCreate:
|
|
flags |= SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE;
|
|
break;
|
|
}
|
|
const std::string path_str = path.string();
|
|
if (path_str.starts_with("file:")) {
|
|
flags |= SQLITE_OPEN_URI;
|
|
}
|
|
|
|
sqlite3* raw_db = nullptr;
|
|
const int open_rc = sqlite3_open_v2(path_str.c_str(), &raw_db, flags, nullptr);
|
|
if (open_rc != SQLITE_OK) {
|
|
Error err = raw_db ? sqlite_error_from_db(raw_db, open_rc, "open")
|
|
: make_sqlite_error(map_sqlite_rc(open_rc),
|
|
std::format("Sqlite: open failed: {}",
|
|
sqlite3_errstr(open_rc)),
|
|
open_rc, open_rc);
|
|
if (raw_db) {
|
|
sqlite3_close_v2(raw_db);
|
|
}
|
|
return Void::Result::fail(std::move(err));
|
|
}
|
|
|
|
auto state = std::make_shared<detail::ConnectionState>();
|
|
state->db = raw_db;
|
|
state->path = path;
|
|
state->options = std::move(options);
|
|
state->caps.sqlite_version = sqlite3_libversion();
|
|
state->caps.sqlite_version_number = sqlite3_libversion_number();
|
|
state->caps.threadsafe_mode = sqlite3_threadsafe();
|
|
state->caps.in_memory = is_memory_path(path);
|
|
state->caps.read_only = (state->options.mode == OpenMode::ReadOnly) ||
|
|
(sqlite3_db_readonly(raw_db, "main") > 0);
|
|
if (auto page_size = query_single_int_pragma(raw_db, "PRAGMA page_size");
|
|
page_size && *page_size > 0) {
|
|
state->page_size = *page_size;
|
|
}
|
|
|
|
// Disable extension loading by default.
|
|
int ext_enabled = 0;
|
|
const int want_ext = state->options.allow_extension_loading ? 1 : 0;
|
|
const int cfg_rc = sqlite3_db_config(
|
|
raw_db, SQLITE_DBCONFIG_ENABLE_LOAD_EXTENSION, want_ext, &ext_enabled);
|
|
if (cfg_rc != SQLITE_OK || ext_enabled != want_ext) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
"Sqlite: failed to configure extension-loading policy",
|
|
cfg_rc,
|
|
cfg_rc));
|
|
}
|
|
state->caps.extension_loading_enabled = (ext_enabled != 0);
|
|
|
|
// Apply native SQLite byte limits. Keep SQLITE_LIMIT_LENGTH at least 4096
|
|
// so internal sqlite_schema DDL rows remain functional even when callers
|
|
// configure strict small value limits on wrapper binds/reads.
|
|
sqlite3_limit(raw_db, SQLITE_LIMIT_SQL_LENGTH,
|
|
clamp_to_int(state->options.limits.max_sql_bytes));
|
|
sqlite3_limit(raw_db, SQLITE_LIMIT_LENGTH,
|
|
clamp_to_int(std::max<std::size_t>(
|
|
state->options.limits.max_value_bytes, 4096)));
|
|
|
|
// Apply busy timeout.
|
|
const auto busy_ms = state->options.limits.busy_timeout.count();
|
|
const int clamped_busy = busy_ms > INT_MAX ? INT_MAX : static_cast<int>(busy_ms);
|
|
const int busy_rc = sqlite3_busy_timeout(raw_db, clamped_busy);
|
|
if (busy_rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(raw_db, busy_rc, "busy_timeout"));
|
|
}
|
|
|
|
if (!state->caps.read_only) {
|
|
// Apply and verify foreign_keys pragma.
|
|
const char* fk_sql = state->options.foreign_keys ? "PRAGMA foreign_keys=ON"
|
|
: "PRAGMA foreign_keys=OFF";
|
|
if (auto r = exec_raw_sql(raw_db, fk_sql, "pragma foreign_keys"); !r) {
|
|
return Void::Result::fail(std::move(r).error());
|
|
}
|
|
auto fk_eff = query_single_int_pragma(raw_db, "PRAGMA foreign_keys");
|
|
if (!fk_eff) return Void::Result::fail(std::move(fk_eff).error());
|
|
const int want_fk = state->options.foreign_keys ? 1 : 0;
|
|
if (*fk_eff != want_fk) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
"Sqlite: effective foreign_keys pragma did not match requested configuration"));
|
|
}
|
|
state->caps.foreign_keys = (*fk_eff != 0);
|
|
|
|
if (!state->caps.in_memory) {
|
|
// Apply and verify journal_mode.
|
|
const std::string want_jm =
|
|
(state->options.journal_mode == JournalMode::Wal) ? "wal" : "delete";
|
|
std::string got_jm;
|
|
if (auto r = query_single_text_pragma(
|
|
raw_db,
|
|
std::format("PRAGMA journal_mode={}", want_jm),
|
|
got_jm);
|
|
!r) {
|
|
return Void::Result::fail(std::move(r).error());
|
|
}
|
|
if (ascii_lower(got_jm) != want_jm) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
std::format("Sqlite: requested journal_mode='{}', effective='{}'",
|
|
want_jm, got_jm)));
|
|
}
|
|
state->caps.journal_mode = ascii_lower(got_jm);
|
|
|
|
// Apply and verify synchronous mode.
|
|
const int want_sync = (state->options.sync_mode == SyncMode::Full) ? 2 : 1;
|
|
const char* sync_sql = (state->options.sync_mode == SyncMode::Full)
|
|
? "PRAGMA synchronous=FULL"
|
|
: "PRAGMA synchronous=NORMAL";
|
|
if (auto r = exec_raw_sql(raw_db, sync_sql, "pragma synchronous"); !r) {
|
|
return Void::Result::fail(std::move(r).error());
|
|
}
|
|
auto got_sync = query_single_int_pragma(raw_db, "PRAGMA synchronous");
|
|
if (!got_sync) return Void::Result::fail(std::move(got_sync).error());
|
|
if (*got_sync != want_sync) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::unsupported_pragma,
|
|
std::format("Sqlite: requested synchronous={}, effective={}",
|
|
want_sync, *got_sync)));
|
|
}
|
|
state->caps.synchronous_mode = *got_sync;
|
|
} else {
|
|
state->caps.journal_mode = "memory";
|
|
auto got_sync = query_single_int_pragma(raw_db, "PRAGMA synchronous");
|
|
if (got_sync) state->caps.synchronous_mode = *got_sync;
|
|
}
|
|
} else {
|
|
std::string got_jm;
|
|
if (auto r = query_single_text_pragma(raw_db, "PRAGMA journal_mode", got_jm); r) {
|
|
state->caps.journal_mode = ascii_lower(got_jm);
|
|
}
|
|
if (auto s = query_single_int_pragma(raw_db, "PRAGMA synchronous"); s) {
|
|
state->caps.synchronous_mode = *s;
|
|
}
|
|
if (auto f = query_single_int_pragma(raw_db, "PRAGMA foreign_keys"); f) {
|
|
state->caps.foreign_keys = (*f != 0);
|
|
}
|
|
}
|
|
|
|
return Database{std::move(state)};
|
|
}
|
|
|
|
Result<void> Database::exec(std::string_view sql)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: exec on closed database"));
|
|
}
|
|
if (m_conn->closing) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: exec rejected while closing"));
|
|
}
|
|
if (sql.size() > m_conn->options.limits.max_sql_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: exec SQL length {} exceeds max_sql_bytes {}",
|
|
sql.size(), m_conn->options.limits.max_sql_bytes)));
|
|
}
|
|
if (sql.find('\0') != std::string_view::npos) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte"));
|
|
}
|
|
const std::string s{sql};
|
|
auto result = exec_raw_sql(m_conn->db, s, "exec");
|
|
m_conn->observe_autocommit_transition();
|
|
return result;
|
|
}
|
|
|
|
Result<Statement> Database::prepare(std::string_view sql)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: prepare on closed database"));
|
|
}
|
|
if (m_conn->closing) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: prepare rejected while closing"));
|
|
}
|
|
if (sql.size() > m_conn->options.limits.max_sql_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: prepare SQL length {} exceeds max_sql_bytes {}",
|
|
sql.size(), m_conn->options.limits.max_sql_bytes)));
|
|
}
|
|
if (m_conn->live_statements >= m_conn->options.limits.max_live_statements) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::statement_limit,
|
|
std::format("Sqlite: live_statements {} reached max_live_statements {}",
|
|
m_conn->live_statements,
|
|
m_conn->options.limits.max_live_statements)));
|
|
}
|
|
if (sql.find('\0') != std::string_view::npos) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument, "Sqlite: SQL contains embedded NUL byte"));
|
|
}
|
|
|
|
sqlite3_stmt* stmt = nullptr;
|
|
const char* tail = nullptr;
|
|
const int rc = sqlite3_prepare_v2(
|
|
m_conn->db,
|
|
sql.data(),
|
|
clamp_to_int(sql.size()),
|
|
&stmt,
|
|
&tail);
|
|
if (rc != SQLITE_OK) {
|
|
if (stmt) sqlite3_finalize(stmt);
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "prepare"));
|
|
}
|
|
if (tail != nullptr) {
|
|
const char* const end = sql.data() + sql.size();
|
|
for (const char* p = tail; p < end; ++p) {
|
|
if (!is_ascii_whitespace(*p)) {
|
|
if (stmt) sqlite3_finalize(stmt);
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::trailing_sql,
|
|
"Sqlite: prepare requires a single statement (non-whitespace trailing SQL rejected)"));
|
|
}
|
|
}
|
|
}
|
|
if (stmt == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: prepare received empty or comment-only SQL"));
|
|
}
|
|
++m_conn->live_statements;
|
|
return Statement{m_conn, stmt};
|
|
}
|
|
|
|
Result<Transaction> Database::begin(BeginMode mode)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: begin on closed database"));
|
|
}
|
|
if (m_conn->closing) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: begin rejected while closing"));
|
|
}
|
|
if (m_conn->active_transaction) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse,
|
|
"Sqlite: nested begin() rejected; use savepoint() for nested scopes"));
|
|
}
|
|
if (mode != BeginMode::Deferred) {
|
|
const auto wal = m_conn->wal_usage(
|
|
m_conn->options.limits.wal_stop_writes_threshold_bytes);
|
|
if (wal.uncheckpointed_bytes >=
|
|
m_conn->options.limits.wal_stop_writes_threshold_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::overloaded,
|
|
"Sqlite: un-checkpointed WAL frames reached write-admission stop "
|
|
"threshold; checkpoint required"));
|
|
}
|
|
}
|
|
|
|
const char* sql = "BEGIN";
|
|
switch (mode) {
|
|
case BeginMode::Deferred: sql = "BEGIN DEFERRED"; break;
|
|
case BeginMode::Immediate: sql = "BEGIN IMMEDIATE"; break;
|
|
case BeginMode::Exclusive: sql = "BEGIN EXCLUSIVE"; break;
|
|
}
|
|
if (auto r = exec_raw_sql(m_conn->db, sql, "begin"); !r) {
|
|
return Void::Result::fail(std::move(r).error());
|
|
}
|
|
m_conn->active_transaction = true;
|
|
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
|
|
if (m_conn->active_transaction_id == 0) {
|
|
m_conn->active_transaction_id = ++m_conn->next_transaction_id;
|
|
}
|
|
return Transaction{m_conn, m_conn->active_transaction_id};
|
|
}
|
|
|
|
Result<Savepoint> Database::savepoint(std::string_view name)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed || m_conn->closing) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: savepoint on closed database"));
|
|
}
|
|
if (!is_valid_savepoint_name(name)) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: invalid savepoint identifier"));
|
|
}
|
|
const std::string sp_name{name};
|
|
if (auto r = exec_raw_sql(m_conn->db, std::format("SAVEPOINT {}", sp_name), "savepoint"); !r) {
|
|
return Void::Result::fail(std::move(r).error());
|
|
}
|
|
++m_conn->open_savepoints;
|
|
return Savepoint{m_conn, sp_name};
|
|
}
|
|
|
|
Result<std::vector<OwnedRow>> Database::query_all(
|
|
Statement& stmt,
|
|
std::size_t max_rows,
|
|
std::size_t max_bytes)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: query_all on closed database"));
|
|
}
|
|
const std::size_t row_cap =
|
|
max_rows == 0 ? m_conn->options.limits.max_query_all_rows : max_rows;
|
|
const std::size_t byte_cap =
|
|
max_bytes == 0 ? m_conn->options.limits.max_query_all_bytes : max_bytes;
|
|
|
|
std::vector<OwnedRow> rows;
|
|
std::size_t total_bytes = 0;
|
|
|
|
for (;;) {
|
|
auto has = stmt.step();
|
|
if (!has) return Void::Result::fail(std::move(has).error());
|
|
if (!*has) break;
|
|
|
|
if (rows.size() >= row_cap) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: query_all exceeded max_rows {}", row_cap)));
|
|
}
|
|
auto row = stmt.copy_row();
|
|
if (!row) return Void::Result::fail(std::move(row).error());
|
|
|
|
std::size_t row_bytes = 0;
|
|
for (const auto& col : row->columns) {
|
|
if (const auto* s = std::get_if<std::string>(&col.value)) {
|
|
row_bytes += s->size();
|
|
} else if (const auto* b = std::get_if<std::vector<std::byte>>(&col.value)) {
|
|
row_bytes += b->size();
|
|
} else if (!col.is_null()) {
|
|
row_bytes += 8;
|
|
}
|
|
}
|
|
if (row_bytes > byte_cap || total_bytes > byte_cap - row_bytes) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::size_limit,
|
|
std::format("Sqlite: query_all exceeded max_bytes {}", byte_cap)));
|
|
}
|
|
total_bytes += row_bytes;
|
|
rows.push_back(std::move(*row));
|
|
}
|
|
|
|
return rows;
|
|
}
|
|
|
|
Result<void> Database::close()
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr || m_conn->closed) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: database is already closed"));
|
|
}
|
|
|
|
m_conn->closing = true;
|
|
if (m_conn->live_statements > 0 ||
|
|
m_conn->active_transaction ||
|
|
m_conn->open_savepoints > 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::busy,
|
|
std::format(
|
|
"Sqlite: cannot close while {} statements, {} tx, {} savepoints are open",
|
|
m_conn->live_statements,
|
|
m_conn->active_transaction ? 1 : 0,
|
|
m_conn->open_savepoints),
|
|
SQLITE_BUSY,
|
|
SQLITE_BUSY));
|
|
}
|
|
|
|
if (const int injected = consume_fault_close(); injected != 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
map_sqlite_rc(injected),
|
|
"Sqlite: injected close failure",
|
|
injected,
|
|
injected));
|
|
}
|
|
|
|
sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr);
|
|
sqlite3_set_authorizer(m_conn->db, nullptr, nullptr);
|
|
{
|
|
std::lock_guard lk{m_conn->interrupt_mu};
|
|
m_conn->active_op_gen = 0;
|
|
m_conn->cancel_requested.store(false, std::memory_order_release);
|
|
}
|
|
m_conn->progress_predicate.reset();
|
|
|
|
const int rc = sqlite3_close(m_conn->db);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "close"));
|
|
}
|
|
{
|
|
std::lock_guard lk{m_conn->interrupt_mu};
|
|
m_conn->db = nullptr;
|
|
}
|
|
m_conn->closed = true;
|
|
m_conn->scalar_functions.clear();
|
|
m_conn->authorizer.reset();
|
|
return {};
|
|
}
|
|
|
|
bool Database::is_open() const noexcept
|
|
{
|
|
return m_conn && m_conn->db != nullptr && !m_conn->closed;
|
|
}
|
|
|
|
EffectiveCapabilities Database::capabilities() const
|
|
{
|
|
return m_conn ? m_conn->caps : EffectiveCapabilities{};
|
|
}
|
|
|
|
ConnectionHealth Database::health() const
|
|
{
|
|
ConnectionHealth out;
|
|
if (!m_conn) return out;
|
|
m_conn->observe_autocommit_transition();
|
|
out.live_statements = m_conn->live_statements;
|
|
out.active_transaction = m_conn->active_transaction;
|
|
out.open_savepoints = m_conn->open_savepoints;
|
|
const auto wal = m_conn->wal_usage(
|
|
m_conn->options.limits.wal_checkpoint_threshold_bytes);
|
|
out.wal_size_bytes = wal.size_bytes;
|
|
out.wal_frames_known = wal.frames_known;
|
|
out.wal_log_frames = std::max(0, wal.log_frames);
|
|
out.wal_checkpointed_frames = std::max(0, wal.checkpointed_frames);
|
|
out.wal_uncheckpointed_frames =
|
|
wal.frames_known
|
|
? std::max(0, wal.log_frames - wal.checkpointed_frames)
|
|
: 0;
|
|
out.wal_uncheckpointed_bytes = wal.uncheckpointed_bytes;
|
|
out.wal_checkpoint_recommended =
|
|
wal.uncheckpointed_bytes >=
|
|
m_conn->options.limits.wal_checkpoint_threshold_bytes;
|
|
out.wal_warn_exceeded =
|
|
wal.uncheckpointed_bytes >= m_conn->options.limits.wal_warn_threshold_bytes;
|
|
out.wal_write_admission_blocked =
|
|
wal.uncheckpointed_bytes >=
|
|
m_conn->options.limits.wal_stop_writes_threshold_bytes;
|
|
return out;
|
|
}
|
|
|
|
const SqliteLimits& Database::limits() const noexcept
|
|
{
|
|
static const SqliteLimits kDefaultLimits{};
|
|
return m_conn ? m_conn->options.limits : kDefaultLimits;
|
|
}
|
|
|
|
std::int64_t Database::last_insert_rowid() const noexcept
|
|
{
|
|
return (m_conn && m_conn->db) ? sqlite3_last_insert_rowid(m_conn->db) : 0;
|
|
}
|
|
|
|
int Database::changes() const noexcept
|
|
{
|
|
return (m_conn && m_conn->db) ? sqlite3_changes(m_conn->db) : 0;
|
|
}
|
|
|
|
Result<int> Database::user_version()
|
|
{
|
|
auto stmt = prepare("PRAGMA user_version");
|
|
if (!stmt) return Void::Result::fail(std::move(stmt).error());
|
|
auto row = stmt->step();
|
|
if (!row) return Void::Result::fail(std::move(row).error());
|
|
if (!*row) return 0;
|
|
return static_cast<int>(stmt->column_int(0));
|
|
}
|
|
|
|
Result<void> Database::migrate(std::span<const Migration> migrations)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: migrate on closed database"));
|
|
}
|
|
|
|
// Validate entire migration plan before executing any SQL.
|
|
int prev_version = 0;
|
|
for (const auto& m : migrations) {
|
|
if (m.version <= 0 || m.version <= prev_version) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: migration versions must be strictly increasing positive ints (got {}, prev {})",
|
|
m.version, prev_version)));
|
|
}
|
|
if (m.sql.empty()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: migration v{} has empty SQL", m.version)));
|
|
}
|
|
prev_version = m.version;
|
|
}
|
|
|
|
auto current = user_version();
|
|
if (!current) return Void::Result::fail(std::move(current).error());
|
|
int version = *current;
|
|
if (!migrations.empty() && version > migrations.back().version) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: database schema v{} is newer than max supplied migration v{}",
|
|
version, migrations.back().version)));
|
|
}
|
|
|
|
for (const auto& m : migrations) {
|
|
if (m.version <= version) continue;
|
|
auto tx = begin(BeginMode::Immediate);
|
|
if (!tx) return Void::Result::fail(std::move(tx).error());
|
|
if (auto r = exec(m.sql); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
if (auto r = exec(std::format("PRAGMA user_version={}", m.version)); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
if (auto r = tx->commit(); !r) {
|
|
if (tx->is_active()) (void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
version = m.version;
|
|
}
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::migrate_checked(std::span<const CheckedMigration> migrations)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: migrate_checked on closed database"));
|
|
}
|
|
if (m_conn->caps.read_only) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::readonly, "Sqlite: migrate_checked on read-only database"));
|
|
}
|
|
|
|
// Validate plan strictly before any read or write.
|
|
int prev_version = 0;
|
|
for (std::size_t i = 0; i < migrations.size(); ++i) {
|
|
const auto& m = migrations[i];
|
|
if (m.version <= 0 || m.version <= prev_version) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
"Sqlite: checked migration versions must be strictly increasing positive ints"));
|
|
}
|
|
if (m.id.empty() || m.checksum.empty() || m.sql.empty()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: checked migration v{} requires non-empty id, checksum, and sql",
|
|
m.version)));
|
|
}
|
|
for (std::size_t j = 0; j < i; ++j) {
|
|
if (migrations[j].id == m.id) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: duplicate migration id '{}'", m.id)));
|
|
}
|
|
}
|
|
prev_version = m.version;
|
|
}
|
|
|
|
auto current = user_version();
|
|
if (!current) return Void::Result::fail(std::move(current).error());
|
|
int version = *current;
|
|
|
|
if (migrations.empty()) {
|
|
if (version > 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
"Sqlite: database schema version exceeds empty migration list"));
|
|
}
|
|
return {};
|
|
}
|
|
if (version > migrations.back().version) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: database schema v{} is newer than max supplied migration v{}",
|
|
version, migrations.back().version)));
|
|
}
|
|
|
|
// Verify existing migration table (without mutating yet).
|
|
bool table_exists = false;
|
|
{
|
|
auto chk = prepare(
|
|
"SELECT 1 FROM sqlite_master WHERE type='table' AND name='_void_schema_migrations'");
|
|
if (!chk) return Void::Result::fail(std::move(chk).error());
|
|
auto step_r = chk->step();
|
|
if (!step_r) return Void::Result::fail(std::move(step_r).error());
|
|
table_exists = *step_r;
|
|
}
|
|
|
|
if (table_exists) {
|
|
auto sel = prepare(
|
|
"SELECT version, id, checksum FROM _void_schema_migrations ORDER BY version ASC");
|
|
if (!sel) return Void::Result::fail(std::move(sel).error());
|
|
for (;;) {
|
|
auto has = sel->step();
|
|
if (!has) return Void::Result::fail(std::move(has).error());
|
|
if (!*has) break;
|
|
auto rv = sel->try_column_int(0);
|
|
auto rid = sel->try_column_text(1);
|
|
auto rsum = sel->try_column_text(2);
|
|
if (!rv || !rid || !rsum) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::corrupt,
|
|
"Sqlite: malformed row in _void_schema_migrations"));
|
|
}
|
|
const CheckedMigration* match = nullptr;
|
|
for (const auto& m : migrations) {
|
|
if (m.version == static_cast<int>(*rv)) {
|
|
match = &m;
|
|
break;
|
|
}
|
|
}
|
|
if (match == nullptr) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: applied migration v{} missing from migration plan", *rv)));
|
|
}
|
|
if (match->id != *rid || match->checksum != *rsum) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
std::format("Sqlite: migration checksum or id drift at version {}", *rv)));
|
|
}
|
|
}
|
|
} else if (version > 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::migration_error,
|
|
"Sqlite: non-zero user_version without _void_schema_migrations history"));
|
|
}
|
|
|
|
bool table_created = table_exists;
|
|
for (const auto& m : migrations) {
|
|
if (m.version <= version) continue;
|
|
|
|
auto tx = begin(BeginMode::Immediate);
|
|
if (!tx) return Void::Result::fail(std::move(tx).error());
|
|
|
|
if (!table_created) {
|
|
if (auto r = exec(
|
|
"CREATE TABLE IF NOT EXISTS _void_schema_migrations("
|
|
"version INTEGER PRIMARY KEY, "
|
|
"id TEXT NOT NULL, "
|
|
"checksum TEXT NOT NULL, "
|
|
"applied_at_ms INTEGER NOT NULL)");
|
|
!r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
}
|
|
|
|
if (auto r = exec(m.sql); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
|
|
{
|
|
auto ins = prepare(
|
|
"INSERT INTO _void_schema_migrations(version, id, checksum, applied_at_ms) "
|
|
"VALUES(?, ?, ?, ?)");
|
|
if (!ins) {
|
|
(void)tx->rollback_checked();
|
|
return Void::Result::fail(std::move(ins).error());
|
|
}
|
|
const auto now_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
|
|
Void::Time::SystemCivilClock::instance().now().time_since_epoch()).count();
|
|
if (auto r = ins->bind_checked(1, ValueView{static_cast<std::int64_t>(m.version)}); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
if (auto r = ins->bind_checked(2, ValueView{m.id}); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
if (auto r = ins->bind_checked(3, ValueView{m.checksum}); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
if (auto r = ins->bind_checked(4, ValueView{static_cast<std::int64_t>(now_ms)}); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
auto sr = ins->step();
|
|
if (!sr) {
|
|
(void)tx->rollback_checked();
|
|
return Void::Result::fail(std::move(sr).error());
|
|
}
|
|
}
|
|
|
|
if (auto r = exec(std::format("PRAGMA user_version={}", m.version)); !r) {
|
|
(void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
|
|
if (auto r = tx->commit(); !r) {
|
|
if (tx->is_active()) (void)tx->rollback_checked();
|
|
return r;
|
|
}
|
|
table_created = true;
|
|
version = m.version;
|
|
}
|
|
|
|
return {};
|
|
}
|
|
|
|
Result<CheckpointReport> Database::checkpoint(CheckpointMode mode)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: checkpoint on closed database"));
|
|
}
|
|
|
|
int native_mode = SQLITE_CHECKPOINT_PASSIVE;
|
|
switch (mode) {
|
|
case CheckpointMode::Passive: native_mode = SQLITE_CHECKPOINT_PASSIVE; break;
|
|
case CheckpointMode::Full: native_mode = SQLITE_CHECKPOINT_FULL; break;
|
|
case CheckpointMode::Restart: native_mode = SQLITE_CHECKPOINT_RESTART; break;
|
|
case CheckpointMode::Truncate: native_mode = SQLITE_CHECKPOINT_TRUNCATE; break;
|
|
}
|
|
|
|
int log_frames = 0;
|
|
int ckpt_frames = 0;
|
|
const int rc = sqlite3_wal_checkpoint_v2(
|
|
m_conn->db, "main", native_mode, &log_frames, &ckpt_frames);
|
|
if (rc != SQLITE_OK && rc != SQLITE_BUSY) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "checkpoint"));
|
|
}
|
|
|
|
CheckpointReport rep;
|
|
rep.log_frames = std::max(0, log_frames);
|
|
rep.checkpointed_frames = std::max(0, ckpt_frames);
|
|
rep.uncheckpointed_frames =
|
|
std::max(0, rep.log_frames - rep.checkpointed_frames);
|
|
rep.busy = (rc == SQLITE_BUSY) || (rep.log_frames > rep.checkpointed_frames);
|
|
rep.wal_size_bytes = m_conn->current_wal_size_bytes();
|
|
return rep;
|
|
}
|
|
|
|
Result<BackupReport> Database::backup_to(
|
|
const std::filesystem::path& destination,
|
|
BackupOptions options)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: backup_to on closed database"));
|
|
}
|
|
if (m_conn->caps.in_memory && destination.empty()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument, "Sqlite: backup destination path is empty"));
|
|
}
|
|
if (options.pages_per_step <= 0 || options.max_steps <= 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument, "Sqlite: BackupOptions bounds must be positive"));
|
|
}
|
|
if (!m_conn->caps.in_memory) {
|
|
std::error_code ec;
|
|
if (std::filesystem::exists(destination, ec) &&
|
|
std::filesystem::equivalent(m_conn->path, destination, ec)) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: backup destination cannot be the active source database"));
|
|
}
|
|
}
|
|
|
|
sqlite3* dst_db = nullptr;
|
|
const int open_rc = sqlite3_open_v2(
|
|
destination.string().c_str(),
|
|
&dst_db,
|
|
SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX,
|
|
nullptr);
|
|
if (open_rc != SQLITE_OK) {
|
|
Error err = sqlite_error_from_db(dst_db, open_rc, "backup open dest");
|
|
if (dst_db) sqlite3_close_v2(dst_db);
|
|
return Void::Result::fail(std::move(err));
|
|
}
|
|
|
|
struct CloseGuard {
|
|
sqlite3* d;
|
|
~CloseGuard() { if (d) sqlite3_close_v2(d); }
|
|
} dst_guard{dst_db};
|
|
|
|
sqlite3_backup* backup = sqlite3_backup_init(dst_db, "main", m_conn->db, "main");
|
|
if (backup == nullptr) {
|
|
return Void::Result::fail(sqlite_error_from_db(dst_db, sqlite3_errcode(dst_db), "backup_init"));
|
|
}
|
|
|
|
BackupReport report;
|
|
int rc = SQLITE_OK;
|
|
for (;;) {
|
|
if (report.steps >= options.max_steps) {
|
|
sqlite3_backup_finish(backup);
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::timeout, "Sqlite: backup exceeded max_steps"));
|
|
}
|
|
rc = sqlite3_backup_step(backup, options.pages_per_step);
|
|
++report.steps;
|
|
if (rc == SQLITE_OK) {
|
|
continue;
|
|
}
|
|
if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
|
|
if (options.step_sleep.count() > 0) {
|
|
std::this_thread::sleep_for(options.step_sleep);
|
|
}
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
|
|
report.total_pages = sqlite3_backup_pagecount(backup);
|
|
report.remaining_pages = sqlite3_backup_remaining(backup);
|
|
const int fin_rc = sqlite3_backup_finish(backup);
|
|
if (rc != SQLITE_DONE || fin_rc != SQLITE_OK) {
|
|
const int err_rc = (fin_rc != SQLITE_OK) ? fin_rc : rc;
|
|
return Void::Result::fail(sqlite_error_from_db(dst_db, err_rc, "backup_step"));
|
|
}
|
|
|
|
// Sync destination explicitly.
|
|
(void)exec_raw_sql(dst_db, "PRAGMA synchronous=FULL", "backup sync");
|
|
const int close_rc = sqlite3_close(dst_db);
|
|
dst_guard.d = nullptr;
|
|
if (close_rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(nullptr, close_rc, "backup close dest"));
|
|
}
|
|
return report;
|
|
}
|
|
|
|
Result<BackupReport> Database::restore_from(
|
|
const std::filesystem::path& source,
|
|
BackupOptions options)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: restore_from on closed database"));
|
|
}
|
|
if (m_conn->caps.read_only) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::readonly, "Sqlite: cannot restore into read-only database"));
|
|
}
|
|
if (m_conn->active_transaction) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::misuse, "Sqlite: cannot restore while transaction is active"));
|
|
}
|
|
if (options.pages_per_step <= 0 || options.max_steps <= 0) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument, "Sqlite: BackupOptions bounds must be positive"));
|
|
}
|
|
std::error_code ec;
|
|
if (!std::filesystem::exists(source, ec)) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::not_found,
|
|
std::format("Sqlite: restore source '{}' does not exist", source.string())));
|
|
}
|
|
if (!m_conn->caps.in_memory &&
|
|
std::filesystem::equivalent(m_conn->path, source, ec)) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: restore source cannot be the active target database"));
|
|
}
|
|
|
|
sqlite3* src_db = nullptr;
|
|
const int open_rc = sqlite3_open_v2(
|
|
source.string().c_str(),
|
|
&src_db,
|
|
SQLITE_OPEN_READONLY | SQLITE_OPEN_FULLMUTEX,
|
|
nullptr);
|
|
if (open_rc != SQLITE_OK) {
|
|
Error err = sqlite_error_from_db(src_db, open_rc, "restore open source");
|
|
if (src_db) sqlite3_close_v2(src_db);
|
|
return Void::Result::fail(std::move(err));
|
|
}
|
|
|
|
struct CloseGuard {
|
|
sqlite3* d;
|
|
~CloseGuard() { if (d) sqlite3_close_v2(d); }
|
|
} src_guard{src_db};
|
|
|
|
sqlite3_backup* backup = sqlite3_backup_init(m_conn->db, "main", src_db, "main");
|
|
if (backup == nullptr) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, sqlite3_errcode(m_conn->db), "restore_init"));
|
|
}
|
|
|
|
BackupReport report;
|
|
int rc = SQLITE_OK;
|
|
for (;;) {
|
|
if (report.steps >= options.max_steps) {
|
|
sqlite3_backup_finish(backup);
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::timeout, "Sqlite: restore exceeded max_steps"));
|
|
}
|
|
rc = sqlite3_backup_step(backup, options.pages_per_step);
|
|
++report.steps;
|
|
if (rc == SQLITE_OK) {
|
|
continue;
|
|
}
|
|
if (rc == SQLITE_BUSY || rc == SQLITE_LOCKED) {
|
|
if (options.step_sleep.count() > 0) {
|
|
std::this_thread::sleep_for(options.step_sleep);
|
|
}
|
|
continue;
|
|
}
|
|
break;
|
|
}
|
|
|
|
report.total_pages = sqlite3_backup_pagecount(backup);
|
|
report.remaining_pages = sqlite3_backup_remaining(backup);
|
|
const int fin_rc = sqlite3_backup_finish(backup);
|
|
if (rc != SQLITE_DONE || fin_rc != SQLITE_OK) {
|
|
const int err_rc = (fin_rc != SQLITE_OK) ? fin_rc : rc;
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, err_rc, "restore_step"));
|
|
}
|
|
|
|
const int close_rc = sqlite3_close(src_db);
|
|
src_guard.d = nullptr;
|
|
if (close_rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(nullptr, close_rc, "restore close source"));
|
|
}
|
|
return report;
|
|
}
|
|
|
|
Result<void> Database::create_scalar_function(
|
|
std::string name,
|
|
int num_args,
|
|
ScalarFunction fn,
|
|
bool deterministic)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: create_scalar_function on closed database"));
|
|
}
|
|
if (name.empty() || !fn) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::invalid_argument,
|
|
"Sqlite: create_scalar_function requires non-empty name and callback"));
|
|
}
|
|
|
|
auto box = std::make_unique<ScalarFunctionBox>(ScalarFunctionBox{std::move(fn)});
|
|
int enc = SQLITE_UTF8;
|
|
if (deterministic) {
|
|
enc |= SQLITE_DETERMINISTIC;
|
|
}
|
|
const int rc = sqlite3_create_function_v2(
|
|
m_conn->db,
|
|
name.c_str(),
|
|
num_args,
|
|
enc,
|
|
box.get(),
|
|
&scalar_function_trampoline,
|
|
nullptr,
|
|
nullptr,
|
|
nullptr);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "create_scalar_function"));
|
|
}
|
|
m_conn->scalar_functions.push_back(std::move(box));
|
|
return {};
|
|
}
|
|
|
|
Result<void> Database::set_authorizer(AuthorizerCallback cb)
|
|
{
|
|
if (!is_open()) {
|
|
return Void::Result::fail(make_sqlite_error(
|
|
SqliteErrorCode::closed, "Sqlite: set_authorizer on closed database"));
|
|
}
|
|
if (!cb) {
|
|
const int rc = sqlite3_set_authorizer(m_conn->db, nullptr, nullptr);
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "clear authorizer"));
|
|
}
|
|
m_conn->authorizer.reset();
|
|
return {};
|
|
}
|
|
auto box = std::make_unique<AuthorizerBox>(AuthorizerBox{std::move(cb)});
|
|
const int rc = sqlite3_set_authorizer(m_conn->db, &authorizer_trampoline, box.get());
|
|
if (rc != SQLITE_OK) {
|
|
return Void::Result::fail(sqlite_error_from_db(m_conn->db, rc, "set_authorizer"));
|
|
}
|
|
m_conn->authorizer = std::move(box);
|
|
return {};
|
|
}
|
|
|
|
sqlite3* Database::handle() const noexcept
|
|
{
|
|
return m_conn ? m_conn->db : nullptr;
|
|
}
|
|
|
|
void Database::begin_leased_operation(
|
|
std::uint64_t generation,
|
|
int progress_steps,
|
|
std::function<bool()> should_interrupt)
|
|
{
|
|
if (!m_conn || m_conn->db == nullptr) return;
|
|
m_conn->progress_predicate =
|
|
should_interrupt
|
|
? std::make_shared<const std::function<bool()>>(std::move(should_interrupt))
|
|
: nullptr;
|
|
if (progress_steps > 0 && m_conn->progress_predicate) {
|
|
sqlite3_progress_handler(
|
|
m_conn->db,
|
|
progress_steps,
|
|
&detail::progress_handler_trampoline,
|
|
m_conn.get());
|
|
} else {
|
|
sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr);
|
|
}
|
|
std::lock_guard lk{m_conn->interrupt_mu};
|
|
m_conn->active_op_gen = generation;
|
|
m_conn->cancel_requested.store(false, std::memory_order_release);
|
|
}
|
|
|
|
void Database::interrupt_leased_operation(std::uint64_t generation) noexcept
|
|
{
|
|
if (!m_conn) return;
|
|
std::lock_guard lk{m_conn->interrupt_mu};
|
|
if (m_conn->db != nullptr && m_conn->active_op_gen == generation && generation != 0) {
|
|
m_conn->cancel_requested.store(true, std::memory_order_release);
|
|
sqlite3_interrupt(m_conn->db);
|
|
}
|
|
}
|
|
|
|
void Database::end_leased_operation(std::uint64_t generation) noexcept
|
|
{
|
|
if (!m_conn) return;
|
|
bool ended = false;
|
|
{
|
|
std::lock_guard lk{m_conn->interrupt_mu};
|
|
if (m_conn->active_op_gen == generation) {
|
|
m_conn->active_op_gen = 0;
|
|
m_conn->cancel_requested.store(false, std::memory_order_release);
|
|
ended = true;
|
|
}
|
|
}
|
|
if (ended) {
|
|
if (m_conn->db != nullptr) {
|
|
sqlite3_progress_handler(m_conn->db, 0, nullptr, nullptr);
|
|
}
|
|
m_conn->progress_predicate.reset();
|
|
}
|
|
}
|
|
|
|
} // namespace Void::Sqlite
|