use std::collections::{BTreeMap, HashMap, HashSet};
use std::path::Path;
use std::sync::{Arc, Mutex};
use rusqlite::{params, Connection, OptionalExtension};
use super::builtin::{apply_row_change, ReadStore, Row};
use super::{
Change, ChangeBatch, DataStore, Origin, PendingMutation, RowClocks, RowRef, SpaceState, StateWrite, SyncStore,
TransactionalStore, TxView, Upload,
};
use crate::error::{Error, Result};
use crate::protocol::{FileState, JsonMap, Mutation};
pub const SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS kovlet_spaces (space_id TEXT PRIMARY KEY, cursor INTEGER NOT NULL DEFAULT 0, state TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS kovlet_clocks (space_id TEXT, tbl TEXT, id TEXT, field TEXT, hlc TEXT NOT NULL, trashed INTEGER,
PRIMARY KEY (space_id, tbl, id, field)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS kovlet_outbox (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
blob TEXT, held TEXT, PRIMARY KEY (space_id, n));
CREATE TABLE IF NOT EXISTS kovlet_meta (key TEXT PRIMARY KEY, value TEXT NOT NULL);
CREATE TABLE IF NOT EXISTS kovlet_queue (space_id TEXT, n INTEGER, mutation_id TEXT NOT NULL UNIQUE, body TEXT NOT NULL,
PRIMARY KEY (space_id, n));
";
fn migrate(conn: &Connection) -> Result<()> {
let has_batch = conn.prepare("SELECT 1 FROM pragma_table_info('kovlet_outbox') WHERE name = 'batch'")?.exists([])?;
if !has_batch {
conn.execute_batch("ALTER TABLE kovlet_outbox ADD COLUMN batch TEXT")?;
}
Ok(())
}
const BUILTIN_SCHEMA: &str = "
CREATE TABLE IF NOT EXISTS kovlet_rows (space_id TEXT, tbl TEXT, id TEXT, fields TEXT NOT NULL, trashed INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (space_id, tbl, id)) WITHOUT ROWID;
CREATE TABLE IF NOT EXISTS kovlet_files (space_id TEXT, id TEXT, state TEXT NOT NULL, PRIMARY KEY (space_id, id)) WITHOUT ROWID;
";
pub type ApplyFn = dyn Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync;
pub type ApplyBatchFn = dyn Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync;
pub type LendFn = dyn Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync;
enum Data {
Builtin { snapshot_files: Mutex<HashMap<String, HashSet<String>>> },
App(Box<ApplyFn>),
AppBatch(Box<ApplyBatchFn>),
}
enum Conn {
Shared(Arc<Mutex<Connection>>),
Lent(Box<LendFn>),
}
pub struct SqliteStore {
conn: Conn,
data: Data,
}
impl SqliteStore {
pub fn open(path: impl AsRef<Path>) -> Result<SqliteStore> {
let conn = Connection::open(path)?;
conn.pragma_update(None, "journal_mode", "WAL")?;
conn.pragma_update(None, "synchronous", "NORMAL")?;
SqliteStore::builtin(conn)
}
pub fn in_memory() -> Result<SqliteStore> {
SqliteStore::builtin(Connection::open_in_memory()?)
}
fn builtin(conn: Connection) -> Result<SqliteStore> {
conn.execute_batch(SCHEMA)?;
migrate(&conn)?;
conn.execute_batch(BUILTIN_SCHEMA)?;
Ok(SqliteStore {
conn: Conn::Shared(Arc::new(Mutex::new(conn))),
data: Data::Builtin { snapshot_files: Mutex::new(HashMap::new()) },
})
}
pub fn shared(
conn: Arc<Mutex<Connection>>,
apply: impl Fn(&Connection, &ChangeBatch, &Change) -> Result<()> + Send + Sync + 'static,
) -> Result<SqliteStore> {
SqliteStore::with(Conn::Shared(conn), Data::App(Box::new(apply)))
}
pub fn shared_batch(
conn: Arc<Mutex<Connection>>,
apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
) -> Result<SqliteStore> {
SqliteStore::with(Conn::Shared(conn), Data::AppBatch(Box::new(apply)))
}
pub fn lending(
lend: impl Fn(&mut dyn FnMut(&Connection) -> Result<()>) -> Result<()> + Send + Sync + 'static,
apply: impl Fn(&Connection, &ChangeBatch) -> Result<()> + Send + Sync + 'static,
) -> Result<SqliteStore> {
SqliteStore::with(Conn::Lent(Box::new(lend)), Data::AppBatch(Box::new(apply)))
}
fn with(conn: Conn, data: Data) -> Result<SqliteStore> {
let store = SqliteStore { conn, data };
store.with_conn(|c| {
c.execute_batch(SCHEMA)?;
migrate(c)
})?;
Ok(store)
}
pub fn connection(&self) -> Option<Arc<Mutex<Connection>>> {
match &self.conn {
Conn::Shared(c) => Some(c.clone()),
Conn::Lent(_) => None,
}
}
fn with_conn<T>(&self, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
match &self.conn {
Conn::Shared(c) => f(&c.lock().unwrap_or_else(|e| e.into_inner())),
Conn::Lent(lend) => {
let mut f = Some(f);
let mut out = None;
lend(&mut |c| {
let f = f.take().ok_or_else(|| Error::config("SqliteStore::lending: lend called f twice"))?;
out = Some(f(c)?);
Ok(())
})?;
out.ok_or_else(|| Error::config("SqliteStore::lending: lend returned without calling f"))
}
}
}
fn apply_in(&self, conn: &Connection, batch: &ChangeBatch) -> Result<()> {
match &self.data {
Data::App(f) => {
for c in &batch.changes {
f(conn, batch, c)?;
}
Ok(())
}
Data::AppBatch(f) => f(conn, batch),
Data::Builtin { snapshot_files } => builtin_apply(conn, batch, snapshot_files),
}
}
}
fn builtin_apply(
conn: &Connection,
batch: &ChangeBatch,
snapshot_files: &Mutex<HashMap<String, HashSet<String>>>,
) -> Result<()> {
let space = &batch.space_id;
for c in &batch.changes {
match c {
Change::File { file } => {
conn.execute(
"INSERT INTO kovlet_files (space_id, id, state) VALUES (?1, ?2, ?3)
ON CONFLICT(space_id, id) DO UPDATE SET state = excluded.state",
params![space, file.id, serde_json::to_string(file)?],
)?;
}
Change::Schema { table, schema: None } => {
conn.execute("DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2", params![space, table])?;
}
Change::Schema { .. } => {}
Change::Purge { table, id } => {
conn.execute(
"DELETE FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
params![space, table, id],
)?;
}
Change::Upsert { table, id, .. } | Change::Delete { table, id } | Change::Restore { table, id } => {
let cur = read_row(conn, space, table, id)?;
let mut tables: BTreeMap<String, BTreeMap<String, Row>> = BTreeMap::new();
if let Some(r) = cur {
tables.entry(table.clone()).or_default().insert(id.clone(), r);
}
apply_row_change(&mut tables, c);
if let Some(r) = tables.get(table).and_then(|t| t.get(id)) {
conn.execute(
"INSERT INTO kovlet_rows (space_id, tbl, id, fields, trashed) VALUES (?1, ?2, ?3, ?4, ?5)
ON CONFLICT(space_id, tbl, id) DO UPDATE SET fields = excluded.fields, trashed = excluded.trashed",
params![space, table, id, serde_json::to_string(&r.fields)?, r.trashed],
)?;
}
}
}
}
if batch.origin == Origin::Snapshot {
let mut snaps = snapshot_files.lock().unwrap();
let seen = snaps.entry(space.clone()).or_default();
for c in &batch.changes {
if let Change::File { file } = c {
seen.insert(file.id.clone());
}
}
if batch.complete {
let seen = snaps.remove(space).unwrap_or_default();
let mut stmt = conn.prepare("SELECT id FROM kovlet_files WHERE space_id = ?1")?;
let ids: Vec<String> = stmt.query_map([space], |r| r.get(0))?.collect::<Result<_, _>>()?;
for id in ids {
if !seen.contains(&id) {
conn.execute("DELETE FROM kovlet_files WHERE space_id = ?1 AND id = ?2", params![space, id])?;
}
}
}
}
Ok(())
}
fn read_row(conn: &Connection, space: &str, table: &str, id: &str) -> Result<Option<Row>> {
let r: Option<(String, bool)> = conn
.query_row(
"SELECT fields, trashed FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
params![space, table, id],
|r| Ok((r.get(0)?, r.get(1)?)),
)
.optional()?;
match r {
None => Ok(None),
Some((f, trashed)) => {
Ok(Some(Row { id: id.to_string(), fields: serde_json::from_str::<JsonMap>(&f)?, trashed }))
}
}
}
fn load(conn: &Connection, space: &str) -> Result<SpaceState> {
let r: Option<(i64, String)> = conn
.query_row("SELECT cursor, state FROM kovlet_spaces WHERE space_id = ?1", [space], |r| {
Ok((r.get(0)?, r.get(1)?))
})
.optional()?;
Ok(match r {
None => SpaceState::default(),
Some((cursor, state)) => SpaceState { cursor, schemas: serde_json::from_str(&state).unwrap_or_default() },
})
}
fn clocks(conn: &Connection, space: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
let mut out: BTreeMap<String, RowClocks> = BTreeMap::new();
let mut stmt = conn
.prepare_cached("SELECT field, hlc, trashed FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3")?;
for id in ids {
let rows = stmt.query_map(params![space, table, id], |r| {
Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?, r.get::<_, Option<bool>>(2)?))
})?;
for row in rows {
let (field, hlc, trashed) = row?;
let rc = out.entry(id.clone()).or_default();
if field == "_deleted" {
rc.deleted = Some(hlc);
rc.trashed = trashed;
} else {
rc.fields.insert(field, hlc);
}
}
}
Ok(out)
}
fn row_ids(conn: &Connection, space: &str) -> Result<Vec<RowRef>> {
let mut stmt = conn.prepare("SELECT DISTINCT tbl, id FROM kovlet_clocks WHERE space_id = ?1")?;
let v = stmt.query_map([space], |r| Ok(RowRef { table: r.get(0)?, id: r.get(1)? }))?.collect::<Result<_, _>>()?;
Ok(v)
}
fn outbox(conn: &Connection, space: &str, limit: usize) -> Result<Vec<PendingMutation>> {
let mut stmt = conn
.prepare_cached("SELECT body, blob, held, batch FROM kovlet_outbox WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
let rows = stmt.query_map(params![space, limit.min(i64::MAX as usize) as i64], |r| {
Ok((
r.get::<_, String>(0)?,
r.get::<_, Option<String>>(1)?,
r.get::<_, Option<String>>(2)?,
r.get::<_, Option<String>>(3)?,
))
})?;
let mut out = Vec::new();
for row in rows {
let (body, blob, held, batch) = row?;
let mutation: Mutation = serde_json::from_str(&body)?;
let upload: Option<Upload> = blob.as_deref().map(serde_json::from_str).transpose()?;
out.push(PendingMutation { mutation, upload, held, batch });
}
Ok(out)
}
fn commit(conn: &Connection, space: &str, w: &StateWrite) -> Result<()> {
for (r, rc) in &w.clocks {
conn.execute(
"DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
params![space, r.table, r.id],
)?;
let mut ins = conn.prepare_cached(
"INSERT INTO kovlet_clocks (space_id, tbl, id, field, hlc, trashed) VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
)?;
for (f, h) in &rc.fields {
ins.execute(params![space, r.table, r.id, f, h, Option::<bool>::None])?;
}
if let Some(d) = &rc.deleted {
ins.execute(params![space, r.table, r.id, "_deleted", d, rc.trashed])?;
}
}
for r in &w.purge {
conn.execute(
"DELETE FROM kovlet_clocks WHERE space_id = ?1 AND tbl = ?2 AND id = ?3",
params![space, r.table, r.id],
)?;
}
for id in &w.outbox_remove {
conn.execute("DELETE FROM kovlet_outbox WHERE space_id = ?1 AND mutation_id = ?2", params![space, id])?;
}
for p in &w.outbox_update {
conn.execute(
"UPDATE kovlet_outbox SET body = ?3, blob = ?4, held = ?5, batch = ?6 WHERE space_id = ?1 AND mutation_id = ?2",
params![
space,
p.mutation.mutation_id,
serde_json::to_string(&p.mutation)?,
p.upload.as_ref().map(serde_json::to_string).transpose()?,
p.held,
p.batch
],
)?;
}
if !w.outbox_add.is_empty() {
let mut n: i64 =
conn.query_row("SELECT coalesce(max(n), 0) FROM kovlet_outbox WHERE space_id = ?1", [space], |r| r.get(0))?;
for p in &w.outbox_add {
n += 1;
conn.execute(
"INSERT OR IGNORE INTO kovlet_outbox (space_id, n, mutation_id, body, blob, held, batch) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)",
params![
space,
n,
p.mutation.mutation_id,
serde_json::to_string(&p.mutation)?,
p.upload.as_ref().map(serde_json::to_string).transpose()?,
p.held,
p.batch
],
)?;
}
}
if w.cursor.is_some() || w.schemas.is_some() {
let cur = load(conn, space)?;
let cursor = w.cursor.unwrap_or(cur.cursor);
let schemas = w.schemas.as_ref().unwrap_or(&cur.schemas);
conn.execute(
"INSERT INTO kovlet_spaces (space_id, cursor, state) VALUES (?1, ?2, ?3)
ON CONFLICT(space_id) DO UPDATE SET cursor = excluded.cursor, state = excluded.state",
params![space, cursor, serde_json::to_string(schemas)?],
)?;
}
for (k, v) in &w.meta {
meta_set(conn, k, v)?;
}
Ok(())
}
fn meta_set(conn: &Connection, key: &str, value: &str) -> Result<()> {
conn.execute(
"INSERT INTO kovlet_meta (key, value) VALUES (?1, ?2) ON CONFLICT(key) DO UPDATE SET value = excluded.value",
params![key, value],
)?;
Ok(())
}
fn in_tx<T>(conn: &Connection, f: impl FnOnce(&Connection) -> Result<T>) -> Result<T> {
let nested = !conn.is_autocommit();
conn.execute_batch(if nested { "SAVEPOINT kovlet" } else { "BEGIN IMMEDIATE" })?;
match f(conn) {
Ok(v) => {
conn.execute_batch(if nested { "RELEASE kovlet" } else { "COMMIT" })?;
Ok(v)
}
Err(e) => {
let _ = conn.execute_batch(if nested { "ROLLBACK TO kovlet; RELEASE kovlet" } else { "ROLLBACK" });
Err(e)
}
}
}
impl SyncStore for SqliteStore {
fn load(&self, space_id: &str) -> Result<SpaceState> {
self.with_conn(|c| load(c, space_id))
}
fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
self.with_conn(|c| clocks(c, space_id, table, ids))
}
fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
self.with_conn(|c| row_ids(c, space_id))
}
fn outbox(&self, space_id: &str, limit: usize) -> Result<Vec<PendingMutation>> {
self.with_conn(|c| outbox(c, space_id, limit))
}
fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
self.with_conn(|conn| in_tx(conn, |c| commit(c, space_id, write)))
}
fn forget_space(&self, space_id: &str) -> Result<()> {
self.with_conn(|conn| {
in_tx(conn, |c| {
for t in ["kovlet_spaces", "kovlet_clocks", "kovlet_outbox", "kovlet_queue"] {
c.execute(&format!("DELETE FROM {t} WHERE space_id = ?1"), [space_id])?;
}
Ok(())
})
})?;
if let Data::Builtin { snapshot_files } = &self.data {
snapshot_files.lock().unwrap().remove(space_id);
}
Ok(())
}
fn meta_get(&self, key: &str) -> Result<Option<String>> {
self.with_conn(|c| {
Ok(c.query_row("SELECT value FROM kovlet_meta WHERE key = ?1", [key], |r| r.get(0)).optional()?)
})
}
fn meta_set(&self, key: &str, value: &str) -> Result<()> {
self.with_conn(|c| meta_set(c, key, value))
}
fn queue_add(&self, space_id: &str, entries: &[Mutation]) -> Result<()> {
self.with_conn(|conn| {
in_tx(conn, |c| {
let mut n: i64 =
c.query_row("SELECT coalesce(max(n), 0) FROM kovlet_queue WHERE space_id = ?1", [space_id], |r| {
r.get(0)
})?;
let mut ins = c.prepare_cached(
"INSERT OR IGNORE INTO kovlet_queue (space_id, n, mutation_id, body) VALUES (?1, ?2, ?3, ?4)",
)?;
for m in entries {
n += 1;
ins.execute(params![space_id, n, m.mutation_id, serde_json::to_string(m)?])?;
}
Ok(())
})
})
}
fn queued(&self, space_id: &str, limit: usize) -> Result<Vec<Mutation>> {
self.with_conn(|conn| {
let mut stmt =
conn.prepare_cached("SELECT body FROM kovlet_queue WHERE space_id = ?1 ORDER BY n LIMIT ?2")?;
let rows =
stmt.query_map(params![space_id, limit.min(i64::MAX as usize) as i64], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for body in rows {
out.push(serde_json::from_str(&body?)?);
}
Ok(out)
})
}
fn queue_remove(&self, space_id: &str, mutation_ids: &[String]) -> Result<()> {
self.with_conn(|conn| {
in_tx(conn, |c| {
let mut del = c.prepare_cached("DELETE FROM kovlet_queue WHERE space_id = ?1 AND mutation_id = ?2")?;
for id in mutation_ids {
del.execute(params![space_id, id])?;
}
Ok(())
})
})
}
fn transactional(&self) -> Option<&dyn TransactionalStore> {
Some(self)
}
}
struct View<'a> {
store: &'a SqliteStore,
conn: &'a Connection,
}
impl TxView for View<'_> {
fn clocks(&self, space_id: &str, table: &str, ids: &[String]) -> Result<BTreeMap<String, RowClocks>> {
clocks(self.conn, space_id, table, ids)
}
fn row_ids(&self, space_id: &str) -> Result<Vec<RowRef>> {
row_ids(self.conn, space_id)
}
fn apply(&self, batch: &ChangeBatch) -> Result<()> {
self.store.apply_in(self.conn, batch)
}
fn commit(&self, space_id: &str, write: &StateWrite) -> Result<()> {
commit(self.conn, space_id, write)
}
fn meta_set(&self, key: &str, value: &str) -> Result<()> {
meta_set(self.conn, key, value)
}
}
impl TransactionalStore for SqliteStore {
fn transaction(&self, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
self.with_conn(|conn| in_tx(conn, |c| f(&View { store: self, conn: c })))
}
}
impl SqliteStore {
pub(crate) fn transaction_on(&self, conn: &Connection, f: &mut dyn FnMut(&dyn TxView) -> Result<()>) -> Result<()> {
in_tx(conn, |c| f(&View { store: self, conn: c }))
}
}
impl DataStore for SqliteStore {
fn apply(&self, batch: &ChangeBatch) -> Result<()> {
self.with_conn(|conn| in_tx(conn, |c| self.apply_in(c, batch)))
}
}
impl ReadStore for SqliteStore {
fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>> {
if !matches!(self.data, Data::Builtin { .. }) {
return Err(Error::config("a shared SqliteStore has no built-in rows: read the app's own tables"));
}
self.with_conn(|conn| {
let mut stmt = conn.prepare(
"SELECT id, fields FROM kovlet_rows WHERE space_id = ?1 AND tbl = ?2 AND trashed = 0 ORDER BY id",
)?;
let rows =
stmt.query_map(params![space_id, table], |r| Ok((r.get::<_, String>(0)?, r.get::<_, String>(1)?)))?;
let mut out = Vec::new();
for row in rows {
let (id, f) = row?;
out.push(Row { id, fields: serde_json::from_str(&f)?, trashed: false });
}
Ok(out)
})
}
fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>> {
self.with_conn(|c| read_row(c, space_id, table, id))
}
fn files(&self, space_id: &str) -> Result<Vec<FileState>> {
self.with_conn(|conn| {
let mut stmt = conn.prepare("SELECT state FROM kovlet_files WHERE space_id = ?1 ORDER BY id")?;
let rows = stmt.query_map([space_id], |r| r.get::<_, String>(0))?;
let mut out = Vec::new();
for s in rows {
let f: FileState = serde_json::from_str(&s?)?;
if !f.deleted {
out.push(f);
}
}
Ok(out)
})
}
}