This repository was archived by the owner on Oct 9, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathsqlite.rs
More file actions
62 lines (61 loc) · 2.16 KB
/
Copy pathsqlite.rs
File metadata and controls
62 lines (61 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
use crate::search::store::{DiffKey, Store, StoredDiff};
use anyhow::{Context, Result};
use rusqlite::{params, Connection, OptionalExtension};
use std::{fs, path::Path, sync::Mutex};
pub struct SqliteStore {
connection: Mutex<Connection>,
}
impl SqliteStore {
pub fn open(path: impl AsRef<Path>) -> Result<Self> {
let path = path.as_ref();
if let Some(parent) = path.parent().filter(|p| !p.as_os_str().is_empty()) {
fs::create_dir_all(parent)?;
}
let connection = Connection::open(path)?;
connection.busy_timeout(std::time::Duration::from_secs(5))?;
connection.execute_batch(
"PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS diffs (key TEXT PRIMARY KEY, data BLOB NOT NULL);",
)?;
Ok(Self {
connection: Mutex::new(connection),
})
}
}
impl Store for SqliteStore {
fn get(&self, key: &DiffKey) -> Result<Option<StoredDiff>> {
let connection = self
.connection
.lock()
.map_err(|_| anyhow::anyhow!("diff store lock poisoned"))?;
let bytes: Option<Vec<u8>> = connection
.query_row(
"SELECT data FROM diffs WHERE key = ?1",
[key.as_str()],
|row| row.get(0),
)
.optional()?;
bytes
.map(|bytes| serde_json::from_slice(&bytes).context("decode SQLite diff entry"))
.transpose()
}
fn put(&self, key: &DiffKey, diff: &StoredDiff) -> Result<()> {
let connection = self
.connection
.lock()
.map_err(|_| anyhow::anyhow!("diff store lock poisoned"))?;
connection.execute(
"INSERT INTO diffs(key,data) VALUES (?1,?2)
ON CONFLICT(key) DO UPDATE SET data=excluded.data",
params![key.as_str(), serde_json::to_vec(diff)?],
)?;
Ok(())
}
fn remove(&self, key: &DiffKey) -> Result<()> {
self.connection
.lock()
.map_err(|_| anyhow::anyhow!("diff store lock poisoned"))?
.execute("DELETE FROM diffs WHERE key = ?1", [key.as_str()])?;
Ok(())
}
}