use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Mutex;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use super::{Change, ChangeBatch, DataStore, Origin};
use crate::error::Result;
use crate::protocol::{FileState, JsonMap};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Row {
pub id: String,
pub fields: JsonMap,
#[serde(default)]
pub trashed: bool,
}
impl Row {
pub fn to_object(&self) -> Value {
let mut m = self.fields.clone();
m.insert("id".into(), Value::String(self.id.clone()));
Value::Object(m)
}
}
pub trait ReadStore: Send + Sync {
fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>>;
fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>>;
fn files(&self, space_id: &str) -> Result<Vec<FileState>>;
}
#[derive(Default)]
struct Data {
rows: HashMap<String, BTreeMap<String, BTreeMap<String, Row>>>, files: HashMap<String, BTreeMap<String, FileState>>,
snapshot_files: HashMap<String, HashSet<String>>,
}
#[derive(Default)]
pub struct MemoryStore {
data: Mutex<Data>,
}
impl MemoryStore {
pub fn new() -> MemoryStore {
MemoryStore::default()
}
}
pub(crate) fn apply_row_change(tables: &mut BTreeMap<String, BTreeMap<String, Row>>, c: &Change) {
match c {
Change::Upsert { table, id, fields, deleted } => {
let t = tables.entry(table.clone()).or_default();
let row =
t.entry(id.clone()).or_insert_with(|| Row { id: id.clone(), fields: JsonMap::new(), trashed: false });
for (k, v) in fields {
if v.is_null() {
row.fields.remove(k);
} else {
row.fields.insert(k.clone(), v.clone());
}
}
row.trashed = *deleted;
}
Change::Delete { table, id } | Change::Restore { table, id } => {
if let Some(row) = tables.get_mut(table).and_then(|t| t.get_mut(id)) {
row.trashed = matches!(c, Change::Delete { .. });
}
}
Change::Purge { table, id } => {
if let Some(t) = tables.get_mut(table) {
t.remove(id);
}
}
Change::Schema { table, schema: None } => {
tables.remove(table);
}
Change::Schema { .. } | Change::File { .. } => {}
}
}
impl DataStore for MemoryStore {
fn apply(&self, batch: &ChangeBatch) -> Result<()> {
let mut d = self.data.lock().unwrap();
for c in &batch.changes {
if let Change::File { file } = c {
d.files.entry(batch.space_id.clone()).or_default().insert(file.id.clone(), file.clone());
continue;
}
let tables = d.rows.entry(batch.space_id.clone()).or_default();
apply_row_change(tables, c);
}
if batch.origin == Origin::Snapshot {
let seen = d.snapshot_files.entry(batch.space_id.clone()).or_default();
for c in &batch.changes {
if let Change::File { file } = c {
seen.insert(file.id.clone());
}
}
if batch.complete {
let seen = d.snapshot_files.remove(&batch.space_id).unwrap_or_default();
if let Some(files) = d.files.get_mut(&batch.space_id) {
files.retain(|id, _| seen.contains(id));
}
}
}
Ok(())
}
}
impl ReadStore for MemoryStore {
fn rows(&self, space_id: &str, table: &str) -> Result<Vec<Row>> {
let d = self.data.lock().unwrap();
Ok(d.rows
.get(space_id)
.and_then(|t| t.get(table))
.map(|t| t.values().filter(|r| !r.trashed).cloned().collect())
.unwrap_or_default())
}
fn get(&self, space_id: &str, table: &str, id: &str) -> Result<Option<Row>> {
let d = self.data.lock().unwrap();
Ok(d.rows.get(space_id).and_then(|t| t.get(table)).and_then(|t| t.get(id)).cloned())
}
fn files(&self, space_id: &str) -> Result<Vec<FileState>> {
let d = self.data.lock().unwrap();
Ok(d.files.get(space_id).map(|f| f.values().filter(|f| !f.deleted).cloned().collect()).unwrap_or_default())
}
}