forge
Explore
Log in

Don't you dare go Hollow

yumush

Clone
★ 0

0 watching0 forksRustAGPL-3.06.8 MiB27ceb05Tahinli8 hours ago399 commits

mod.rs168 lines, 4.4 KiBHistoryRawDownload
1pub mod attachment;
2pub mod avatar;
3pub mod community;
4pub mod direct;
5pub mod friend;
6pub mod invitation;
7pub mod log;
8pub mod member;
9pub mod message;
10pub mod poll;
11pub mod registration_code;
12pub mod release;
13pub mod report;
14pub mod server_ban;
15pub mod session;
16pub mod settings;
17pub mod snippet;
18pub mod stats;
19pub mod user;
20
21use std::sync::Arc;
22
23use bitcode::DecodeOwned;
24use common::{error::Error, model::Named};
25use tokio::sync::{Mutex, MutexGuard};
26use turso::{Builder, Database, IntoParams, Row, core::types::FromValue};
27
28pub use turso::Connection;
29
30use crate::error::ServerError;
31
32const SCHEMA: &str = include_str!("schema.sql");
33
34#[derive(Clone)]
35pub struct Db {
36 database: Database,
37 conn: Arc<Mutex<Connection>>,
38}
39
40impl 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
89pub 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
100async 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
110pub struct Reader<'a> {
111 row: &'a Row,
112 at: usize,
113}
114
115impl 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
132pub 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
146pub 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
155pub 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
166pub async fn run(db: &Connection, sql: &str, params: impl IntoParams) -> Result<u64, ServerError> {
167 Ok(db.prepare_cached(sql).await?.execute(params).await?)
168}