AkurAI Build
Menu

Public repository / 5a670f50456c986205eb8383dc434f55b645c82b

AkurAI-IDP / src/db/mod.rs

Latest change b9cab20747eb8021df002afc9dfff94b0df4867a - scaffold: project skeleton with db schema, config, and module stubs by Ólafur Búi Ólafsson

pub mod schema;

use rusqlite::Connection;
use std::sync::Mutex;
use std::sync::LazyLock;
use crate::config;

static DB: LazyLock<Mutex<Connection>> = LazyLock::new(|| {
    let cfg = config::get();
    if let Some(parent) = std::path::Path::new(&cfg.db_path).parent() {
        std::fs::create_dir_all(parent).ok();
    }
    let conn = Connection::open(&cfg.db_path).expect("failed to open SQLite database");
    conn.execute_batch("PRAGMA journal_mode = WAL; PRAGMA foreign_keys = ON;")
        .expect("failed to set pragmas");
    schema::create_tables(&conn);
    Mutex::new(conn)
});

pub fn with_db<F, R>(f: F) -> R
where
    F: FnOnce(&Connection) -> R,
{
    let conn = DB.lock().unwrap();
    f(&conn)
}