Menu
Public repository / 01b0c3e49ec2c526bbda745999ffed8ebfa8b8ee
AkurAI-Drive / backend/src/db/mod.rs
Latest change 6e3a0824f4ec4d2bea2524a20b4960c7ab9e2766 - backend: akurai-drive-api (OIDC RP + per-tenant S3 provisioning) by olibuijr
use crate::config;
use rusqlite::Connection;
use std::sync::LazyLock;
use std::sync::Mutex;
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");
create_tables(&conn);
Mutex::new(conn)
});
/// Run a closure with exclusive access to the single shared connection.
pub fn with_db<F, R>(f: F) -> R
where
F: FnOnce(&Connection) -> R,
{
let conn = DB.lock().unwrap();
f(&conn)
}
fn create_tables(conn: &Connection) {
conn.execute_batch(
"
CREATE TABLE IF NOT EXISTS sessions (
id TEXT PRIMARY KEY,
sub TEXT NOT NULL,
email TEXT NOT NULL,
groups TEXT NOT NULL, -- JSON array of group names
tenant_id TEXT,
created INTEGER NOT NULL,
expires INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_expires_idx ON sessions(expires);
CREATE TABLE IF NOT EXISTS storage (
id TEXT PRIMARY KEY,
owner_sub TEXT NOT NULL,
org TEXT NOT NULL,
email TEXT NOT NULL,
plan TEXT NOT NULL,
bucket TEXT NOT NULL,
region TEXT NOT NULL,
created INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS storage_owner_idx ON storage(owner_sub);
",
)
.expect("failed to create tables");
}