use std::sync::{
Arc, Mutex,
atomic::{AtomicU64, Ordering},
};
use rusqlite::{Connection, OptionalExtension, params};
use serde::{Serialize, de::DeserializeOwned};
use crate::Error;
#[derive(Clone)]
pub struct Store {
db: Arc<Mutex<Option<Connection>>>,
committed: Arc<AtomicU64>,
turns: Arc<tokio::sync::Mutex<()>>,
}
impl std::fmt::Debug for Store {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str("Store")
}
}
impl Store {
pub fn open(url: &str, schema: &str) -> Result<Store, Error> {
let db = if url == "memory:" {
Connection::open_in_memory()?
} else {
Connection::open(url.strip_prefix("sqlite:").unwrap_or(url))?
};
db.execute_batch(
"PRAGMA journal_mode = WAL;
PRAGMA secure_delete = ON;
CREATE TABLE IF NOT EXISTS data (ns TEXT NOT NULL, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (ns, key));
CREATE TABLE IF NOT EXISTS meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);",
)?;
truncate(&db)?;
let meta = |key: &str| -> Result<Option<String>, rusqlite::Error> {
db.query_row("SELECT value FROM meta WHERE key = ?", [key], |r| r.get(0))
.optional()
};
if meta("schema")?.as_deref() != Some(schema) {
db.execute_batch(
"BEGIN; DELETE FROM data; DELETE FROM meta WHERE key LIKE 'position:%';",
)?;
db.execute(
"INSERT OR REPLACE INTO meta (key, value) VALUES ('schema', ?), ('position', '0')",
[schema],
)?;
db.execute_batch("COMMIT")?;
}
let committed = meta("position")?.and_then(|p| p.parse().ok()).unwrap_or(0);
Ok(Store {
db: Arc::new(Mutex::new(Some(db))),
committed: Arc::new(AtomicU64::new(committed)),
turns: Arc::default(),
})
}
pub fn committed(&self) -> u64 {
self.committed.load(Ordering::SeqCst)
}
pub fn committed_for(&self, part: &str) -> Result<u64, Error> {
if part.is_empty() {
return Ok(self.committed());
}
let value: Option<String> = self.with(|db| {
db.query_row(
"SELECT value FROM meta WHERE key = ?",
[format!("position:{part}")],
|r| r.get(0),
)
.optional()
})?;
Ok(value.and_then(|v| v.parse().ok()).unwrap_or(0))
}
pub(crate) async fn turn(&self) -> tokio::sync::OwnedMutexGuard<()> {
Arc::clone(&self.turns).lock_owned().await
}
fn with<T>(&self, f: impl FnOnce(&Connection) -> rusqlite::Result<T>) -> Result<T, Error> {
let db = self.db.lock().unwrap();
let db = db.as_ref().ok_or_else(|| {
rusqlite::Error::SqliteFailure(
rusqlite::ffi::Error::new(rusqlite::ffi::SQLITE_MISUSE),
Some("the store is closed".into()),
)
})?;
Ok(f(db)?)
}
pub fn get<T: DeserializeOwned>(&self, ns: &str, key: &str) -> Result<Option<T>, Error> {
let value: Option<String> = self.with(|db| {
db.query_row(
"SELECT value FROM data WHERE ns = ? AND key = ?",
[ns, key],
|r| r.get(0),
)
.optional()
})?;
Ok(value.map(|v| serde_json::from_str(&v)).transpose()?)
}
pub fn set<T: Serialize + ?Sized>(&self, ns: &str, key: &str, value: &T) -> Result<(), Error> {
let value = serde_json::to_string(value)?;
self.with(|db| {
db.execute(
"INSERT OR REPLACE INTO data (ns, key, value) VALUES (?, ?, ?)",
params![ns, key, value],
)
})?;
Ok(())
}
pub fn remove(&self, ns: &str, key: &str) -> Result<(), Error> {
self.with(|db| db.execute("DELETE FROM data WHERE ns = ? AND key = ?", [ns, key]))?;
Ok(())
}
pub fn all<T: DeserializeOwned>(&self, ns: &str) -> Result<Vec<(String, T)>, Error> {
let rows = self.with(|db| {
db.prepare("SELECT key, value FROM data WHERE ns = ? ORDER BY key")?
.query_map([ns], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?))
})?
.collect::<Result<Vec<_>, _>>()
})?;
rows.into_iter()
.map(|(k, v)| Ok((k, serde_json::from_str(&v)?)))
.collect()
}
pub fn reset(&self, ns: Option<&str>) -> Result<(), Error> {
self.with(|db| match ns {
Some(ns) => db.execute("DELETE FROM data WHERE ns = ?", [ns]),
None => db.execute("DELETE FROM data", []),
})?;
Ok(())
}
pub(crate) fn begin(&self) -> Result<(), Error> {
self.with(|db| {
if !db.is_autocommit() {
db.execute_batch("ROLLBACK")?;
}
db.execute_batch("BEGIN")
})
}
pub(crate) fn commit_part(&self, position: u64, erased: bool, part: &str) -> Result<(), Error> {
self.with(|db| {
if part.is_empty() {
db.execute(
"UPDATE meta SET value = ? WHERE key = 'position'",
[position.to_string()],
)?;
} else {
db.execute(
"INSERT OR REPLACE INTO meta (key, value) VALUES (?, ?)",
[format!("position:{part}"), position.to_string()],
)?;
}
db.execute_batch("COMMIT")?;
if erased {
truncate(db)?;
}
Ok(())
})?;
if part.is_empty() {
self.committed.store(position, Ordering::SeqCst);
}
Ok(())
}
pub(crate) fn savepoint(&self) -> Result<(), Error> {
self.with(|db| db.execute_batch("SAVEPOINT event"))
}
pub(crate) fn release(&self) -> Result<(), Error> {
self.with(|db| db.execute_batch("RELEASE event"))
}
pub(crate) fn rollback_event(&self) -> Result<(), Error> {
self.with(|db| db.execute_batch("ROLLBACK TO event; RELEASE event"))
}
pub(crate) fn rollback(&self) {
let _ = self.with(|db| {
if !db.is_autocommit() {
db.execute_batch("ROLLBACK")?;
}
Ok(())
});
}
pub fn close(&self) {
if let Some(db) = self.db.lock().unwrap().take() {
if !db.is_autocommit() {
let _ = db.execute_batch("ROLLBACK");
}
let _ = truncate(&db);
let _ = db.close();
}
}
}
fn truncate(db: &Connection) -> rusqlite::Result<()> {
db.query_row("PRAGMA wal_checkpoint(TRUNCATE)", [], |_| Ok(()))
}