pub mod attachment; pub mod avatar; pub mod community; pub mod direct; pub mod friend; pub mod invitation; pub mod log; pub mod member; pub mod message; pub mod poll; pub mod registration_code; pub mod release; pub mod report; pub mod server_ban; pub mod session; pub mod settings; pub mod snippet; pub mod stats; pub mod user; use std::sync::Arc; use bitcode::DecodeOwned; use common::{error::Error, model::Named}; use tokio::sync::{Mutex, MutexGuard}; use turso::{Builder, Database, IntoParams, Row, core::types::FromValue}; pub use turso::Connection; use crate::error::{ServerError, ensure_with}; const SCHEMA: &str = include_str!("schema.sql"); #[derive(Clone)] pub struct Db { database: Database, conn: Arc>, } impl Db { pub async fn open(path: &str) -> Result { let database = Builder::new_local(path).build().await?; let conn = database.connect()?; conn.execute_batch("PRAGMA foreign_keys = ON").await?; if schema(&conn).await?.is_empty() { conn.execute_batch(SCHEMA).await?; } let fresh_database = Builder::new_local(":memory:").build().await?; let fresh = fresh_database.connect()?; fresh.execute_batch(SCHEMA).await?; if schema(&conn).await? != schema(&fresh).await? { return Err(ServerError::Internal(format!( "{path} has an old schema, delete it" ))); } settings::read(&conn).await?; Ok(Self { database, conn: Arc::new(Mutex::new(conn)), }) } pub async fn lock(&self) -> Result, ServerError> { let conn = self.conn.lock().await; if !conn.is_autocommit()? { conn.execute("ROLLBACK", ()).await?; } Ok(conn) } pub async fn run( &self, work: impl AsyncFnOnce(&Connection) -> Result, ) -> Result { let db = self.lock().await?; atomic(&db, work(&db)).await } pub async fn backup(&self, target: &str) -> Result<(), ServerError> { self.database .connect()? .execute("VACUUM INTO ?1", (target,)) .await?; Ok(()) } } pub async fn atomic( db: &Connection, work: impl Future>, ) -> Result { db.execute("BEGIN IMMEDIATE", ()).await?; let result = work.await; db.execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }, ()) .await?; result } async fn schema(db: &Connection) -> Result, ServerError> { all( db, "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name", (), |r| r.get(), ) .await } pub struct Reader<'a> { row: &'a Row, at: usize, } impl Reader<'_> { pub fn get(&mut self) -> Result { self.at += 1; Ok(self.row.get(self.at - 1)?) } pub fn named(&mut self) -> Result { let text: String = self.get()?; T::parse(&text).ok_or_else(|| ServerError::Internal(format!("unknown enum text {text}"))) } pub fn blob(&mut self) -> Result { let bytes: Vec = self.get()?; Ok(bitcode::decode(&bytes)?) } } pub async fn all( db: &Connection, sql: &str, params: impl IntoParams, read: impl Fn(&mut Reader) -> Result, ) -> Result, ServerError> { let mut rows = db.prepare_cached(sql).await?.query(params).await?; let mut values = Vec::new(); while let Some(row) = rows.next().await? { values.push(read(&mut Reader { row: &row, at: 0 })?); } Ok(values) } pub async fn maybe( db: &Connection, sql: &str, params: impl IntoParams, read: impl Fn(&mut Reader) -> Result, ) -> Result, ServerError> { let mut rows = db.prepare_cached(sql).await?.query(params).await?; rows.next() .await? .map(|row| read(&mut Reader { row: &row, at: 0 })) .transpose() } pub async fn one( db: &Connection, sql: &str, params: impl IntoParams, read: impl Fn(&mut Reader) -> Result, ) -> Result { maybe(db, sql, params, read) .await? .ok_or_else(|| Error::NotFound.into()) } pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result { Ok(db.prepare_cached(sql).await?.execute(params).await?) } pub async fn exec(db: &Connection, sql: &str, params: impl IntoParams) -> Result<(), ServerError> { run(db, sql, params).await?; Ok(()) } pub async fn exec_one( db: &Connection, sql: &str, params: impl IntoParams, ) -> Result<(), ServerError> { ensure_with(run(db, sql, params).await? == 1, Error::NotFound) }