1use std::sync::{
7 Arc, Mutex,
8 atomic::{AtomicU64, Ordering},
9};
10
11use rusqlite::{Connection, OptionalExtension, params};
12use serde::{Serialize, de::DeserializeOwned};
13
14use crate::Error;
15
16#[derive(Clone)]
22pub struct Store {
23 db: Arc<Mutex<Option<Connection>>>,
25 committed: Arc<AtomicU64>,
26 turns: Arc<tokio::sync::Mutex<()>>,
28}
29
30impl std::fmt::Debug for Store {
31 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
32 f.write_str("Store")
33 }
34}
35
36impl Store {
37 pub fn open(url: &str, schema: &str) -> Result<Store, Error> {
40 let db = if url == "memory:" {
41 Connection::open_in_memory()?
42 } else {
43 Connection::open(url.strip_prefix("sqlite:").unwrap_or(url))?
44 };
45 db.execute_batch(
46 "PRAGMA journal_mode = WAL;
47 PRAGMA secure_delete = ON;
48 CREATE TABLE IF NOT EXISTS data (ns TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (ns, key));
49 CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);",
50 )?;
51 truncate(&db)?;
54 let meta = |key: &str| -> Result<Option<String>, rusqlite::Error> {
55 db.query_row("SELECT value FROM meta WHERE key = ?", [key], |r| r.get(0))
56 .optional()
57 };
58 if meta("schema")?.as_deref() != Some(schema) {
59 db.execute_batch(
60 "BEGIN; DELETE FROM data; DELETE FROM meta WHERE key LIKE 'position:%';",
61 )?;
62 db.execute(
63 "INSERT OR REPLACE INTO meta (key, value) VALUES ('schema', ?), ('position', '0')",
64 [schema],
65 )?;
66 db.execute_batch("COMMIT")?;
67 }
68 let committed = meta("position")?.and_then(|p| p.parse().ok()).unwrap_or(0);
69 Ok(Store {
70 db: Arc::new(Mutex::new(Some(db))),
71 committed: Arc::new(AtomicU64::new(committed)),
72 turns: Arc::default(),
73 })
74 }
75
76 pub fn committed(&self) -> u64 {
78 self.committed.load(Ordering::SeqCst)
79 }
80
81 pub fn committed_for(&self, part: &str) -> Result<u64, Error> {
84 if part.is_empty() {
85 return Ok(self.committed());
86 }
87 let value: Option<String> = self.with(|db| {
88 db.query_row(
89 "SELECT value FROM meta WHERE key = ?",
90 [format!("position:{part}")],
91 |r| r.get(0),
92 )
93 .optional()
94 })?;
95 Ok(value.and_then(|v| v.parse().ok()).unwrap_or(0))
96 }
97
98 pub(crate) async fn turn(&self) -> tokio::sync::OwnedMutexGuard<()> {
100 Arc::clone(&self.turns).lock_owned().await
101 }
102
103 fn with<T>(&self, f: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T, Error> {
105 let db = self.db.lock().unwrap();
106 let db = db.as_ref().ok_or_else(|| {
107 rusqlite::Error::SqliteFailure(
108 rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_MISUSE),
109 Some("the store is closed".into()),
110 )
111 })?;
112 Ok(f(db)?)
113 }
114
115 pub fn get<T: DeserializeOwned>(&self, ns: &str, key: &str) -> Result<Option<T>, Error> {
117 let value: Option<String> = self.with(|db| {
118 db.query_row(
119 "SELECT value FROM data WHERE ns = ? AND key = ?",
120 [ns, key],
121 |r| r.get(0),
122 )
123 .optional()
124 })?;
125 Ok(value.map(|v| serde_json::from_str(&v)).transpose()?)
126 }
127
128 pub fn set<T: Serialize + ?Sized>(&self, ns: &str, key: &str, value: &T) -> Result<(), Error> {
130 let value = serde_json::to_string(value)?;
131 self.with(|db| {
132 db.execute(
133 "INSERT OR REPLACE INTO data (ns, key, value) VALUES (?, ?, ?)",
134 params![ns, key, value],
135 )
136 })?;
137 Ok(())
138 }
139
140 pub fn remove(&self, ns: &str, key: &str) -> Result<(), Error> {
142 self.with(|db| db.execute("DELETE FROM data WHERE ns = ? AND key = ?", [ns, key]))?;
143 Ok(())
144 }
145
146 pub fn all<T: DeserializeOwned>(&self, ns: &str) -> Result<Vec<(String, T)>, Error> {
148 let rows = self.with(|db| {
149 db.prepare("SELECT key, value FROM data WHERE ns = ? ORDER BY key")?
150 .query_map([ns], |r| {
151 Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
152 })?
153 .collect::<Result<Vec<_>, _>>()
154 })?;
155 rows.into_iter()
156 .map(|(k, v)| Ok((k, serde_json::from_str(&v)?)))
157 .collect()
158 }
159
160 pub fn reset(&self, ns: Option<&str>) -> Result<(), Error> {
162 self.with(|db| match ns {
163 Some(ns) => db.execute("DELETE FROM data WHERE ns = ?", [ns]),
164 None => db.execute("DELETE FROM data", []),
165 })?;
166 Ok(())
167 }
168
169 pub(crate) fn begin(&self) -> Result<(), Error> {
171 self.with(|db| {
172 if !db.is_autocommit() {
173 db.execute_batch("ROLLBACK")?;
174 }
175 db.execute_batch("BEGIN")
176 })
177 }
178
179 pub(crate) fn commit_part(&self, position: u64, erased: bool, part: &str) -> Result<(), Error> {
183 self.with(|db| {
184 if part.is_empty() {
185 db.execute(
186 "UPDATE meta SET value = ? WHERE key = 'position'",
187 [position.to_string()],
188 )?;
189 } else {
190 db.execute(
191 "INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
192 [format!("position:{part}"), position.to_string()],
193 )?;
194 }
195 db.execute_batch("COMMIT")?;
196 if erased {
197 truncate(db)?;
198 }
199 Ok(())
200 })?;
201 if part.is_empty() {
202 self.committed.store(position, Ordering::SeqCst);
203 }
204 Ok(())
205 }
206
207 pub(crate) fn savepoint(&self) -> Result<(), Error> {
209 self.with(|db| db.execute_batch("SAVEPOINT event"))
210 }
211
212 pub(crate) fn release(&self) -> Result<(), Error> {
214 self.with(|db| db.execute_batch("RELEASE event"))
215 }
216
217 pub(crate) fn rollback_event(&self) -> Result<(), Error> {
219 self.with(|db| db.execute_batch("ROLLBACK TO event; RELEASE event"))
220 }
221
222 pub(crate) fn rollback(&self) {
224 let _ = self.with(|db| {
225 if !db.is_autocommit() {
226 db.execute_batch("ROLLBACK")?;
227 }
228 Ok(())
229 });
230 }
231
232 pub fn close(&self) {
237 if let Some(db) = self.db.lock().unwrap().take() {
238 if !db.is_autocommit() {
239 let _ = db.execute_batch("ROLLBACK");
240 }
241 let _ = truncate(&db);
242 let _ = db.close();
243 }
244 }
245}
246
247fn truncate(db: &Connection) -> rusqlite::Result<()> {
249 db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
250}