| 1 | pub mod attachment; |
| 2 | pub mod avatar; |
| 3 | pub mod community; |
| 4 | pub mod direct; |
| 5 | pub mod friend; |
| 6 | pub mod invitation; |
| 7 | pub mod log; |
| 8 | pub mod member; |
| 9 | pub mod message; |
| 10 | pub mod poll; |
| 11 | pub mod registration_code; |
| 12 | pub mod release; |
| 13 | pub mod report; |
| 14 | pub mod server_ban; |
| 15 | pub mod session; |
| 16 | pub mod settings; |
| 17 | pub mod snippet; |
| 18 | pub mod stats; |
| 19 | pub mod user; |
| 20 | |
| 21 | use std::sync::Arc; |
| 22 | |
| 23 | use bitcode::DecodeOwned; |
| 24 | use common::{error::Error, model::Named}; |
| 25 | use tokio::sync::{Mutex, MutexGuard}; |
| 26 | use turso::{Builder, Database, IntoParams, Row, core::types::FromValue}; |
| 27 | |
| 28 | pub use turso::Connection; |
| 29 | |
| 30 | use crate::error::ServerError; |
| 31 | |
| 32 | const SCHEMA: &str = include_str!("schema.sql"); |
| 33 | |
| 34 | #[derive(Clone)] |
| 35 | pub struct Db { |
| 36 | database: Database, |
| 37 | conn: Arc<Mutex<Connection>>, |
| 38 | } |
| 39 | |
| 40 | impl Db { |
| 41 | pub async fn open(path: &str) -> Result<Self, ServerError> { |
| 42 | let database = Builder::new_local(path).build().await?; |
| 43 | let conn = database.connect()?; |
| 44 | conn.execute_batch("PRAGMA foreign_keys = ON").await?; |
| 45 | if schema(&conn).await?.is_empty() { |
| 46 | conn.execute_batch(SCHEMA).await?; |
| 47 | } |
| 48 | let fresh_database = Builder::new_local(":memory:").build().await?; |
| 49 | let fresh = fresh_database.connect()?; |
| 50 | fresh.execute_batch(SCHEMA).await?; |
| 51 | if schema(&conn).await? != schema(&fresh).await? { |
| 52 | return Err(ServerError::Internal(format!( |
| 53 | "{path} has an old schema, delete it" |
| 54 | ))); |
| 55 | } |
| 56 | settings::read(&conn).await?; |
| 57 | |
| 58 | Ok(Self { |
| 59 | database, |
| 60 | conn: Arc::new(Mutex::new(conn)), |
| 61 | }) |
| 62 | } |
| 63 | |
| 64 | pub async fn lock(&self) -> Result<MutexGuard<'_, Connection>, ServerError> { |
| 65 | let conn = self.conn.lock().await; |
| 66 | if !conn.is_autocommit()? { |
| 67 | conn.execute("ROLLBACK", ()).await?; |
| 68 | } |
| 69 | Ok(conn) |
| 70 | } |
| 71 | |
| 72 | pub async fn run<T>( |
| 73 | &self, |
| 74 | work: impl AsyncFnOnce(&Connection) -> Result<T, ServerError>, |
| 75 | ) -> Result<T, ServerError> { |
| 76 | let db = self.lock().await?; |
| 77 | atomic(&db, work(&db)).await |
| 78 | } |
| 79 | |
| 80 | pub async fn backup(&self, target: &str) -> Result<(), ServerError> { |
| 81 | self.database |
| 82 | .connect()? |
| 83 | .execute("VACUUM INTO ?1", (target,)) |
| 84 | .await?; |
| 85 | Ok(()) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | pub async fn atomic<T>( |
| 90 | db: &Connection, |
| 91 | work: impl Future<Output = Result<T, ServerError>>, |
| 92 | ) -> Result<T, ServerError> { |
| 93 | db.execute("BEGIN IMMEDIATE", ()).await?; |
| 94 | let result = work.await; |
| 95 | db.execute(if result.is_ok() { "COMMIT" } else { "ROLLBACK" }, ()) |
| 96 | .await?; |
| 97 | result |
| 98 | } |
| 99 | |
| 100 | async fn schema(db: &Connection) -> Result<Vec<String>, ServerError> { |
| 101 | all( |
| 102 | db, |
| 103 | "SELECT sql FROM sqlite_schema WHERE sql IS NOT NULL ORDER BY name", |
| 104 | (), |
| 105 | |r| r.get(), |
| 106 | ) |
| 107 | .await |
| 108 | } |
| 109 | |
| 110 | pub struct Reader<'a> { |
| 111 | row: &'a Row, |
| 112 | at: usize, |
| 113 | } |
| 114 | |
| 115 | impl Reader<'_> { |
| 116 | pub fn get<T: FromValue>(&mut self) -> Result<T, ServerError> { |
| 117 | self.at += 1; |
| 118 | Ok(self.row.get(self.at - 1)?) |
| 119 | } |
| 120 | |
| 121 | pub fn named<T: Named>(&mut self) -> Result<T, ServerError> { |
| 122 | let text: String = self.get()?; |
| 123 | T::parse(&text).ok_or_else(|| ServerError::Internal(format!("unknown enum text {text}"))) |
| 124 | } |
| 125 | |
| 126 | pub fn blob<T: DecodeOwned>(&mut self) -> Result<T, ServerError> { |
| 127 | let bytes: Vec<u8> = self.get()?; |
| 128 | Ok(bitcode::decode(&bytes)?) |
| 129 | } |
| 130 | } |
| 131 | |
| 132 | pub async fn all<T>( |
| 133 | db: &Connection, |
| 134 | sql: &str, |
| 135 | params: impl IntoParams, |
| 136 | read: impl Fn(&mut Reader) -> Result<T, ServerError>, |
| 137 | ) -> Result<Vec<T>, ServerError> { |
| 138 | let mut rows = db.prepare_cached(sql).await?.query(params).await?; |
| 139 | let mut values = Vec::new(); |
| 140 | while let Some(row) = rows.next().await? { |
| 141 | values.push(read(&mut Reader { row: &row, at: 0 })?); |
| 142 | } |
| 143 | Ok(values) |
| 144 | } |
| 145 | |
| 146 | pub async fn maybe<T>( |
| 147 | db: &Connection, |
| 148 | sql: &str, |
| 149 | params: impl IntoParams, |
| 150 | read: impl Fn(&mut Reader) -> Result<T, ServerError>, |
| 151 | ) -> Result<Option<T>, ServerError> { |
| 152 | Ok(all(db, sql, params, read).await?.into_iter().next()) |
| 153 | } |
| 154 | |
| 155 | pub async fn one<T>( |
| 156 | db: &Connection, |
| 157 | sql: &str, |
| 158 | params: impl IntoParams, |
| 159 | read: impl Fn(&mut Reader) -> Result<T, ServerError>, |
| 160 | ) -> Result<T, ServerError> { |
| 161 | maybe(db, sql, params, read) |
| 162 | .await? |
| 163 | .ok_or_else(|| Error::NotFound.into()) |
| 164 | } |
| 165 | |
| 166 | pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result<u64, ServerError> { |
| 167 | Ok(db.prepare_cached(sql).await?.execute(params).await?) |
| 168 | } |