summaryrefslogtreecommitdiffstats
path: root/src/db/world.rs
blob: 19a28f171e2ad143870a4fc706065eb5cbfed469 (plain)
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
use rusqlite::params;

use crate::db::{json_or, Db, WorldMember, Writer};
use crate::error::Result;
use crate::time;

// --------------------------------------------------------- world snapshots --

pub fn put_world_snapshot(writer: &Writer, members: &[WorldMember]) -> Result<i64> {
    let mut sorted = members.to_vec();
    sorted.sort();
    sorted.dedup();
    let hash = crate::hash::canonical_json(&sorted)?;
    let json = serde_json::to_string(&sorted)?;
    let at = time::now();
    writer.tx(move |tx| {
        tx.execute(
            "INSERT INTO world_snapshot (hash, members_json, created_at) VALUES (?1,?2,?3)
             ON CONFLICT(hash) DO NOTHING",
            params![hash, json, at],
        )?;
        tx.query_row("SELECT id FROM world_snapshot WHERE hash=?1", params![hash], |r| r.get(0)).map_err(Into::into)
    })
}

/// Read the members of a world snapshot.
///
/// Test-tier only: production writes world snapshots and never reads one back
/// member by member; the index is served from the release rows.
#[cfg(feature = "test-support")]
pub fn world_members(db: &Db, id: i64) -> Result<Vec<WorldMember>> {
    db.read(|c| {
        let s: String =
            c.query_row("SELECT members_json FROM world_snapshot WHERE id=?1", params![id], |r| r.get(0))?;
        Ok(json_or(&s, Vec::new()))
    })
}