database.cpp

src/storage/database.cpp

@file database.cpp @brief SqliteDatabase implementation with migration runner.

Owners: @tvanfossen

close

void entropic::SqliteDatabase::close()

Close database connection.

src/storage/database.cpp:221

Show on the map →

Called by SCENARIO, close, ~SqliteDatabase

Calls none

Source · 7 lines
void SqliteDatabase::close() {
    std::lock_guard lock(mutex_);
    if (db_) {
        sqlite3_close(db_);
        db_ = nullptr;
    }
}
Activity · 4 steps
lines 222–222std::lock_guard lock(mutex_);lines 223–223◇ if (db_)lines 224–224sqlite3_close(db_);lines 225–225db_ = nullptr;

Requirements

REQ-STOR-001

execute

bool entropic::SqliteDatabase::execute(std::string_view sql, std::function< void(sqlite3_stmt *)> binder=nullptr)

Execute a write statement (INSERT, UPDATE, DELETE).

src/storage/database.cpp:269

Source · 18 lines
bool SqliteDatabase::execute(std::string_view sql,
                             std::function<void(sqlite3_stmt*)> binder) {
    std::lock_guard lock(mutex_);
    if (!db_) return false;

    auto* stmt = prepare(sql);
    if (!stmt) return false;

    if (binder) binder(stmt);

    int rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    bool ok = (rc == SQLITE_DONE);
    if (!ok) {
        logger->error("SQL execute failed: {}", sqlite3_errmsg(db_));
    }
    return ok;
}
Activity · 14 steps
lines 271–271std::lock_guard lock(mutex_);lines 272–272◇ if (!db_)lines 272–272return false;lines 274–274auto* stmt = prepare(sql);lines 275–275◇ if (!stmt)lines 275–275return false;lines 277–277◇ if (binder)lines 277–277binder(stmt);lines 279–279int rc = sqlite3_step(stmt);lines 280–280sqlite3_finalize(stmt);lines 281–281bool ok = (rc == SQLITE_DONE);lines 282–282◇ if (!ok)lines 283–283logger->error("SQL execute failed: {}", sqlite3_errmsg(db_));lines 285–285return ok;

Requirements

REQ-STOR-002

execute_raw

bool entropic::SqliteDatabase::execute_raw(std::string_view sql)

Execute raw SQL (multiple statements, no binding).

src/storage/database.cpp:295

Show on the map →

Called by none

Calls none

Source · 17 lines
bool SqliteDatabase::execute_raw(std::string_view sql) {
    std::lock_guard lock(mutex_);
    if (!db_) return false;

    char* err_msg = nullptr;
    int rc = sqlite3_exec(
        db_, std::string(sql).c_str(),
        nullptr, nullptr, &err_msg);

    if (rc != SQLITE_OK) {
        logger->error("SQL exec failed: {}",
                      err_msg ? err_msg : "unknown error");
        sqlite3_free(err_msg);
        return false;
    }
    return true;
}
Activity · 10 steps
lines 296–296std::lock_guard lock(mutex_);lines 297–297◇ if (!db_)lines 297–297return false;lines 299–299char* err_msg = nullptr;lines 300–302int rc = sqlite3_exec( db_, std::string(sql).c_str(), nullptr, nullptr, &err_msg);lines 304–304◇ if (rc != SQLITE_OK)lines 305–306logger->error("SQL exec failed: {}", err_msg ? err_msg : "unknown error");lines 307–307sqlite3_free(err_msg);lines 308–308return false;lines 310–310return true;

Requirements

REQ-STOR-002

fetch_all

size_t entropic::SqliteDatabase::fetch_all(std::string_view sql, std::function< void(sqlite3_stmt *)> binder, std::function< void(sqlite3_stmt *)> row_handler)

Fetch all matching rows.

src/storage/database.cpp:353

Source · 21 lines
size_t SqliteDatabase::fetch_all(
        std::string_view sql,
        std::function<void(sqlite3_stmt*)> binder,
        std::function<void(sqlite3_stmt*)> row_handler) {
    std::lock_guard lock(mutex_);
    if (!db_) return 0;

    auto* stmt = prepare(sql);
    if (!stmt) return 0;

    if (binder) binder(stmt);

    size_t count = 0;
    while (sqlite3_step(stmt) == SQLITE_ROW) {
        if (row_handler) row_handler(stmt);
        ++count;
    }

    sqlite3_finalize(stmt);
    return count;
}
Activity · 15 steps
lines 357–357std::lock_guard lock(mutex_);lines 358–358◇ if (!db_)lines 358–358return 0;lines 360–360auto* stmt = prepare(sql);lines 361–361◇ if (!stmt)lines 361–361return 0;lines 363–363◇ if (binder)lines 363–363binder(stmt);lines 365–365size_t count = 0;lines 366–366◇ while (sqlite3_step(stmt) == SQLITE_ROW)lines 367–367◇ if (row_handler)lines 367–367row_handler(stmt);lines 368–368++count;lines 371–371sqlite3_finalize(stmt);lines 372–372return count;

Requirements

REQ-STOR-002

fetch_one

bool entropic::SqliteDatabase::fetch_one(std::string_view sql, std::function< void(sqlite3_stmt *)> binder, std::function< void(sqlite3_stmt *)> extractor)

Fetch a single row.

src/storage/database.cpp:322

Source · 21 lines
bool SqliteDatabase::fetch_one(
        std::string_view sql,
        std::function<void(sqlite3_stmt*)> binder,
        std::function<void(sqlite3_stmt*)> extractor) {
    std::lock_guard lock(mutex_);
    if (!db_) return false;

    auto* stmt = prepare(sql);
    if (!stmt) return false;

    if (binder) binder(stmt);

    int rc = sqlite3_step(stmt);
    bool found = (rc == SQLITE_ROW);
    if (found && extractor) {
        extractor(stmt);
    }

    sqlite3_finalize(stmt);
    return found;
}
Activity · 14 steps
lines 326–326std::lock_guard lock(mutex_);lines 327–327◇ if (!db_)lines 327–327return false;lines 329–329auto* stmt = prepare(sql);lines 330–330◇ if (!stmt)lines 330–330return false;lines 332–332◇ if (binder)lines 332–332binder(stmt);lines 334–334int rc = sqlite3_step(stmt);lines 335–335bool found = (rc == SQLITE_ROW);lines 336–336◇ if (found && extractor)lines 337–337extractor(stmt);lines 340–340sqlite3_finalize(stmt);lines 341–341return found;

Requirements

REQ-STOR-002

initialize

bool entropic::SqliteDatabase::initialize()

Initialize database and run pending migrations.

src/storage/database.cpp:183

Source · 32 lines
bool SqliteDatabase::initialize() {
    std::lock_guard lock(mutex_);

    // Ensure parent directory exists
    auto parent = db_path_.parent_path();
    if (!parent.empty()) {
        std::filesystem::create_directories(parent);
    }

    int rc = sqlite3_open_v2(
        db_path_.c_str(), &db_,
        SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX,
        nullptr);

    if (rc != SQLITE_OK) {
        logger->error("Failed to open database {}: {}",
                      db_path_.string(), sqlite3_errmsg(db_));
        return false;
    }

    // Enable foreign keys and WAL mode
    sqlite3_exec(db_, "PRAGMA foreign_keys = ON", nullptr, nullptr, nullptr);
    sqlite3_exec(db_, "PRAGMA journal_mode = WAL", nullptr, nullptr, nullptr);

    if (!run_migrations()) {
        logger->error("Migration failed for {}", db_path_.string());
        return false;
    }

    logger->info("Database initialized: {}", db_path_.string());
    return true;
}
Activity · 15 steps
lines 184–184std::lock_guard lock(mutex_);lines 187–187auto parent = db_path_.parent_path();lines 188–188◇ if (!parent.empty())lines 189–189std::filesystem::create_directories(parent);lines 192–195int rc = sqlite3_open_v2( db_path_.c_str(), &db_, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE | SQLITE_OPEN_FULLMUTEX, nullptr);lines 197–197◇ if (rc != SQLITE_OK)lines 198–199logger->error("Failed to open database {}: {}", db_path_.string(), sqlite3_errmsg(db_));lines 200–200return false;lines 204–204sqlite3_exec(db_, "PRAGMA foreign_keys = ON", nullptr, nullptr, nullptr);lines 205–205sqlite3_exec(db_, "PRAGMA journal_mode = WAL", nullptr, nullptr, nullptr);lines 207–207◇ if (!run_migrations())lines 208–208logger->error("Migration failed for {}", db_path_.string());lines 209–209return false;lines 212–212logger->info("Database initialized: {}", db_path_.string());lines 213–213return true;

Requirements

REQ-STOR-001

is_open

bool entropic::SqliteDatabase::is_open() const

Check if database is open.

src/storage/database.cpp:235

Show on the map →

Called by SCENARIO

Calls none

Source · 4 lines
bool SqliteDatabase::is_open() const {
    std::lock_guard lock(mutex_);
    return db_ != nullptr;
}
Activity · 2 steps
lines 236–236std::lock_guard lock(mutex_);lines 237–237return db_ != nullptr;

Requirements

REQ-STOR-001

prepare

sqlite3_stmt * entropic::SqliteDatabase::prepare(std::string_view sql)

Prepare a SQL statement.

src/storage/database.cpp:247

Source · 13 lines
sqlite3_stmt* SqliteDatabase::prepare(std::string_view sql) {
    sqlite3_stmt* stmt = nullptr;
    int rc = sqlite3_prepare_v2(
        db_, sql.data(), static_cast<int>(sql.size()),
        &stmt, nullptr);

    if (rc != SQLITE_OK) {
        logger->error("SQL prepare failed: {} — {}",
                      sqlite3_errmsg(db_), std::string(sql));
        return nullptr;
    }
    return stmt;
}
Activity · 6 steps
lines 248–248sqlite3_stmt* stmt = nullptr;lines 249–251int rc = sqlite3_prepare_v2( db_, sql.data(), static_cast<int>(sql.size()), &stmt, nullptr);lines 253–253◇ if (rc != SQLITE_OK)lines 254–255logger->error("SQL prepare failed: {} — {}", sqlite3_errmsg(db_), std::string(sql));lines 256–256return nullptr;lines 258–258return stmt;

Requirements

REQ-STOR-002

run_migrations

bool entropic::SqliteDatabase::run_migrations()

Run all pending migrations.

src/storage/database.cpp:469

Show on the map →

Called by initialize

Calls apply_migration, get_applied_migrations, is_applied

Source · 24 lines
bool SqliteDatabase::run_migrations() {
    char* err_msg = nullptr;
    int rc = sqlite3_exec(db_,
        "CREATE TABLE IF NOT EXISTS migrations ("
        "  id INTEGER PRIMARY KEY,"
        "  name TEXT UNIQUE,"
        "  applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP"
        ")",
        nullptr, nullptr, &err_msg);

    if (rc != SQLITE_OK) {
        logger->error("Failed to create migrations table: {}",
                      err_msg ? err_msg : "unknown");
        sqlite3_free(err_msg);
        return false;
    }

    auto applied = get_applied_migrations(db_);
    for (const auto& mig : MIGRATIONS) {
        if (is_applied(applied, mig.name)) continue;
        if (!apply_migration(db_, mig)) return false;
    }
    return true;
}
Activity · 13 steps
lines 470–470char* err_msg = nullptr;lines 471–477int rc = sqlite3_exec(db_, "CREATE TABLE IF NOT EXISTS migrations (" " id INTEGER PRIMARY KEY," " name TEXT UNIQUE," " applied_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP" ")", nullptr, nullptr, &err_msg);lines 479–479◇ if (rc != SQLITE_OK)lines 480–481logger->error("Failed to create migrations table: {}", err_msg ? err_msg : "unknown");lines 482–482sqlite3_free(err_msg);lines 483–483return false;lines 486–486auto applied = get_applied_migrations(db_);lines 487–487◇ for (const auto& mig : MIGRATIONS)lines 488–488◇ if (is_applied(applied, mig.name))lines 488–488continue;lines 489–489◇ if (!apply_migration(db_, mig))lines 489–489return false;lines 491–491return true;

Requirements

REQ-STOR-001 REQ-STOR-004